blob: 93d67e843bbd5aeed7d1902254743223a12c12b3 [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) {
133 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000134 if (CurVariant == Variant || CurVariant == ~0U)
135 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
136 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000137 LastEmitted = DollarPos;
Nate Begeman817affc2008-03-17 07:26:14 +0000138 } else if (AsmString[DollarPos] == '\\') {
139 if (DollarPos+1 != AsmString.size() &&
140 (CurVariant == Variant || CurVariant == ~0U)) {
141 if (AsmString[DollarPos+1] == 'n') {
142 AddLiteralString("\\n");
143 } else if (AsmString[DollarPos+1] == 't') {
144 AddLiteralString("\\t");
145 } else if (std::string("${|}\\").find(AsmString[DollarPos+1])
146 != std::string::npos) {
147 AddLiteralString(std::string(1, AsmString[DollarPos+1]));
148 } else {
149 throw "Non-supported escaped character found in instruction '" +
150 CGI.TheDef->getName() + "'!";
151 }
152 LastEmitted = DollarPos+2;
153 continue;
154 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000155 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000156 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000157 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000158 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000159 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000160 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000161 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000162 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000163 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000164 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000165 ++CurVariant;
166 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000167 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000168 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000169 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000170 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000171 ++LastEmitted;
172 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000173 } else if (DollarPos+1 != AsmString.size() &&
174 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000175 if (CurVariant == Variant || CurVariant == ~0U)
176 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000177 LastEmitted = DollarPos+2;
178 } else {
179 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000180 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000181
182 // handle ${foo}bar as $foo by detecting whether the character following
183 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
184 // so the variable name does not contain the leading curly brace.
185 bool hasCurlyBraces = false;
186 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
187 hasCurlyBraces = true;
188 ++DollarPos;
189 ++VarEnd;
190 }
191
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000192 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
193 ++VarEnd;
194 std::string VarName(AsmString.begin()+DollarPos+1,
195 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000196
Chris Lattner04cadb32006-02-06 23:40:48 +0000197 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000198 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000199 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000200 std::string Modifier;
201
Nate Begemanafc54562005-07-14 22:50:30 +0000202 // In order to avoid starting the next string at the terminating curly
203 // brace, advance the end position past it if we found an opening curly
204 // brace.
205 if (hasCurlyBraces) {
206 if (VarEnd >= AsmString.size())
207 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000208 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000209
210 // Look for a modifier string.
211 if (AsmString[VarEnd] == ':') {
212 ++VarEnd;
213 if (VarEnd >= AsmString.size())
214 throw "Reached end of string before terminating curly brace in '"
215 + CGI.TheDef->getName() + "'";
216
217 unsigned ModifierStart = VarEnd;
218 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
219 ++VarEnd;
220 Modifier = std::string(AsmString.begin()+ModifierStart,
221 AsmString.begin()+VarEnd);
222 if (Modifier.empty())
223 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
224 }
225
Nate Begemanafc54562005-07-14 22:50:30 +0000226 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000227 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000228 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000229 ++VarEnd;
230 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000231 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000232 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000233 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000234
Chris Lattner1bf63612006-09-26 23:45:08 +0000235 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000236 // Just a modifier, pass this into PrintSpecial.
237 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000238 } else {
239 // Otherwise, normal operand.
240 unsigned OpNo = CGI.getOperandNamed(VarName);
241 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000242
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000243 if (CurVariant == Variant || CurVariant == ~0U) {
244 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner1bf63612006-09-26 23:45:08 +0000245 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
246 Modifier));
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000247 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000248 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000249 LastEmitted = VarEnd;
250 }
251 }
252
253 AddLiteralString("\\n");
254}
255
Chris Lattnerf8766682005-01-22 19:22:23 +0000256/// MatchesAllButOneOp - If this instruction is exactly identical to the
257/// specified instruction except for one differing operand, return the differing
258/// operand number. If more than one operand mismatches, return ~1, otherwise
259/// if the instructions are identical return ~0.
260unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
261 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000262
263 unsigned MismatchOperand = ~0U;
264 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000265 if (Operands[i] != Other.Operands[i]) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000266 if (MismatchOperand != ~0U) // Already have one mismatch?
267 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000268 else
Chris Lattner870c0162005-01-22 18:38:13 +0000269 MismatchOperand = i;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000270 }
Chris Lattner870c0162005-01-22 18:38:13 +0000271 }
272 return MismatchOperand;
273}
274
Chris Lattner38c07512005-01-22 20:31:17 +0000275static void PrintCases(std::vector<std::pair<std::string,
276 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
277 O << " case " << OpsToPrint.back().first << ": ";
278 AsmWriterOperand TheOp = OpsToPrint.back().second;
279 OpsToPrint.pop_back();
280
281 // Check to see if any other operands are identical in this list, and if so,
282 // emit a case label for them.
283 for (unsigned i = OpsToPrint.size(); i != 0; --i)
284 if (OpsToPrint[i-1].second == TheOp) {
285 O << "\n case " << OpsToPrint[i-1].first << ": ";
286 OpsToPrint.erase(OpsToPrint.begin()+i-1);
287 }
288
289 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000290 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000291 O << "break;\n";
292}
293
Chris Lattner870c0162005-01-22 18:38:13 +0000294
295/// EmitInstructions - Emit the last instruction in the vector and any other
296/// instructions that are suitably similar to it.
297static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
298 std::ostream &O) {
299 AsmWriterInst FirstInst = Insts.back();
300 Insts.pop_back();
301
302 std::vector<AsmWriterInst> SimilarInsts;
303 unsigned DifferingOperand = ~0;
304 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000305 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
306 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000307 if (DifferingOperand == ~0U) // First match!
308 DifferingOperand = DiffOp;
309
310 // If this differs in the same operand as the rest of the instructions in
311 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000312 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000313 SimilarInsts.push_back(Insts[i-1]);
314 Insts.erase(Insts.begin()+i-1);
315 }
316 }
317 }
318
Chris Lattnera1e8a802006-05-01 17:01:17 +0000319 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000320 << FirstInst.CGI->TheDef->getName() << ":\n";
321 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000322 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000323 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
324 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
325 if (i != DifferingOperand) {
326 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000327 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000328 } else {
329 // If this is the operand that varies between all of the instructions,
330 // emit a switch for just this operand now.
331 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000332 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000333 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000334 FirstInst.CGI->TheDef->getName(),
335 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000336
Chris Lattner870c0162005-01-22 18:38:13 +0000337 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000338 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000339 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000340 AWI.CGI->TheDef->getName(),
341 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000342 }
Chris Lattner38c07512005-01-22 20:31:17 +0000343 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
344 while (!OpsToPrint.empty())
345 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000346 O << " }";
347 }
348 O << "\n";
349 }
350
351 O << " break;\n";
352}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000353
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000354void AsmWriterEmitter::
355FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000356 std::vector<unsigned> &InstIdxs,
357 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000358 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000359
360 // This vector parallels UniqueOperandCommands, keeping track of which
361 // instructions each case are used for. It is a comma separated string of
362 // enums.
363 std::vector<std::string> InstrsForCase;
364 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000365 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000366
367 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
368 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Dan Gohman44066042008-07-01 00:05:16 +0000369 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000370
371 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000372 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000373 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000374
Chris Lattnerb8462862006-07-18 17:56:07 +0000375 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000376
377 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000378 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000379 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000380
381 // Check to see if we already have 'Command' in UniqueOperandCommands.
382 // If not, add it.
383 bool FoundIt = false;
384 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
385 if (UniqueOperandCommands[idx] == Command) {
386 InstIdxs[i] = idx;
387 InstrsForCase[idx] += ", ";
388 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
389 FoundIt = true;
390 break;
391 }
392 if (!FoundIt) {
393 InstIdxs[i] = UniqueOperandCommands.size();
394 UniqueOperandCommands.push_back(Command);
395 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000396
397 // This command matches one operand so far.
398 InstOpsUsed.push_back(1);
399 }
400 }
401
402 // For each entry of UniqueOperandCommands, there is a set of instructions
403 // that uses it. If the next command of all instructions in the set are
404 // identical, fold it into the command.
405 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
406 CommandIdx != e; ++CommandIdx) {
407
408 for (unsigned Op = 1; ; ++Op) {
409 // Scan for the first instruction in the set.
410 std::vector<unsigned>::iterator NIT =
411 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
412 if (NIT == InstIdxs.end()) break; // No commonality.
413
414 // If this instruction has no more operands, we isn't anything to merge
415 // into this command.
416 const AsmWriterInst *FirstInst =
417 getAsmWriterInstByID(NIT-InstIdxs.begin());
418 if (!FirstInst || FirstInst->Operands.size() == Op)
419 break;
420
421 // Otherwise, scan to see if all of the other instructions in this command
422 // set share the operand.
423 bool AllSame = true;
424
Chris Lattner96c1ade2006-07-18 18:28:27 +0000425 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
426 NIT != InstIdxs.end();
427 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
428 // Okay, found another instruction in this command set. If the operand
429 // matches, we're ok, otherwise bail out.
430 const AsmWriterInst *OtherInst =
431 getAsmWriterInstByID(NIT-InstIdxs.begin());
432 if (!OtherInst || OtherInst->Operands.size() == Op ||
433 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
434 AllSame = false;
435 break;
436 }
437 }
438 if (!AllSame) break;
439
440 // Okay, everything in this command set has the same next operand. Add it
441 // to UniqueOperandCommands and remember that it was consumed.
442 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
443
444 // If this is the last operand, emit a return after the code.
445 if (FirstInst->Operands.size() == Op+1)
446 Command += " return true;\n";
447
448 UniqueOperandCommands[CommandIdx] += Command;
449 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000450 }
451 }
452
453 // Prepend some of the instructions each case is used for onto the case val.
454 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
455 std::string Instrs = InstrsForCase[i];
456 if (Instrs.size() > 70) {
457 Instrs.erase(Instrs.begin()+70, Instrs.end());
458 Instrs += "...";
459 }
460
461 if (!Instrs.empty())
462 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
463 UniqueOperandCommands[i];
464 }
465}
466
467
468
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000469void AsmWriterEmitter::run(std::ostream &O) {
470 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
471
472 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000473 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000474 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
475 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000476
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000477 O <<
478 "/// printInstruction - This method is automatically generated by tablegen\n"
479 "/// from the instruction set description. This method returns true if the\n"
480 "/// machine instruction was sufficiently described to print it, otherwise\n"
481 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000482 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000483 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000484
Chris Lattner5765dba2005-01-22 17:40:38 +0000485 std::vector<AsmWriterInst> Instructions;
486
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000487 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
488 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000489 if (!I->second.AsmString.empty())
490 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000491
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000492 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000493 Target.getInstructionsByEnumValue(NumberedInstructions);
494
Chris Lattner6af022f2006-07-14 22:59:11 +0000495 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
496 // all machine instructions are necessarily being printed, so there may be
497 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000498 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
499 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000500
Chris Lattner6af022f2006-07-14 22:59:11 +0000501 // Build an aggregate string, and build a table of offsets into it.
502 std::map<std::string, unsigned> StringOffset;
503 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000504 AggregateString.push_back(0); // "\0"
505 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000506
Chris Lattner259bda42006-09-27 16:44:09 +0000507 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000508 /// chunk of the output as well as indices used for operand printing.
509 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000510
Chris Lattner55616402006-07-18 17:32:27 +0000511 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000512 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
513 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
514 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000515 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000516 // Something not handled by the asmwriter printer.
517 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000518 } else if (AWI->Operands[0].OperandType !=
519 AsmWriterOperand::isLiteralTextOperand ||
520 AWI->Operands[0].Str.empty()) {
521 // Something handled by the asmwriter printer, but with no leading string.
522 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000523 } else {
524 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
525 if (Entry == 0) {
526 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000527 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000528 std::string Str = AWI->Operands[0].Str;
529 UnescapeString(Str);
530 AggregateString += Str;
531 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000532 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000533 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000534
535 // Nuke the string from the operand list. It is now handled!
536 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000537 }
Chris Lattner55616402006-07-18 17:32:27 +0000538 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000539 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000540
Chris Lattner55616402006-07-18 17:32:27 +0000541 // Figure out how many bits we used for the string index.
Nate Begeman59d28132008-04-09 16:24:11 +0000542 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
Chris Lattner55616402006-07-18 17:32:27 +0000543
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000544 // To reduce code size, we compactify common instructions into a few bits
545 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000546 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000547
548 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
549
Chris Lattnerb8462862006-07-18 17:56:07 +0000550 bool isFirst = true;
551 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000552 std::vector<std::string> UniqueOperandCommands;
553
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000554 // For the first operand check, add a default value for instructions with
555 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000556 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000557 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000558 isFirst = false;
559 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000560
561 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000562 std::vector<unsigned> NumInstOpsHandled;
563 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
564 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000565
566 // If we ran out of operands to print, we're done.
567 if (UniqueOperandCommands.empty()) break;
568
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000569 // Compute the number of bits we need to represent these cases, this is
570 // ceil(log2(numentries)).
571 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
572
573 // If we don't have enough bits for this operand, don't include it.
574 if (NumBits > BitsLeft) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000575 DOUT << "Not enough bits to densely encode " << NumBits
576 << " more bits\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000577 break;
578 }
579
580 // Otherwise, we can include this in the initial lookup table. Add it in.
581 BitsLeft -= NumBits;
582 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000583 if (InstIdxs[i] != ~0U)
584 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000585
Chris Lattnerb8462862006-07-18 17:56:07 +0000586 // Remove the info about this operand.
587 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
588 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000589 if (!Inst->Operands.empty()) {
590 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000591 assert(NumOps <= Inst->Operands.size() &&
592 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000593 Inst->Operands.erase(Inst->Operands.begin(),
594 Inst->Operands.begin()+NumOps);
595 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000596 }
597
598 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000599 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
600 }
601
602
603
Chris Lattner55616402006-07-18 17:32:27 +0000604 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000605 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000606 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000607 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000608 }
609 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000610 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000611 O << " };\n\n";
612
613 // Emit the string itself.
614 O << " const char *AsmStrs = \n \"";
615 unsigned CharsPrinted = 0;
616 EscapeString(AggregateString);
617 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
618 if (CharsPrinted > 70) {
619 O << "\"\n \"";
620 CharsPrinted = 0;
621 }
622 O << AggregateString[i];
623 ++CharsPrinted;
624
625 // Print escape sequences all together.
626 if (AggregateString[i] == '\\') {
627 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
628 if (isdigit(AggregateString[i+1])) {
629 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
630 "Expected 3 digit octal escape!");
631 O << AggregateString[++i];
632 O << AggregateString[++i];
633 O << AggregateString[++i];
634 CharsPrinted += 3;
635 } else {
636 O << AggregateString[++i];
637 ++CharsPrinted;
638 }
639 }
640 }
641 O << "\";\n\n";
642
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000643 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000644 << " O << \"\\t\";\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000645 << " printInlineAsm(MI);\n"
646 << " return true;\n"
Dan Gohman44066042008-07-01 00:05:16 +0000647 << " } else if (MI->isLabel()) {\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +0000648 << " printLabel(MI);\n"
649 << " return true;\n"
Evan Chenga844bde2008-02-02 04:07:54 +0000650 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
651 << " printDeclare(MI);\n"
652 << " return true;\n"
Evan Chengda47e6e2008-03-15 00:03:38 +0000653 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
654 << " printImplicitDef(MI);\n"
655 << " return true;\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000656 << " }\n\n";
657
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000658 O << " O << \"\\t\";\n\n";
659
Chris Lattner6af022f2006-07-14 22:59:11 +0000660 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000661 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000662 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000663 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000664
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000665 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000666 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000667 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
668 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
669
670 // Compute the number of bits we need to represent these cases, this is
671 // ceil(log2(numentries)).
672 unsigned NumBits = Log2_32_Ceil(Commands.size());
673 assert(NumBits <= BitsLeft && "consistency error");
674
675 // Emit code to extract this field from Bits.
676 BitsLeft -= NumBits;
677
678 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000679 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000680
Chris Lattner96c1ade2006-07-18 18:28:27 +0000681 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000682 // Emit two possibilitys with if/else.
683 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
684 << ((1 << NumBits)-1) << ") {\n"
685 << Commands[1]
686 << " } else {\n"
687 << Commands[0]
688 << " }\n\n";
689 } else {
690 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
691 << ((1 << NumBits)-1) << ") {\n"
692 << " default: // unreachable.\n";
693
694 // Print out all the cases.
695 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
696 O << " case " << i << ":\n";
697 O << Commands[i];
698 O << " break;\n";
699 }
700 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000701 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000702 }
703
Chris Lattnerb8462862006-07-18 17:56:07 +0000704 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000705 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
706 // Entire instruction has been emitted?
707 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000708 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000709 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000710 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000711 }
712 }
713
714
715 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000716 // elements in the vector.
717 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000718
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000719 if (!Instructions.empty()) {
720 // Find the opcode # of inline asm.
721 O << " switch (MI->getOpcode()) {\n";
722 while (!Instructions.empty())
723 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000724
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000725 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000726 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000727 }
728
Chris Lattner0a012122006-07-18 19:06:01 +0000729 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000730}