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 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
42 /// an operand, specified with syntax like ${opname:modifier}.
43 std::string MiModifier;
45 AsmWriterOperand(const std::string &LitStr)
46 : OperandType(isLiteralTextOperand), Str(LitStr) {}
48 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
49 const std::string &Modifier)
50 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
51 MiModifier(Modifier) {}
53 bool operator!=(const AsmWriterOperand &Other) const {
54 if (OperandType != Other.OperandType || Str != Other.Str) return true;
55 if (OperandType == isMachineInstrOperand)
56 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
59 bool operator==(const AsmWriterOperand &Other) const {
60 return !operator!=(Other);
62 void EmitCode(std::ostream &OS) const;
65 struct AsmWriterInst {
66 std::vector<AsmWriterOperand> Operands;
67 const CodeGenInstruction *CGI;
69 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
71 /// MatchesAllButOneOp - If this instruction is exactly identical to the
72 /// specified instruction except for one differing operand, return the
73 /// differing operand number. Otherwise return ~0.
74 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
77 void AddLiteralString(const std::string &Str) {
78 // If the last operand was already a literal text string, append this to
79 // it, otherwise add a new operand.
80 if (!Operands.empty() &&
81 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
82 Operands.back().Str.append(Str);
84 Operands.push_back(AsmWriterOperand(Str));
90 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
91 if (OperandType == isLiteralTextOperand)
92 OS << "O << \"" << Str << "\"; ";
94 OS << Str << "(MI, " << MIOpNo;
95 if (!MiModifier.empty())
96 OS << ", \"" << MiModifier << '"';
102 /// ParseAsmString - Parse the specified Instruction's AsmString into this
105 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
107 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
109 // NOTE: Any extensions to this code need to be mirrored in the
110 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
111 // that inline asm strings should also get the new feature)!
112 const std::string &AsmString = CGI.AsmString;
113 std::string::size_type LastEmitted = 0;
114 while (LastEmitted != AsmString.size()) {
115 std::string::size_type DollarPos =
116 AsmString.find_first_of("${|}", LastEmitted);
117 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
119 // Emit a constant string fragment.
120 if (DollarPos != LastEmitted) {
121 // TODO: this should eventually handle escaping.
122 if (CurVariant == Variant || CurVariant == ~0U)
123 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
124 AsmString.begin()+DollarPos));
125 LastEmitted = DollarPos;
126 } else if (AsmString[DollarPos] == '{') {
127 if (CurVariant != ~0U)
128 throw "Nested variants found for instruction '" +
129 CGI.TheDef->getName() + "'!";
130 LastEmitted = DollarPos+1;
131 CurVariant = 0; // We are now inside of the variant!
132 } else if (AsmString[DollarPos] == '|') {
133 if (CurVariant == ~0U)
134 throw "'|' character found outside of a variant in instruction '"
135 + CGI.TheDef->getName() + "'!";
138 } else if (AsmString[DollarPos] == '}') {
139 if (CurVariant == ~0U)
140 throw "'}' character found outside of a variant in instruction '"
141 + CGI.TheDef->getName() + "'!";
144 } else if (DollarPos+1 != AsmString.size() &&
145 AsmString[DollarPos+1] == '$') {
146 if (CurVariant == Variant || CurVariant == ~0U)
147 AddLiteralString("$"); // "$$" -> $
148 LastEmitted = DollarPos+2;
150 // Get the name of the variable.
151 std::string::size_type VarEnd = DollarPos+1;
153 // handle ${foo}bar as $foo by detecting whether the character following
154 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
155 // so the variable name does not contain the leading curly brace.
156 bool hasCurlyBraces = false;
157 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
158 hasCurlyBraces = true;
163 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
165 std::string VarName(AsmString.begin()+DollarPos+1,
166 AsmString.begin()+VarEnd);
168 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
169 // into printOperand.
170 std::string Modifier;
172 // In order to avoid starting the next string at the terminating curly
173 // brace, advance the end position past it if we found an opening curly
175 if (hasCurlyBraces) {
176 if (VarEnd >= AsmString.size())
177 throw "Reached end of string before terminating curly brace in '"
178 + CGI.TheDef->getName() + "'";
180 // Look for a modifier string.
181 if (AsmString[VarEnd] == ':') {
183 if (VarEnd >= AsmString.size())
184 throw "Reached end of string before terminating curly brace in '"
185 + CGI.TheDef->getName() + "'";
187 unsigned ModifierStart = VarEnd;
188 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
190 Modifier = std::string(AsmString.begin()+ModifierStart,
191 AsmString.begin()+VarEnd);
192 if (Modifier.empty())
193 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
196 if (AsmString[VarEnd] != '}')
197 throw "Variable name beginning with '{' did not end with '}' in '"
198 + CGI.TheDef->getName() + "'";
202 throw "Stray '$' in '" + CGI.TheDef->getName() +
203 "' asm string, maybe you want $$?";
205 unsigned OpNo = CGI.getOperandNamed(VarName);
206 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
208 // If this is a two-address instruction and we are not accessing the
209 // 0th operand, remove an operand.
210 unsigned MIOp = OpInfo.MIOperandNo;
211 if (CGI.isTwoAddress && MIOp != 0) {
213 throw "Should refer to operand #0 instead of #1 for two-address"
214 " instruction '" + CGI.TheDef->getName() + "'!";
218 if (CurVariant == Variant || CurVariant == ~0U)
219 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
221 LastEmitted = VarEnd;
225 AddLiteralString("\\n");
228 /// MatchesAllButOneOp - If this instruction is exactly identical to the
229 /// specified instruction except for one differing operand, return the differing
230 /// operand number. If more than one operand mismatches, return ~1, otherwise
231 /// if the instructions are identical return ~0.
232 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
233 if (Operands.size() != Other.Operands.size()) return ~1;
235 unsigned MismatchOperand = ~0U;
236 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
237 if (Operands[i] != Other.Operands[i])
238 if (MismatchOperand != ~0U) // Already have one mismatch?
243 return MismatchOperand;
246 static void PrintCases(std::vector<std::pair<std::string,
247 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
248 O << " case " << OpsToPrint.back().first << ": ";
249 AsmWriterOperand TheOp = OpsToPrint.back().second;
250 OpsToPrint.pop_back();
252 // Check to see if any other operands are identical in this list, and if so,
253 // emit a case label for them.
254 for (unsigned i = OpsToPrint.size(); i != 0; --i)
255 if (OpsToPrint[i-1].second == TheOp) {
256 O << "\n case " << OpsToPrint[i-1].first << ": ";
257 OpsToPrint.erase(OpsToPrint.begin()+i-1);
260 // Finally, emit the code.
266 /// EmitInstructions - Emit the last instruction in the vector and any other
267 /// instructions that are suitably similar to it.
268 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
270 AsmWriterInst FirstInst = Insts.back();
273 std::vector<AsmWriterInst> SimilarInsts;
274 unsigned DifferingOperand = ~0;
275 for (unsigned i = Insts.size(); i != 0; --i) {
276 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
278 if (DifferingOperand == ~0U) // First match!
279 DifferingOperand = DiffOp;
281 // If this differs in the same operand as the rest of the instructions in
282 // this class, move it to the SimilarInsts list.
283 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
284 SimilarInsts.push_back(Insts[i-1]);
285 Insts.erase(Insts.begin()+i-1);
290 O << " case " << FirstInst.CGI->Namespace << "::"
291 << FirstInst.CGI->TheDef->getName() << ":\n";
292 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
293 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
294 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
295 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
296 if (i != DifferingOperand) {
297 // If the operand is the same for all instructions, just print it.
299 FirstInst.Operands[i].EmitCode(O);
301 // If this is the operand that varies between all of the instructions,
302 // emit a switch for just this operand now.
303 O << " switch (MI->getOpcode()) {\n";
304 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
305 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
306 FirstInst.CGI->TheDef->getName(),
307 FirstInst.Operands[i]));
309 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
310 AsmWriterInst &AWI = SimilarInsts[si];
311 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
312 AWI.CGI->TheDef->getName(),
315 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
316 while (!OpsToPrint.empty())
317 PrintCases(OpsToPrint, O);
326 void AsmWriterEmitter::run(std::ostream &O) {
327 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
329 CodeGenTarget Target;
330 Record *AsmWriter = Target.getAsmWriter();
331 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
332 unsigned Variant = AsmWriter->getValueAsInt("Variant");
335 "/// printInstruction - This method is automatically generated by tablegen\n"
336 "/// from the instruction set description. This method returns true if the\n"
337 "/// machine instruction was sufficiently described to print it, otherwise\n"
338 "/// it returns false.\n"
339 "bool " << Target.getName() << ClassName
340 << "::printInstruction(const MachineInstr *MI) {\n";
342 std::vector<AsmWriterInst> Instructions;
344 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
345 E = Target.inst_end(); I != E; ++I)
346 if (!I->second.AsmString.empty())
347 Instructions.push_back(AsmWriterInst(I->second, Variant));
349 // If all of the instructions start with a constant string (a very very common
350 // occurance), emit all of the constant strings as a big table lookup instead
351 // of requiring a switch for them.
352 bool AllStartWithString = true;
354 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
355 if (Instructions[i].Operands.empty() ||
356 Instructions[i].Operands[0].OperandType !=
357 AsmWriterOperand::isLiteralTextOperand) {
358 AllStartWithString = false;
362 std::vector<const CodeGenInstruction*> NumberedInstructions;
363 Target.getInstructionsByEnumValue(NumberedInstructions);
365 if (AllStartWithString) {
366 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
367 // all machine instructions are necessarily being printed, so there may be
368 // target instructions not in this map.
369 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
370 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
371 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
373 // Emit a table of constant strings.
374 O << " static const char * const OpStrs[] = {\n";
375 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
376 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
378 // Something not handled by the asmwriter printer.
381 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
382 // Nuke the string from the operand list. It is now handled!
383 AWI->Operands.erase(AWI->Operands.begin());
385 O << NumberedInstructions[i]->TheDef->getName() << "\n";
388 << " // Emit the opcode for the instruction.\n"
389 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
390 << " O << AsmStr;\n\n";
393 // Because this is a vector we want to emit from the end. Reverse all of the
394 // elements in the vector.
395 std::reverse(Instructions.begin(), Instructions.end());
397 // Find the opcode # of inline asm
398 O << " switch (MI->getOpcode()) {\n"
399 " default: return false;\n"
400 " case " << NumberedInstructions.back()->Namespace
401 << "::INLINEASM: printInlineAsm(MI); break;\n";
403 while (!Instructions.empty())
404 EmitInstructions(Instructions, O);