blob: 07ef2e5c8d0fe4d7e7cd652ff550e8819b2cab41 [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
Chris Lattnerb0b55e72005-01-22 17:32:42 +000048 AsmWriterOperand(const std::string &LitStr)
Nate Begeman391c5d22005-11-30 18:54:35 +000049 : OperandType(isLiteralTextOperand), Str(LitStr) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000050
Chris Lattner04cadb32006-02-06 23:40:48 +000051 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
52 const std::string &Modifier)
53 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
54 MiModifier(Modifier) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000055
Chris Lattner870c0162005-01-22 18:38:13 +000056 bool operator!=(const AsmWriterOperand &Other) const {
57 if (OperandType != Other.OperandType || Str != Other.Str) return true;
58 if (OperandType == isMachineInstrOperand)
Chris Lattner04cadb32006-02-06 23:40:48 +000059 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
Chris Lattner870c0162005-01-22 18:38:13 +000060 return false;
61 }
Chris Lattner38c07512005-01-22 20:31:17 +000062 bool operator==(const AsmWriterOperand &Other) const {
63 return !operator!=(Other);
64 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +000065
66 /// getCode - Return the code that prints this operand.
67 std::string getCode() const;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000068 };
Chris Lattnerbdff5f92006-07-18 17:18:03 +000069}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000070
Chris Lattnerbdff5f92006-07-18 17:18:03 +000071namespace llvm {
Jeff Cohend41b30d2006-11-05 19:31:28 +000072 class AsmWriterInst {
73 public:
Chris Lattnerb0b55e72005-01-22 17:32:42 +000074 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000075 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000076
Chris Lattner5765dba2005-01-22 17:40:38 +000077 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000078
Chris Lattnerf8766682005-01-22 19:22:23 +000079 /// MatchesAllButOneOp - If this instruction is exactly identical to the
80 /// specified instruction except for one differing operand, return the
81 /// differing operand number. Otherwise return ~0.
82 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000083
Chris Lattnerb0b55e72005-01-22 17:32:42 +000084 private:
85 void AddLiteralString(const std::string &Str) {
86 // If the last operand was already a literal text string, append this to
87 // it, otherwise add a new operand.
88 if (!Operands.empty() &&
89 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
90 Operands.back().Str.append(Str);
91 else
92 Operands.push_back(AsmWriterOperand(Str));
93 }
94 };
95}
96
97
Chris Lattnerbdff5f92006-07-18 17:18:03 +000098std::string AsmWriterOperand::getCode() const {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000099 if (OperandType == isLiteralTextOperand)
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000100 return "O << \"" + Str + "\"; ";
101
Chris Lattner1bf63612006-09-26 23:45:08 +0000102 std::string Result = Str + "(MI";
103 if (MIOpNo != ~0U)
104 Result += ", " + utostr(MIOpNo);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000105 if (!MiModifier.empty())
106 Result += ", \"" + MiModifier + '"';
107 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000108}
109
110
111/// ParseAsmString - Parse the specified Instruction's AsmString into this
112/// AsmWriterInst.
113///
Chris Lattner5765dba2005-01-22 17:40:38 +0000114AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
115 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000116 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000117
Chris Lattner1cf9d962006-02-01 19:12:23 +0000118 // NOTE: Any extensions to this code need to be mirrored in the
119 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
120 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000121 const std::string &AsmString = CGI.AsmString;
122 std::string::size_type LastEmitted = 0;
123 while (LastEmitted != AsmString.size()) {
124 std::string::size_type DollarPos =
125 AsmString.find_first_of("${|}", LastEmitted);
126 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
127
128 // Emit a constant string fragment.
129 if (DollarPos != LastEmitted) {
130 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000131 if (CurVariant == Variant || CurVariant == ~0U)
132 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
133 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000134 LastEmitted = DollarPos;
135 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000136 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000137 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000138 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000139 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000140 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000141 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000142 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000143 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000144 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000145 ++CurVariant;
146 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000147 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000148 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000149 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000150 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000151 ++LastEmitted;
152 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000153 } else if (DollarPos+1 != AsmString.size() &&
154 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000155 if (CurVariant == Variant || CurVariant == ~0U)
156 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000157 LastEmitted = DollarPos+2;
158 } else {
159 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000160 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000161
162 // handle ${foo}bar as $foo by detecting whether the character following
163 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
164 // so the variable name does not contain the leading curly brace.
165 bool hasCurlyBraces = false;
166 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
167 hasCurlyBraces = true;
168 ++DollarPos;
169 ++VarEnd;
170 }
171
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000172 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
173 ++VarEnd;
174 std::string VarName(AsmString.begin()+DollarPos+1,
175 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000176
Chris Lattner04cadb32006-02-06 23:40:48 +0000177 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000178 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000179 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000180 std::string Modifier;
181
Nate Begemanafc54562005-07-14 22:50:30 +0000182 // In order to avoid starting the next string at the terminating curly
183 // brace, advance the end position past it if we found an opening curly
184 // brace.
185 if (hasCurlyBraces) {
186 if (VarEnd >= AsmString.size())
187 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000188 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000189
190 // Look for a modifier string.
191 if (AsmString[VarEnd] == ':') {
192 ++VarEnd;
193 if (VarEnd >= AsmString.size())
194 throw "Reached end of string before terminating curly brace in '"
195 + CGI.TheDef->getName() + "'";
196
197 unsigned ModifierStart = VarEnd;
198 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
199 ++VarEnd;
200 Modifier = std::string(AsmString.begin()+ModifierStart,
201 AsmString.begin()+VarEnd);
202 if (Modifier.empty())
203 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
204 }
205
Nate Begemanafc54562005-07-14 22:50:30 +0000206 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000207 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000208 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000209 ++VarEnd;
210 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000211 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000212 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000213 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000214
Chris Lattner1bf63612006-09-26 23:45:08 +0000215 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000216 // Just a modifier, pass this into PrintSpecial.
217 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000218 } else {
219 // Otherwise, normal operand.
220 unsigned OpNo = CGI.getOperandNamed(VarName);
221 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000222
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000223 if (CurVariant == Variant || CurVariant == ~0U) {
224 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner1bf63612006-09-26 23:45:08 +0000225 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
226 Modifier));
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000227 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000228 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000229 LastEmitted = VarEnd;
230 }
231 }
232
233 AddLiteralString("\\n");
234}
235
Chris Lattnerf8766682005-01-22 19:22:23 +0000236/// MatchesAllButOneOp - If this instruction is exactly identical to the
237/// specified instruction except for one differing operand, return the differing
238/// operand number. If more than one operand mismatches, return ~1, otherwise
239/// if the instructions are identical return ~0.
240unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
241 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000242
243 unsigned MismatchOperand = ~0U;
244 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000245 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000246 if (MismatchOperand != ~0U) // Already have one mismatch?
247 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000248 else
Chris Lattner870c0162005-01-22 18:38:13 +0000249 MismatchOperand = i;
250 }
251 return MismatchOperand;
252}
253
Chris Lattner38c07512005-01-22 20:31:17 +0000254static void PrintCases(std::vector<std::pair<std::string,
255 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
256 O << " case " << OpsToPrint.back().first << ": ";
257 AsmWriterOperand TheOp = OpsToPrint.back().second;
258 OpsToPrint.pop_back();
259
260 // Check to see if any other operands are identical in this list, and if so,
261 // emit a case label for them.
262 for (unsigned i = OpsToPrint.size(); i != 0; --i)
263 if (OpsToPrint[i-1].second == TheOp) {
264 O << "\n case " << OpsToPrint[i-1].first << ": ";
265 OpsToPrint.erase(OpsToPrint.begin()+i-1);
266 }
267
268 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000269 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000270 O << "break;\n";
271}
272
Chris Lattner870c0162005-01-22 18:38:13 +0000273
274/// EmitInstructions - Emit the last instruction in the vector and any other
275/// instructions that are suitably similar to it.
276static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
277 std::ostream &O) {
278 AsmWriterInst FirstInst = Insts.back();
279 Insts.pop_back();
280
281 std::vector<AsmWriterInst> SimilarInsts;
282 unsigned DifferingOperand = ~0;
283 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000284 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
285 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000286 if (DifferingOperand == ~0U) // First match!
287 DifferingOperand = DiffOp;
288
289 // If this differs in the same operand as the rest of the instructions in
290 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000291 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000292 SimilarInsts.push_back(Insts[i-1]);
293 Insts.erase(Insts.begin()+i-1);
294 }
295 }
296 }
297
Chris Lattnera1e8a802006-05-01 17:01:17 +0000298 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000299 << FirstInst.CGI->TheDef->getName() << ":\n";
300 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000301 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000302 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
303 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
304 if (i != DifferingOperand) {
305 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000306 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000307 } else {
308 // If this is the operand that varies between all of the instructions,
309 // emit a switch for just this operand now.
310 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000311 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000312 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000313 FirstInst.CGI->TheDef->getName(),
314 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000315
Chris Lattner870c0162005-01-22 18:38:13 +0000316 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000317 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000318 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000319 AWI.CGI->TheDef->getName(),
320 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000321 }
Chris Lattner38c07512005-01-22 20:31:17 +0000322 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
323 while (!OpsToPrint.empty())
324 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000325 O << " }";
326 }
327 O << "\n";
328 }
329
330 O << " break;\n";
331}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000332
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000333void AsmWriterEmitter::
334FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000335 std::vector<unsigned> &InstIdxs,
336 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000337 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000338
339 // This vector parallels UniqueOperandCommands, keeping track of which
340 // instructions each case are used for. It is a comma separated string of
341 // enums.
342 std::vector<std::string> InstrsForCase;
343 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000344 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000345
346 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
347 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Jim Laskeya683f9b2007-01-26 17:29:20 +0000348 if (Inst == 0) continue; // PHI, INLINEASM, LABEL, etc.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000349
350 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000351 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000352 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000353
Chris Lattnerb8462862006-07-18 17:56:07 +0000354 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000355
356 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000357 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000358 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000359
360 // Check to see if we already have 'Command' in UniqueOperandCommands.
361 // If not, add it.
362 bool FoundIt = false;
363 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
364 if (UniqueOperandCommands[idx] == Command) {
365 InstIdxs[i] = idx;
366 InstrsForCase[idx] += ", ";
367 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
368 FoundIt = true;
369 break;
370 }
371 if (!FoundIt) {
372 InstIdxs[i] = UniqueOperandCommands.size();
373 UniqueOperandCommands.push_back(Command);
374 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000375
376 // This command matches one operand so far.
377 InstOpsUsed.push_back(1);
378 }
379 }
380
381 // For each entry of UniqueOperandCommands, there is a set of instructions
382 // that uses it. If the next command of all instructions in the set are
383 // identical, fold it into the command.
384 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
385 CommandIdx != e; ++CommandIdx) {
386
387 for (unsigned Op = 1; ; ++Op) {
388 // Scan for the first instruction in the set.
389 std::vector<unsigned>::iterator NIT =
390 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
391 if (NIT == InstIdxs.end()) break; // No commonality.
392
393 // If this instruction has no more operands, we isn't anything to merge
394 // into this command.
395 const AsmWriterInst *FirstInst =
396 getAsmWriterInstByID(NIT-InstIdxs.begin());
397 if (!FirstInst || FirstInst->Operands.size() == Op)
398 break;
399
400 // Otherwise, scan to see if all of the other instructions in this command
401 // set share the operand.
402 bool AllSame = true;
403
Chris Lattner96c1ade2006-07-18 18:28:27 +0000404 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
405 NIT != InstIdxs.end();
406 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
407 // Okay, found another instruction in this command set. If the operand
408 // matches, we're ok, otherwise bail out.
409 const AsmWriterInst *OtherInst =
410 getAsmWriterInstByID(NIT-InstIdxs.begin());
411 if (!OtherInst || OtherInst->Operands.size() == Op ||
412 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
413 AllSame = false;
414 break;
415 }
416 }
417 if (!AllSame) break;
418
419 // Okay, everything in this command set has the same next operand. Add it
420 // to UniqueOperandCommands and remember that it was consumed.
421 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
422
423 // If this is the last operand, emit a return after the code.
424 if (FirstInst->Operands.size() == Op+1)
425 Command += " return true;\n";
426
427 UniqueOperandCommands[CommandIdx] += Command;
428 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000429 }
430 }
431
432 // Prepend some of the instructions each case is used for onto the case val.
433 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
434 std::string Instrs = InstrsForCase[i];
435 if (Instrs.size() > 70) {
436 Instrs.erase(Instrs.begin()+70, Instrs.end());
437 Instrs += "...";
438 }
439
440 if (!Instrs.empty())
441 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
442 UniqueOperandCommands[i];
443 }
444}
445
446
447
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000448void AsmWriterEmitter::run(std::ostream &O) {
449 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
450
451 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000452 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000453 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
454 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000455
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000456 O <<
457 "/// printInstruction - This method is automatically generated by tablegen\n"
458 "/// from the instruction set description. This method returns true if the\n"
459 "/// machine instruction was sufficiently described to print it, otherwise\n"
460 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000461 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000462 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000463
Chris Lattner5765dba2005-01-22 17:40:38 +0000464 std::vector<AsmWriterInst> Instructions;
465
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000466 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
467 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000468 if (!I->second.AsmString.empty())
469 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000470
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000471 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000472 Target.getInstructionsByEnumValue(NumberedInstructions);
473
Chris Lattner6af022f2006-07-14 22:59:11 +0000474 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
475 // all machine instructions are necessarily being printed, so there may be
476 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000477 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
478 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000479
Chris Lattner6af022f2006-07-14 22:59:11 +0000480 // Build an aggregate string, and build a table of offsets into it.
481 std::map<std::string, unsigned> StringOffset;
482 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000483 AggregateString.push_back(0); // "\0"
484 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000485
Chris Lattner259bda42006-09-27 16:44:09 +0000486 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000487 /// chunk of the output as well as indices used for operand printing.
488 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000489
Chris Lattner55616402006-07-18 17:32:27 +0000490 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000491 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
492 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
493 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000494 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000495 // Something not handled by the asmwriter printer.
496 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000497 } else if (AWI->Operands[0].OperandType !=
498 AsmWriterOperand::isLiteralTextOperand ||
499 AWI->Operands[0].Str.empty()) {
500 // Something handled by the asmwriter printer, but with no leading string.
501 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000502 } else {
503 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
504 if (Entry == 0) {
505 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000506 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000507 std::string Str = AWI->Operands[0].Str;
508 UnescapeString(Str);
509 AggregateString += Str;
510 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000511 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000512 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000513
514 // Nuke the string from the operand list. It is now handled!
515 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000516 }
Chris Lattner55616402006-07-18 17:32:27 +0000517 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000518 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000519
Chris Lattner55616402006-07-18 17:32:27 +0000520 // Figure out how many bits we used for the string index.
521 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
522
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000523 // To reduce code size, we compactify common instructions into a few bits
524 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000525 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000526
527 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
528
Chris Lattnerb8462862006-07-18 17:56:07 +0000529 bool isFirst = true;
530 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000531 std::vector<std::string> UniqueOperandCommands;
532
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000533 // For the first operand check, add a default value for instructions with
534 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000535 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000536 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000537 isFirst = false;
538 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000539
540 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000541 std::vector<unsigned> NumInstOpsHandled;
542 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
543 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000544
545 // If we ran out of operands to print, we're done.
546 if (UniqueOperandCommands.empty()) break;
547
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000548 // Compute the number of bits we need to represent these cases, this is
549 // ceil(log2(numentries)).
550 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
551
552 // If we don't have enough bits for this operand, don't include it.
553 if (NumBits > BitsLeft) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000554 DOUT << "Not enough bits to densely encode " << NumBits
555 << " more bits\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000556 break;
557 }
558
559 // Otherwise, we can include this in the initial lookup table. Add it in.
560 BitsLeft -= NumBits;
561 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000562 if (InstIdxs[i] != ~0U)
563 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000564
Chris Lattnerb8462862006-07-18 17:56:07 +0000565 // Remove the info about this operand.
566 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
567 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000568 if (!Inst->Operands.empty()) {
569 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000570 assert(NumOps <= Inst->Operands.size() &&
571 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000572 Inst->Operands.erase(Inst->Operands.begin(),
573 Inst->Operands.begin()+NumOps);
574 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000575 }
576
577 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000578 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
579 }
580
581
582
Chris Lattner55616402006-07-18 17:32:27 +0000583 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000584 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000585 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000586 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000587 }
588 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000589 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000590 O << " };\n\n";
591
592 // Emit the string itself.
593 O << " const char *AsmStrs = \n \"";
594 unsigned CharsPrinted = 0;
595 EscapeString(AggregateString);
596 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
597 if (CharsPrinted > 70) {
598 O << "\"\n \"";
599 CharsPrinted = 0;
600 }
601 O << AggregateString[i];
602 ++CharsPrinted;
603
604 // Print escape sequences all together.
605 if (AggregateString[i] == '\\') {
606 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
607 if (isdigit(AggregateString[i+1])) {
608 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
609 "Expected 3 digit octal escape!");
610 O << AggregateString[++i];
611 O << AggregateString[++i];
612 O << AggregateString[++i];
613 CharsPrinted += 3;
614 } else {
615 O << AggregateString[++i];
616 ++CharsPrinted;
617 }
618 }
619 }
620 O << "\";\n\n";
621
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000622 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000623 << " O << \"\\t\";\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000624 << " printInlineAsm(MI);\n"
625 << " return true;\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +0000626 << " } else if (MI->getOpcode() == TargetInstrInfo::LABEL) {\n"
627 << " printLabel(MI);\n"
628 << " return true;\n"
Evan Chenga844bde2008-02-02 04:07:54 +0000629 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
630 << " printDeclare(MI);\n"
631 << " return true;\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000632 << " }\n\n";
633
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000634 O << " O << \"\\t\";\n\n";
635
Chris Lattner6af022f2006-07-14 22:59:11 +0000636 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000637 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000638 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000639 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000640
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000641 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000642 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000643 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
644 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
645
646 // Compute the number of bits we need to represent these cases, this is
647 // ceil(log2(numentries)).
648 unsigned NumBits = Log2_32_Ceil(Commands.size());
649 assert(NumBits <= BitsLeft && "consistency error");
650
651 // Emit code to extract this field from Bits.
652 BitsLeft -= NumBits;
653
654 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000655 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000656
Chris Lattner96c1ade2006-07-18 18:28:27 +0000657 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000658 // Emit two possibilitys with if/else.
659 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
660 << ((1 << NumBits)-1) << ") {\n"
661 << Commands[1]
662 << " } else {\n"
663 << Commands[0]
664 << " }\n\n";
665 } else {
666 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
667 << ((1 << NumBits)-1) << ") {\n"
668 << " default: // unreachable.\n";
669
670 // Print out all the cases.
671 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
672 O << " case " << i << ":\n";
673 O << Commands[i];
674 O << " break;\n";
675 }
676 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000677 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000678 }
679
Chris Lattnerb8462862006-07-18 17:56:07 +0000680 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000681 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
682 // Entire instruction has been emitted?
683 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000684 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000685 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000686 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000687 }
688 }
689
690
691 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000692 // elements in the vector.
693 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000694
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000695 if (!Instructions.empty()) {
696 // Find the opcode # of inline asm.
697 O << " switch (MI->getOpcode()) {\n";
698 while (!Instructions.empty())
699 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000700
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000701 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000702 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000703 }
704
Chris Lattner0a012122006-07-18 19:06:01 +0000705 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000706}