1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "AsmWriterEmitter.h"
16 #include "CodeGenTarget.h"
22 static bool isIdentChar(char C) {
23 return (C >= 'a' && C <= 'z') ||
24 (C >= 'A' && C <= 'Z') ||
25 (C >= '0' && C <= '9') ||
30 struct AsmWriterOperand {
31 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
33 /// Str - For isLiteralTextOperand, this IS the literal text. For
34 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
37 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
38 /// machine instruction.
41 AsmWriterOperand(const std::string &LitStr)
42 : OperandType(isLiteralTextOperand), Str(LitStr) {}
44 AsmWriterOperand(const std::string &Printer, unsigned OpNo)
45 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
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;
53 bool operator==(const AsmWriterOperand &Other) const {
54 return !operator!=(Other);
56 void EmitCode(std::ostream &OS) const;
59 struct AsmWriterInst {
60 std::vector<AsmWriterOperand> Operands;
61 const CodeGenInstruction *CGI;
63 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
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;
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);
78 Operands.push_back(AsmWriterOperand(Str));
84 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
85 if (OperandType == isLiteralTextOperand)
86 OS << "O << \"" << Str << "\"; ";
88 OS << Str << "(MI, " << MIOpNo << "); ";
92 /// ParseAsmString - Parse the specified Instruction's AsmString into this
95 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
97 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
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();
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() + "'!";
128 } else if (AsmString[DollarPos] == '}') {
129 if (CurVariant == ~0U)
130 throw "'}' character found outside of a variant in instruction '"
131 + CGI.TheDef->getName() + "'!";
134 } else if (DollarPos+1 != AsmString.size() &&
135 AsmString[DollarPos+1] == '$') {
136 if (CurVariant == Variant || CurVariant == ~0U)
137 AddLiteralString("$"); // "$$" -> $
138 LastEmitted = DollarPos+2;
140 // Get the name of the variable.
141 std::string::size_type VarEnd = DollarPos+1;
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;
153 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
155 std::string VarName(AsmString.begin()+DollarPos+1,
156 AsmString.begin()+VarEnd);
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
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() + "'";
171 throw "Stray '$' in '" + CGI.TheDef->getName() +
172 "' asm string, maybe you want $$?";
174 unsigned OpNo = CGI.getOperandNamed(VarName);
175 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
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) {
182 throw "Should refer to operand #0 instead of #1 for two-address"
183 " instruction '" + CGI.TheDef->getName() + "'!";
187 if (CurVariant == Variant || CurVariant == ~0U)
188 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
189 LastEmitted = VarEnd;
193 AddLiteralString("\\n");
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;
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?
211 return MismatchOperand;
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();
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);
228 // Finally, emit the code.
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,
238 AsmWriterInst FirstInst = Insts.back();
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);
246 if (DifferingOperand == ~0U) // First match!
247 DifferingOperand = DiffOp;
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);
258 std::string Namespace = FirstInst.CGI->Namespace;
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.
269 FirstInst.Operands[i].EmitCode(O);
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]));
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(),
285 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
286 while (!OpsToPrint.empty())
287 PrintCases(OpsToPrint, O);
296 void AsmWriterEmitter::run(std::ostream &O) {
297 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
299 CodeGenTarget Target;
300 Record *AsmWriter = Target.getAsmWriter();
301 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
302 unsigned Variant = AsmWriter->getValueAsInt("Variant");
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";
312 std::string Namespace = Target.inst_begin()->second.Namespace;
314 std::vector<AsmWriterInst> Instructions;
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));
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;
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;
334 std::vector<const CodeGenInstruction*> NumberedInstructions;
335 Target.getInstructionsByEnumValue(NumberedInstructions);
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]));
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]];
350 // Something not handled by the asmwriter printer.
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());
357 O << NumberedInstructions[i]->TheDef->getName() << "\n";
360 << " // Emit the opcode for the instruction.\n"
361 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
362 << " O << AsmStr;\n\n";
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());
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";
375 while (!Instructions.empty())
376 EmitInstructions(Instructions, O);