Implement *even more* factoring. In particular, if all of the instruction
[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     /// OpVT - For isMachineInstrOperand, this is the value type for the
42     /// operand.
43     MVT::ValueType OpVT;
44
45     AsmWriterOperand(const std::string &LitStr)
46       : OperandType(isLiteralTextOperand),  Str(LitStr) {}
47
48     AsmWriterOperand(const std::string &Printer, unsigned OpNo,
49                      MVT::ValueType VT) : OperandType(isMachineInstrOperand),
50                                           Str(Printer), MIOpNo(OpNo), OpVT(VT){}
51
52     bool operator!=(const AsmWriterOperand &Other) const {
53       if (OperandType != Other.OperandType || Str != Other.Str) return true;
54       if (OperandType == isMachineInstrOperand)
55         return MIOpNo != Other.MIOpNo || OpVT != Other.OpVT;
56       return false;
57     }
58     void EmitCode(std::ostream &OS) const;
59   };
60
61   struct AsmWriterInst {
62     std::vector<AsmWriterOperand> Operands;
63     const CodeGenInstruction *CGI;
64     
65     AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
66
67     /// MatchesAllButOneOp - If this instruction is exactly identical to the
68     /// specified instruction except for one differing operand, return the
69     /// differing operand number.  Otherwise return ~0.
70     unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
71
72   private:
73     void AddLiteralString(const std::string &Str) {
74       // If the last operand was already a literal text string, append this to
75       // it, otherwise add a new operand.
76       if (!Operands.empty() &&
77           Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
78         Operands.back().Str.append(Str);
79       else
80         Operands.push_back(AsmWriterOperand(Str));
81     }
82   };
83 }
84
85
86 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
87   if (OperandType == isLiteralTextOperand)
88     OS << "O << \"" << Str << "\"; ";
89   else
90     OS << Str << "(MI, " << MIOpNo << ", MVT::" << getName(OpVT) << "); ";
91 }
92
93
94 /// ParseAsmString - Parse the specified Instruction's AsmString into this
95 /// AsmWriterInst.
96 ///
97 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
98   this->CGI = &CGI;
99   bool inVariant = false;  // True if we are inside a {.|.|.} region.
100
101   const std::string &AsmString = CGI.AsmString;
102   std::string::size_type LastEmitted = 0;
103   while (LastEmitted != AsmString.size()) {
104     std::string::size_type DollarPos =
105       AsmString.find_first_of("${|}", LastEmitted);
106     if (DollarPos == std::string::npos) DollarPos = AsmString.size();
107
108     // Emit a constant string fragment.
109     if (DollarPos != LastEmitted) {
110       // TODO: this should eventually handle escaping.
111       AddLiteralString(std::string(AsmString.begin()+LastEmitted,
112                                    AsmString.begin()+DollarPos));
113       LastEmitted = DollarPos;
114     } else if (AsmString[DollarPos] == '{') {
115       if (inVariant)
116         throw "Nested variants found for instruction '" + CGI.Name + "'!";
117       LastEmitted = DollarPos+1;
118       inVariant = true;   // We are now inside of the variant!
119       for (unsigned i = 0; i != Variant; ++i) {
120         // Skip over all of the text for an irrelevant variant here.  The
121         // next variant starts at |, or there may not be text for this
122         // variant if we see a }.
123         std::string::size_type NP =
124           AsmString.find_first_of("|}", LastEmitted);
125         if (NP == std::string::npos)
126           throw "Incomplete variant for instruction '" + CGI.Name + "'!";
127         LastEmitted = NP+1;
128         if (AsmString[NP] == '}') {
129           inVariant = false;        // No text for this variant.
130           break;
131         }
132       }
133     } else if (AsmString[DollarPos] == '|') {
134       if (!inVariant)
135         throw "'|' character found outside of a variant in instruction '"
136           + CGI.Name + "'!";
137       // Move to the end of variant list.
138       std::string::size_type NP = AsmString.find('}', LastEmitted);
139       if (NP == std::string::npos)
140         throw "Incomplete variant for instruction '" + CGI.Name + "'!";
141       LastEmitted = NP+1;
142       inVariant = false;
143     } else if (AsmString[DollarPos] == '}') {
144       if (!inVariant)
145         throw "'}' character found outside of a variant in instruction '"
146           + CGI.Name + "'!";
147       LastEmitted = DollarPos+1;
148       inVariant = false;
149     } else if (DollarPos+1 != AsmString.size() &&
150                AsmString[DollarPos+1] == '$') {
151       AddLiteralString("$");  // "$$" -> $
152       LastEmitted = DollarPos+2;
153     } else {
154       // Get the name of the variable.
155       // TODO: should eventually handle ${foo}bar as $foo
156       std::string::size_type VarEnd = DollarPos+1;
157       while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
158         ++VarEnd;
159       std::string VarName(AsmString.begin()+DollarPos+1,
160                           AsmString.begin()+VarEnd);
161       if (VarName.empty())
162         throw "Stray '$' in '" + CGI.Name + "' asm string, maybe you want $$?";
163
164       unsigned OpNo = CGI.getOperandNamed(VarName);
165       CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
166
167       // If this is a two-address instruction and we are not accessing the
168       // 0th operand, remove an operand.
169       unsigned MIOp = OpInfo.MIOperandNo;
170       if (CGI.isTwoAddress && MIOp != 0) {
171         if (MIOp == 1)
172           throw "Should refer to operand #0 instead of #1 for two-address"
173             " instruction '" + CGI.Name + "'!";
174         --MIOp;
175       }
176
177       Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,
178                                           MIOp, OpInfo.Ty));
179       LastEmitted = VarEnd;
180     }
181   }
182
183   AddLiteralString("\\n");
184 }
185
186 /// MatchesAllButOneOp - If this instruction is exactly identical to the
187 /// specified instruction except for one differing operand, return the differing
188 /// operand number.  If more than one operand mismatches, return ~1, otherwise
189 /// if the instructions are identical return ~0.
190 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
191   if (Operands.size() != Other.Operands.size()) return ~1;
192
193   unsigned MismatchOperand = ~0U;
194   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
195     if (Operands[i] != Other.Operands[i])
196       if (MismatchOperand != ~0U)  // Already have one mismatch?
197         return ~1U;
198       else 
199         MismatchOperand = i;
200   }
201   return MismatchOperand;
202 }
203
204
205 /// EmitInstructions - Emit the last instruction in the vector and any other
206 /// instructions that are suitably similar to it.
207 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
208                              std::ostream &O) {
209   AsmWriterInst FirstInst = Insts.back();
210   Insts.pop_back();
211
212   std::vector<AsmWriterInst> SimilarInsts;
213   unsigned DifferingOperand = ~0;
214   for (unsigned i = Insts.size(); i != 0; --i) {
215     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
216     if (DiffOp != ~1U) {
217       if (DifferingOperand == ~0U)  // First match!
218         DifferingOperand = DiffOp;
219
220       // If this differs in the same operand as the rest of the instructions in
221       // this class, move it to the SimilarInsts list.
222       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
223         SimilarInsts.push_back(Insts[i-1]);
224         Insts.erase(Insts.begin()+i-1);
225       }
226     }
227   }
228
229   std::string Namespace = FirstInst.CGI->Namespace;
230
231   O << "  case " << Namespace << "::"
232     << FirstInst.CGI->TheDef->getName() << ":\n";
233   for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
234     O << "  case " << Namespace << "::"
235       << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
236   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
237     if (i != DifferingOperand) {
238       // If the operand is the same for all instructions, just print it.
239       O << "    ";
240       FirstInst.Operands[i].EmitCode(O);
241     } else {
242       // If this is the operand that varies between all of the instructions,
243       // emit a switch for just this operand now.
244       O << "    switch (MI->getOpcode()) {\n";
245       O << "    case " << Namespace << "::"
246         << FirstInst.CGI->TheDef->getName() << ": ";
247       FirstInst.Operands[i].EmitCode(O);
248       O << "break;\n";
249       for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
250         O << "    case " << Namespace << "::"
251           << SimilarInsts[si].CGI->TheDef->getName() << ": ";
252         SimilarInsts[si].Operands[i].EmitCode(O);
253         O << "break;\n";
254       }
255       O << "    }";
256     }
257     O << "\n";
258   }
259
260   O << "    break;\n";
261 }
262
263 void AsmWriterEmitter::run(std::ostream &O) {
264   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
265
266   CodeGenTarget Target;
267   Record *AsmWriter = Target.getAsmWriter();
268   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
269   unsigned Variant = AsmWriter->getValueAsInt("Variant");
270
271   O <<
272   "/// printInstruction - This method is automatically generated by tablegen\n"
273   "/// from the instruction set description.  This method returns true if the\n"
274   "/// machine instruction was sufficiently described to print it, otherwise\n"
275   "/// it returns false.\n"
276     "bool " << Target.getName() << ClassName
277             << "::printInstruction(const MachineInstr *MI) {\n";
278
279   std::string Namespace = Target.inst_begin()->second.Namespace;
280
281   std::vector<AsmWriterInst> Instructions;
282
283   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
284          E = Target.inst_end(); I != E; ++I)
285     if (!I->second.AsmString.empty())
286       Instructions.push_back(AsmWriterInst(I->second, Variant));
287
288   // If all of the instructions start with a constant string (a very very common
289   // occurance), emit all of the constant strings as a big table lookup instead
290   // of requiring a switch for them.  
291   bool AllStartWithString = true;
292
293   for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
294     if (Instructions[i].Operands.empty() ||
295         Instructions[i].Operands[0].OperandType !=
296                           AsmWriterOperand::isLiteralTextOperand) {
297       AllStartWithString = false;
298       break;
299     }
300   
301   if (AllStartWithString) {
302     // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
303     // all machine instructions are necessarily being printed, so there may be
304     // target instructions not in this map.
305     std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
306     for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
307       CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
308
309     // Emit a table of constant strings.
310     std::vector<const CodeGenInstruction*> NumberedInstructions;
311     Target.getInstructionsByEnumValue(NumberedInstructions);
312
313     O << "  static const char * const OpStrs[] = {\n";
314     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
315       AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
316       if (AWI == 0) {
317         // Something not handled by the asmwriter printer.
318         O << "    0,\t// ";
319       } else {
320         O << "    \"" << AWI->Operands[0].Str << "\",\t// ";
321         // Nuke the string from the operand list.  It is now handled!
322         AWI->Operands.erase(AWI->Operands.begin());
323       }
324       O << NumberedInstructions[i]->TheDef->getName() << "\n";
325     }
326     O << "  };\n\n"
327       << "  // Emit the opcode for the instruction.\n"
328       << "  if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
329       << "    O << AsmStr;\n\n";
330   }
331
332   // Because this is a vector we want to emit from the end.  Reverse all of the
333   // elements in the vector.
334   std::reverse(Instructions.begin(), Instructions.end());
335
336   O << "  switch (MI->getOpcode()) {\n"
337        "  default: return false;\n";
338   
339   while (!Instructions.empty())
340     EmitInstructions(Instructions, O);
341
342   O << "  }\n"
343        "  return true;\n"
344        "}\n";
345 }