Simplify the variant handling code, no functionality change.
[oota-llvm.git] / utils / TableGen / AsmWriterEmitter.cpp
1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend is emits an assembly printer for the current target.
11 // Note that this is currently fairly skeletal, but will grow over time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "AsmWriterEmitter.h"
16 #include "CodeGenTarget.h"
17 #include "Record.h"
18 #include <algorithm>
19 #include <ostream>
20 using namespace llvm;
21
22 static bool isIdentChar(char C) {
23   return (C >= 'a' && C <= 'z') ||
24          (C >= 'A' && C <= 'Z') ||
25          (C >= '0' && C <= '9') ||
26          C == '_';
27 }
28
29 namespace {
30   struct AsmWriterOperand {
31     enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
32
33     /// Str - For isLiteralTextOperand, this IS the literal text.  For
34     /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
35     std::string Str;
36
37     /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
38     /// machine instruction.
39     unsigned MIOpNo;
40
41     AsmWriterOperand(const std::string &LitStr)
42       : OperandType(isLiteralTextOperand), Str(LitStr) {}
43
44     AsmWriterOperand(const std::string &Printer, unsigned OpNo) 
45       : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
46
47     bool operator!=(const AsmWriterOperand &Other) const {
48       if (OperandType != Other.OperandType || Str != Other.Str) return true;
49       if (OperandType == isMachineInstrOperand)
50         return MIOpNo != Other.MIOpNo;
51       return false;
52     }
53     bool operator==(const AsmWriterOperand &Other) const {
54       return !operator!=(Other);
55     }
56     void EmitCode(std::ostream &OS) const;
57   };
58
59   struct AsmWriterInst {
60     std::vector<AsmWriterOperand> Operands;
61     const CodeGenInstruction *CGI;
62
63     AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
64
65     /// MatchesAllButOneOp - If this instruction is exactly identical to the
66     /// specified instruction except for one differing operand, return the
67     /// differing operand number.  Otherwise return ~0.
68     unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
69
70   private:
71     void AddLiteralString(const std::string &Str) {
72       // If the last operand was already a literal text string, append this to
73       // it, otherwise add a new operand.
74       if (!Operands.empty() &&
75           Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
76         Operands.back().Str.append(Str);
77       else
78         Operands.push_back(AsmWriterOperand(Str));
79     }
80   };
81 }
82
83
84 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
85   if (OperandType == isLiteralTextOperand)
86     OS << "O << \"" << Str << "\"; ";
87   else
88     OS << Str << "(MI, " << MIOpNo << "); ";
89 }
90
91
92 /// ParseAsmString - Parse the specified Instruction's AsmString into this
93 /// AsmWriterInst.
94 ///
95 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
96   this->CGI = &CGI;
97   unsigned CurVariant = ~0U;  // ~0 if we are outside a {.|.|.} region, other #.
98
99   // NOTE: Any extensions to this code need to be mirrored in the 
100   // AsmPrinter::printInlineAsm code that executes as compile time (assuming
101   // that inline asm strings should also get the new feature)!
102   const std::string &AsmString = CGI.AsmString;
103   std::string::size_type LastEmitted = 0;
104   while (LastEmitted != AsmString.size()) {
105     std::string::size_type DollarPos =
106       AsmString.find_first_of("${|}", LastEmitted);
107     if (DollarPos == std::string::npos) DollarPos = AsmString.size();
108
109     // Emit a constant string fragment.
110     if (DollarPos != LastEmitted) {
111       // TODO: this should eventually handle escaping.
112       if (CurVariant == Variant || CurVariant == ~0U)
113         AddLiteralString(std::string(AsmString.begin()+LastEmitted,
114                                      AsmString.begin()+DollarPos));
115       LastEmitted = DollarPos;
116     } else if (AsmString[DollarPos] == '{') {
117       if (CurVariant != ~0U)
118         throw "Nested variants found for instruction '" +
119               CGI.TheDef->getName() + "'!";
120       LastEmitted = DollarPos+1;
121       CurVariant = 0;   // We are now inside of the variant!
122     } else if (AsmString[DollarPos] == '|') {
123       if (CurVariant == ~0U)
124         throw "'|' character found outside of a variant in instruction '"
125           + CGI.TheDef->getName() + "'!";
126       ++CurVariant;
127       ++LastEmitted;
128     } else if (AsmString[DollarPos] == '}') {
129       if (CurVariant == ~0U)
130         throw "'}' character found outside of a variant in instruction '"
131           + CGI.TheDef->getName() + "'!";
132       ++LastEmitted;
133       CurVariant = ~0U;
134     } else if (DollarPos+1 != AsmString.size() &&
135                AsmString[DollarPos+1] == '$') {
136       if (CurVariant == Variant || CurVariant == ~0U) 
137         AddLiteralString("$");  // "$$" -> $
138       LastEmitted = DollarPos+2;
139     } else {
140       // Get the name of the variable.
141       std::string::size_type VarEnd = DollarPos+1;
142
143       // handle ${foo}bar as $foo by detecting whether the character following
144       // the dollar sign is a curly brace.  If so, advance VarEnd and DollarPos
145       // so the variable name does not contain the leading curly brace.
146       bool hasCurlyBraces = false;
147       if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
148         hasCurlyBraces = true;
149         ++DollarPos;
150         ++VarEnd;
151       }
152
153       while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
154         ++VarEnd;
155       std::string VarName(AsmString.begin()+DollarPos+1,
156                           AsmString.begin()+VarEnd);
157
158       // In order to avoid starting the next string at the terminating curly
159       // brace, advance the end position past it if we found an opening curly
160       // brace.
161       if (hasCurlyBraces) {
162         if (VarEnd >= AsmString.size())
163           throw "Reached end of string before terminating curly brace in '"
164                 + CGI.TheDef->getName() + "'";
165         if (AsmString[VarEnd] != '}')
166           throw "Variable name beginning with '{' did not end with '}' in '"
167                 + CGI.TheDef->getName() + "'";
168         ++VarEnd;
169       }
170       if (VarName.empty())
171         throw "Stray '$' in '" + CGI.TheDef->getName() +
172               "' asm string, maybe you want $$?";
173
174       unsigned OpNo = CGI.getOperandNamed(VarName);
175       CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
176
177       // If this is a two-address instruction and we are not accessing the
178       // 0th operand, remove an operand.
179       unsigned MIOp = OpInfo.MIOperandNo;
180       if (CGI.isTwoAddress && MIOp != 0) {
181         if (MIOp == 1)
182           throw "Should refer to operand #0 instead of #1 for two-address"
183             " instruction '" + CGI.TheDef->getName() + "'!";
184         --MIOp;
185       }
186
187       if (CurVariant == Variant || CurVariant == ~0U) 
188         Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
189       LastEmitted = VarEnd;
190     }
191   }
192
193   AddLiteralString("\\n");
194 }
195
196 /// MatchesAllButOneOp - If this instruction is exactly identical to the
197 /// specified instruction except for one differing operand, return the differing
198 /// operand number.  If more than one operand mismatches, return ~1, otherwise
199 /// if the instructions are identical return ~0.
200 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
201   if (Operands.size() != Other.Operands.size()) return ~1;
202
203   unsigned MismatchOperand = ~0U;
204   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
205     if (Operands[i] != Other.Operands[i])
206       if (MismatchOperand != ~0U)  // Already have one mismatch?
207         return ~1U;
208       else
209         MismatchOperand = i;
210   }
211   return MismatchOperand;
212 }
213
214 static void PrintCases(std::vector<std::pair<std::string,
215                        AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
216   O << "    case " << OpsToPrint.back().first << ": ";
217   AsmWriterOperand TheOp = OpsToPrint.back().second;
218   OpsToPrint.pop_back();
219
220   // Check to see if any other operands are identical in this list, and if so,
221   // emit a case label for them.
222   for (unsigned i = OpsToPrint.size(); i != 0; --i)
223     if (OpsToPrint[i-1].second == TheOp) {
224       O << "\n    case " << OpsToPrint[i-1].first << ": ";
225       OpsToPrint.erase(OpsToPrint.begin()+i-1);
226     }
227
228   // Finally, emit the code.
229   TheOp.EmitCode(O);
230   O << "break;\n";
231 }
232
233
234 /// EmitInstructions - Emit the last instruction in the vector and any other
235 /// instructions that are suitably similar to it.
236 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
237                              std::ostream &O) {
238   AsmWriterInst FirstInst = Insts.back();
239   Insts.pop_back();
240
241   std::vector<AsmWriterInst> SimilarInsts;
242   unsigned DifferingOperand = ~0;
243   for (unsigned i = Insts.size(); i != 0; --i) {
244     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
245     if (DiffOp != ~1U) {
246       if (DifferingOperand == ~0U)  // First match!
247         DifferingOperand = DiffOp;
248
249       // If this differs in the same operand as the rest of the instructions in
250       // this class, move it to the SimilarInsts list.
251       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
252         SimilarInsts.push_back(Insts[i-1]);
253         Insts.erase(Insts.begin()+i-1);
254       }
255     }
256   }
257
258   std::string Namespace = FirstInst.CGI->Namespace;
259
260   O << "  case " << Namespace << "::"
261     << FirstInst.CGI->TheDef->getName() << ":\n";
262   for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
263     O << "  case " << Namespace << "::"
264       << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
265   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
266     if (i != DifferingOperand) {
267       // If the operand is the same for all instructions, just print it.
268       O << "    ";
269       FirstInst.Operands[i].EmitCode(O);
270     } else {
271       // If this is the operand that varies between all of the instructions,
272       // emit a switch for just this operand now.
273       O << "    switch (MI->getOpcode()) {\n";
274       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
275       OpsToPrint.push_back(std::make_pair(Namespace+"::"+
276                                           FirstInst.CGI->TheDef->getName(),
277                                           FirstInst.Operands[i]));
278
279       for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
280         AsmWriterInst &AWI = SimilarInsts[si];
281         OpsToPrint.push_back(std::make_pair(Namespace+"::"+
282                                             AWI.CGI->TheDef->getName(),
283                                             AWI.Operands[i]));
284       }
285       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
286       while (!OpsToPrint.empty())
287         PrintCases(OpsToPrint, O);
288       O << "    }";
289     }
290     O << "\n";
291   }
292
293   O << "    break;\n";
294 }
295
296 void AsmWriterEmitter::run(std::ostream &O) {
297   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
298
299   CodeGenTarget Target;
300   Record *AsmWriter = Target.getAsmWriter();
301   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
302   unsigned Variant = AsmWriter->getValueAsInt("Variant");
303
304   O <<
305   "/// printInstruction - This method is automatically generated by tablegen\n"
306   "/// from the instruction set description.  This method returns true if the\n"
307   "/// machine instruction was sufficiently described to print it, otherwise\n"
308   "/// it returns false.\n"
309     "bool " << Target.getName() << ClassName
310             << "::printInstruction(const MachineInstr *MI) {\n";
311
312   std::string Namespace = Target.inst_begin()->second.Namespace;
313
314   std::vector<AsmWriterInst> Instructions;
315
316   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
317          E = Target.inst_end(); I != E; ++I)
318     if (!I->second.AsmString.empty())
319       Instructions.push_back(AsmWriterInst(I->second, Variant));
320
321   // If all of the instructions start with a constant string (a very very common
322   // occurance), emit all of the constant strings as a big table lookup instead
323   // of requiring a switch for them.
324   bool AllStartWithString = true;
325
326   for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
327     if (Instructions[i].Operands.empty() ||
328         Instructions[i].Operands[0].OperandType !=
329                           AsmWriterOperand::isLiteralTextOperand) {
330       AllStartWithString = false;
331       break;
332     }
333
334   std::vector<const CodeGenInstruction*> NumberedInstructions;
335   Target.getInstructionsByEnumValue(NumberedInstructions);
336   
337   if (AllStartWithString) {
338     // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
339     // all machine instructions are necessarily being printed, so there may be
340     // target instructions not in this map.
341     std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
342     for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
343       CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
344
345     // Emit a table of constant strings.
346     O << "  static const char * const OpStrs[] = {\n";
347     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
348       AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
349       if (AWI == 0) {
350         // Something not handled by the asmwriter printer.
351         O << "    0,\t// ";
352       } else {
353         O << "    \"" << AWI->Operands[0].Str << "\",\t// ";
354         // Nuke the string from the operand list.  It is now handled!
355         AWI->Operands.erase(AWI->Operands.begin());
356       }
357       O << NumberedInstructions[i]->TheDef->getName() << "\n";
358     }
359     O << "  };\n\n"
360       << "  // Emit the opcode for the instruction.\n"
361       << "  if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
362       << "    O << AsmStr;\n\n";
363   }
364
365   // Because this is a vector we want to emit from the end.  Reverse all of the
366   // elements in the vector.
367   std::reverse(Instructions.begin(), Instructions.end());
368
369   // Find the opcode # of inline asm
370   O << "  switch (MI->getOpcode()) {\n"
371        "  default: return false;\n"
372        "  case " << NumberedInstructions.back()->Namespace
373     << "::INLINEASM: printInlineAsm(MI); break;\n";
374
375   while (!Instructions.empty())
376     EmitInstructions(Instructions, O);
377
378   O << "  }\n"
379        "  return true;\n"
380        "}\n";
381 }