Minor refactoring, 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 <ostream>
19 using namespace llvm;
20
21 static bool isIdentChar(char C) {
22   return (C >= 'a' && C <= 'z') ||
23          (C >= 'A' && C <= 'Z') ||
24          (C >= '0' && C <= '9') ||
25          C == '_';
26 }
27
28 namespace {
29   struct AsmWriterOperand {
30     enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
31
32     /// Str - For isLiteralTextOperand, this IS the literal text.  For
33     /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
34     std::string Str;
35
36     /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
37     /// machine instruction.
38     unsigned MIOpNo;
39
40     /// OpVT - For isMachineInstrOperand, this is the value type for the
41     /// operand.
42     MVT::ValueType OpVT;
43
44     AsmWriterOperand(const std::string &LitStr)
45       : OperandType(isLiteralTextOperand),  Str(LitStr) {}
46
47     AsmWriterOperand(const std::string &Printer, unsigned OpNo,
48                      MVT::ValueType VT) : OperandType(isMachineInstrOperand),
49                                           Str(Printer), MIOpNo(OpNo), OpVT(VT){}
50
51     void EmitCode(std::ostream &OS) const;
52   };
53
54   struct AsmWriterInst {
55     std::vector<AsmWriterOperand> Operands;
56     const CodeGenInstruction *CGI;
57     
58     AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
59     void EmitCode(std::ostream &OS) const {
60       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
61         Operands[i].EmitCode(OS);
62     }
63   private:
64     void AddLiteralString(const std::string &Str) {
65       // If the last operand was already a literal text string, append this to
66       // it, otherwise add a new operand.
67       if (!Operands.empty() &&
68           Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
69         Operands.back().Str.append(Str);
70       else
71         Operands.push_back(AsmWriterOperand(Str));
72     }
73   };
74 }
75
76
77 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
78   if (OperandType == isLiteralTextOperand)
79     OS << "O << \"" << Str << "\"; ";
80   else
81     OS << Str << "(MI, " << MIOpNo << ", MVT::" << getName(OpVT) << "); ";
82 }
83
84
85 /// ParseAsmString - Parse the specified Instruction's AsmString into this
86 /// AsmWriterInst.
87 ///
88 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
89   this->CGI = &CGI;
90   bool inVariant = false;  // True if we are inside a {.|.|.} region.
91
92   const std::string &AsmString = CGI.AsmString;
93   std::string::size_type LastEmitted = 0;
94   while (LastEmitted != AsmString.size()) {
95     std::string::size_type DollarPos =
96       AsmString.find_first_of("${|}", LastEmitted);
97     if (DollarPos == std::string::npos) DollarPos = AsmString.size();
98
99     // Emit a constant string fragment.
100     if (DollarPos != LastEmitted) {
101       // TODO: this should eventually handle escaping.
102       AddLiteralString(std::string(AsmString.begin()+LastEmitted,
103                                    AsmString.begin()+DollarPos));
104       LastEmitted = DollarPos;
105     } else if (AsmString[DollarPos] == '{') {
106       if (inVariant)
107         throw "Nested variants found for instruction '" + CGI.Name + "'!";
108       LastEmitted = DollarPos+1;
109       inVariant = true;   // We are now inside of the variant!
110       for (unsigned i = 0; i != Variant; ++i) {
111         // Skip over all of the text for an irrelevant variant here.  The
112         // next variant starts at |, or there may not be text for this
113         // variant if we see a }.
114         std::string::size_type NP =
115           AsmString.find_first_of("|}", LastEmitted);
116         if (NP == std::string::npos)
117           throw "Incomplete variant for instruction '" + CGI.Name + "'!";
118         LastEmitted = NP+1;
119         if (AsmString[NP] == '}') {
120           inVariant = false;        // No text for this variant.
121           break;
122         }
123       }
124     } else if (AsmString[DollarPos] == '|') {
125       if (!inVariant)
126         throw "'|' character found outside of a variant in instruction '"
127           + CGI.Name + "'!";
128       // Move to the end of variant list.
129       std::string::size_type NP = AsmString.find('}', LastEmitted);
130       if (NP == std::string::npos)
131         throw "Incomplete variant for instruction '" + CGI.Name + "'!";
132       LastEmitted = NP+1;
133       inVariant = false;
134     } else if (AsmString[DollarPos] == '}') {
135       if (!inVariant)
136         throw "'}' character found outside of a variant in instruction '"
137           + CGI.Name + "'!";
138       LastEmitted = DollarPos+1;
139       inVariant = false;
140     } else if (DollarPos+1 != AsmString.size() &&
141                AsmString[DollarPos+1] == '$') {
142       AddLiteralString("$");  // "$$" -> $
143       LastEmitted = DollarPos+2;
144     } else {
145       // Get the name of the variable.
146       // TODO: should eventually handle ${foo}bar as $foo
147       std::string::size_type VarEnd = DollarPos+1;
148       while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
149         ++VarEnd;
150       std::string VarName(AsmString.begin()+DollarPos+1,
151                           AsmString.begin()+VarEnd);
152       if (VarName.empty())
153         throw "Stray '$' in '" + CGI.Name + "' asm string, maybe you want $$?";
154
155       unsigned OpNo = CGI.getOperandNamed(VarName);
156       CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
157
158       // If this is a two-address instruction and we are not accessing the
159       // 0th operand, remove an operand.
160       unsigned MIOp = OpInfo.MIOperandNo;
161       if (CGI.isTwoAddress && MIOp != 0) {
162         if (MIOp == 1)
163           throw "Should refer to operand #0 instead of #1 for two-address"
164             " instruction '" + CGI.Name + "'!";
165         --MIOp;
166       }
167
168       Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,
169                                           MIOp, OpInfo.Ty));
170       LastEmitted = VarEnd;
171     }
172   }
173
174   AddLiteralString("\\n");
175 }
176
177
178 void AsmWriterEmitter::run(std::ostream &O) {
179   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
180
181   CodeGenTarget Target;
182   Record *AsmWriter = Target.getAsmWriter();
183   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
184   unsigned Variant = AsmWriter->getValueAsInt("Variant");
185
186   O <<
187   "/// printInstruction - This method is automatically generated by tablegen\n"
188   "/// from the instruction set description.  This method returns true if the\n"
189   "/// machine instruction was sufficiently described to print it, otherwise\n"
190   "/// it returns false.\n"
191     "bool " << Target.getName() << ClassName
192             << "::printInstruction(const MachineInstr *MI) {\n";
193   O << "  switch (MI->getOpcode()) {\n"
194        "  default: return false;\n";
195
196   std::string Namespace = Target.inst_begin()->second.Namespace;
197
198   std::vector<AsmWriterInst> Instructions;
199
200   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
201          E = Target.inst_end(); I != E; ++I)
202     if (!I->second.AsmString.empty())
203       Instructions.push_back(AsmWriterInst(I->second, Variant));
204
205   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
206     O << "  case " << Namespace << "::"
207       << Instructions[i].CGI->Name << ": ";
208     Instructions[i].EmitCode(O);
209     O << " break;\n";
210   }
211   
212   O << "  }\n"
213        "  return true;\n"
214        "}\n";
215 }