blob: 6cddc6d5b84f56b0702136ef775cc9f0f3608b31 [file] [log] [blame]
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
11// assembly operands in the MCInst structures.
12//
Daniel Dunbar20927f22009-08-07 08:26:05 +000013// The input to the target specific matcher is a list of literal tokens and
14// operands. The target specific parser should generally eliminate any syntax
15// which is not relevant for matching; for example, comma tokens should have
16// already been consumed and eliminated by the parser. Most instructions will
17// end up with a single literal token (the instruction name) and some number of
18// operands.
19//
20// Some example inputs, for X86:
21// 'addl' (immediate ...) (register ...)
22// 'add' (immediate ...) (memory ...)
Jim Grosbacha7c78222010-10-29 22:13:48 +000023// 'call' '*' %epc
Daniel Dunbar20927f22009-08-07 08:26:05 +000024//
25// The assembly matcher is responsible for converting this input into a precise
26// machine instruction (i.e., an instruction with a well defined encoding). This
27// mapping has several properties which complicate matching:
28//
29// - It may be ambiguous; many architectures can legally encode particular
30// variants of an instruction in different ways (for example, using a smaller
31// encoding for small immediates). Such ambiguities should never be
32// arbitrarily resolved by the assembler, the assembler is always responsible
33// for choosing the "best" available instruction.
34//
35// - It may depend on the subtarget or the assembler context. Instructions
36// which are invalid for the current mode, but otherwise unambiguous (e.g.,
37// an SSE instruction in a file being assembled for i486) should be accepted
38// and rejected by the assembler front end. However, if the proper encoding
39// for an instruction is dependent on the assembler context then the matcher
40// is responsible for selecting the correct machine instruction for the
41// current mode.
42//
43// The core matching algorithm attempts to exploit the regularity in most
44// instruction sets to quickly determine the set of possibly matching
45// instructions, and the simplify the generated code. Additionally, this helps
46// to ensure that the ambiguities are intentionally resolved by the user.
47//
48// The matching is divided into two distinct phases:
49//
50// 1. Classification: Each operand is mapped to the unique set which (a)
51// contains it, and (b) is the largest such subset for which a single
52// instruction could match all members.
53//
54// For register classes, we can generate these subgroups automatically. For
55// arbitrary operands, we expect the user to define the classes and their
56// relations to one another (for example, 8-bit signed immediates as a
57// subset of 32-bit immediates).
58//
59// By partitioning the operands in this way, we guarantee that for any
60// tuple of classes, any single instruction must match either all or none
61// of the sets of operands which could classify to that tuple.
62//
63// In addition, the subset relation amongst classes induces a partial order
64// on such tuples, which we use to resolve ambiguities.
65//
66// FIXME: What do we do if a crazy case shows up where this is the wrong
67// resolution?
68//
69// 2. The input can now be treated as a tuple of classes (static tokens are
70// simple singleton sets). Each such tuple should generally map to a single
71// instruction (we currently ignore cases where this isn't true, whee!!!),
72// which we can emit a simple matcher for.
73//
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Chris Lattner5845e5c2010-09-06 02:01:51 +000079#include "StringMatcher.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000080#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000081#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000082#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000083#include "llvm/ADT/StringExtras.h"
84#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000085#include "llvm/Support/Debug.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000086#include <list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +000087#include <map>
88#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000089using namespace llvm;
90
Daniel Dunbar27249152009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +000094
Daniel Dunbara027d222009-07-31 02:32:59 +000095/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbacha7c78222010-10-29 22:13:48 +000096static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbara027d222009-07-31 02:32:59 +000097 SmallVectorImpl<StringRef> &Tokens) {
98 unsigned Prev = 0;
99 bool InTok = true;
100 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
101 switch (AsmString[i]) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000102 case '[':
103 case ']':
Daniel Dunbara027d222009-07-31 02:32:59 +0000104 case '*':
105 case '!':
106 case ' ':
107 case '\t':
108 case ',':
109 if (InTok) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000110 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara027d222009-07-31 02:32:59 +0000111 InTok = false;
112 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000113 if (!isspace(AsmString[i]) && AsmString[i] != ',')
114 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara027d222009-07-31 02:32:59 +0000115 Prev = i + 1;
116 break;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000117
Daniel Dunbar20927f22009-08-07 08:26:05 +0000118 case '\\':
119 if (InTok) {
120 Tokens.push_back(AsmString.slice(Prev, i));
121 InTok = false;
122 }
123 ++i;
124 assert(i != AsmString.size() && "Invalid quoted character");
125 Tokens.push_back(AsmString.substr(i, 1));
126 Prev = i + 1;
127 break;
128
129 case '$': {
130 // If this isn't "${", treat like a normal token.
131 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
132 if (InTok) {
133 Tokens.push_back(AsmString.slice(Prev, i));
134 InTok = false;
135 }
136 Prev = i;
137 break;
138 }
139
140 if (InTok) {
141 Tokens.push_back(AsmString.slice(Prev, i));
142 InTok = false;
143 }
144
145 StringRef::iterator End =
146 std::find(AsmString.begin() + i, AsmString.end(), '}');
147 assert(End != AsmString.end() && "Missing brace in operand reference!");
148 size_t EndPos = End - AsmString.begin();
149 Tokens.push_back(AsmString.slice(i, EndPos+1));
150 Prev = EndPos + 1;
151 i = EndPos;
152 break;
153 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000154
Daniel Dunbar4d39b672010-08-11 06:36:59 +0000155 case '.':
156 if (InTok) {
157 Tokens.push_back(AsmString.slice(Prev, i));
158 }
159 Prev = i;
160 InTok = true;
161 break;
162
Daniel Dunbara027d222009-07-31 02:32:59 +0000163 default:
164 InTok = true;
165 }
166 }
167 if (InTok && Prev != AsmString.size())
Daniel Dunbar20927f22009-08-07 08:26:05 +0000168 Tokens.push_back(AsmString.substr(Prev));
169}
170
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000171static bool IsAssemblerInstruction(StringRef Name,
Jim Grosbacha7c78222010-10-29 22:13:48 +0000172 const CodeGenInstruction &CGI,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000173 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000174 // Ignore "codegen only" instructions.
175 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
176 return false;
177
Daniel Dunbar72fa87f2009-08-09 08:19:00 +0000178 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
179 //
180 // FIXME: This is a total hack.
181 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
182 return false;
183
Chris Lattner4d1189f2010-11-01 00:46:16 +0000184 // Reject instructions with no .s string.
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000185 if (CGI.AsmString.empty()) {
186 PrintError(CGI.TheDef->getLoc(),
187 "instruction with empty asm string");
188 throw std::string("ERROR: Invalid instruction for asm matcher");
189 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000190
Chris Lattner4d1189f2010-11-01 00:46:16 +0000191 // Reject any instructions with a newline in them, they should be marked
192 // isCodeGenOnly if they are pseudo instructions.
193 if (CGI.AsmString.find('\n') != std::string::npos) {
194 PrintError(CGI.TheDef->getLoc(),
195 "multiline instruction is not valid for the asmparser, "
196 "mark it isCodeGenOnly");
197 throw std::string("ERROR: Invalid instruction");
198 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000199
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000200 // Reject instructions with attributes, these aren't something we can handle,
201 // the target should be refactored to use operands instead of modifiers.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000202 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000203 // Also, check for instructions which reference the operand multiple times;
204 // this implies a constraint we would not honor.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000205 std::set<std::string> OperandNames;
206 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
Chris Lattner8b2f0822010-10-31 19:05:32 +0000207 if (Tokens[i][0] == '$' &&
Chris Lattner39ee0362010-10-31 19:10:56 +0000208 Tokens[i].find(':') != StringRef::npos) {
209 PrintError(CGI.TheDef->getLoc(),
210 "instruction with operand modifier '" + Tokens[i].str() +
211 "' not supported by asm matcher. Mark isCodeGenOnly!");
212 throw std::string("ERROR: Invalid instruction");
Chris Lattner8b2f0822010-10-31 19:05:32 +0000213 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000214
Chris Lattner52de0ef2010-11-01 00:51:32 +0000215 // FIXME: Should reject these. The ARM backend hits this with $lane in a
216 // bunch of instructions. It is unclear what the right answer is for this.
Chris Lattner8b2f0822010-10-31 19:05:32 +0000217 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
218 DEBUG({
Chris Lattner39ee0362010-10-31 19:10:56 +0000219 errs() << "warning: '" << Name << "': "
220 << "ignoring instruction with tied operand '"
221 << Tokens[i].str() << "'\n";
222 });
Chris Lattner8b2f0822010-10-31 19:05:32 +0000223 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000224 }
225 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000226
Daniel Dunbar20927f22009-08-07 08:26:05 +0000227 return true;
228}
229
230namespace {
231
Daniel Dunbar54074b52010-07-19 05:44:09 +0000232struct SubtargetFeatureInfo;
233
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000234/// ClassInfo - Helper class for storing the information about a particular
235/// class of operands which can be matched.
236struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000237 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000238 /// Invalid kind, for use as a sentinel value.
239 Invalid = 0,
240
241 /// The class for a particular token.
242 Token,
243
244 /// The (first) register class, subsequent register classes are
245 /// RegisterClass0+1, and so on.
246 RegisterClass0,
247
248 /// The (first) user defined class, subsequent user defined classes are
249 /// UserClass0+1, and so on.
250 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000251 };
252
253 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
254 /// N) for the Nth user defined class.
255 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000256
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000257 /// SuperClasses - The super classes of this class. Note that for simplicities
258 /// sake user operands only record their immediate super class, while register
259 /// operands include all superclasses.
260 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000261
Daniel Dunbar6745d422009-08-09 05:18:30 +0000262 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000263 std::string Name;
264
Daniel Dunbar6745d422009-08-09 05:18:30 +0000265 /// ClassName - The unadorned generic name for this class (e.g., Token).
266 std::string ClassName;
267
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000268 /// ValueName - The name of the value this class represents; for a token this
269 /// is the literal token string, for an operand it is the TableGen class (or
270 /// empty if this is a derived class).
271 std::string ValueName;
272
273 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000274 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000275 std::string PredicateMethod;
276
277 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000278 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000279 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000280
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000281 /// For register classes, the records for all the registers in this class.
282 std::set<Record*> Registers;
283
284public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000285 /// isRegisterClass() - Check if this is a register class.
286 bool isRegisterClass() const {
287 return Kind >= RegisterClass0 && Kind < UserClass0;
288 }
289
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000290 /// isUserClass() - Check if this is a user defined class.
291 bool isUserClass() const {
292 return Kind >= UserClass0;
293 }
294
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000295 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
296 /// are related if they are in the same class hierarchy.
297 bool isRelatedTo(const ClassInfo &RHS) const {
298 // Tokens are only related to tokens.
299 if (Kind == Token || RHS.Kind == Token)
300 return Kind == Token && RHS.Kind == Token;
301
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000302 // Registers classes are only related to registers classes, and only if
303 // their intersection is non-empty.
304 if (isRegisterClass() || RHS.isRegisterClass()) {
305 if (!isRegisterClass() || !RHS.isRegisterClass())
306 return false;
307
308 std::set<Record*> Tmp;
309 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000310 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000311 RHS.Registers.begin(), RHS.Registers.end(),
312 II);
313
314 return !Tmp.empty();
315 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000316
317 // Otherwise we have two users operands; they are related if they are in the
318 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000319 //
320 // FIXME: This is an oversimplification, they should only be related if they
321 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000322 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
323 const ClassInfo *Root = this;
324 while (!Root->SuperClasses.empty())
325 Root = Root->SuperClasses.front();
326
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000327 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000328 while (!RHSRoot->SuperClasses.empty())
329 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000330
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000331 return Root == RHSRoot;
332 }
333
Jim Grosbacha7c78222010-10-29 22:13:48 +0000334 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000335 bool isSubsetOf(const ClassInfo &RHS) const {
336 // This is a subset of RHS if it is the same class...
337 if (this == &RHS)
338 return true;
339
340 // ... or if any of its super classes are a subset of RHS.
341 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
342 ie = SuperClasses.end(); it != ie; ++it)
343 if ((*it)->isSubsetOf(RHS))
344 return true;
345
346 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000347 }
348
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000349 /// operator< - Compare two classes.
350 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000351 if (this == &RHS)
352 return false;
353
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000354 // Unrelated classes can be ordered by kind.
355 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000356 return Kind < RHS.Kind;
357
358 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000359 case Invalid:
360 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000361 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000362 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000363 //
364 // FIXME: Compare by enum value.
365 return ValueName < RHS.ValueName;
366
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000367 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000368 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000369 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000370 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000371 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000372 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000373
374 // Otherwise, order by name to ensure we have a total ordering.
375 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000376 }
377 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000378};
379
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000380/// InstructionInfo - Helper class for storing the necessary information for an
381/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000382struct InstructionInfo {
383 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000384 /// The unique class instance this operand should match.
385 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000386
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000387 /// The original operand this corresponds to, if any.
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000388 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000389 };
390
391 /// InstrName - The target name for this instruction.
392 std::string InstrName;
393
394 /// Instr - The instruction this matches.
395 const CodeGenInstruction *Instr;
396
397 /// AsmString - The assembly string for this instruction (with variants
398 /// removed).
399 std::string AsmString;
400
401 /// Tokens - The tokenized assembly pattern that this instruction matches.
402 SmallVector<StringRef, 4> Tokens;
403
404 /// Operands - The operands that this instruction matches.
405 SmallVector<Operand, 4> Operands;
406
Daniel Dunbar54074b52010-07-19 05:44:09 +0000407 /// Predicates - The required subtarget features to match this instruction.
408 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
409
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000410 /// ConversionFnKind - The enum value which is passed to the generated
411 /// ConvertToMCInst to convert parsed operands into an MCInst for this
412 /// function.
413 std::string ConversionFnKind;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000414
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000415 /// operator< - Compare two instructions.
416 bool operator<(const InstructionInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000417 // The primary comparator is the instruction mnemonic.
418 if (Tokens[0] != RHS.Tokens[0])
419 return Tokens[0] < RHS.Tokens[0];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000420
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000421 if (Operands.size() != RHS.Operands.size())
422 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000423
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000424 // Compare lexicographically by operand. The matcher validates that other
425 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
426 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000427 if (*Operands[i].Class < *RHS.Operands[i].Class)
428 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000429 if (*RHS.Operands[i].Class < *Operands[i].Class)
430 return false;
431 }
432
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000433 return false;
434 }
435
Daniel Dunbar2b544812009-08-09 06:05:33 +0000436 /// CouldMatchAmiguouslyWith - Check whether this instruction could
437 /// ambiguously match the same set of operands as \arg RHS (without being a
438 /// strictly superior match).
439 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
440 // The number of operands is unambiguous.
441 if (Operands.size() != RHS.Operands.size())
442 return false;
443
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000444 // Otherwise, make sure the ordering of the two instructions is unambiguous
445 // by checking that either (a) a token or operand kind discriminates them,
446 // or (b) the ordering among equivalent kinds is consistent.
447
Daniel Dunbar2b544812009-08-09 06:05:33 +0000448 // Tokens and operand kinds are unambiguous (assuming a correct target
449 // specific parser).
450 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
451 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
452 Operands[i].Class->Kind == ClassInfo::Token)
453 if (*Operands[i].Class < *RHS.Operands[i].Class ||
454 *RHS.Operands[i].Class < *Operands[i].Class)
455 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000456
Daniel Dunbar2b544812009-08-09 06:05:33 +0000457 // Otherwise, this operand could commute if all operands are equivalent, or
458 // there is a pair of operands that compare less than and a pair that
459 // compare greater than.
460 bool HasLT = false, HasGT = false;
461 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
462 if (*Operands[i].Class < *RHS.Operands[i].Class)
463 HasLT = true;
464 if (*RHS.Operands[i].Class < *Operands[i].Class)
465 HasGT = true;
466 }
467
468 return !(HasLT ^ HasGT);
469 }
470
Daniel Dunbar20927f22009-08-07 08:26:05 +0000471 void dump();
472};
473
Daniel Dunbar54074b52010-07-19 05:44:09 +0000474/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
475/// feature which participates in instruction matching.
476struct SubtargetFeatureInfo {
477 /// \brief The predicate record for this feature.
478 Record *TheDef;
479
480 /// \brief An unique index assigned to represent this feature.
481 unsigned Index;
482
Chris Lattner0aed1e72010-10-30 20:07:57 +0000483 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
484
Daniel Dunbar54074b52010-07-19 05:44:09 +0000485 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000486 std::string getEnumName() const {
487 return "Feature_" + TheDef->getName();
488 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000489};
490
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000491class AsmMatcherInfo {
492public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000493 /// The tablegen AsmParser record.
494 Record *AsmParser;
495
496 /// The AsmParser "CommentDelimiter" value.
497 std::string CommentDelimiter;
498
499 /// The AsmParser "RegisterPrefix" value.
500 std::string RegisterPrefix;
501
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000502 /// The classes which are needed for matching.
503 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000504
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000505 /// The information on the instruction to match.
506 std::vector<InstructionInfo*> Instructions;
507
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000508 /// Map of Register records to their class information.
509 std::map<Record*, ClassInfo*> RegisterClasses;
510
Daniel Dunbar54074b52010-07-19 05:44:09 +0000511 /// Map of Predicate records to their subtarget information.
512 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner6fa152c2010-10-30 20:15:02 +0000513
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000514private:
515 /// Map of token to class information which has already been constructed.
516 std::map<std::string, ClassInfo*> TokenClasses;
517
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000518 /// Map of RegisterClass records to their class information.
519 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000520
Daniel Dunbar338825c2009-08-10 18:41:10 +0000521 /// Map of AsmOperandClass records to their class information.
522 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000523
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000524private:
525 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000526 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000527
528 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000529 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000530 const CodeGenInstruction::OperandInfo &OI);
531
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000532 /// BuildRegisterClasses - Build the ClassInfo* instances for register
533 /// classes.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000534 void BuildRegisterClasses(CodeGenTarget &Target,
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000535 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000536
537 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
538 /// operand classes.
539 void BuildOperandClasses(CodeGenTarget &Target);
540
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000541public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000542 AsmMatcherInfo(Record *_AsmParser);
543
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000544 /// BuildInfo - Construct the various tables used during matching.
545 void BuildInfo(CodeGenTarget &Target);
Chris Lattner6fa152c2010-10-30 20:15:02 +0000546
547 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
548 /// given operand.
549 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
550 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
551 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
552 SubtargetFeatures.find(Def);
553 return I == SubtargetFeatures.end() ? 0 : I->second;
554 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000555};
556
Daniel Dunbar20927f22009-08-07 08:26:05 +0000557}
558
559void InstructionInfo::dump() {
560 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
561 << ", tokens:[";
562 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
563 errs() << Tokens[i];
564 if (i + 1 != e)
565 errs() << ", ";
566 }
567 errs() << "]\n";
568
569 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
570 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000571 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000572 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000573 errs() << '\"' << Tokens[i] << "\"\n";
574 continue;
575 }
576
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000577 if (!Op.OperandInfo) {
578 errs() << "(singleton register)\n";
579 continue;
580 }
581
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000582 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000583 errs() << OI.Name << " " << OI.Rec->getName()
584 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
585 }
586}
587
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000588static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000589 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000590
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000591 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
592 switch (*it) {
593 case '*': Res += "_STAR_"; break;
594 case '%': Res += "_PCT_"; break;
595 case ':': Res += "_COLON_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000596 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000597 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000598 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000599 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000600 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000601 }
602 }
603
604 return Res;
605}
606
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000607/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000608static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000609 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
610 const CodeGenRegister &Reg = Target.getRegisters()[i];
611 if (Name == Reg.TheDef->getValueAsString("AsmName"))
612 return Reg.TheDef;
613 }
614
615 return 0;
616}
617
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000618ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000619 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000620
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000621 if (!Entry) {
622 Entry = new ClassInfo();
623 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000624 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000625 Entry->Name = "MCK_" + getEnumNameForToken(Token);
626 Entry->ValueName = Token;
627 Entry->PredicateMethod = "<invalid>";
628 Entry->RenderMethod = "<invalid>";
629 Classes.push_back(Entry);
630 }
631
632 return Entry;
633}
634
635ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000636AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000637 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000638 if (OI.Rec->isSubClassOf("RegisterClass")) {
639 ClassInfo *CI = RegisterClassClasses[OI.Rec];
640
641 if (!CI) {
642 PrintError(OI.Rec->getLoc(), "register class has no class info!");
643 throw std::string("ERROR: Missing register class!");
644 }
645
646 return CI;
647 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000648
Daniel Dunbar338825c2009-08-10 18:41:10 +0000649 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
650 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
651 ClassInfo *CI = AsmOperandClasses[MatchClass];
652
653 if (!CI) {
654 PrintError(OI.Rec->getLoc(), "operand has no match class!");
655 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000656 }
657
Daniel Dunbar338825c2009-08-10 18:41:10 +0000658 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000659}
660
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000661void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
662 std::set<std::string>
663 &SingletonRegisterNames) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000664 std::vector<CodeGenRegisterClass> RegisterClasses;
665 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000666
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000667 RegisterClasses = Target.getRegisterClasses();
668 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000669
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000670 // The register sets used for matching.
671 std::set< std::set<Record*> > RegisterSets;
672
Jim Grosbacha7c78222010-10-29 22:13:48 +0000673 // Gather the defined sets.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000674 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
675 ie = RegisterClasses.end(); it != ie; ++it)
676 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
677 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000678
679 // Add any required singleton sets.
680 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
681 ie = SingletonRegisterNames.end(); it != ie; ++it)
682 if (Record *Rec = getRegisterRecord(Target, *it))
683 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
Jim Grosbacha7c78222010-10-29 22:13:48 +0000684
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000685 // Introduce derived sets where necessary (when a register does not determine
686 // a unique register set class), and build the mapping of registers to the set
687 // they should classify to.
688 std::map<Record*, std::set<Record*> > RegisterMap;
689 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
690 ie = Registers.end(); it != ie; ++it) {
691 CodeGenRegister &CGR = *it;
692 // Compute the intersection of all sets containing this register.
693 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000694
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000695 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
696 ie = RegisterSets.end(); it != ie; ++it) {
697 if (!it->count(CGR.TheDef))
698 continue;
699
700 if (ContainingSet.empty()) {
701 ContainingSet = *it;
702 } else {
703 std::set<Record*> Tmp;
704 std::swap(Tmp, ContainingSet);
705 std::insert_iterator< std::set<Record*> > II(ContainingSet,
706 ContainingSet.begin());
707 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
708 II);
709 }
710 }
711
712 if (!ContainingSet.empty()) {
713 RegisterSets.insert(ContainingSet);
714 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
715 }
716 }
717
718 // Construct the register classes.
719 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
720 unsigned Index = 0;
721 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
722 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
723 ClassInfo *CI = new ClassInfo();
724 CI->Kind = ClassInfo::RegisterClass0 + Index;
725 CI->ClassName = "Reg" + utostr(Index);
726 CI->Name = "MCK_Reg" + utostr(Index);
727 CI->ValueName = "";
728 CI->PredicateMethod = ""; // unused
729 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000730 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000731 Classes.push_back(CI);
732 RegisterSetClasses.insert(std::make_pair(*it, CI));
733 }
734
735 // Find the superclasses; we could compute only the subgroup lattice edges,
736 // but there isn't really a point.
737 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
738 ie = RegisterSets.end(); it != ie; ++it) {
739 ClassInfo *CI = RegisterSetClasses[*it];
740 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
741 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000742 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000743 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
744 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
745 }
746
747 // Name the register classes which correspond to a user defined RegisterClass.
748 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
749 ie = RegisterClasses.end(); it != ie; ++it) {
750 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
751 it->Elements.end())];
752 if (CI->ValueName.empty()) {
753 CI->ClassName = it->getName();
754 CI->Name = "MCK_" + it->getName();
755 CI->ValueName = it->getName();
756 } else
757 CI->ValueName = CI->ValueName + "," + it->getName();
758
759 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
760 }
761
762 // Populate the map for individual registers.
763 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
764 ie = RegisterMap.end(); it != ie; ++it)
765 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000766
767 // Name the register classes which correspond to singleton registers.
768 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
769 ie = SingletonRegisterNames.end(); it != ie; ++it) {
770 if (Record *Rec = getRegisterRecord(Target, *it)) {
771 ClassInfo *CI = this->RegisterClasses[Rec];
772 assert(CI && "Missing singleton register class info!");
773
774 if (CI->ValueName.empty()) {
775 CI->ClassName = Rec->getName();
776 CI->Name = "MCK_" + Rec->getName();
777 CI->ValueName = Rec->getName();
778 } else
779 CI->ValueName = CI->ValueName + "," + Rec->getName();
780 }
781 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000782}
783
784void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000785 std::vector<Record*> AsmOperands;
786 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000787
788 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000789 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000790 ie = AsmOperands.end(); it != ie; ++it)
791 AsmOperandClasses[*it] = new ClassInfo();
792
Daniel Dunbar338825c2009-08-10 18:41:10 +0000793 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000794 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +0000795 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000796 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000797 CI->Kind = ClassInfo::UserClass0 + Index;
798
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000799 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
800 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
801 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
802 if (!DI) {
803 PrintError((*it)->getLoc(), "Invalid super class reference!");
804 continue;
805 }
806
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000807 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
808 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000809 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000810 else
811 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000812 }
813 CI->ClassName = (*it)->getValueAsString("Name");
814 CI->Name = "MCK_" + CI->ClassName;
815 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000816
817 // Get or construct the predicate method name.
818 Init *PMName = (*it)->getValueInit("PredicateMethod");
819 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
820 CI->PredicateMethod = SI->getValue();
821 } else {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000822 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000823 "Unexpected PredicateMethod field!");
824 CI->PredicateMethod = "is" + CI->ClassName;
825 }
826
827 // Get or construct the render method name.
828 Init *RMName = (*it)->getValueInit("RenderMethod");
829 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
830 CI->RenderMethod = SI->getValue();
831 } else {
832 assert(dynamic_cast<UnsetInit*>(RMName) &&
833 "Unexpected RenderMethod field!");
834 CI->RenderMethod = "add" + CI->ClassName + "Operands";
835 }
836
Daniel Dunbar338825c2009-08-10 18:41:10 +0000837 AsmOperandClasses[*it] = CI;
838 Classes.push_back(CI);
839 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000840}
841
Chris Lattner0aed1e72010-10-30 20:07:57 +0000842AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
843 : AsmParser(asmParser),
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000844 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
845 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
846{
847}
848
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000849void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Chris Lattner0aed1e72010-10-30 20:07:57 +0000850 // Build information about all of the AssemblerPredicates.
851 std::vector<Record*> AllPredicates =
852 Records.getAllDerivedDefinitions("Predicate");
853 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
854 Record *Pred = AllPredicates[i];
855 // Ignore predicates that are not intended for the assembler.
856 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
857 continue;
858
859 if (Pred->getName().empty()) {
860 PrintError(Pred->getLoc(), "Predicate has no name!");
861 throw std::string("ERROR: Predicate defs must be named");
862 }
863
864 unsigned FeatureNo = SubtargetFeatures.size();
865 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
866 assert(FeatureNo < 32 && "Too many subtarget features!");
867 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000868
Chris Lattner39ee0362010-10-31 19:10:56 +0000869 // Parse the instructions; we need to do this first so that we can gather the
870 // singleton register classes.
871 std::set<std::string> SingletonRegisterNames;
872 const std::vector<const CodeGenInstruction*> &InstrList =
873 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000874 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
875 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbar20927f22009-08-07 08:26:05 +0000876
Chris Lattner39ee0362010-10-31 19:10:56 +0000877 // If the tblgen -match-prefix option is specified (for tblgen hackers),
878 // filter the set of instructions we consider.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000879 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000880 continue;
881
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000882 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000883
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000884 II->InstrName = CGI.TheDef->getName();
885 II->Instr = &CGI;
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000886 // TODO: Eventually support asmparser for Variant != 0.
887 II->AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, 0);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000888
Chris Lattner39ee0362010-10-31 19:10:56 +0000889 // Remove comments from the asm string. We know that the asmstring only
890 // has one line.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000891 if (!CommentDelimiter.empty()) {
892 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
893 if (Idx != StringRef::npos)
894 II->AsmString = II->AsmString.substr(0, Idx);
895 }
896
Daniel Dunbar20927f22009-08-07 08:26:05 +0000897 TokenizeAsmString(II->AsmString, II->Tokens);
898
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000899 // Ignore instructions which shouldn't be matched and diagnose invalid
900 // instruction definitions with an error.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000901 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000902 continue;
Chris Lattner39ee0362010-10-31 19:10:56 +0000903
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000904 // Collect singleton registers, if used.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000905 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
906 if (!II->Tokens[i].startswith(RegisterPrefix))
907 continue;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000908
Chris Lattner4e692ab2010-10-28 21:28:42 +0000909 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
910 Record *Rec = getRegisterRecord(Target, RegName);
Jim Grosbacha7c78222010-10-29 22:13:48 +0000911
Chris Lattner4e692ab2010-10-28 21:28:42 +0000912 if (!Rec) {
913 // If there is no register prefix (i.e. "%" in "%eax"), then this may
914 // be some random non-register token, just ignore it.
915 if (RegisterPrefix.empty())
916 continue;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000917
918 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner4e692ab2010-10-28 21:28:42 +0000919 "' (which matches register prefix)";
920 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000921 }
Chris Lattner4e692ab2010-10-28 21:28:42 +0000922
923 SingletonRegisterNames.insert(RegName);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000924 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000925
926 // Compute the require features.
Chris Lattner0f899c72010-10-30 19:38:20 +0000927 std::vector<Record*> Predicates =
928 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner6fa152c2010-10-30 20:15:02 +0000929 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
930 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
931 II->RequiredFeatures.push_back(Feature);
Daniel Dunbar54074b52010-07-19 05:44:09 +0000932
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000933 Instructions.push_back(II.take());
934 }
935
936 // Build info for the register classes.
937 BuildRegisterClasses(Target, SingletonRegisterNames);
938
939 // Build info for the user defined assembly operand classes.
940 BuildOperandClasses(Target);
941
942 // Build the instruction information.
943 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
944 ie = Instructions.end(); it != ie; ++it) {
945 InstructionInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000946
Chris Lattnere206fcf2010-09-06 21:01:37 +0000947 // The first token of the instruction is the mnemonic, which must be a
948 // simple string.
949 assert(!II->Tokens.empty() && "Instruction has no tokens?");
950 StringRef Mnemonic = II->Tokens[0];
951 assert(Mnemonic[0] != '$' &&
952 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
Jim Grosbacha7c78222010-10-29 22:13:48 +0000953
Chris Lattnere206fcf2010-09-06 21:01:37 +0000954 // Parse the tokens after the mnemonic.
955 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000956 StringRef Token = II->Tokens[i];
957
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000958 // Check for singleton registers.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000959 if (Token.startswith(RegisterPrefix)) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000960 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
Chris Lattner4e692ab2010-10-28 21:28:42 +0000961 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
962 InstructionInfo::Operand Op;
963 Op.Class = RegisterClasses[RegRecord];
964 Op.OperandInfo = 0;
965 assert(Op.Class && Op.Class->Registers.size() == 1 &&
966 "Unexpected class for singleton register");
967 II->Operands.push_back(Op);
968 continue;
969 }
970
971 if (!RegisterPrefix.empty()) {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000972 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner4e692ab2010-10-28 21:28:42 +0000973 "' (which matches register prefix)";
974 throw TGError(II->Instr->TheDef->getLoc(), Err);
975 }
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000976 }
977
Daniel Dunbar20927f22009-08-07 08:26:05 +0000978 // Check for simple tokens.
979 if (Token[0] != '$') {
980 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000981 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000982 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000983 II->Operands.push_back(Op);
984 continue;
985 }
986
987 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000988 StringRef OperandName;
989 if (Token[1] == '{')
990 OperandName = Token.substr(2, Token.size() - 3);
991 else
992 OperandName = Token.substr(1);
993
994 // Map this token to an operand. FIXME: Move elsewhere.
995 unsigned Idx;
996 try {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000997 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000998 } catch(...) {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000999 throw std::string("error: unable to find operand: '" +
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001000 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001001 }
1002
Daniel Dunbaraf616812010-02-10 08:15:48 +00001003 // FIXME: This is annoying, the named operand may be tied (e.g.,
1004 // XCHG8rm). What we want is the untied operand, which we now have to
1005 // grovel for. Only worry about this for single entry operands, we have to
1006 // clean this up anyway.
1007 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1008 if (OI->Constraints[0].isTied()) {
1009 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1010
1011 // The tied operand index is an MIOperand index, find the operand that
1012 // contains it.
1013 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1014 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1015 OI = &II->Instr->OperandList[i];
1016 break;
1017 }
1018 }
1019
1020 assert(OI && "Unable to find tied operand target!");
1021 }
1022
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001023 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001024 Op.Class = getOperandClass(Token, *OI);
1025 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001026 II->Operands.push_back(Op);
1027 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001028 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001029
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001030 // Reorder classes so that classes preceed super classes.
1031 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001032}
1033
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001034static std::pair<unsigned, unsigned> *
1035GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1036 unsigned Index) {
1037 for (unsigned i = 0, e = List.size(); i != e; ++i)
1038 if (Index == List[i].first)
1039 return &List[i];
1040
1041 return 0;
1042}
1043
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001044static void EmitConvertToMCInst(CodeGenTarget &Target,
1045 std::vector<InstructionInfo*> &Infos,
1046 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001047 // Write the convert function to a separate stream, so we can drop it after
1048 // the enum.
1049 std::string ConvertFnBody;
1050 raw_string_ostream CvtOS(ConvertFnBody);
1051
Daniel Dunbar20927f22009-08-07 08:26:05 +00001052 // Function we have already generated.
1053 std::set<std::string> GeneratedFns;
1054
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001055 // Start the unified conversion function.
1056
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001057 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001058 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001059 << " const SmallVectorImpl<MCParsedAsmOperand*"
1060 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001061 CvtOS << " Inst.setOpcode(Opcode);\n";
1062 CvtOS << " switch (Kind) {\n";
1063 CvtOS << " default:\n";
1064
1065 // Start the enum, which we will generate inline.
1066
1067 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001068 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001069
Chris Lattner98986712010-01-14 22:21:20 +00001070 // TargetOperandClass - This is the target's operand class, like X86Operand.
1071 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001072
Daniel Dunbar20927f22009-08-07 08:26:05 +00001073 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1074 ie = Infos.end(); it != ie; ++it) {
1075 InstructionInfo &II = **it;
1076
1077 // Order the (class) operands by the order to convert them into an MCInst.
1078 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1079 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1080 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001081 if (Op.OperandInfo)
1082 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001083 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001084
1085 // Find any tied operands.
1086 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1087 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1088 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1089 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1090 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1091 if (CI.isTied())
1092 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1093 CI.getTiedOperand()));
1094 }
1095 }
1096
Daniel Dunbar20927f22009-08-07 08:26:05 +00001097 std::sort(MIOperandList.begin(), MIOperandList.end());
1098
1099 // Compute the total number of operands.
1100 unsigned NumMIOperands = 0;
1101 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1102 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001103 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbar20927f22009-08-07 08:26:05 +00001104 OI.MIOperandNo + OI.MINumOperands);
1105 }
1106
1107 // Build the conversion function signature.
1108 std::string Signature = "Convert";
1109 unsigned CurIndex = 0;
1110 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1111 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001112 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001113 "Duplicate match for instruction operand!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001114
Daniel Dunbar20927f22009-08-07 08:26:05 +00001115 // Skip operands which weren't matched by anything, this occurs when the
1116 // .td file encodes "implicit" operands as explicit ones.
1117 //
1118 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001119 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001120 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1121 CurIndex);
1122 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001123 Signature += "__Imp";
1124 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001125 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001126 }
1127
1128 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001129
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001130 // Registers are always converted the same, don't duplicate the conversion
1131 // function based on them.
1132 //
1133 // FIXME: We could generalize this based on the render method, if it
1134 // mattered.
1135 if (Op.Class->isRegisterClass())
1136 Signature += "Reg";
1137 else
1138 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001139 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001140 Signature += "_" + utostr(MIOperandList[i].second);
1141
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001142 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001143 }
1144
1145 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001146 for (; CurIndex != NumMIOperands; ++CurIndex) {
1147 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1148 CurIndex);
1149 if (!Tie)
1150 Signature += "__Imp";
1151 else
1152 Signature += "__Tie" + utostr(Tie->second);
1153 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001154
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001155 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001156
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001157 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001158 if (!GeneratedFns.insert(Signature).second)
1159 continue;
1160
1161 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001162
1163 // Add to the enum list.
1164 OS << " " << Signature << ",\n";
1165
1166 // And to the convert function.
1167 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001168 CurIndex = 0;
1169 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1170 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1171
1172 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001173 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1174 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001175 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1176 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001177
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001178 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001179 // If not, this is some implicit operand. Just assume it is a register
1180 // for now.
1181 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1182 } else {
1183 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001184 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001185 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001186 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001187 }
1188 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001189
Chris Lattner98986712010-01-14 22:21:20 +00001190 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbacha7c78222010-10-29 22:13:48 +00001191 << MIOperandList[i].second
1192 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001193 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1194 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001195 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001196
Daniel Dunbar20927f22009-08-07 08:26:05 +00001197 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001198 for (; CurIndex != NumMIOperands; ++CurIndex) {
1199 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1200 CurIndex);
1201
1202 if (!Tie) {
1203 // If not, this is some implicit operand. Just assume it is a register
1204 // for now.
1205 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1206 } else {
1207 // Copy the tied operand.
1208 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1209 CvtOS << " Inst.addOperand(Inst.getOperand("
1210 << Tie->second << "));\n";
1211 }
1212 }
1213
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001214 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001215 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001216
1217 // Finish the convert function.
1218
1219 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001220 CvtOS << "}\n\n";
1221
1222 // Finish the enum, and drop the convert function after it.
1223
1224 OS << " NumConversionVariants\n";
1225 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001226
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001227 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001228}
1229
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001230/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1231static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1232 std::vector<ClassInfo*> &Infos,
1233 raw_ostream &OS) {
1234 OS << "namespace {\n\n";
1235
1236 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1237 << "/// instruction matching.\n";
1238 OS << "enum MatchClassKind {\n";
1239 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001240 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001241 ie = Infos.end(); it != ie; ++it) {
1242 ClassInfo &CI = **it;
1243 OS << " " << CI.Name << ", // ";
1244 if (CI.Kind == ClassInfo::Token) {
1245 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001246 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001247 if (!CI.ValueName.empty())
1248 OS << "register class '" << CI.ValueName << "'\n";
1249 else
1250 OS << "derived register class\n";
1251 } else {
1252 OS << "user defined class '" << CI.ValueName << "'\n";
1253 }
1254 }
1255 OS << " NumMatchClassKinds\n";
1256 OS << "};\n\n";
1257
1258 OS << "}\n\n";
1259}
1260
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001261/// EmitClassifyOperand - Emit the function to classify an operand.
1262static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001263 AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001264 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001265 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1266 << " " << Target.getName() << "Operand &Operand = *("
1267 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001268
1269 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001270 OS << " if (Operand.isToken())\n";
1271 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001272
1273 // Classify registers.
1274 //
1275 // FIXME: Don't hardcode isReg, getReg.
1276 OS << " if (Operand.isReg()) {\n";
1277 OS << " switch (Operand.getReg()) {\n";
1278 OS << " default: return InvalidMatchClass;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001279 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001280 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1281 it != ie; ++it)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001282 OS << " case " << Target.getName() << "::"
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001283 << it->first->getName() << ": return " << it->second->Name << ";\n";
1284 OS << " }\n";
1285 OS << " }\n\n";
1286
1287 // Classify user defined operands.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001288 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001289 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001290 ClassInfo &CI = **it;
1291
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001292 if (!CI.isUserClass())
1293 continue;
1294
1295 OS << " // '" << CI.ClassName << "' class";
1296 if (!CI.SuperClasses.empty()) {
1297 OS << ", subclass of ";
1298 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1299 if (i) OS << ", ";
1300 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1301 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001302 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001303 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001304 OS << "\n";
1305
1306 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001307
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001308 // Validate subclass relationships.
1309 if (!CI.SuperClasses.empty()) {
1310 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1311 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1312 << "() && \"Invalid class relationship!\");\n";
1313 }
1314
1315 OS << " return " << CI.Name << ";\n";
1316 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001317 }
1318 OS << " return InvalidMatchClass;\n";
1319 OS << "}\n\n";
1320}
1321
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001322/// EmitIsSubclass - Emit the subclass predicate function.
1323static void EmitIsSubclass(CodeGenTarget &Target,
1324 std::vector<ClassInfo*> &Infos,
1325 raw_ostream &OS) {
1326 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1327 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1328 OS << " if (A == B)\n";
1329 OS << " return true;\n\n";
1330
1331 OS << " switch (A) {\n";
1332 OS << " default:\n";
1333 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001334 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001335 ie = Infos.end(); it != ie; ++it) {
1336 ClassInfo &A = **it;
1337
1338 if (A.Kind != ClassInfo::Token) {
1339 std::vector<StringRef> SuperClasses;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001340 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001341 ie = Infos.end(); it != ie; ++it) {
1342 ClassInfo &B = **it;
1343
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001344 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001345 SuperClasses.push_back(B.Name);
1346 }
1347
1348 if (SuperClasses.empty())
1349 continue;
1350
1351 OS << "\n case " << A.Name << ":\n";
1352
1353 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001354 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001355 continue;
1356 }
1357
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001358 OS << " switch (B) {\n";
1359 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001360 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001361 OS << " case " << SuperClasses[i] << ": return true;\n";
1362 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001363 }
1364 }
1365 OS << " }\n";
1366 OS << "}\n\n";
1367}
1368
Chris Lattner70add882009-08-08 20:02:57 +00001369
1370
Daniel Dunbar245f0582009-08-08 21:22:41 +00001371/// EmitMatchTokenString - Emit the function to match a token string to the
1372/// appropriate match class value.
1373static void EmitMatchTokenString(CodeGenTarget &Target,
1374 std::vector<ClassInfo*> &Infos,
1375 raw_ostream &OS) {
1376 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001377 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001378 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001379 ie = Infos.end(); it != ie; ++it) {
1380 ClassInfo &CI = **it;
1381
1382 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001383 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1384 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001385 }
1386
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001387 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001388
Chris Lattner5845e5c2010-09-06 02:01:51 +00001389 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001390
1391 OS << " return InvalidMatchClass;\n";
1392 OS << "}\n\n";
1393}
Chris Lattner70add882009-08-08 20:02:57 +00001394
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001395/// EmitMatchRegisterName - Emit the function to match a string to the target
1396/// specific register enum.
1397static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1398 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001399 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001400 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001401 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1402 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001403 if (Reg.TheDef->getValueAsString("AsmName").empty())
1404 continue;
1405
Chris Lattner5845e5c2010-09-06 02:01:51 +00001406 Matches.push_back(StringMatcher::StringPair(
1407 Reg.TheDef->getValueAsString("AsmName"),
1408 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001409 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001410
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001411 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001412
Chris Lattner5845e5c2010-09-06 02:01:51 +00001413 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001414
Daniel Dunbar245f0582009-08-08 21:22:41 +00001415 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001416 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001417}
Daniel Dunbara027d222009-07-31 02:32:59 +00001418
Daniel Dunbar54074b52010-07-19 05:44:09 +00001419/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1420/// definitions.
1421static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1422 AsmMatcherInfo &Info,
1423 raw_ostream &OS) {
1424 OS << "// Flags for subtarget features that participate in "
1425 << "instruction matching.\n";
1426 OS << "enum SubtargetFeatureFlag {\n";
1427 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1428 it = Info.SubtargetFeatures.begin(),
1429 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1430 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001431 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001432 }
1433 OS << " Feature_None = 0\n";
1434 OS << "};\n\n";
1435}
1436
1437/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1438/// available features given a subtarget.
1439static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1440 AsmMatcherInfo &Info,
1441 raw_ostream &OS) {
1442 std::string ClassName =
1443 Info.AsmParser->getValueAsString("AsmParserClassName");
1444
1445 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1446 << "ComputeAvailableFeatures(const " << Target.getName()
1447 << "Subtarget *Subtarget) const {\n";
1448 OS << " unsigned Features = 0;\n";
1449 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1450 it = Info.SubtargetFeatures.begin(),
1451 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1452 SubtargetFeatureInfo &SFI = *it->second;
1453 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1454 << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001455 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001456 }
1457 OS << " return Features;\n";
1458 OS << "}\n\n";
1459}
1460
Chris Lattner6fa152c2010-10-30 20:15:02 +00001461static std::string GetAliasRequiredFeatures(Record *R,
1462 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00001463 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00001464 std::string Result;
1465 unsigned NumFeatures = 0;
1466 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner6fa152c2010-10-30 20:15:02 +00001467 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1468 if (NumFeatures)
1469 Result += '|';
Chris Lattner693173f2010-10-30 19:23:13 +00001470
Chris Lattner6fa152c2010-10-30 20:15:02 +00001471 Result += F->getEnumName();
1472 ++NumFeatures;
1473 }
Chris Lattner693173f2010-10-30 19:23:13 +00001474 }
1475
1476 if (NumFeatures > 1)
1477 Result = '(' + Result + ')';
1478 return Result;
1479}
1480
Chris Lattner674c1dc2010-10-30 17:36:36 +00001481/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001482/// emit a function for them and return true, otherwise return false.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001483static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattner674c1dc2010-10-30 17:36:36 +00001484 std::vector<Record*> Aliases =
1485 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001486 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001487
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001488 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1489 "unsigned Features) {\n";
1490
Chris Lattner4fd32c62010-10-30 18:56:12 +00001491 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1492 // iteration order of the map is stable.
1493 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1494
Chris Lattner674c1dc2010-10-30 17:36:36 +00001495 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1496 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001497 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001498 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001499
1500 // Process each alias a "from" mnemonic at a time, building the code executed
1501 // by the string remapper.
1502 std::vector<StringMatcher::StringPair> Cases;
1503 for (std::map<std::string, std::vector<Record*> >::iterator
1504 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1505 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00001506 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00001507
1508 // Loop through each alias and emit code that handles each case. If there
1509 // are two instructions without predicates, emit an error. If there is one,
1510 // emit it last.
1511 std::string MatchCode;
1512 int AliasWithNoPredicate = -1;
Chris Lattner4fd32c62010-10-30 18:56:12 +00001513
Chris Lattner693173f2010-10-30 19:23:13 +00001514 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1515 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00001516 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner693173f2010-10-30 19:23:13 +00001517
1518 // If this unconditionally matches, remember it for later and diagnose
1519 // duplicates.
1520 if (FeatureMask.empty()) {
1521 if (AliasWithNoPredicate != -1) {
1522 // We can't have two aliases from the same mnemonic with no predicate.
1523 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1524 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001525 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1526 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner693173f2010-10-30 19:23:13 +00001527 }
1528
1529 AliasWithNoPredicate = i;
1530 continue;
1531 }
1532
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001533 if (!MatchCode.empty())
1534 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00001535 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1536 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00001537 }
1538
Chris Lattner693173f2010-10-30 19:23:13 +00001539 if (AliasWithNoPredicate != -1) {
1540 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001541 if (!MatchCode.empty())
1542 MatchCode += "else\n ";
1543 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00001544 }
1545
1546 MatchCode += "return;";
1547
1548 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00001549 }
1550
Chris Lattner674c1dc2010-10-30 17:36:36 +00001551
1552 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner7fd44892010-10-30 18:48:18 +00001553 OS << "}\n";
1554
1555 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001556}
1557
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001558void AsmMatcherEmitter::run(raw_ostream &OS) {
1559 CodeGenTarget Target;
1560 Record *AsmParser = Target.getAsmParser();
1561 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1562
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001563 // Compute the information on the instructions to match.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001564 AsmMatcherInfo Info(AsmParser);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001565 Info.BuildInfo(Target);
Daniel Dunbara027d222009-07-31 02:32:59 +00001566
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001567 // Sort the instruction table using the partial order on classes. We use
1568 // stable_sort to ensure that ambiguous instructions are still
1569 // deterministically ordered.
1570 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1571 less_ptr<InstructionInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001572
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001573 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001574 for (std::vector<InstructionInfo*>::iterator
1575 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001576 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001577 (*it)->dump();
1578 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001579
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001580 // Check for ambiguous instructions.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001581 DEBUG_WITH_TYPE("ambiguous_instrs", {
1582 unsigned NumAmbiguous = 0;
Chris Lattner87410362010-09-06 20:21:47 +00001583 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1584 for (unsigned j = i + 1; j != e; ++j) {
1585 InstructionInfo &A = *Info.Instructions[i];
1586 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001587
Chris Lattner87410362010-09-06 20:21:47 +00001588 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001589 errs() << "warning: ambiguous instruction match:\n";
1590 A.dump();
1591 errs() << "\nis incomparable with:\n";
1592 B.dump();
1593 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00001594 ++NumAmbiguous;
1595 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00001596 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001597 }
Chris Lattner87410362010-09-06 20:21:47 +00001598 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001599 errs() << "warning: " << NumAmbiguous
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001600 << " ambiguous instructions!\n";
1601 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001602
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001603 // Write the output.
1604
1605 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1606
Chris Lattner0692ee62010-09-06 19:11:01 +00001607 // Information for the class declaration.
1608 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1609 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001610 OS << " // This should be included into the middle of the declaration of \n";
1611 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001612 OS << " unsigned ComputeAvailableFeatures(const " <<
1613 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001614 OS << " enum MatchResultTy {\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001615 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1616 OS << " Match_MissingFeature\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001617 OS << " };\n";
Jim Grosbachbb168242010-10-08 18:13:57 +00001618 OS << " MatchResultTy MatchInstructionImpl(const "
1619 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattnerce4a3352010-09-06 22:11:18 +00001620 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001621 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1622
Jim Grosbacha7c78222010-10-29 22:13:48 +00001623
1624
1625
Chris Lattner0692ee62010-09-06 19:11:01 +00001626 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1627 OS << "#undef GET_REGISTER_MATCHER\n\n";
1628
Daniel Dunbar54074b52010-07-19 05:44:09 +00001629 // Emit the subtarget feature enumeration.
1630 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1631
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001632 // Emit the function to match a register name to number.
1633 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001634
1635 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001636
Chris Lattner0692ee62010-09-06 19:11:01 +00001637
1638 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1639 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001640
Chris Lattner7fd44892010-10-30 18:48:18 +00001641 // Generate the function that remaps for mnemonic aliases.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001642 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner7fd44892010-10-30 18:48:18 +00001643
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001644 // Generate the unified function to convert operands into an MCInst.
1645 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001646
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001647 // Emit the enumeration for classes which participate in matching.
1648 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001649
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001650 // Emit the routine to match token strings to their match class.
1651 EmitMatchTokenString(Target, Info.Classes, OS);
1652
1653 // Emit the routine to classify an operand.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001654 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001655
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001656 // Emit the subclass predicate routine.
1657 EmitIsSubclass(Target, Info.Classes, OS);
1658
Daniel Dunbar54074b52010-07-19 05:44:09 +00001659 // Emit the available features compute function.
1660 EmitComputeAvailableFeatures(Target, Info, OS);
1661
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001662
1663 size_t MaxNumOperands = 0;
1664 for (std::vector<InstructionInfo*>::const_iterator it =
1665 Info.Instructions.begin(), ie = Info.Instructions.end();
1666 it != ie; ++it)
1667 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001668
1669
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001670 // Emit the static match table; unused classes get initalized to 0 which is
1671 // guaranteed to be InvalidMatchClass.
1672 //
1673 // FIXME: We can reduce the size of this table very easily. First, we change
1674 // it so that store the kinds in separate bit-fields for each index, which
1675 // only needs to be the max width used for classes at that index (we also need
1676 // to reject based on this during classification). If we then make sure to
1677 // order the match kinds appropriately (putting mnemonics last), then we
1678 // should only end up using a few bits for each class, especially the ones
1679 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00001680 OS << "namespace {\n";
1681 OS << " struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001682 OS << " unsigned Opcode;\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001683 OS << " const char *Mnemonic;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001684 OS << " ConversionKind ConvertFn;\n";
1685 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001686 OS << " unsigned RequiredFeatures;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001687 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001688
Chris Lattner2b1f9432010-09-06 21:22:45 +00001689 OS << "// Predicate for searching for an opcode.\n";
1690 OS << " struct LessOpcode {\n";
1691 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1692 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1693 OS << " }\n";
1694 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1695 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1696 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00001697 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1698 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1699 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00001700 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001701
Chris Lattner96352e52010-09-06 21:08:38 +00001702 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001703
Chris Lattner96352e52010-09-06 21:08:38 +00001704 OS << "static const MatchEntry MatchTable["
1705 << Info.Instructions.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001706
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001707 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner96352e52010-09-06 21:08:38 +00001708 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001709 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001710 InstructionInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001711
Chris Lattner96352e52010-09-06 21:08:38 +00001712 OS << " { " << Target.getName() << "::" << II.InstrName
1713 << ", \"" << II.Tokens[0] << "\""
1714 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001715 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1716 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001717
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001718 if (i) OS << ", ";
1719 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001720 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001721 OS << " }, ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001722
Daniel Dunbar54074b52010-07-19 05:44:09 +00001723 // Write the required features mask.
1724 if (!II.RequiredFeatures.empty()) {
1725 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1726 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001727 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00001728 }
1729 } else
1730 OS << "0";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001731
Daniel Dunbar54074b52010-07-19 05:44:09 +00001732 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001733 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001734
Chris Lattner96352e52010-09-06 21:08:38 +00001735 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001736
Chris Lattner96352e52010-09-06 21:08:38 +00001737 // Finally, build the match function.
1738 OS << Target.getName() << ClassName << "::MatchResultTy "
1739 << Target.getName() << ClassName << "::\n"
1740 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1741 << " &Operands,\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001742 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001743
1744 // Emit code to get the available features.
1745 OS << " // Get the current feature set.\n";
1746 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1747
Chris Lattner674c1dc2010-10-30 17:36:36 +00001748 OS << " // Get the instruction mnemonic, which is the first token.\n";
1749 OS << " StringRef Mnemonic = ((" << Target.getName()
1750 << "Operand*)Operands[0])->getToken();\n\n";
1751
Chris Lattner7fd44892010-10-30 18:48:18 +00001752 if (HasMnemonicAliases) {
1753 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1754 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1755 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00001756
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001757 // Emit code to compute the class list for this operand vector.
1758 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001759 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1760 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1761 OS << " return Match_InvalidOperand;\n";
1762 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001763
1764 OS << " // Compute the class list for this operand vector.\n";
1765 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001766 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1767 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001768
1769 OS << " // Check for invalid operands before matching.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001770 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1771 OS << " ErrorInfo = i;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001772 OS << " return Match_InvalidOperand;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001773 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001774 OS << " }\n\n";
1775
1776 OS << " // Mark unused classes.\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001777 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001778 << "i != e; ++i)\n";
1779 OS << " Classes[i] = InvalidMatchClass;\n\n";
1780
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001781 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001782 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001783 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1784 OS << " // wrong for all instances of the instruction.\n";
1785 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001786
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001787 // Emit code to search the table.
1788 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001789 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1790 OS << " std::equal_range(MatchTable, MatchTable+"
1791 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001792
Chris Lattnera008e8a2010-09-06 21:54:15 +00001793 OS << " // Return a more specific error code if no mnemonics match.\n";
1794 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1795 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001796
Chris Lattner2b1f9432010-09-06 21:22:45 +00001797 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00001798 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001799 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001800
Gabor Greife53ee3b2010-09-07 06:06:06 +00001801 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattner44b0daa2010-09-06 21:25:43 +00001802 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001803
Daniel Dunbar54074b52010-07-19 05:44:09 +00001804 // Emit check that the subclasses match.
Chris Lattnerce4a3352010-09-06 22:11:18 +00001805 OS << " bool OperandsValid = true;\n";
1806 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1807 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1808 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001809 OS << " // If this operand is broken for all of the instances of this\n";
1810 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1811 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001812 OS << " ErrorInfo = i+1;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001813 OS << " else\n";
1814 OS << " ErrorInfo = ~0U;";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001815 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1816 OS << " OperandsValid = false;\n";
1817 OS << " break;\n";
1818 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001819
Chris Lattnerce4a3352010-09-06 22:11:18 +00001820 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00001821
1822 // Emit check that the required features are available.
1823 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1824 << "!= it->RequiredFeatures) {\n";
1825 OS << " HadMatchOtherThanFeatures = true;\n";
1826 OS << " continue;\n";
1827 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001828
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001829 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001830 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1831
1832 // Call the post-processing function, if used.
1833 std::string InsnCleanupFn =
1834 AsmParser->getValueAsString("AsmParserInstCleanup");
1835 if (!InsnCleanupFn.empty())
1836 OS << " " << InsnCleanupFn << "(Inst);\n";
1837
Chris Lattner79ed3f72010-09-06 19:22:17 +00001838 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001839 OS << " }\n\n";
1840
Chris Lattnerec6789f2010-09-06 20:08:02 +00001841 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1842 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001843 OS << " return Match_InvalidOperand;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001844 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001845
Chris Lattner0692ee62010-09-06 19:11:01 +00001846 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001847}