No longer track value types for asm printer operands, and remove them as
[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   bool inVariant = false;  // True if we are inside a {.|.|.} region.
98
99   const std::string &AsmString = CGI.AsmString;
100   std::string::size_type LastEmitted = 0;
101   while (LastEmitted != AsmString.size()) {
102     std::string::size_type DollarPos =
103       AsmString.find_first_of("${|}", LastEmitted);
104     if (DollarPos == std::string::npos) DollarPos = AsmString.size();
105
106     // Emit a constant string fragment.
107     if (DollarPos != LastEmitted) {
108       // TODO: this should eventually handle escaping.
109       AddLiteralString(std::string(AsmString.begin()+LastEmitted,
110                                    AsmString.begin()+DollarPos));
111       LastEmitted = DollarPos;
112     } else if (AsmString[DollarPos] == '{') {
113       if (inVariant)
114         throw "Nested variants found for instruction '" +
115               CGI.TheDef->getName() + "'!";
116       LastEmitted = DollarPos+1;
117       inVariant = true;   // We are now inside of the variant!
118       for (unsigned i = 0; i != Variant; ++i) {
119         // Skip over all of the text for an irrelevant variant here.  The
120         // next variant starts at |, or there may not be text for this
121         // variant if we see a }.
122         std::string::size_type NP =
123           AsmString.find_first_of("|}", LastEmitted);
124         if (NP == std::string::npos)
125           throw "Incomplete variant for instruction '" +
126                 CGI.TheDef->getName() + "'!";
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.TheDef->getName() + "'!";
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 '" +
141               CGI.TheDef->getName() + "'!";
142       LastEmitted = NP+1;
143       inVariant = false;
144     } else if (AsmString[DollarPos] == '}') {
145       if (!inVariant)
146         throw "'}' character found outside of a variant in instruction '"
147           + CGI.TheDef->getName() + "'!";
148       LastEmitted = DollarPos+1;
149       inVariant = false;
150     } else if (DollarPos+1 != AsmString.size() &&
151                AsmString[DollarPos+1] == '$') {
152       AddLiteralString("$");  // "$$" -> $
153       LastEmitted = DollarPos+2;
154     } else {
155       // Get the name of the variable.
156       std::string::size_type VarEnd = DollarPos+1;
157
158       // handle ${foo}bar as $foo by detecting whether the character following
159       // the dollar sign is a curly brace.  If so, advance VarEnd and DollarPos
160       // so the variable name does not contain the leading curly brace.
161       bool hasCurlyBraces = false;
162       if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
163         hasCurlyBraces = true;
164         ++DollarPos;
165         ++VarEnd;
166       }
167
168       while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
169         ++VarEnd;
170       std::string VarName(AsmString.begin()+DollarPos+1,
171                           AsmString.begin()+VarEnd);
172
173       // In order to avoid starting the next string at the terminating curly
174       // brace, advance the end position past it if we found an opening curly
175       // brace.
176       if (hasCurlyBraces) {
177         if (VarEnd >= AsmString.size())
178           throw "Reached end of string before terminating curly brace in '"
179                 + CGI.TheDef->getName() + "'";
180         if (AsmString[VarEnd] != '}')
181           throw "Variant name beginning with '{' did not end with '}' in '"
182                 + CGI.TheDef->getName() + "'";
183         ++VarEnd;
184       }
185       if (VarName.empty())
186         throw "Stray '$' in '" + CGI.TheDef->getName() +
187               "' asm string, maybe you want $$?";
188
189       unsigned OpNo = CGI.getOperandNamed(VarName);
190       CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
191
192       // If this is a two-address instruction and we are not accessing the
193       // 0th operand, remove an operand.
194       unsigned MIOp = OpInfo.MIOperandNo;
195       if (CGI.isTwoAddress && MIOp != 0) {
196         if (MIOp == 1)
197           throw "Should refer to operand #0 instead of #1 for two-address"
198             " instruction '" + CGI.TheDef->getName() + "'!";
199         --MIOp;
200       }
201
202       Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
203       LastEmitted = VarEnd;
204     }
205   }
206
207   AddLiteralString("\\n");
208 }
209
210 /// MatchesAllButOneOp - If this instruction is exactly identical to the
211 /// specified instruction except for one differing operand, return the differing
212 /// operand number.  If more than one operand mismatches, return ~1, otherwise
213 /// if the instructions are identical return ~0.
214 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
215   if (Operands.size() != Other.Operands.size()) return ~1;
216
217   unsigned MismatchOperand = ~0U;
218   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
219     if (Operands[i] != Other.Operands[i])
220       if (MismatchOperand != ~0U)  // Already have one mismatch?
221         return ~1U;
222       else
223         MismatchOperand = i;
224   }
225   return MismatchOperand;
226 }
227
228 static void PrintCases(std::vector<std::pair<std::string,
229                        AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
230   O << "    case " << OpsToPrint.back().first << ": ";
231   AsmWriterOperand TheOp = OpsToPrint.back().second;
232   OpsToPrint.pop_back();
233
234   // Check to see if any other operands are identical in this list, and if so,
235   // emit a case label for them.
236   for (unsigned i = OpsToPrint.size(); i != 0; --i)
237     if (OpsToPrint[i-1].second == TheOp) {
238       O << "\n    case " << OpsToPrint[i-1].first << ": ";
239       OpsToPrint.erase(OpsToPrint.begin()+i-1);
240     }
241
242   // Finally, emit the code.
243   TheOp.EmitCode(O);
244   O << "break;\n";
245 }
246
247
248 /// EmitInstructions - Emit the last instruction in the vector and any other
249 /// instructions that are suitably similar to it.
250 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
251                              std::ostream &O) {
252   AsmWriterInst FirstInst = Insts.back();
253   Insts.pop_back();
254
255   std::vector<AsmWriterInst> SimilarInsts;
256   unsigned DifferingOperand = ~0;
257   for (unsigned i = Insts.size(); i != 0; --i) {
258     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
259     if (DiffOp != ~1U) {
260       if (DifferingOperand == ~0U)  // First match!
261         DifferingOperand = DiffOp;
262
263       // If this differs in the same operand as the rest of the instructions in
264       // this class, move it to the SimilarInsts list.
265       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
266         SimilarInsts.push_back(Insts[i-1]);
267         Insts.erase(Insts.begin()+i-1);
268       }
269     }
270   }
271
272   std::string Namespace = FirstInst.CGI->Namespace;
273
274   O << "  case " << Namespace << "::"
275     << FirstInst.CGI->TheDef->getName() << ":\n";
276   for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
277     O << "  case " << Namespace << "::"
278       << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
279   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
280     if (i != DifferingOperand) {
281       // If the operand is the same for all instructions, just print it.
282       O << "    ";
283       FirstInst.Operands[i].EmitCode(O);
284     } else {
285       // If this is the operand that varies between all of the instructions,
286       // emit a switch for just this operand now.
287       O << "    switch (MI->getOpcode()) {\n";
288       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
289       OpsToPrint.push_back(std::make_pair(Namespace+"::"+
290                                           FirstInst.CGI->TheDef->getName(),
291                                           FirstInst.Operands[i]));
292
293       for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
294         AsmWriterInst &AWI = SimilarInsts[si];
295         OpsToPrint.push_back(std::make_pair(Namespace+"::"+
296                                             AWI.CGI->TheDef->getName(),
297                                             AWI.Operands[i]));
298       }
299       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
300       while (!OpsToPrint.empty())
301         PrintCases(OpsToPrint, O);
302       O << "    }";
303     }
304     O << "\n";
305   }
306
307   O << "    break;\n";
308 }
309
310 void AsmWriterEmitter::run(std::ostream &O) {
311   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
312
313   CodeGenTarget Target;
314   Record *AsmWriter = Target.getAsmWriter();
315   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
316   unsigned Variant = AsmWriter->getValueAsInt("Variant");
317
318   O <<
319   "/// printInstruction - This method is automatically generated by tablegen\n"
320   "/// from the instruction set description.  This method returns true if the\n"
321   "/// machine instruction was sufficiently described to print it, otherwise\n"
322   "/// it returns false.\n"
323     "bool " << Target.getName() << ClassName
324             << "::printInstruction(const MachineInstr *MI) {\n";
325
326   std::string Namespace = Target.inst_begin()->second.Namespace;
327
328   std::vector<AsmWriterInst> Instructions;
329
330   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
331          E = Target.inst_end(); I != E; ++I)
332     if (!I->second.AsmString.empty())
333       Instructions.push_back(AsmWriterInst(I->second, Variant));
334
335   // If all of the instructions start with a constant string (a very very common
336   // occurance), emit all of the constant strings as a big table lookup instead
337   // of requiring a switch for them.
338   bool AllStartWithString = true;
339
340   for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
341     if (Instructions[i].Operands.empty() ||
342         Instructions[i].Operands[0].OperandType !=
343                           AsmWriterOperand::isLiteralTextOperand) {
344       AllStartWithString = false;
345       break;
346     }
347
348   if (AllStartWithString) {
349     // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
350     // all machine instructions are necessarily being printed, so there may be
351     // target instructions not in this map.
352     std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
353     for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
354       CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
355
356     // Emit a table of constant strings.
357     std::vector<const CodeGenInstruction*> NumberedInstructions;
358     Target.getInstructionsByEnumValue(NumberedInstructions);
359
360     O << "  static const char * const OpStrs[] = {\n";
361     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
362       AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
363       if (AWI == 0) {
364         // Something not handled by the asmwriter printer.
365         O << "    0,\t// ";
366       } else {
367         O << "    \"" << AWI->Operands[0].Str << "\",\t// ";
368         // Nuke the string from the operand list.  It is now handled!
369         AWI->Operands.erase(AWI->Operands.begin());
370       }
371       O << NumberedInstructions[i]->TheDef->getName() << "\n";
372     }
373     O << "  };\n\n"
374       << "  // Emit the opcode for the instruction.\n"
375       << "  if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
376       << "    O << AsmStr;\n\n";
377   }
378
379   // Because this is a vector we want to emit from the end.  Reverse all of the
380   // elements in the vector.
381   std::reverse(Instructions.begin(), Instructions.end());
382
383   O << "  switch (MI->getOpcode()) {\n"
384        "  default: return false;\n";
385
386   while (!Instructions.empty())
387     EmitInstructions(Instructions, O);
388
389   O << "  }\n"
390        "  return true;\n"
391        "}\n";
392 }