blob: cc59aa105ad1108b31c222c341d73eaaa75eb6b9 [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
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)
Jeff Cohen00b168892005-07-27 06:12:32 +0000114 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000115 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000116 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)
Jeff Cohen00b168892005-07-27 06:12:32 +0000125 throw "Incomplete variant for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000126 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000127 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 '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000136 + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000137 // Move to the end of variant list.
138 std::string::size_type NP = AsmString.find('}', LastEmitted);
139 if (NP == std::string::npos)
Jeff Cohen00b168892005-07-27 06:12:32 +0000140 throw "Incomplete variant for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000141 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000142 LastEmitted = NP+1;
143 inVariant = false;
144 } else if (AsmString[DollarPos] == '}') {
145 if (!inVariant)
146 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000147 + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000148 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.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000156 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000157
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
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000168 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
169 ++VarEnd;
170 std::string VarName(AsmString.begin()+DollarPos+1,
171 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000172
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 '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000179 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000180 if (AsmString[VarEnd] != '}')
181 throw "Variant name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000182 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000183 ++VarEnd;
184 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000185 if (VarName.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000186 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000187 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000188
189 unsigned OpNo = CGI.getOperandNamed(VarName);
Chris Lattner5765dba2005-01-22 17:40:38 +0000190 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000191
192 // If this is a two-address instruction and we are not accessing the
193 // 0th operand, remove an operand.
Chris Lattner5765dba2005-01-22 17:40:38 +0000194 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000195 if (CGI.isTwoAddress && MIOp != 0) {
196 if (MIOp == 1)
197 throw "Should refer to operand #0 instead of #1 for two-address"
Chris Lattner3e3def92005-07-15 22:43:04 +0000198 " instruction '" + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000199 --MIOp;
200 }
201
Nate Begeman391c5d22005-11-30 18:54:35 +0000202 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000203 LastEmitted = VarEnd;
204 }
205 }
206
207 AddLiteralString("\\n");
208}
209
Chris Lattnerf8766682005-01-22 19:22:23 +0000210/// 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.
214unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
215 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000216
217 unsigned MismatchOperand = ~0U;
218 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000219 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000220 if (MismatchOperand != ~0U) // Already have one mismatch?
221 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000222 else
Chris Lattner870c0162005-01-22 18:38:13 +0000223 MismatchOperand = i;
224 }
225 return MismatchOperand;
226}
227
Chris Lattner38c07512005-01-22 20:31:17 +0000228static 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
Chris Lattner870c0162005-01-22 18:38:13 +0000247
248/// EmitInstructions - Emit the last instruction in the vector and any other
249/// instructions that are suitably similar to it.
250static 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) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000258 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
259 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000260 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.
Chris Lattnerf8766682005-01-22 19:22:23 +0000265 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000266 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";
Chris Lattner38c07512005-01-22 20:31:17 +0000288 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]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000292
Chris Lattner870c0162005-01-22 18:38:13 +0000293 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000294 AsmWriterInst &AWI = SimilarInsts[si];
295 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
296 AWI.CGI->TheDef->getName(),
297 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000298 }
Chris Lattner38c07512005-01-22 20:31:17 +0000299 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
300 while (!OpsToPrint.empty())
301 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000302 O << " }";
303 }
304 O << "\n";
305 }
306
307 O << " break;\n";
308}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000309
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000310void AsmWriterEmitter::run(std::ostream &O) {
311 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
312
313 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000314 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000315 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
316 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000317
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000318 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"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000323 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000324 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000325
326 std::string Namespace = Target.inst_begin()->second.Namespace;
327
Chris Lattner5765dba2005-01-22 17:40:38 +0000328 std::vector<AsmWriterInst> Instructions;
329
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000330 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
331 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000332 if (!I->second.AsmString.empty())
333 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000334
Chris Lattnerf8766682005-01-22 19:22:23 +0000335 // 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
Misha Brukman3da94ae2005-04-22 00:00:37 +0000337 // of requiring a switch for them.
Chris Lattnerf8766682005-01-22 19:22:23 +0000338 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 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000347
Chris Lattnerf8766682005-01-22 19:22:23 +0000348 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
Chris Lattner870c0162005-01-22 18:38:13 +0000379 // 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());
Chris Lattnerf8766682005-01-22 19:22:23 +0000382
383 O << " switch (MI->getOpcode()) {\n"
384 " default: return false;\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000385
Chris Lattner870c0162005-01-22 18:38:13 +0000386 while (!Instructions.empty())
387 EmitInstructions(Instructions, O);
388
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000389 O << " }\n"
390 " return true;\n"
391 "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000392}