blob: 183c6912bae9a10f37e4aa226572ca003e8f70fd [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//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Chris Lattner6af022f2006-07-14 22:59:11 +000018#include "llvm/ADT/StringExtras.h"
Chris Lattnerbdff5f92006-07-18 17:18:03 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/MathExtras.h"
Jeff Cohen615ed992005-01-22 18:50:10 +000021#include <algorithm>
Chris Lattner2e1f51b2004-08-01 05:59:33 +000022using namespace llvm;
23
Chris Lattner076efa72004-08-01 07:43:02 +000024static bool isIdentChar(char C) {
25 return (C >= 'a' && C <= 'z') ||
26 (C >= 'A' && C <= 'Z') ||
27 (C >= '0' && C <= '9') ||
28 C == '_';
29}
30
Chris Lattnerad8c5312007-07-18 04:51:57 +000031// This should be an anon namespace, this works around a GCC warning.
32namespace llvm {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000033 struct AsmWriterOperand {
34 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
35
36 /// Str - For isLiteralTextOperand, this IS the literal text. For
37 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
38 std::string Str;
39
40 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
41 /// machine instruction.
42 unsigned MIOpNo;
Chris Lattner04cadb32006-02-06 23:40:48 +000043
44 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
45 /// an operand, specified with syntax like ${opname:modifier}.
46 std::string MiModifier;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000047
Cedric Venet7caa2d02008-10-27 19:21:35 +000048 // To make VS STL happy
49 AsmWriterOperand():OperandType(isLiteralTextOperand) {}
Cedric Venet3bff2df2008-10-26 15:40:44 +000050
Dan Gohman38deef92009-02-18 16:37:45 +000051 explicit AsmWriterOperand(const std::string &LitStr)
Nate Begeman391c5d22005-11-30 18:54:35 +000052 : OperandType(isLiteralTextOperand), Str(LitStr) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000053
Chris Lattner04cadb32006-02-06 23:40:48 +000054 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
55 const std::string &Modifier)
56 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
57 MiModifier(Modifier) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000058
Chris Lattner870c0162005-01-22 18:38:13 +000059 bool operator!=(const AsmWriterOperand &Other) const {
60 if (OperandType != Other.OperandType || Str != Other.Str) return true;
61 if (OperandType == isMachineInstrOperand)
Chris Lattner04cadb32006-02-06 23:40:48 +000062 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
Chris Lattner870c0162005-01-22 18:38:13 +000063 return false;
64 }
Chris Lattner38c07512005-01-22 20:31:17 +000065 bool operator==(const AsmWriterOperand &Other) const {
66 return !operator!=(Other);
67 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +000068
69 /// getCode - Return the code that prints this operand.
70 std::string getCode() const;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000071 };
Chris Lattnerbdff5f92006-07-18 17:18:03 +000072}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000073
Chris Lattnerbdff5f92006-07-18 17:18:03 +000074namespace llvm {
Jeff Cohend41b30d2006-11-05 19:31:28 +000075 class AsmWriterInst {
76 public:
Chris Lattnerb0b55e72005-01-22 17:32:42 +000077 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000078 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000079
Chris Lattner5765dba2005-01-22 17:40:38 +000080 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000081
Chris Lattnerf8766682005-01-22 19:22:23 +000082 /// MatchesAllButOneOp - If this instruction is exactly identical to the
83 /// specified instruction except for one differing operand, return the
84 /// differing operand number. Otherwise return ~0.
85 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000086
Chris Lattnerb0b55e72005-01-22 17:32:42 +000087 private:
88 void AddLiteralString(const std::string &Str) {
89 // If the last operand was already a literal text string, append this to
90 // it, otherwise add a new operand.
91 if (!Operands.empty() &&
92 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
93 Operands.back().Str.append(Str);
94 else
95 Operands.push_back(AsmWriterOperand(Str));
96 }
97 };
98}
99
100
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000101std::string AsmWriterOperand::getCode() const {
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000102 if (OperandType == isLiteralTextOperand)
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000103 return "O << \"" + Str + "\"; ";
104
Chris Lattner1bf63612006-09-26 23:45:08 +0000105 std::string Result = Str + "(MI";
106 if (MIOpNo != ~0U)
107 Result += ", " + utostr(MIOpNo);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000108 if (!MiModifier.empty())
109 Result += ", \"" + MiModifier + '"';
110 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000111}
112
113
114/// ParseAsmString - Parse the specified Instruction's AsmString into this
115/// AsmWriterInst.
116///
Chris Lattner5765dba2005-01-22 17:40:38 +0000117AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
118 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000119 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000120
Chris Lattner1cf9d962006-02-01 19:12:23 +0000121 // NOTE: Any extensions to this code need to be mirrored in the
122 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
123 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000124 const std::string &AsmString = CGI.AsmString;
125 std::string::size_type LastEmitted = 0;
126 while (LastEmitted != AsmString.size()) {
127 std::string::size_type DollarPos =
Nate Begeman817affc2008-03-17 07:26:14 +0000128 AsmString.find_first_of("${|}\\", LastEmitted);
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000129 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
130
131 // Emit a constant string fragment.
132 if (DollarPos != LastEmitted) {
Chris Lattner7f3b28a2009-03-13 21:33:17 +0000133 if (CurVariant == Variant || CurVariant == ~0U) {
134 for (; LastEmitted != DollarPos; ++LastEmitted)
135 switch (AsmString[LastEmitted]) {
136 case '\n': AddLiteralString("\\n"); break;
137 case '\t': AddLiteralString("\\t"); break;
138 case '"': AddLiteralString("\\\""); break;
139 case '\\': AddLiteralString("\\\\"); break;
140 default:
141 AddLiteralString(std::string(1, AsmString[LastEmitted]));
142 break;
143 }
144 } else {
145 LastEmitted = DollarPos;
146 }
Nate Begeman817affc2008-03-17 07:26:14 +0000147 } else if (AsmString[DollarPos] == '\\') {
148 if (DollarPos+1 != AsmString.size() &&
149 (CurVariant == Variant || CurVariant == ~0U)) {
150 if (AsmString[DollarPos+1] == 'n') {
151 AddLiteralString("\\n");
152 } else if (AsmString[DollarPos+1] == 't') {
153 AddLiteralString("\\t");
154 } else if (std::string("${|}\\").find(AsmString[DollarPos+1])
155 != std::string::npos) {
156 AddLiteralString(std::string(1, AsmString[DollarPos+1]));
157 } else {
158 throw "Non-supported escaped character found in instruction '" +
159 CGI.TheDef->getName() + "'!";
160 }
161 LastEmitted = DollarPos+2;
162 continue;
163 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000164 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000165 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000166 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000167 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000168 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000169 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000170 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000171 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000172 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000173 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000174 ++CurVariant;
175 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000176 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000177 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000178 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000179 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000180 ++LastEmitted;
181 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000182 } else if (DollarPos+1 != AsmString.size() &&
183 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000184 if (CurVariant == Variant || CurVariant == ~0U)
185 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000186 LastEmitted = DollarPos+2;
187 } else {
188 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000189 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000190
191 // handle ${foo}bar as $foo by detecting whether the character following
192 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
193 // so the variable name does not contain the leading curly brace.
194 bool hasCurlyBraces = false;
195 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
196 hasCurlyBraces = true;
197 ++DollarPos;
198 ++VarEnd;
199 }
200
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000201 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
202 ++VarEnd;
203 std::string VarName(AsmString.begin()+DollarPos+1,
204 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000205
Chris Lattner04cadb32006-02-06 23:40:48 +0000206 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000207 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000208 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000209 std::string Modifier;
210
Nate Begemanafc54562005-07-14 22:50:30 +0000211 // In order to avoid starting the next string at the terminating curly
212 // brace, advance the end position past it if we found an opening curly
213 // brace.
214 if (hasCurlyBraces) {
215 if (VarEnd >= AsmString.size())
216 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000217 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000218
219 // Look for a modifier string.
220 if (AsmString[VarEnd] == ':') {
221 ++VarEnd;
222 if (VarEnd >= AsmString.size())
223 throw "Reached end of string before terminating curly brace in '"
224 + CGI.TheDef->getName() + "'";
225
226 unsigned ModifierStart = VarEnd;
227 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
228 ++VarEnd;
229 Modifier = std::string(AsmString.begin()+ModifierStart,
230 AsmString.begin()+VarEnd);
231 if (Modifier.empty())
232 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
233 }
234
Nate Begemanafc54562005-07-14 22:50:30 +0000235 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000236 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000237 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000238 ++VarEnd;
239 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000240 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000241 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000242 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000243
Chris Lattner1bf63612006-09-26 23:45:08 +0000244 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000245 // Just a modifier, pass this into PrintSpecial.
246 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000247 } else {
248 // Otherwise, normal operand.
249 unsigned OpNo = CGI.getOperandNamed(VarName);
250 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000251
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000252 if (CurVariant == Variant || CurVariant == ~0U) {
253 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner1bf63612006-09-26 23:45:08 +0000254 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
255 Modifier));
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000256 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000257 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000258 LastEmitted = VarEnd;
259 }
260 }
261
262 AddLiteralString("\\n");
263}
264
Chris Lattnerf8766682005-01-22 19:22:23 +0000265/// MatchesAllButOneOp - If this instruction is exactly identical to the
266/// specified instruction except for one differing operand, return the differing
267/// operand number. If more than one operand mismatches, return ~1, otherwise
268/// if the instructions are identical return ~0.
269unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
270 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000271
272 unsigned MismatchOperand = ~0U;
273 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000274 if (Operands[i] != Other.Operands[i]) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000275 if (MismatchOperand != ~0U) // Already have one mismatch?
276 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000277 else
Chris Lattner870c0162005-01-22 18:38:13 +0000278 MismatchOperand = i;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000279 }
Chris Lattner870c0162005-01-22 18:38:13 +0000280 }
281 return MismatchOperand;
282}
283
Chris Lattner38c07512005-01-22 20:31:17 +0000284static void PrintCases(std::vector<std::pair<std::string,
285 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
286 O << " case " << OpsToPrint.back().first << ": ";
287 AsmWriterOperand TheOp = OpsToPrint.back().second;
288 OpsToPrint.pop_back();
289
290 // Check to see if any other operands are identical in this list, and if so,
291 // emit a case label for them.
292 for (unsigned i = OpsToPrint.size(); i != 0; --i)
293 if (OpsToPrint[i-1].second == TheOp) {
294 O << "\n case " << OpsToPrint[i-1].first << ": ";
295 OpsToPrint.erase(OpsToPrint.begin()+i-1);
296 }
297
298 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000299 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000300 O << "break;\n";
301}
302
Chris Lattner870c0162005-01-22 18:38:13 +0000303
304/// EmitInstructions - Emit the last instruction in the vector and any other
305/// instructions that are suitably similar to it.
306static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
307 std::ostream &O) {
308 AsmWriterInst FirstInst = Insts.back();
309 Insts.pop_back();
310
311 std::vector<AsmWriterInst> SimilarInsts;
312 unsigned DifferingOperand = ~0;
313 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000314 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
315 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000316 if (DifferingOperand == ~0U) // First match!
317 DifferingOperand = DiffOp;
318
319 // If this differs in the same operand as the rest of the instructions in
320 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000321 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000322 SimilarInsts.push_back(Insts[i-1]);
323 Insts.erase(Insts.begin()+i-1);
324 }
325 }
326 }
327
Chris Lattnera1e8a802006-05-01 17:01:17 +0000328 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000329 << FirstInst.CGI->TheDef->getName() << ":\n";
330 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000331 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000332 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
333 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
334 if (i != DifferingOperand) {
335 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000336 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000337 } else {
338 // If this is the operand that varies between all of the instructions,
339 // emit a switch for just this operand now.
340 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000341 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000342 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000343 FirstInst.CGI->TheDef->getName(),
344 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000345
Chris Lattner870c0162005-01-22 18:38:13 +0000346 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000347 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000348 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000349 AWI.CGI->TheDef->getName(),
350 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000351 }
Chris Lattner38c07512005-01-22 20:31:17 +0000352 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
353 while (!OpsToPrint.empty())
354 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000355 O << " }";
356 }
357 O << "\n";
358 }
359
360 O << " break;\n";
361}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000362
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000363void AsmWriterEmitter::
364FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000365 std::vector<unsigned> &InstIdxs,
366 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000367 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000368
369 // This vector parallels UniqueOperandCommands, keeping track of which
370 // instructions each case are used for. It is a comma separated string of
371 // enums.
372 std::vector<std::string> InstrsForCase;
373 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000374 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000375
376 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
377 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Dan Gohman44066042008-07-01 00:05:16 +0000378 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000379
380 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000381 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000382 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000383
Chris Lattnerb8462862006-07-18 17:56:07 +0000384 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000385
386 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000387 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000388 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000389
390 // Check to see if we already have 'Command' in UniqueOperandCommands.
391 // If not, add it.
392 bool FoundIt = false;
393 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
394 if (UniqueOperandCommands[idx] == Command) {
395 InstIdxs[i] = idx;
396 InstrsForCase[idx] += ", ";
397 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
398 FoundIt = true;
399 break;
400 }
401 if (!FoundIt) {
402 InstIdxs[i] = UniqueOperandCommands.size();
403 UniqueOperandCommands.push_back(Command);
404 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000405
406 // This command matches one operand so far.
407 InstOpsUsed.push_back(1);
408 }
409 }
410
411 // For each entry of UniqueOperandCommands, there is a set of instructions
412 // that uses it. If the next command of all instructions in the set are
413 // identical, fold it into the command.
414 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
415 CommandIdx != e; ++CommandIdx) {
416
417 for (unsigned Op = 1; ; ++Op) {
418 // Scan for the first instruction in the set.
419 std::vector<unsigned>::iterator NIT =
420 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
421 if (NIT == InstIdxs.end()) break; // No commonality.
422
423 // If this instruction has no more operands, we isn't anything to merge
424 // into this command.
425 const AsmWriterInst *FirstInst =
426 getAsmWriterInstByID(NIT-InstIdxs.begin());
427 if (!FirstInst || FirstInst->Operands.size() == Op)
428 break;
429
430 // Otherwise, scan to see if all of the other instructions in this command
431 // set share the operand.
432 bool AllSame = true;
433
Chris Lattner96c1ade2006-07-18 18:28:27 +0000434 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
435 NIT != InstIdxs.end();
436 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
437 // Okay, found another instruction in this command set. If the operand
438 // matches, we're ok, otherwise bail out.
439 const AsmWriterInst *OtherInst =
440 getAsmWriterInstByID(NIT-InstIdxs.begin());
441 if (!OtherInst || OtherInst->Operands.size() == Op ||
442 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
443 AllSame = false;
444 break;
445 }
446 }
447 if (!AllSame) break;
448
449 // Okay, everything in this command set has the same next operand. Add it
450 // to UniqueOperandCommands and remember that it was consumed.
451 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
452
453 // If this is the last operand, emit a return after the code.
454 if (FirstInst->Operands.size() == Op+1)
455 Command += " return true;\n";
456
457 UniqueOperandCommands[CommandIdx] += Command;
458 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000459 }
460 }
461
462 // Prepend some of the instructions each case is used for onto the case val.
463 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
464 std::string Instrs = InstrsForCase[i];
465 if (Instrs.size() > 70) {
466 Instrs.erase(Instrs.begin()+70, Instrs.end());
467 Instrs += "...";
468 }
469
470 if (!Instrs.empty())
471 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
472 UniqueOperandCommands[i];
473 }
474}
475
476
477
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000478void AsmWriterEmitter::run(std::ostream &O) {
479 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
480
481 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000482 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000483 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
484 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000485
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000486 O <<
487 "/// printInstruction - This method is automatically generated by tablegen\n"
488 "/// from the instruction set description. This method returns true if the\n"
489 "/// machine instruction was sufficiently described to print it, otherwise\n"
490 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000491 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000492 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000493
Chris Lattner5765dba2005-01-22 17:40:38 +0000494 std::vector<AsmWriterInst> Instructions;
495
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000496 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
497 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000498 if (!I->second.AsmString.empty())
499 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000500
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000501 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000502 Target.getInstructionsByEnumValue(NumberedInstructions);
503
Chris Lattner6af022f2006-07-14 22:59:11 +0000504 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
505 // all machine instructions are necessarily being printed, so there may be
506 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000507 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
508 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000509
Chris Lattner6af022f2006-07-14 22:59:11 +0000510 // Build an aggregate string, and build a table of offsets into it.
511 std::map<std::string, unsigned> StringOffset;
512 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000513 AggregateString.push_back(0); // "\0"
514 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000515
Chris Lattner259bda42006-09-27 16:44:09 +0000516 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000517 /// chunk of the output as well as indices used for operand printing.
518 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000519
Chris Lattner55616402006-07-18 17:32:27 +0000520 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000521 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
522 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
523 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000524 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000525 // Something not handled by the asmwriter printer.
526 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000527 } else if (AWI->Operands[0].OperandType !=
528 AsmWriterOperand::isLiteralTextOperand ||
529 AWI->Operands[0].Str.empty()) {
530 // Something handled by the asmwriter printer, but with no leading string.
531 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000532 } else {
533 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
534 if (Entry == 0) {
535 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000536 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000537 std::string Str = AWI->Operands[0].Str;
538 UnescapeString(Str);
539 AggregateString += Str;
540 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000541 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000542 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000543
544 // Nuke the string from the operand list. It is now handled!
545 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000546 }
Chris Lattner55616402006-07-18 17:32:27 +0000547 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000548 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000549
Chris Lattner55616402006-07-18 17:32:27 +0000550 // Figure out how many bits we used for the string index.
Nate Begeman59d28132008-04-09 16:24:11 +0000551 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
Chris Lattner55616402006-07-18 17:32:27 +0000552
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000553 // To reduce code size, we compactify common instructions into a few bits
554 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000555 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000556
557 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
558
Chris Lattnerb8462862006-07-18 17:56:07 +0000559 bool isFirst = true;
560 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000561 std::vector<std::string> UniqueOperandCommands;
562
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000563 // For the first operand check, add a default value for instructions with
564 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000565 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000566 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000567 isFirst = false;
568 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000569
570 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000571 std::vector<unsigned> NumInstOpsHandled;
572 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
573 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000574
575 // If we ran out of operands to print, we're done.
576 if (UniqueOperandCommands.empty()) break;
577
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000578 // Compute the number of bits we need to represent these cases, this is
579 // ceil(log2(numentries)).
580 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
581
582 // If we don't have enough bits for this operand, don't include it.
583 if (NumBits > BitsLeft) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000584 DOUT << "Not enough bits to densely encode " << NumBits
585 << " more bits\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000586 break;
587 }
588
589 // Otherwise, we can include this in the initial lookup table. Add it in.
590 BitsLeft -= NumBits;
591 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000592 if (InstIdxs[i] != ~0U)
593 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000594
Chris Lattnerb8462862006-07-18 17:56:07 +0000595 // Remove the info about this operand.
596 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
597 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000598 if (!Inst->Operands.empty()) {
599 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000600 assert(NumOps <= Inst->Operands.size() &&
601 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000602 Inst->Operands.erase(Inst->Operands.begin(),
603 Inst->Operands.begin()+NumOps);
604 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000605 }
606
607 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000608 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
609 }
610
611
612
Chris Lattner55616402006-07-18 17:32:27 +0000613 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000614 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000615 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000616 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000617 }
618 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000619 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000620 O << " };\n\n";
621
622 // Emit the string itself.
623 O << " const char *AsmStrs = \n \"";
624 unsigned CharsPrinted = 0;
625 EscapeString(AggregateString);
626 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
627 if (CharsPrinted > 70) {
628 O << "\"\n \"";
629 CharsPrinted = 0;
630 }
631 O << AggregateString[i];
632 ++CharsPrinted;
633
634 // Print escape sequences all together.
635 if (AggregateString[i] == '\\') {
636 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
637 if (isdigit(AggregateString[i+1])) {
638 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
639 "Expected 3 digit octal escape!");
640 O << AggregateString[++i];
641 O << AggregateString[++i];
642 O << AggregateString[++i];
643 CharsPrinted += 3;
644 } else {
645 O << AggregateString[++i];
646 ++CharsPrinted;
647 }
648 }
649 }
650 O << "\";\n\n";
651
Argyrios Kyrtzidiscd762402009-05-07 13:55:51 +0000652 O << " processDebugLoc(MI->getDebugLoc());\n\n";
Bill Wendlingcb819f12009-02-18 23:12:06 +0000653
Chris Lattner5b842c32009-06-19 23:57:53 +0000654 O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n";
655
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000656 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000657 << " O << \"\\t\";\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000658 << " printInlineAsm(MI);\n"
659 << " return true;\n"
Dan Gohman44066042008-07-01 00:05:16 +0000660 << " } else if (MI->isLabel()) {\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +0000661 << " printLabel(MI);\n"
662 << " return true;\n"
Evan Chenga844bde2008-02-02 04:07:54 +0000663 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
664 << " printDeclare(MI);\n"
665 << " return true;\n"
Evan Chengda47e6e2008-03-15 00:03:38 +0000666 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
667 << " printImplicitDef(MI);\n"
668 << " return true;\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000669 << " }\n\n";
Chris Lattner5b842c32009-06-19 23:57:53 +0000670
671 O << "\n#endif\n";
672
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000673 O << " O << \"\\t\";\n\n";
674
Chris Lattner6af022f2006-07-14 22:59:11 +0000675 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000676 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000677 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000678 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000679
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000680 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000681 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000682 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
683 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
684
685 // Compute the number of bits we need to represent these cases, this is
686 // ceil(log2(numentries)).
687 unsigned NumBits = Log2_32_Ceil(Commands.size());
688 assert(NumBits <= BitsLeft && "consistency error");
689
690 // Emit code to extract this field from Bits.
691 BitsLeft -= NumBits;
692
693 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000694 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000695
Chris Lattner96c1ade2006-07-18 18:28:27 +0000696 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000697 // Emit two possibilitys with if/else.
698 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
699 << ((1 << NumBits)-1) << ") {\n"
700 << Commands[1]
701 << " } else {\n"
702 << Commands[0]
703 << " }\n\n";
704 } else {
705 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
706 << ((1 << NumBits)-1) << ") {\n"
707 << " default: // unreachable.\n";
708
709 // Print out all the cases.
710 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
711 O << " case " << i << ":\n";
712 O << Commands[i];
713 O << " break;\n";
714 }
715 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000716 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000717 }
718
Chris Lattnerb8462862006-07-18 17:56:07 +0000719 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000720 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
721 // Entire instruction has been emitted?
722 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000723 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000724 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000725 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000726 }
727 }
728
729
730 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000731 // elements in the vector.
732 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000733
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000734 if (!Instructions.empty()) {
735 // Find the opcode # of inline asm.
736 O << " switch (MI->getOpcode()) {\n";
737 while (!Instructions.empty())
738 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000739
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000740 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000741 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000742 }
743
Chris Lattner0a012122006-07-18 19:06:01 +0000744 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000745}