blob: 24d2eef07a05fda85b7795622fe9ba93e212032e [file] [log] [blame]
Chris Lattner2e1f51b2004-08-01 05:59:33 +00001//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Chris Lattner2e1f51b2004-08-01 05:59:33 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Chris Lattner2e1f51b2004-08-01 05:59:33 +00008//===----------------------------------------------------------------------===//
9//
10// This tablegen backend is emits an assembly printer for the current target.
11// Note that this is currently fairly skeletal, but will grow over time.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AsmWriterEmitter.h"
16#include "CodeGenTarget.h"
Chris Lattner175580c2004-08-14 22:50:53 +000017#include "Record.h"
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 Lattnerb0b55e72005-01-22 17:32:42 +000031namespace {
32 struct AsmWriterOperand {
33 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
34
35 /// Str - For isLiteralTextOperand, this IS the literal text. For
36 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
37 std::string Str;
38
39 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
40 /// machine instruction.
41 unsigned MIOpNo;
Chris Lattner04cadb32006-02-06 23:40:48 +000042
43 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
44 /// an operand, specified with syntax like ${opname:modifier}.
45 std::string MiModifier;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000046
Chris Lattnerb0b55e72005-01-22 17:32:42 +000047 AsmWriterOperand(const std::string &LitStr)
Nate Begeman391c5d22005-11-30 18:54:35 +000048 : OperandType(isLiteralTextOperand), Str(LitStr) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000049
Chris Lattner04cadb32006-02-06 23:40:48 +000050 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
51 const std::string &Modifier)
52 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
53 MiModifier(Modifier) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000054
Chris Lattner870c0162005-01-22 18:38:13 +000055 bool operator!=(const AsmWriterOperand &Other) const {
56 if (OperandType != Other.OperandType || Str != Other.Str) return true;
57 if (OperandType == isMachineInstrOperand)
Chris Lattner04cadb32006-02-06 23:40:48 +000058 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
Chris Lattner870c0162005-01-22 18:38:13 +000059 return false;
60 }
Chris Lattner38c07512005-01-22 20:31:17 +000061 bool operator==(const AsmWriterOperand &Other) const {
62 return !operator!=(Other);
63 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +000064
65 /// getCode - Return the code that prints this operand.
66 std::string getCode() const;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000067 };
Chris Lattnerbdff5f92006-07-18 17:18:03 +000068}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000069
Chris Lattnerbdff5f92006-07-18 17:18:03 +000070namespace llvm {
Jeff Cohend41b30d2006-11-05 19:31:28 +000071 class AsmWriterInst {
72 public:
Chris Lattnerb0b55e72005-01-22 17:32:42 +000073 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000074 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000075
Chris Lattner5765dba2005-01-22 17:40:38 +000076 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000077
Chris Lattnerf8766682005-01-22 19:22:23 +000078 /// MatchesAllButOneOp - If this instruction is exactly identical to the
79 /// specified instruction except for one differing operand, return the
80 /// differing operand number. Otherwise return ~0.
81 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000082
Chris Lattnerb0b55e72005-01-22 17:32:42 +000083 private:
84 void AddLiteralString(const std::string &Str) {
85 // If the last operand was already a literal text string, append this to
86 // it, otherwise add a new operand.
87 if (!Operands.empty() &&
88 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
89 Operands.back().Str.append(Str);
90 else
91 Operands.push_back(AsmWriterOperand(Str));
92 }
93 };
94}
95
96
Chris Lattnerbdff5f92006-07-18 17:18:03 +000097std::string AsmWriterOperand::getCode() const {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000098 if (OperandType == isLiteralTextOperand)
Chris Lattnerbdff5f92006-07-18 17:18:03 +000099 return "O << \"" + Str + "\"; ";
100
Chris Lattner1bf63612006-09-26 23:45:08 +0000101 std::string Result = Str + "(MI";
102 if (MIOpNo != ~0U)
103 Result += ", " + utostr(MIOpNo);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000104 if (!MiModifier.empty())
105 Result += ", \"" + MiModifier + '"';
106 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000107}
108
109
110/// ParseAsmString - Parse the specified Instruction's AsmString into this
111/// AsmWriterInst.
112///
Chris Lattner5765dba2005-01-22 17:40:38 +0000113AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
114 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000115 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000116
Chris Lattner1cf9d962006-02-01 19:12:23 +0000117 // NOTE: Any extensions to this code need to be mirrored in the
118 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
119 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000120 const std::string &AsmString = CGI.AsmString;
121 std::string::size_type LastEmitted = 0;
122 while (LastEmitted != AsmString.size()) {
123 std::string::size_type DollarPos =
124 AsmString.find_first_of("${|}", LastEmitted);
125 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
126
127 // Emit a constant string fragment.
128 if (DollarPos != LastEmitted) {
129 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000130 if (CurVariant == Variant || CurVariant == ~0U)
131 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
132 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000133 LastEmitted = DollarPos;
134 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000135 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000136 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000137 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000138 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000139 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000140 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000141 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000142 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000143 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000144 ++CurVariant;
145 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000146 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000147 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000148 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000149 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000150 ++LastEmitted;
151 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000152 } else if (DollarPos+1 != AsmString.size() &&
153 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000154 if (CurVariant == Variant || CurVariant == ~0U)
155 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000156 LastEmitted = DollarPos+2;
157 } else {
158 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000159 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000160
161 // handle ${foo}bar as $foo by detecting whether the character following
162 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
163 // so the variable name does not contain the leading curly brace.
164 bool hasCurlyBraces = false;
165 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
166 hasCurlyBraces = true;
167 ++DollarPos;
168 ++VarEnd;
169 }
170
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000171 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
172 ++VarEnd;
173 std::string VarName(AsmString.begin()+DollarPos+1,
174 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000175
Chris Lattner04cadb32006-02-06 23:40:48 +0000176 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000177 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000178 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000179 std::string Modifier;
180
Nate Begemanafc54562005-07-14 22:50:30 +0000181 // In order to avoid starting the next string at the terminating curly
182 // brace, advance the end position past it if we found an opening curly
183 // brace.
184 if (hasCurlyBraces) {
185 if (VarEnd >= AsmString.size())
186 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000187 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000188
189 // Look for a modifier string.
190 if (AsmString[VarEnd] == ':') {
191 ++VarEnd;
192 if (VarEnd >= AsmString.size())
193 throw "Reached end of string before terminating curly brace in '"
194 + CGI.TheDef->getName() + "'";
195
196 unsigned ModifierStart = VarEnd;
197 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
198 ++VarEnd;
199 Modifier = std::string(AsmString.begin()+ModifierStart,
200 AsmString.begin()+VarEnd);
201 if (Modifier.empty())
202 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
203 }
204
Nate Begemanafc54562005-07-14 22:50:30 +0000205 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000206 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000207 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000208 ++VarEnd;
209 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000210 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000211 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000212 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000213
Chris Lattner1bf63612006-09-26 23:45:08 +0000214 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000215 // Just a modifier, pass this into PrintSpecial.
216 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000217 } else {
218 // Otherwise, normal operand.
219 unsigned OpNo = CGI.getOperandNamed(VarName);
220 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000221
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000222 if (CurVariant == Variant || CurVariant == ~0U) {
223 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner1bf63612006-09-26 23:45:08 +0000224 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
225 Modifier));
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000226 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000227 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000228 LastEmitted = VarEnd;
229 }
230 }
231
232 AddLiteralString("\\n");
233}
234
Chris Lattnerf8766682005-01-22 19:22:23 +0000235/// MatchesAllButOneOp - If this instruction is exactly identical to the
236/// specified instruction except for one differing operand, return the differing
237/// operand number. If more than one operand mismatches, return ~1, otherwise
238/// if the instructions are identical return ~0.
239unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
240 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000241
242 unsigned MismatchOperand = ~0U;
243 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000244 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000245 if (MismatchOperand != ~0U) // Already have one mismatch?
246 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000247 else
Chris Lattner870c0162005-01-22 18:38:13 +0000248 MismatchOperand = i;
249 }
250 return MismatchOperand;
251}
252
Chris Lattner38c07512005-01-22 20:31:17 +0000253static void PrintCases(std::vector<std::pair<std::string,
254 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
255 O << " case " << OpsToPrint.back().first << ": ";
256 AsmWriterOperand TheOp = OpsToPrint.back().second;
257 OpsToPrint.pop_back();
258
259 // Check to see if any other operands are identical in this list, and if so,
260 // emit a case label for them.
261 for (unsigned i = OpsToPrint.size(); i != 0; --i)
262 if (OpsToPrint[i-1].second == TheOp) {
263 O << "\n case " << OpsToPrint[i-1].first << ": ";
264 OpsToPrint.erase(OpsToPrint.begin()+i-1);
265 }
266
267 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000268 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000269 O << "break;\n";
270}
271
Chris Lattner870c0162005-01-22 18:38:13 +0000272
273/// EmitInstructions - Emit the last instruction in the vector and any other
274/// instructions that are suitably similar to it.
275static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
276 std::ostream &O) {
277 AsmWriterInst FirstInst = Insts.back();
278 Insts.pop_back();
279
280 std::vector<AsmWriterInst> SimilarInsts;
281 unsigned DifferingOperand = ~0;
282 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000283 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
284 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000285 if (DifferingOperand == ~0U) // First match!
286 DifferingOperand = DiffOp;
287
288 // If this differs in the same operand as the rest of the instructions in
289 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000290 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000291 SimilarInsts.push_back(Insts[i-1]);
292 Insts.erase(Insts.begin()+i-1);
293 }
294 }
295 }
296
Chris Lattnera1e8a802006-05-01 17:01:17 +0000297 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000298 << FirstInst.CGI->TheDef->getName() << ":\n";
299 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000300 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000301 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
302 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
303 if (i != DifferingOperand) {
304 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000305 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000306 } else {
307 // If this is the operand that varies between all of the instructions,
308 // emit a switch for just this operand now.
309 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000310 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000311 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000312 FirstInst.CGI->TheDef->getName(),
313 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000314
Chris Lattner870c0162005-01-22 18:38:13 +0000315 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000316 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000317 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000318 AWI.CGI->TheDef->getName(),
319 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000320 }
Chris Lattner38c07512005-01-22 20:31:17 +0000321 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
322 while (!OpsToPrint.empty())
323 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000324 O << " }";
325 }
326 O << "\n";
327 }
328
329 O << " break;\n";
330}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000331
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000332void AsmWriterEmitter::
333FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000334 std::vector<unsigned> &InstIdxs,
335 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000336 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000337
338 // This vector parallels UniqueOperandCommands, keeping track of which
339 // instructions each case are used for. It is a comma separated string of
340 // enums.
341 std::vector<std::string> InstrsForCase;
342 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000343 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000344
345 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
346 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
347 if (Inst == 0) continue; // PHI, INLINEASM, etc.
348
349 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000350 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000351 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000352
Chris Lattnerb8462862006-07-18 17:56:07 +0000353 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000354
355 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000356 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000357 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000358
359 // Check to see if we already have 'Command' in UniqueOperandCommands.
360 // If not, add it.
361 bool FoundIt = false;
362 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
363 if (UniqueOperandCommands[idx] == Command) {
364 InstIdxs[i] = idx;
365 InstrsForCase[idx] += ", ";
366 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
367 FoundIt = true;
368 break;
369 }
370 if (!FoundIt) {
371 InstIdxs[i] = UniqueOperandCommands.size();
372 UniqueOperandCommands.push_back(Command);
373 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000374
375 // This command matches one operand so far.
376 InstOpsUsed.push_back(1);
377 }
378 }
379
380 // For each entry of UniqueOperandCommands, there is a set of instructions
381 // that uses it. If the next command of all instructions in the set are
382 // identical, fold it into the command.
383 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
384 CommandIdx != e; ++CommandIdx) {
385
386 for (unsigned Op = 1; ; ++Op) {
387 // Scan for the first instruction in the set.
388 std::vector<unsigned>::iterator NIT =
389 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
390 if (NIT == InstIdxs.end()) break; // No commonality.
391
392 // If this instruction has no more operands, we isn't anything to merge
393 // into this command.
394 const AsmWriterInst *FirstInst =
395 getAsmWriterInstByID(NIT-InstIdxs.begin());
396 if (!FirstInst || FirstInst->Operands.size() == Op)
397 break;
398
399 // Otherwise, scan to see if all of the other instructions in this command
400 // set share the operand.
401 bool AllSame = true;
402
Chris Lattner96c1ade2006-07-18 18:28:27 +0000403 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
404 NIT != InstIdxs.end();
405 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
406 // Okay, found another instruction in this command set. If the operand
407 // matches, we're ok, otherwise bail out.
408 const AsmWriterInst *OtherInst =
409 getAsmWriterInstByID(NIT-InstIdxs.begin());
410 if (!OtherInst || OtherInst->Operands.size() == Op ||
411 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
412 AllSame = false;
413 break;
414 }
415 }
416 if (!AllSame) break;
417
418 // Okay, everything in this command set has the same next operand. Add it
419 // to UniqueOperandCommands and remember that it was consumed.
420 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
421
422 // If this is the last operand, emit a return after the code.
423 if (FirstInst->Operands.size() == Op+1)
424 Command += " return true;\n";
425
426 UniqueOperandCommands[CommandIdx] += Command;
427 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000428 }
429 }
430
431 // Prepend some of the instructions each case is used for onto the case val.
432 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
433 std::string Instrs = InstrsForCase[i];
434 if (Instrs.size() > 70) {
435 Instrs.erase(Instrs.begin()+70, Instrs.end());
436 Instrs += "...";
437 }
438
439 if (!Instrs.empty())
440 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
441 UniqueOperandCommands[i];
442 }
443}
444
445
446
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000447void AsmWriterEmitter::run(std::ostream &O) {
448 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
449
450 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000451 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000452 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
453 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000454
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000455 O <<
456 "/// printInstruction - This method is automatically generated by tablegen\n"
457 "/// from the instruction set description. This method returns true if the\n"
458 "/// machine instruction was sufficiently described to print it, otherwise\n"
459 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000460 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000461 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000462
Chris Lattner5765dba2005-01-22 17:40:38 +0000463 std::vector<AsmWriterInst> Instructions;
464
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000465 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
466 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000467 if (!I->second.AsmString.empty())
468 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000469
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000470 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000471 Target.getInstructionsByEnumValue(NumberedInstructions);
472
Chris Lattner6af022f2006-07-14 22:59:11 +0000473 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
474 // all machine instructions are necessarily being printed, so there may be
475 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000476 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
477 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000478
Chris Lattner6af022f2006-07-14 22:59:11 +0000479 // Build an aggregate string, and build a table of offsets into it.
480 std::map<std::string, unsigned> StringOffset;
481 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000482 AggregateString.push_back(0); // "\0"
483 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000484
Chris Lattner259bda42006-09-27 16:44:09 +0000485 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000486 /// chunk of the output as well as indices used for operand printing.
487 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000488
Chris Lattner55616402006-07-18 17:32:27 +0000489 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000490 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
491 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
492 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000493 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000494 // Something not handled by the asmwriter printer.
495 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000496 } else if (AWI->Operands[0].OperandType !=
497 AsmWriterOperand::isLiteralTextOperand ||
498 AWI->Operands[0].Str.empty()) {
499 // Something handled by the asmwriter printer, but with no leading string.
500 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000501 } else {
502 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
503 if (Entry == 0) {
504 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000505 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000506 std::string Str = AWI->Operands[0].Str;
507 UnescapeString(Str);
508 AggregateString += Str;
509 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000510 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000511 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000512
513 // Nuke the string from the operand list. It is now handled!
514 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000515 }
Chris Lattner55616402006-07-18 17:32:27 +0000516 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000517 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000518
Chris Lattner55616402006-07-18 17:32:27 +0000519 // Figure out how many bits we used for the string index.
520 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
521
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000522 // To reduce code size, we compactify common instructions into a few bits
523 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000524 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000525
526 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
527
Chris Lattnerb8462862006-07-18 17:56:07 +0000528 bool isFirst = true;
529 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000530 std::vector<std::string> UniqueOperandCommands;
531
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000532 // For the first operand check, add a default value for instructions with
533 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000534 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000535 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000536 isFirst = false;
537 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000538
539 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000540 std::vector<unsigned> NumInstOpsHandled;
541 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
542 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000543
544 // If we ran out of operands to print, we're done.
545 if (UniqueOperandCommands.empty()) break;
546
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000547 // Compute the number of bits we need to represent these cases, this is
548 // ceil(log2(numentries)).
549 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
550
551 // If we don't have enough bits for this operand, don't include it.
552 if (NumBits > BitsLeft) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000553 DOUT << "Not enough bits to densely encode " << NumBits
554 << " more bits\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000555 break;
556 }
557
558 // Otherwise, we can include this in the initial lookup table. Add it in.
559 BitsLeft -= NumBits;
560 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000561 if (InstIdxs[i] != ~0U)
562 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000563
Chris Lattnerb8462862006-07-18 17:56:07 +0000564 // Remove the info about this operand.
565 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
566 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000567 if (!Inst->Operands.empty()) {
568 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000569 assert(NumOps <= Inst->Operands.size() &&
570 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000571 Inst->Operands.erase(Inst->Operands.begin(),
572 Inst->Operands.begin()+NumOps);
573 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000574 }
575
576 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000577 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
578 }
579
580
581
Chris Lattner55616402006-07-18 17:32:27 +0000582 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000583 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000584 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000585 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000586 }
587 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000588 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000589 O << " };\n\n";
590
591 // Emit the string itself.
592 O << " const char *AsmStrs = \n \"";
593 unsigned CharsPrinted = 0;
594 EscapeString(AggregateString);
595 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
596 if (CharsPrinted > 70) {
597 O << "\"\n \"";
598 CharsPrinted = 0;
599 }
600 O << AggregateString[i];
601 ++CharsPrinted;
602
603 // Print escape sequences all together.
604 if (AggregateString[i] == '\\') {
605 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
606 if (isdigit(AggregateString[i+1])) {
607 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
608 "Expected 3 digit octal escape!");
609 O << AggregateString[++i];
610 O << AggregateString[++i];
611 O << AggregateString[++i];
612 CharsPrinted += 3;
613 } else {
614 O << AggregateString[++i];
615 ++CharsPrinted;
616 }
617 }
618 }
619 O << "\";\n\n";
620
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000621 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
622 << " printInlineAsm(MI);\n"
623 << " return true;\n"
624 << " }\n\n";
625
Chris Lattner6af022f2006-07-14 22:59:11 +0000626 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000627 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000628 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000629 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000630
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000631 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000632 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000633 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
634 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
635
636 // Compute the number of bits we need to represent these cases, this is
637 // ceil(log2(numentries)).
638 unsigned NumBits = Log2_32_Ceil(Commands.size());
639 assert(NumBits <= BitsLeft && "consistency error");
640
641 // Emit code to extract this field from Bits.
642 BitsLeft -= NumBits;
643
644 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000645 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000646
Chris Lattner96c1ade2006-07-18 18:28:27 +0000647 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000648 // Emit two possibilitys with if/else.
649 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
650 << ((1 << NumBits)-1) << ") {\n"
651 << Commands[1]
652 << " } else {\n"
653 << Commands[0]
654 << " }\n\n";
655 } else {
656 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
657 << ((1 << NumBits)-1) << ") {\n"
658 << " default: // unreachable.\n";
659
660 // Print out all the cases.
661 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
662 O << " case " << i << ":\n";
663 O << Commands[i];
664 O << " break;\n";
665 }
666 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000667 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000668 }
669
Chris Lattnerb8462862006-07-18 17:56:07 +0000670 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000671 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
672 // Entire instruction has been emitted?
673 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000674 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000675 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000676 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000677 }
678 }
679
680
681 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000682 // elements in the vector.
683 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000684
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000685 if (!Instructions.empty()) {
686 // Find the opcode # of inline asm.
687 O << " switch (MI->getOpcode()) {\n";
688 while (!Instructions.empty())
689 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000690
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000691 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000692 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000693 }
694
Chris Lattner0a012122006-07-18 19:06:01 +0000695 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000696}