blob: 14a1d3916fe193aa5bab2aec38a8cb9c157f9863 [file] [log] [blame]
Chris Lattner2e1f51b2004-08-01 05:59:33 +00001//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Chris Lattner2e1f51b2004-08-01 05:59:33 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Chris Lattner2e1f51b2004-08-01 05:59:33 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattner175580c2004-08-14 22:50:53 +000017#include "Record.h"
Jeff Cohen615ed992005-01-22 18:50:10 +000018#include <algorithm>
Chris Lattner2e1f51b2004-08-01 05:59:33 +000019#include <ostream>
20using namespace llvm;
21
Chris Lattner076efa72004-08-01 07:43:02 +000022static bool isIdentChar(char C) {
23 return (C >= 'a' && C <= 'z') ||
24 (C >= 'A' && C <= 'Z') ||
25 (C >= '0' && C <= '9') ||
26 C == '_';
27}
28
Chris Lattnerb0b55e72005-01-22 17:32:42 +000029namespace {
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
Chris Lattnerb0b55e72005-01-22 17:32:42 +000041 AsmWriterOperand(const std::string &LitStr)
Nate Begeman391c5d22005-11-30 18:54:35 +000042 : OperandType(isLiteralTextOperand), Str(LitStr) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000043
Nate Begeman391c5d22005-11-30 18:54:35 +000044 AsmWriterOperand(const std::string &Printer, unsigned OpNo)
45 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000046
Chris Lattner870c0162005-01-22 18:38:13 +000047 bool operator!=(const AsmWriterOperand &Other) const {
48 if (OperandType != Other.OperandType || Str != Other.Str) return true;
49 if (OperandType == isMachineInstrOperand)
Nate Begeman391c5d22005-11-30 18:54:35 +000050 return MIOpNo != Other.MIOpNo;
Chris Lattner870c0162005-01-22 18:38:13 +000051 return false;
52 }
Chris Lattner38c07512005-01-22 20:31:17 +000053 bool operator==(const AsmWriterOperand &Other) const {
54 return !operator!=(Other);
55 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +000056 void EmitCode(std::ostream &OS) const;
57 };
58
59 struct AsmWriterInst {
60 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000061 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000062
Chris Lattner5765dba2005-01-22 17:40:38 +000063 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000064
Chris Lattnerf8766682005-01-22 19:22:23 +000065 /// 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;
Chris Lattner870c0162005-01-22 18:38:13 +000069
Chris Lattnerb0b55e72005-01-22 17:32:42 +000070 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
84void AsmWriterOperand::EmitCode(std::ostream &OS) const {
85 if (OperandType == isLiteralTextOperand)
86 OS << "O << \"" << Str << "\"; ";
87 else
Nate Begeman391c5d22005-11-30 18:54:35 +000088 OS << Str << "(MI, " << MIOpNo << "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +000089}
90
91
92/// ParseAsmString - Parse the specified Instruction's AsmString into this
93/// AsmWriterInst.
94///
Chris Lattner5765dba2005-01-22 17:40:38 +000095AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
96 this->CGI = &CGI;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000097 bool inVariant = false; // True if we are inside a {.|.|.} region.
98
Chris Lattner1cf9d962006-02-01 19:12:23 +000099 // 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)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000102 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();
108
109 // Emit a constant string fragment.
110 if (DollarPos != LastEmitted) {
111 // TODO: this should eventually handle escaping.
112 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
113 AsmString.begin()+DollarPos));
114 LastEmitted = DollarPos;
115 } else if (AsmString[DollarPos] == '{') {
116 if (inVariant)
Jeff Cohen00b168892005-07-27 06:12:32 +0000117 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000118 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000119 LastEmitted = DollarPos+1;
120 inVariant = true; // We are now inside of the variant!
121 for (unsigned i = 0; i != Variant; ++i) {
122 // Skip over all of the text for an irrelevant variant here. The
123 // next variant starts at |, or there may not be text for this
124 // variant if we see a }.
125 std::string::size_type NP =
126 AsmString.find_first_of("|}", LastEmitted);
127 if (NP == std::string::npos)
Jeff Cohen00b168892005-07-27 06:12:32 +0000128 throw "Incomplete variant for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000129 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000130 LastEmitted = NP+1;
131 if (AsmString[NP] == '}') {
132 inVariant = false; // No text for this variant.
133 break;
134 }
135 }
136 } else if (AsmString[DollarPos] == '|') {
137 if (!inVariant)
138 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000139 + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000140 // Move to the end of variant list.
141 std::string::size_type NP = AsmString.find('}', LastEmitted);
142 if (NP == std::string::npos)
Jeff Cohen00b168892005-07-27 06:12:32 +0000143 throw "Incomplete variant for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000144 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000145 LastEmitted = NP+1;
146 inVariant = false;
147 } else if (AsmString[DollarPos] == '}') {
148 if (!inVariant)
149 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000150 + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000151 LastEmitted = DollarPos+1;
152 inVariant = false;
153 } else if (DollarPos+1 != AsmString.size() &&
154 AsmString[DollarPos+1] == '$') {
155 AddLiteralString("$"); // "$$" -> $
156 LastEmitted = DollarPos+2;
157 } else {
158 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000159 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000160
161 // handle ${foo}bar as $foo by detecting whether the character following
162 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
163 // so the variable name does not contain the leading curly brace.
164 bool hasCurlyBraces = false;
165 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
166 hasCurlyBraces = true;
167 ++DollarPos;
168 ++VarEnd;
169 }
170
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000171 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
172 ++VarEnd;
173 std::string VarName(AsmString.begin()+DollarPos+1,
174 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000175
176 // In order to avoid starting the next string at the terminating curly
177 // brace, advance the end position past it if we found an opening curly
178 // brace.
179 if (hasCurlyBraces) {
180 if (VarEnd >= AsmString.size())
181 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000182 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000183 if (AsmString[VarEnd] != '}')
184 throw "Variant name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000185 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000186 ++VarEnd;
187 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000188 if (VarName.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000189 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000190 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000191
192 unsigned OpNo = CGI.getOperandNamed(VarName);
Chris Lattner5765dba2005-01-22 17:40:38 +0000193 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000194
195 // If this is a two-address instruction and we are not accessing the
196 // 0th operand, remove an operand.
Chris Lattner5765dba2005-01-22 17:40:38 +0000197 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000198 if (CGI.isTwoAddress && MIOp != 0) {
199 if (MIOp == 1)
200 throw "Should refer to operand #0 instead of #1 for two-address"
Chris Lattner3e3def92005-07-15 22:43:04 +0000201 " instruction '" + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000202 --MIOp;
203 }
204
Nate Begeman391c5d22005-11-30 18:54:35 +0000205 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000206 LastEmitted = VarEnd;
207 }
208 }
209
210 AddLiteralString("\\n");
211}
212
Chris Lattnerf8766682005-01-22 19:22:23 +0000213/// MatchesAllButOneOp - If this instruction is exactly identical to the
214/// specified instruction except for one differing operand, return the differing
215/// operand number. If more than one operand mismatches, return ~1, otherwise
216/// if the instructions are identical return ~0.
217unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
218 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000219
220 unsigned MismatchOperand = ~0U;
221 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000222 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000223 if (MismatchOperand != ~0U) // Already have one mismatch?
224 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000225 else
Chris Lattner870c0162005-01-22 18:38:13 +0000226 MismatchOperand = i;
227 }
228 return MismatchOperand;
229}
230
Chris Lattner38c07512005-01-22 20:31:17 +0000231static void PrintCases(std::vector<std::pair<std::string,
232 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
233 O << " case " << OpsToPrint.back().first << ": ";
234 AsmWriterOperand TheOp = OpsToPrint.back().second;
235 OpsToPrint.pop_back();
236
237 // Check to see if any other operands are identical in this list, and if so,
238 // emit a case label for them.
239 for (unsigned i = OpsToPrint.size(); i != 0; --i)
240 if (OpsToPrint[i-1].second == TheOp) {
241 O << "\n case " << OpsToPrint[i-1].first << ": ";
242 OpsToPrint.erase(OpsToPrint.begin()+i-1);
243 }
244
245 // Finally, emit the code.
246 TheOp.EmitCode(O);
247 O << "break;\n";
248}
249
Chris Lattner870c0162005-01-22 18:38:13 +0000250
251/// EmitInstructions - Emit the last instruction in the vector and any other
252/// instructions that are suitably similar to it.
253static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
254 std::ostream &O) {
255 AsmWriterInst FirstInst = Insts.back();
256 Insts.pop_back();
257
258 std::vector<AsmWriterInst> SimilarInsts;
259 unsigned DifferingOperand = ~0;
260 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000261 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
262 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000263 if (DifferingOperand == ~0U) // First match!
264 DifferingOperand = DiffOp;
265
266 // If this differs in the same operand as the rest of the instructions in
267 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000268 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000269 SimilarInsts.push_back(Insts[i-1]);
270 Insts.erase(Insts.begin()+i-1);
271 }
272 }
273 }
274
275 std::string Namespace = FirstInst.CGI->Namespace;
276
277 O << " case " << Namespace << "::"
278 << FirstInst.CGI->TheDef->getName() << ":\n";
279 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
280 O << " case " << Namespace << "::"
281 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
282 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
283 if (i != DifferingOperand) {
284 // If the operand is the same for all instructions, just print it.
285 O << " ";
286 FirstInst.Operands[i].EmitCode(O);
287 } else {
288 // If this is the operand that varies between all of the instructions,
289 // emit a switch for just this operand now.
290 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000291 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
292 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
293 FirstInst.CGI->TheDef->getName(),
294 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000295
Chris Lattner870c0162005-01-22 18:38:13 +0000296 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000297 AsmWriterInst &AWI = SimilarInsts[si];
298 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
299 AWI.CGI->TheDef->getName(),
300 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000301 }
Chris Lattner38c07512005-01-22 20:31:17 +0000302 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
303 while (!OpsToPrint.empty())
304 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000305 O << " }";
306 }
307 O << "\n";
308 }
309
310 O << " break;\n";
311}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000312
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000313void AsmWriterEmitter::run(std::ostream &O) {
314 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
315
316 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000317 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000318 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
319 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000320
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000321 O <<
322 "/// printInstruction - This method is automatically generated by tablegen\n"
323 "/// from the instruction set description. This method returns true if the\n"
324 "/// machine instruction was sufficiently described to print it, otherwise\n"
325 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000326 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000327 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000328
329 std::string Namespace = Target.inst_begin()->second.Namespace;
330
Chris Lattner5765dba2005-01-22 17:40:38 +0000331 std::vector<AsmWriterInst> Instructions;
332
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000333 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
334 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000335 if (!I->second.AsmString.empty())
336 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000337
Chris Lattnerf8766682005-01-22 19:22:23 +0000338 // If all of the instructions start with a constant string (a very very common
339 // occurance), emit all of the constant strings as a big table lookup instead
Misha Brukman3da94ae2005-04-22 00:00:37 +0000340 // of requiring a switch for them.
Chris Lattnerf8766682005-01-22 19:22:23 +0000341 bool AllStartWithString = true;
342
343 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
344 if (Instructions[i].Operands.empty() ||
345 Instructions[i].Operands[0].OperandType !=
346 AsmWriterOperand::isLiteralTextOperand) {
347 AllStartWithString = false;
348 break;
349 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000350
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000351 std::vector<const CodeGenInstruction*> NumberedInstructions;
352 Target.getInstructionsByEnumValue(NumberedInstructions);
353
Chris Lattnerf8766682005-01-22 19:22:23 +0000354 if (AllStartWithString) {
355 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
356 // all machine instructions are necessarily being printed, so there may be
357 // target instructions not in this map.
358 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
359 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
360 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
361
362 // Emit a table of constant strings.
Chris Lattnerf8766682005-01-22 19:22:23 +0000363 O << " static const char * const OpStrs[] = {\n";
364 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
365 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
366 if (AWI == 0) {
367 // Something not handled by the asmwriter printer.
368 O << " 0,\t// ";
369 } else {
370 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
371 // Nuke the string from the operand list. It is now handled!
372 AWI->Operands.erase(AWI->Operands.begin());
373 }
374 O << NumberedInstructions[i]->TheDef->getName() << "\n";
375 }
376 O << " };\n\n"
377 << " // Emit the opcode for the instruction.\n"
378 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
379 << " O << AsmStr;\n\n";
380 }
381
Chris Lattner870c0162005-01-22 18:38:13 +0000382 // Because this is a vector we want to emit from the end. Reverse all of the
383 // elements in the vector.
384 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerf8766682005-01-22 19:22:23 +0000385
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000386 // Find the opcode # of inline asm
Chris Lattnerf8766682005-01-22 19:22:23 +0000387 O << " switch (MI->getOpcode()) {\n"
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000388 " default: return false;\n"
389 " case " << NumberedInstructions.back()->Namespace
390 << "::INLINEASM: printInlineAsm(MI); break;\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000391
Chris Lattner870c0162005-01-22 18:38:13 +0000392 while (!Instructions.empty())
393 EmitInstructions(Instructions, O);
394
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000395 O << " }\n"
396 " return true;\n"
397 "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000398}