blob: 2ea74494f24a14600358d92f4a533825156d0cf3 [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 +000022#include <ostream>
23using namespace llvm;
24
Chris Lattner076efa72004-08-01 07:43:02 +000025static bool isIdentChar(char C) {
26 return (C >= 'a' && C <= 'z') ||
27 (C >= 'A' && C <= 'Z') ||
28 (C >= '0' && C <= '9') ||
29 C == '_';
30}
31
Chris Lattnerb0b55e72005-01-22 17:32:42 +000032namespace {
33 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 {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000072 struct AsmWriterInst {
73 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
101 std::string Result = Str + "(MI, " + utostr(MIOpNo);
102 if (!MiModifier.empty())
103 Result += ", \"" + MiModifier + '"';
104 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000105}
106
107
108/// ParseAsmString - Parse the specified Instruction's AsmString into this
109/// AsmWriterInst.
110///
Chris Lattner5765dba2005-01-22 17:40:38 +0000111AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
112 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000113 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000114
Chris Lattner1cf9d962006-02-01 19:12:23 +0000115 // NOTE: Any extensions to this code need to be mirrored in the
116 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
117 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000118 const std::string &AsmString = CGI.AsmString;
119 std::string::size_type LastEmitted = 0;
120 while (LastEmitted != AsmString.size()) {
121 std::string::size_type DollarPos =
122 AsmString.find_first_of("${|}", LastEmitted);
123 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
124
125 // Emit a constant string fragment.
126 if (DollarPos != LastEmitted) {
127 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000128 if (CurVariant == Variant || CurVariant == ~0U)
129 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
130 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000131 LastEmitted = DollarPos;
132 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000133 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000134 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000135 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000136 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000137 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000138 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000139 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000140 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000141 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000142 ++CurVariant;
143 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000144 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000145 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000146 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000147 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000148 ++LastEmitted;
149 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000150 } else if (DollarPos+1 != AsmString.size() &&
151 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000152 if (CurVariant == Variant || CurVariant == ~0U)
153 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000154 LastEmitted = DollarPos+2;
155 } else {
156 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000157 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000158
159 // handle ${foo}bar as $foo by detecting whether the character following
160 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
161 // so the variable name does not contain the leading curly brace.
162 bool hasCurlyBraces = false;
163 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
164 hasCurlyBraces = true;
165 ++DollarPos;
166 ++VarEnd;
167 }
168
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000169 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
170 ++VarEnd;
171 std::string VarName(AsmString.begin()+DollarPos+1,
172 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000173
Chris Lattner04cadb32006-02-06 23:40:48 +0000174 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
175 // into printOperand.
176 std::string Modifier;
177
Nate Begemanafc54562005-07-14 22:50:30 +0000178 // In order to avoid starting the next string at the terminating curly
179 // brace, advance the end position past it if we found an opening curly
180 // brace.
181 if (hasCurlyBraces) {
182 if (VarEnd >= AsmString.size())
183 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000184 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000185
186 // Look for a modifier string.
187 if (AsmString[VarEnd] == ':') {
188 ++VarEnd;
189 if (VarEnd >= AsmString.size())
190 throw "Reached end of string before terminating curly brace in '"
191 + CGI.TheDef->getName() + "'";
192
193 unsigned ModifierStart = VarEnd;
194 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
195 ++VarEnd;
196 Modifier = std::string(AsmString.begin()+ModifierStart,
197 AsmString.begin()+VarEnd);
198 if (Modifier.empty())
199 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
200 }
201
Nate Begemanafc54562005-07-14 22:50:30 +0000202 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000203 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000204 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000205 ++VarEnd;
206 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000207 if (VarName.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000208 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000209 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000210
211 unsigned OpNo = CGI.getOperandNamed(VarName);
Chris Lattner5765dba2005-01-22 17:40:38 +0000212 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000213
Chris Lattner29268692006-09-05 02:12:02 +0000214 // If this is a two-address instruction, verify the second operand isn't
215 // used.
Chris Lattner5765dba2005-01-22 17:40:38 +0000216 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner29268692006-09-05 02:12:02 +0000217 if (CGI.isTwoAddress && MIOp == 1)
218 throw "Should refer to operand #0 instead of #1 for two-address"
219 " instruction '" + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000220
Chris Lattnerb03b0802006-02-06 22:43:28 +0000221 if (CurVariant == Variant || CurVariant == ~0U)
Chris Lattner04cadb32006-02-06 23:40:48 +0000222 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
223 Modifier));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000224 LastEmitted = VarEnd;
225 }
226 }
227
228 AddLiteralString("\\n");
229}
230
Chris Lattnerf8766682005-01-22 19:22:23 +0000231/// MatchesAllButOneOp - If this instruction is exactly identical to the
232/// specified instruction except for one differing operand, return the differing
233/// operand number. If more than one operand mismatches, return ~1, otherwise
234/// if the instructions are identical return ~0.
235unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
236 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000237
238 unsigned MismatchOperand = ~0U;
239 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000240 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000241 if (MismatchOperand != ~0U) // Already have one mismatch?
242 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000243 else
Chris Lattner870c0162005-01-22 18:38:13 +0000244 MismatchOperand = i;
245 }
246 return MismatchOperand;
247}
248
Chris Lattner38c07512005-01-22 20:31:17 +0000249static void PrintCases(std::vector<std::pair<std::string,
250 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
251 O << " case " << OpsToPrint.back().first << ": ";
252 AsmWriterOperand TheOp = OpsToPrint.back().second;
253 OpsToPrint.pop_back();
254
255 // Check to see if any other operands are identical in this list, and if so,
256 // emit a case label for them.
257 for (unsigned i = OpsToPrint.size(); i != 0; --i)
258 if (OpsToPrint[i-1].second == TheOp) {
259 O << "\n case " << OpsToPrint[i-1].first << ": ";
260 OpsToPrint.erase(OpsToPrint.begin()+i-1);
261 }
262
263 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000264 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000265 O << "break;\n";
266}
267
Chris Lattner870c0162005-01-22 18:38:13 +0000268
269/// EmitInstructions - Emit the last instruction in the vector and any other
270/// instructions that are suitably similar to it.
271static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
272 std::ostream &O) {
273 AsmWriterInst FirstInst = Insts.back();
274 Insts.pop_back();
275
276 std::vector<AsmWriterInst> SimilarInsts;
277 unsigned DifferingOperand = ~0;
278 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000279 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
280 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000281 if (DifferingOperand == ~0U) // First match!
282 DifferingOperand = DiffOp;
283
284 // If this differs in the same operand as the rest of the instructions in
285 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000286 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000287 SimilarInsts.push_back(Insts[i-1]);
288 Insts.erase(Insts.begin()+i-1);
289 }
290 }
291 }
292
Chris Lattnera1e8a802006-05-01 17:01:17 +0000293 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000294 << FirstInst.CGI->TheDef->getName() << ":\n";
295 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000296 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000297 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
298 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
299 if (i != DifferingOperand) {
300 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000301 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000302 } else {
303 // If this is the operand that varies between all of the instructions,
304 // emit a switch for just this operand now.
305 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000306 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000307 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000308 FirstInst.CGI->TheDef->getName(),
309 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000310
Chris Lattner870c0162005-01-22 18:38:13 +0000311 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000312 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000313 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000314 AWI.CGI->TheDef->getName(),
315 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000316 }
Chris Lattner38c07512005-01-22 20:31:17 +0000317 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
318 while (!OpsToPrint.empty())
319 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000320 O << " }";
321 }
322 O << "\n";
323 }
324
325 O << " break;\n";
326}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000327
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000328void AsmWriterEmitter::
329FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000330 std::vector<unsigned> &InstIdxs,
331 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000332 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000333
334 // This vector parallels UniqueOperandCommands, keeping track of which
335 // instructions each case are used for. It is a comma separated string of
336 // enums.
337 std::vector<std::string> InstrsForCase;
338 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000339 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000340
341 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
342 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
343 if (Inst == 0) continue; // PHI, INLINEASM, etc.
344
345 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000346 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000347 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000348
Chris Lattnerb8462862006-07-18 17:56:07 +0000349 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000350
351 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000352 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000353 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000354
355 // Check to see if we already have 'Command' in UniqueOperandCommands.
356 // If not, add it.
357 bool FoundIt = false;
358 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
359 if (UniqueOperandCommands[idx] == Command) {
360 InstIdxs[i] = idx;
361 InstrsForCase[idx] += ", ";
362 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
363 FoundIt = true;
364 break;
365 }
366 if (!FoundIt) {
367 InstIdxs[i] = UniqueOperandCommands.size();
368 UniqueOperandCommands.push_back(Command);
369 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000370
371 // This command matches one operand so far.
372 InstOpsUsed.push_back(1);
373 }
374 }
375
376 // For each entry of UniqueOperandCommands, there is a set of instructions
377 // that uses it. If the next command of all instructions in the set are
378 // identical, fold it into the command.
379 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
380 CommandIdx != e; ++CommandIdx) {
381
382 for (unsigned Op = 1; ; ++Op) {
383 // Scan for the first instruction in the set.
384 std::vector<unsigned>::iterator NIT =
385 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
386 if (NIT == InstIdxs.end()) break; // No commonality.
387
388 // If this instruction has no more operands, we isn't anything to merge
389 // into this command.
390 const AsmWriterInst *FirstInst =
391 getAsmWriterInstByID(NIT-InstIdxs.begin());
392 if (!FirstInst || FirstInst->Operands.size() == Op)
393 break;
394
395 // Otherwise, scan to see if all of the other instructions in this command
396 // set share the operand.
397 bool AllSame = true;
398
Chris Lattner96c1ade2006-07-18 18:28:27 +0000399 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
400 NIT != InstIdxs.end();
401 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
402 // Okay, found another instruction in this command set. If the operand
403 // matches, we're ok, otherwise bail out.
404 const AsmWriterInst *OtherInst =
405 getAsmWriterInstByID(NIT-InstIdxs.begin());
406 if (!OtherInst || OtherInst->Operands.size() == Op ||
407 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
408 AllSame = false;
409 break;
410 }
411 }
412 if (!AllSame) break;
413
414 // Okay, everything in this command set has the same next operand. Add it
415 // to UniqueOperandCommands and remember that it was consumed.
416 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
417
418 // If this is the last operand, emit a return after the code.
419 if (FirstInst->Operands.size() == Op+1)
420 Command += " return true;\n";
421
422 UniqueOperandCommands[CommandIdx] += Command;
423 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000424 }
425 }
426
427 // Prepend some of the instructions each case is used for onto the case val.
428 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
429 std::string Instrs = InstrsForCase[i];
430 if (Instrs.size() > 70) {
431 Instrs.erase(Instrs.begin()+70, Instrs.end());
432 Instrs += "...";
433 }
434
435 if (!Instrs.empty())
436 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
437 UniqueOperandCommands[i];
438 }
439}
440
441
442
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000443void AsmWriterEmitter::run(std::ostream &O) {
444 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
445
446 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000447 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000448 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
449 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000450
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000451 O <<
452 "/// printInstruction - This method is automatically generated by tablegen\n"
453 "/// from the instruction set description. This method returns true if the\n"
454 "/// machine instruction was sufficiently described to print it, otherwise\n"
455 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000456 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000457 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000458
Chris Lattner5765dba2005-01-22 17:40:38 +0000459 std::vector<AsmWriterInst> Instructions;
460
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000461 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
462 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000463 if (!I->second.AsmString.empty())
464 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000465
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000466 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000467 Target.getInstructionsByEnumValue(NumberedInstructions);
468
Chris Lattner6af022f2006-07-14 22:59:11 +0000469 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
470 // all machine instructions are necessarily being printed, so there may be
471 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000472 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
473 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000474
Chris Lattner6af022f2006-07-14 22:59:11 +0000475 // Build an aggregate string, and build a table of offsets into it.
476 std::map<std::string, unsigned> StringOffset;
477 std::string AggregateString;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000478 AggregateString += "\0\0";
Chris Lattner6af022f2006-07-14 22:59:11 +0000479
Chris Lattner55616402006-07-18 17:32:27 +0000480 /// OpcodeInfo - Theis encodes the index of the string to use for the first
481 /// chunk of the output as well as indices used for operand printing.
482 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000483
Chris Lattner55616402006-07-18 17:32:27 +0000484 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000485 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
486 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
487 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000488 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000489 // Something not handled by the asmwriter printer.
490 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000491 } else if (AWI->Operands[0].OperandType !=
492 AsmWriterOperand::isLiteralTextOperand ||
493 AWI->Operands[0].Str.empty()) {
494 // Something handled by the asmwriter printer, but with no leading string.
495 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000496 } else {
497 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
498 if (Entry == 0) {
499 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000500 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000501 std::string Str = AWI->Operands[0].Str;
502 UnescapeString(Str);
503 AggregateString += Str;
504 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000505 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000506 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000507
508 // Nuke the string from the operand list. It is now handled!
509 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000510 }
Chris Lattner55616402006-07-18 17:32:27 +0000511 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000512 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000513
Chris Lattner55616402006-07-18 17:32:27 +0000514 // Figure out how many bits we used for the string index.
515 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
516
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000517 // To reduce code size, we compactify common instructions into a few bits
518 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000519 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000520
521 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
522
Chris Lattnerb8462862006-07-18 17:56:07 +0000523 bool isFirst = true;
524 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000525 std::vector<std::string> UniqueOperandCommands;
526
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000527 // For the first operand check, add a default value for instructions with
528 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000529 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000530 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000531 isFirst = false;
532 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000533
534 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000535 std::vector<unsigned> NumInstOpsHandled;
536 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
537 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000538
539 // If we ran out of operands to print, we're done.
540 if (UniqueOperandCommands.empty()) break;
541
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000542 // Compute the number of bits we need to represent these cases, this is
543 // ceil(log2(numentries)).
544 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
545
546 // If we don't have enough bits for this operand, don't include it.
547 if (NumBits > BitsLeft) {
548 DEBUG(std::cerr << "Not enough bits to densely encode " << NumBits
549 << " more bits\n");
550 break;
551 }
552
553 // Otherwise, we can include this in the initial lookup table. Add it in.
554 BitsLeft -= NumBits;
555 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000556 if (InstIdxs[i] != ~0U)
557 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000558
Chris Lattnerb8462862006-07-18 17:56:07 +0000559 // Remove the info about this operand.
560 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
561 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000562 if (!Inst->Operands.empty()) {
563 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000564 assert(NumOps <= Inst->Operands.size() &&
565 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000566 Inst->Operands.erase(Inst->Operands.begin(),
567 Inst->Operands.begin()+NumOps);
568 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000569 }
570
571 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000572 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
573 }
574
575
576
Chris Lattner55616402006-07-18 17:32:27 +0000577 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000578 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000579 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000580 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000581 }
582 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000583 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000584 O << " };\n\n";
585
586 // Emit the string itself.
587 O << " const char *AsmStrs = \n \"";
588 unsigned CharsPrinted = 0;
589 EscapeString(AggregateString);
590 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
591 if (CharsPrinted > 70) {
592 O << "\"\n \"";
593 CharsPrinted = 0;
594 }
595 O << AggregateString[i];
596 ++CharsPrinted;
597
598 // Print escape sequences all together.
599 if (AggregateString[i] == '\\') {
600 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
601 if (isdigit(AggregateString[i+1])) {
602 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
603 "Expected 3 digit octal escape!");
604 O << AggregateString[++i];
605 O << AggregateString[++i];
606 O << AggregateString[++i];
607 CharsPrinted += 3;
608 } else {
609 O << AggregateString[++i];
610 ++CharsPrinted;
611 }
612 }
613 }
614 O << "\";\n\n";
615
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000616 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
617 << " printInlineAsm(MI);\n"
618 << " return true;\n"
619 << " }\n\n";
620
Chris Lattner6af022f2006-07-14 22:59:11 +0000621 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000622 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000623 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000624 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000625
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000626 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000627 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000628 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
629 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
630
631 // Compute the number of bits we need to represent these cases, this is
632 // ceil(log2(numentries)).
633 unsigned NumBits = Log2_32_Ceil(Commands.size());
634 assert(NumBits <= BitsLeft && "consistency error");
635
636 // Emit code to extract this field from Bits.
637 BitsLeft -= NumBits;
638
639 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000640 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000641
Chris Lattner96c1ade2006-07-18 18:28:27 +0000642 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000643 // Emit two possibilitys with if/else.
644 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
645 << ((1 << NumBits)-1) << ") {\n"
646 << Commands[1]
647 << " } else {\n"
648 << Commands[0]
649 << " }\n\n";
650 } else {
651 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
652 << ((1 << NumBits)-1) << ") {\n"
653 << " default: // unreachable.\n";
654
655 // Print out all the cases.
656 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
657 O << " case " << i << ":\n";
658 O << Commands[i];
659 O << " break;\n";
660 }
661 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000662 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000663 }
664
Chris Lattnerb8462862006-07-18 17:56:07 +0000665 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000666 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
667 // Entire instruction has been emitted?
668 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000669 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000670 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000671 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000672 }
673 }
674
675
676 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000677 // elements in the vector.
678 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000679
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000680 if (!Instructions.empty()) {
681 // Find the opcode # of inline asm.
682 O << " switch (MI->getOpcode()) {\n";
683 while (!Instructions.empty())
684 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000685
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000686 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000687 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000688 }
689
Chris Lattner0a012122006-07-18 19:06:01 +0000690 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000691}