blob: 254a719959fae433280b6f8d2f8b9251a29d7e9e [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"
Chris Lattner1de88232010-11-01 01:47:07 +000081#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000082#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000083#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000084#include "llvm/ADT/StringExtras.h"
85#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000086#include "llvm/Support/Debug.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000087#include <list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +000088#include <map>
89#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000090using namespace llvm;
91
Daniel Dunbar27249152009-08-07 20:33:39 +000092static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000093MatchPrefix("match-prefix", cl::init(""),
94 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +000095
Daniel Dunbara027d222009-07-31 02:32:59 +000096/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbacha7c78222010-10-29 22:13:48 +000097static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbara027d222009-07-31 02:32:59 +000098 SmallVectorImpl<StringRef> &Tokens) {
99 unsigned Prev = 0;
100 bool InTok = true;
101 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
102 switch (AsmString[i]) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000103 case '[':
104 case ']':
Daniel Dunbara027d222009-07-31 02:32:59 +0000105 case '*':
106 case '!':
107 case ' ':
108 case '\t':
109 case ',':
110 if (InTok) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000111 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara027d222009-07-31 02:32:59 +0000112 InTok = false;
113 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000114 if (!isspace(AsmString[i]) && AsmString[i] != ',')
115 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara027d222009-07-31 02:32:59 +0000116 Prev = i + 1;
117 break;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000118
Daniel Dunbar20927f22009-08-07 08:26:05 +0000119 case '\\':
120 if (InTok) {
121 Tokens.push_back(AsmString.slice(Prev, i));
122 InTok = false;
123 }
124 ++i;
125 assert(i != AsmString.size() && "Invalid quoted character");
126 Tokens.push_back(AsmString.substr(i, 1));
127 Prev = i + 1;
128 break;
129
130 case '$': {
131 // If this isn't "${", treat like a normal token.
132 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
133 if (InTok) {
134 Tokens.push_back(AsmString.slice(Prev, i));
135 InTok = false;
136 }
137 Prev = i;
138 break;
139 }
140
141 if (InTok) {
142 Tokens.push_back(AsmString.slice(Prev, i));
143 InTok = false;
144 }
145
146 StringRef::iterator End =
147 std::find(AsmString.begin() + i, AsmString.end(), '}');
148 assert(End != AsmString.end() && "Missing brace in operand reference!");
149 size_t EndPos = End - AsmString.begin();
150 Tokens.push_back(AsmString.slice(i, EndPos+1));
151 Prev = EndPos + 1;
152 i = EndPos;
153 break;
154 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000155
Daniel Dunbar4d39b672010-08-11 06:36:59 +0000156 case '.':
157 if (InTok) {
158 Tokens.push_back(AsmString.slice(Prev, i));
159 }
160 Prev = i;
161 InTok = true;
162 break;
163
Daniel Dunbara027d222009-07-31 02:32:59 +0000164 default:
165 InTok = true;
166 }
167 }
168 if (InTok && Prev != AsmString.size())
Daniel Dunbar20927f22009-08-07 08:26:05 +0000169 Tokens.push_back(AsmString.substr(Prev));
170}
171
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000172static bool IsAssemblerInstruction(StringRef Name,
Jim Grosbacha7c78222010-10-29 22:13:48 +0000173 const CodeGenInstruction &CGI,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000174 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000175 // Ignore "codegen only" instructions.
176 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
177 return false;
178
Daniel Dunbar72fa87f2009-08-09 08:19:00 +0000179 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
180 //
181 // FIXME: This is a total hack.
182 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
183 return false;
184
Chris Lattner4d1189f2010-11-01 00:46:16 +0000185 // Reject instructions with no .s string.
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000186 if (CGI.AsmString.empty()) {
187 PrintError(CGI.TheDef->getLoc(),
188 "instruction with empty asm string");
189 throw std::string("ERROR: Invalid instruction for asm matcher");
190 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000191
Chris Lattner4d1189f2010-11-01 00:46:16 +0000192 // Reject any instructions with a newline in them, they should be marked
193 // isCodeGenOnly if they are pseudo instructions.
194 if (CGI.AsmString.find('\n') != std::string::npos) {
195 PrintError(CGI.TheDef->getLoc(),
196 "multiline instruction is not valid for the asmparser, "
197 "mark it isCodeGenOnly");
198 throw std::string("ERROR: Invalid instruction");
199 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000200
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000201 // Reject instructions with attributes, these aren't something we can handle,
202 // the target should be refactored to use operands instead of modifiers.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000203 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000204 // Also, check for instructions which reference the operand multiple times;
205 // this implies a constraint we would not honor.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000206 std::set<std::string> OperandNames;
207 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
Chris Lattner8b2f0822010-10-31 19:05:32 +0000208 if (Tokens[i][0] == '$' &&
Chris Lattner39ee0362010-10-31 19:10:56 +0000209 Tokens[i].find(':') != StringRef::npos) {
210 PrintError(CGI.TheDef->getLoc(),
211 "instruction with operand modifier '" + Tokens[i].str() +
212 "' not supported by asm matcher. Mark isCodeGenOnly!");
213 throw std::string("ERROR: Invalid instruction");
Chris Lattner8b2f0822010-10-31 19:05:32 +0000214 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000215
Chris Lattner52de0ef2010-11-01 00:51:32 +0000216 // FIXME: Should reject these. The ARM backend hits this with $lane in a
217 // bunch of instructions. It is unclear what the right answer is for this.
Chris Lattner8b2f0822010-10-31 19:05:32 +0000218 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
219 DEBUG({
Chris Lattner39ee0362010-10-31 19:10:56 +0000220 errs() << "warning: '" << Name << "': "
221 << "ignoring instruction with tied operand '"
222 << Tokens[i].str() << "'\n";
223 });
Chris Lattner8b2f0822010-10-31 19:05:32 +0000224 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000225 }
226 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000227
Daniel Dunbar20927f22009-08-07 08:26:05 +0000228 return true;
229}
230
231namespace {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000232 class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000233struct SubtargetFeatureInfo;
234
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000235/// ClassInfo - Helper class for storing the information about a particular
236/// class of operands which can be matched.
237struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000238 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000239 /// Invalid kind, for use as a sentinel value.
240 Invalid = 0,
241
242 /// The class for a particular token.
243 Token,
244
245 /// The (first) register class, subsequent register classes are
246 /// RegisterClass0+1, and so on.
247 RegisterClass0,
248
249 /// The (first) user defined class, subsequent user defined classes are
250 /// UserClass0+1, and so on.
251 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000252 };
253
254 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
255 /// N) for the Nth user defined class.
256 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000257
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000258 /// SuperClasses - The super classes of this class. Note that for simplicities
259 /// sake user operands only record their immediate super class, while register
260 /// operands include all superclasses.
261 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000262
Daniel Dunbar6745d422009-08-09 05:18:30 +0000263 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000264 std::string Name;
265
Daniel Dunbar6745d422009-08-09 05:18:30 +0000266 /// ClassName - The unadorned generic name for this class (e.g., Token).
267 std::string ClassName;
268
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000269 /// ValueName - The name of the value this class represents; for a token this
270 /// is the literal token string, for an operand it is the TableGen class (or
271 /// empty if this is a derived class).
272 std::string ValueName;
273
274 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000275 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000276 std::string PredicateMethod;
277
278 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000279 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000280 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000281
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000282 /// For register classes, the records for all the registers in this class.
283 std::set<Record*> Registers;
284
285public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000286 /// isRegisterClass() - Check if this is a register class.
287 bool isRegisterClass() const {
288 return Kind >= RegisterClass0 && Kind < UserClass0;
289 }
290
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000291 /// isUserClass() - Check if this is a user defined class.
292 bool isUserClass() const {
293 return Kind >= UserClass0;
294 }
295
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000296 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
297 /// are related if they are in the same class hierarchy.
298 bool isRelatedTo(const ClassInfo &RHS) const {
299 // Tokens are only related to tokens.
300 if (Kind == Token || RHS.Kind == Token)
301 return Kind == Token && RHS.Kind == Token;
302
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000303 // Registers classes are only related to registers classes, and only if
304 // their intersection is non-empty.
305 if (isRegisterClass() || RHS.isRegisterClass()) {
306 if (!isRegisterClass() || !RHS.isRegisterClass())
307 return false;
308
309 std::set<Record*> Tmp;
310 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000311 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000312 RHS.Registers.begin(), RHS.Registers.end(),
313 II);
314
315 return !Tmp.empty();
316 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000317
318 // Otherwise we have two users operands; they are related if they are in the
319 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000320 //
321 // FIXME: This is an oversimplification, they should only be related if they
322 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000323 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
324 const ClassInfo *Root = this;
325 while (!Root->SuperClasses.empty())
326 Root = Root->SuperClasses.front();
327
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000328 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000329 while (!RHSRoot->SuperClasses.empty())
330 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000331
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000332 return Root == RHSRoot;
333 }
334
Jim Grosbacha7c78222010-10-29 22:13:48 +0000335 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000336 bool isSubsetOf(const ClassInfo &RHS) const {
337 // This is a subset of RHS if it is the same class...
338 if (this == &RHS)
339 return true;
340
341 // ... or if any of its super classes are a subset of RHS.
342 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
343 ie = SuperClasses.end(); it != ie; ++it)
344 if ((*it)->isSubsetOf(RHS))
345 return true;
346
347 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000348 }
349
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000350 /// operator< - Compare two classes.
351 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000352 if (this == &RHS)
353 return false;
354
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000355 // Unrelated classes can be ordered by kind.
356 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000357 return Kind < RHS.Kind;
358
359 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000360 case Invalid:
361 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000362 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000363 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000364 //
365 // FIXME: Compare by enum value.
366 return ValueName < RHS.ValueName;
367
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000368 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000369 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000370 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000371 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000372 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000373 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000374
375 // Otherwise, order by name to ensure we have a total ordering.
376 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000377 }
378 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000379};
380
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000381/// InstructionInfo - Helper class for storing the necessary information for an
382/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000383struct InstructionInfo {
384 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000385 /// The unique class instance this operand should match.
386 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000387
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000388 /// The original operand this corresponds to, if any.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000389 const CGIOperandList::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000390 };
391
392 /// InstrName - The target name for this instruction.
393 std::string InstrName;
394
395 /// Instr - The instruction this matches.
396 const CodeGenInstruction *Instr;
397
398 /// AsmString - The assembly string for this instruction (with variants
399 /// removed).
400 std::string AsmString;
401
402 /// Tokens - The tokenized assembly pattern that this instruction matches.
403 SmallVector<StringRef, 4> Tokens;
404
405 /// Operands - The operands that this instruction matches.
406 SmallVector<Operand, 4> Operands;
407
Daniel Dunbar54074b52010-07-19 05:44:09 +0000408 /// Predicates - The required subtarget features to match this instruction.
409 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
410
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000411 /// ConversionFnKind - The enum value which is passed to the generated
412 /// ConvertToMCInst to convert parsed operands into an MCInst for this
413 /// function.
414 std::string ConversionFnKind;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000415
416 /// getSingletonRegisterForToken - If the specified token is a singleton
Chris Lattner1de88232010-11-01 01:47:07 +0000417 /// register, return the Record for it, otherwise return null.
418 Record *getSingletonRegisterForToken(unsigned i,
419 const AsmMatcherInfo &Info) const;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000420
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000421 /// operator< - Compare two instructions.
422 bool operator<(const InstructionInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000423 // The primary comparator is the instruction mnemonic.
424 if (Tokens[0] != RHS.Tokens[0])
425 return Tokens[0] < RHS.Tokens[0];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000426
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000427 if (Operands.size() != RHS.Operands.size())
428 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000429
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000430 // Compare lexicographically by operand. The matcher validates that other
431 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
432 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000433 if (*Operands[i].Class < *RHS.Operands[i].Class)
434 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000435 if (*RHS.Operands[i].Class < *Operands[i].Class)
436 return false;
437 }
438
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000439 return false;
440 }
441
Daniel Dunbar2b544812009-08-09 06:05:33 +0000442 /// CouldMatchAmiguouslyWith - Check whether this instruction could
443 /// ambiguously match the same set of operands as \arg RHS (without being a
444 /// strictly superior match).
445 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
446 // The number of operands is unambiguous.
447 if (Operands.size() != RHS.Operands.size())
448 return false;
449
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000450 // Otherwise, make sure the ordering of the two instructions is unambiguous
451 // by checking that either (a) a token or operand kind discriminates them,
452 // or (b) the ordering among equivalent kinds is consistent.
453
Daniel Dunbar2b544812009-08-09 06:05:33 +0000454 // Tokens and operand kinds are unambiguous (assuming a correct target
455 // specific parser).
456 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
457 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
458 Operands[i].Class->Kind == ClassInfo::Token)
459 if (*Operands[i].Class < *RHS.Operands[i].Class ||
460 *RHS.Operands[i].Class < *Operands[i].Class)
461 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000462
Daniel Dunbar2b544812009-08-09 06:05:33 +0000463 // Otherwise, this operand could commute if all operands are equivalent, or
464 // there is a pair of operands that compare less than and a pair that
465 // compare greater than.
466 bool HasLT = false, HasGT = false;
467 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
468 if (*Operands[i].Class < *RHS.Operands[i].Class)
469 HasLT = true;
470 if (*RHS.Operands[i].Class < *Operands[i].Class)
471 HasGT = true;
472 }
473
474 return !(HasLT ^ HasGT);
475 }
476
Daniel Dunbar20927f22009-08-07 08:26:05 +0000477 void dump();
478};
479
Daniel Dunbar54074b52010-07-19 05:44:09 +0000480/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
481/// feature which participates in instruction matching.
482struct SubtargetFeatureInfo {
483 /// \brief The predicate record for this feature.
484 Record *TheDef;
485
486 /// \brief An unique index assigned to represent this feature.
487 unsigned Index;
488
Chris Lattner0aed1e72010-10-30 20:07:57 +0000489 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
490
Daniel Dunbar54074b52010-07-19 05:44:09 +0000491 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000492 std::string getEnumName() const {
493 return "Feature_" + TheDef->getName();
494 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000495};
496
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000497class AsmMatcherInfo {
498public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000499 /// The tablegen AsmParser record.
500 Record *AsmParser;
501
Chris Lattner02bcbc92010-11-01 01:37:30 +0000502 /// Target - The target information.
503 CodeGenTarget &Target;
504
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000505 /// The AsmParser "CommentDelimiter" value.
506 std::string CommentDelimiter;
507
508 /// The AsmParser "RegisterPrefix" value.
509 std::string RegisterPrefix;
510
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000511 /// The classes which are needed for matching.
512 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000513
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000514 /// The information on the instruction to match.
515 std::vector<InstructionInfo*> Instructions;
516
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000517 /// Map of Register records to their class information.
518 std::map<Record*, ClassInfo*> RegisterClasses;
519
Daniel Dunbar54074b52010-07-19 05:44:09 +0000520 /// Map of Predicate records to their subtarget information.
521 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner6fa152c2010-10-30 20:15:02 +0000522
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000523private:
524 /// Map of token to class information which has already been constructed.
525 std::map<std::string, ClassInfo*> TokenClasses;
526
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000527 /// Map of RegisterClass records to their class information.
528 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000529
Daniel Dunbar338825c2009-08-10 18:41:10 +0000530 /// Map of AsmOperandClass records to their class information.
531 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000532
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000533private:
534 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000535 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000536
537 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000538 ClassInfo *getOperandClass(StringRef Token,
Chris Lattnerc240bb02010-11-01 04:03:32 +0000539 const CGIOperandList::OperandInfo &OI);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000540
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000541 /// BuildRegisterClasses - Build the ClassInfo* instances for register
542 /// classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000543 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000544
545 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
546 /// operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000547 void BuildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000548
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000549public:
Chris Lattner02bcbc92010-11-01 01:37:30 +0000550 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000551
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000552 /// BuildInfo - Construct the various tables used during matching.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000553 void BuildInfo();
Chris Lattner6fa152c2010-10-30 20:15:02 +0000554
555 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
556 /// given operand.
557 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
558 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
559 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
560 SubtargetFeatures.find(Def);
561 return I == SubtargetFeatures.end() ? 0 : I->second;
562 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000563};
564
Daniel Dunbar20927f22009-08-07 08:26:05 +0000565}
566
567void InstructionInfo::dump() {
568 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
569 << ", tokens:[";
570 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
571 errs() << Tokens[i];
572 if (i + 1 != e)
573 errs() << ", ";
574 }
575 errs() << "]\n";
576
577 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
578 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000579 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000580 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000581 errs() << '\"' << Tokens[i] << "\"\n";
582 continue;
583 }
584
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000585 if (!Op.OperandInfo) {
586 errs() << "(singleton register)\n";
587 continue;
588 }
589
Chris Lattnerc240bb02010-11-01 04:03:32 +0000590 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000591 errs() << OI.Name << " " << OI.Rec->getName()
592 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
593 }
594}
595
Chris Lattner02bcbc92010-11-01 01:37:30 +0000596/// getRegisterRecord - Get the register record for \arg name, or 0.
597static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
598 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
599 const CodeGenRegister &Reg = Target.getRegisters()[i];
600 if (Name == Reg.TheDef->getValueAsString("AsmName"))
601 return Reg.TheDef;
602 }
603
604 return 0;
605}
606
607/// getSingletonRegisterForToken - If the specified token is a singleton
608/// register, return the register name, otherwise return a null StringRef.
Chris Lattner1de88232010-11-01 01:47:07 +0000609Record *InstructionInfo::
Chris Lattner02bcbc92010-11-01 01:37:30 +0000610getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
611 StringRef Tok = Tokens[i];
612 if (!Tok.startswith(Info.RegisterPrefix))
Chris Lattner1de88232010-11-01 01:47:07 +0000613 return 0;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000614
615 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
Chris Lattner1de88232010-11-01 01:47:07 +0000616 if (Record *Rec = getRegisterRecord(Info.Target, RegName))
617 return Rec;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000618
Chris Lattner1de88232010-11-01 01:47:07 +0000619 // If there is no register prefix (i.e. "%" in "%eax"), then this may
620 // be some random non-register token, just ignore it.
621 if (Info.RegisterPrefix.empty())
622 return 0;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000623
Chris Lattner1de88232010-11-01 01:47:07 +0000624 std::string Err = "unable to find register for '" + RegName.str() +
625 "' (which matches register prefix)";
626 throw TGError(Instr->TheDef->getLoc(), Err);
Chris Lattner02bcbc92010-11-01 01:37:30 +0000627}
628
629
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000630static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000631 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000632
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000633 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
634 switch (*it) {
635 case '*': Res += "_STAR_"; break;
636 case '%': Res += "_PCT_"; break;
637 case ':': Res += "_COLON_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000638 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000639 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000640 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000641 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000642 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000643 }
644 }
645
646 return Res;
647}
648
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000649ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000650 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000651
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000652 if (!Entry) {
653 Entry = new ClassInfo();
654 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000655 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000656 Entry->Name = "MCK_" + getEnumNameForToken(Token);
657 Entry->ValueName = Token;
658 Entry->PredicateMethod = "<invalid>";
659 Entry->RenderMethod = "<invalid>";
660 Classes.push_back(Entry);
661 }
662
663 return Entry;
664}
665
666ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000667AsmMatcherInfo::getOperandClass(StringRef Token,
Chris Lattnerc240bb02010-11-01 04:03:32 +0000668 const CGIOperandList::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000669 if (OI.Rec->isSubClassOf("RegisterClass")) {
670 ClassInfo *CI = RegisterClassClasses[OI.Rec];
671
672 if (!CI) {
673 PrintError(OI.Rec->getLoc(), "register class has no class info!");
674 throw std::string("ERROR: Missing register class!");
675 }
676
677 return CI;
678 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000679
Daniel Dunbar338825c2009-08-10 18:41:10 +0000680 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
681 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
682 ClassInfo *CI = AsmOperandClasses[MatchClass];
683
684 if (!CI) {
685 PrintError(OI.Rec->getLoc(), "operand has no match class!");
686 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000687 }
688
Daniel Dunbar338825c2009-08-10 18:41:10 +0000689 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000690}
691
Chris Lattner1de88232010-11-01 01:47:07 +0000692void AsmMatcherInfo::
693BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000694 std::vector<CodeGenRegisterClass> RegisterClasses;
695 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000696
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000697 RegisterClasses = Target.getRegisterClasses();
698 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000699
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000700 // The register sets used for matching.
701 std::set< std::set<Record*> > RegisterSets;
702
Jim Grosbacha7c78222010-10-29 22:13:48 +0000703 // Gather the defined sets.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000704 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
705 ie = RegisterClasses.end(); it != ie; ++it)
706 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
707 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000708
709 // Add any required singleton sets.
Chris Lattner1de88232010-11-01 01:47:07 +0000710 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
711 ie = SingletonRegisters.end(); it != ie; ++it) {
712 Record *Rec = *it;
713 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
714 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000715
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000716 // Introduce derived sets where necessary (when a register does not determine
717 // a unique register set class), and build the mapping of registers to the set
718 // they should classify to.
719 std::map<Record*, std::set<Record*> > RegisterMap;
720 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
721 ie = Registers.end(); it != ie; ++it) {
722 CodeGenRegister &CGR = *it;
723 // Compute the intersection of all sets containing this register.
724 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000725
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000726 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
727 ie = RegisterSets.end(); it != ie; ++it) {
728 if (!it->count(CGR.TheDef))
729 continue;
730
731 if (ContainingSet.empty()) {
732 ContainingSet = *it;
733 } else {
734 std::set<Record*> Tmp;
735 std::swap(Tmp, ContainingSet);
736 std::insert_iterator< std::set<Record*> > II(ContainingSet,
737 ContainingSet.begin());
738 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
739 II);
740 }
741 }
742
743 if (!ContainingSet.empty()) {
744 RegisterSets.insert(ContainingSet);
745 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
746 }
747 }
748
749 // Construct the register classes.
750 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
751 unsigned Index = 0;
752 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
753 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
754 ClassInfo *CI = new ClassInfo();
755 CI->Kind = ClassInfo::RegisterClass0 + Index;
756 CI->ClassName = "Reg" + utostr(Index);
757 CI->Name = "MCK_Reg" + utostr(Index);
758 CI->ValueName = "";
759 CI->PredicateMethod = ""; // unused
760 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000761 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000762 Classes.push_back(CI);
763 RegisterSetClasses.insert(std::make_pair(*it, CI));
764 }
765
766 // Find the superclasses; we could compute only the subgroup lattice edges,
767 // but there isn't really a point.
768 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
769 ie = RegisterSets.end(); it != ie; ++it) {
770 ClassInfo *CI = RegisterSetClasses[*it];
771 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
772 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000773 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000774 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
775 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
776 }
777
778 // Name the register classes which correspond to a user defined RegisterClass.
779 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
780 ie = RegisterClasses.end(); it != ie; ++it) {
781 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
782 it->Elements.end())];
783 if (CI->ValueName.empty()) {
784 CI->ClassName = it->getName();
785 CI->Name = "MCK_" + it->getName();
786 CI->ValueName = it->getName();
787 } else
788 CI->ValueName = CI->ValueName + "," + it->getName();
789
790 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
791 }
792
793 // Populate the map for individual registers.
794 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
795 ie = RegisterMap.end(); it != ie; ++it)
796 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000797
798 // Name the register classes which correspond to singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +0000799 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
800 ie = SingletonRegisters.end(); it != ie; ++it) {
801 Record *Rec = *it;
802 ClassInfo *CI = this->RegisterClasses[Rec];
803 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000804
Chris Lattner1de88232010-11-01 01:47:07 +0000805 if (CI->ValueName.empty()) {
806 CI->ClassName = Rec->getName();
807 CI->Name = "MCK_" + Rec->getName();
808 CI->ValueName = Rec->getName();
809 } else
810 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000811 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000812}
813
Chris Lattner02bcbc92010-11-01 01:37:30 +0000814void AsmMatcherInfo::BuildOperandClasses() {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000815 std::vector<Record*> AsmOperands;
816 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000817
818 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000819 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000820 ie = AsmOperands.end(); it != ie; ++it)
821 AsmOperandClasses[*it] = new ClassInfo();
822
Daniel Dunbar338825c2009-08-10 18:41:10 +0000823 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000824 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +0000825 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000826 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000827 CI->Kind = ClassInfo::UserClass0 + Index;
828
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000829 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
830 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
831 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
832 if (!DI) {
833 PrintError((*it)->getLoc(), "Invalid super class reference!");
834 continue;
835 }
836
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000837 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
838 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000839 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000840 else
841 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000842 }
843 CI->ClassName = (*it)->getValueAsString("Name");
844 CI->Name = "MCK_" + CI->ClassName;
845 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000846
847 // Get or construct the predicate method name.
848 Init *PMName = (*it)->getValueInit("PredicateMethod");
849 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
850 CI->PredicateMethod = SI->getValue();
851 } else {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000852 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000853 "Unexpected PredicateMethod field!");
854 CI->PredicateMethod = "is" + CI->ClassName;
855 }
856
857 // Get or construct the render method name.
858 Init *RMName = (*it)->getValueInit("RenderMethod");
859 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
860 CI->RenderMethod = SI->getValue();
861 } else {
862 assert(dynamic_cast<UnsetInit*>(RMName) &&
863 "Unexpected RenderMethod field!");
864 CI->RenderMethod = "add" + CI->ClassName + "Operands";
865 }
866
Daniel Dunbar338825c2009-08-10 18:41:10 +0000867 AsmOperandClasses[*it] = CI;
868 Classes.push_back(CI);
869 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000870}
871
Chris Lattner02bcbc92010-11-01 01:37:30 +0000872AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
873 : AsmParser(asmParser), Target(target),
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000874 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
875 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
876{
877}
878
Chris Lattner02bcbc92010-11-01 01:37:30 +0000879void AsmMatcherInfo::BuildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +0000880 // Build information about all of the AssemblerPredicates.
881 std::vector<Record*> AllPredicates =
882 Records.getAllDerivedDefinitions("Predicate");
883 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
884 Record *Pred = AllPredicates[i];
885 // Ignore predicates that are not intended for the assembler.
886 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
887 continue;
888
889 if (Pred->getName().empty()) {
890 PrintError(Pred->getLoc(), "Predicate has no name!");
891 throw std::string("ERROR: Predicate defs must be named");
892 }
893
894 unsigned FeatureNo = SubtargetFeatures.size();
895 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
896 assert(FeatureNo < 32 && "Too many subtarget features!");
897 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000898
Chris Lattner39ee0362010-10-31 19:10:56 +0000899 // Parse the instructions; we need to do this first so that we can gather the
900 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000901 SmallPtrSet<Record*, 16> SingletonRegisters;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000902 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
903 E = Target.inst_end(); I != E; ++I) {
904 const CodeGenInstruction &CGI = **I;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000905
Chris Lattner39ee0362010-10-31 19:10:56 +0000906 // If the tblgen -match-prefix option is specified (for tblgen hackers),
907 // filter the set of instructions we consider.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000908 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000909 continue;
910
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000911 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000912
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000913 II->InstrName = CGI.TheDef->getName();
914 II->Instr = &CGI;
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000915 // TODO: Eventually support asmparser for Variant != 0.
916 II->AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, 0);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000917
Chris Lattner39ee0362010-10-31 19:10:56 +0000918 // Remove comments from the asm string. We know that the asmstring only
919 // has one line.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000920 if (!CommentDelimiter.empty()) {
921 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
922 if (Idx != StringRef::npos)
923 II->AsmString = II->AsmString.substr(0, Idx);
924 }
925
Daniel Dunbar20927f22009-08-07 08:26:05 +0000926 TokenizeAsmString(II->AsmString, II->Tokens);
927
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000928 // Ignore instructions which shouldn't be matched and diagnose invalid
929 // instruction definitions with an error.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000930 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000931 continue;
Chris Lattner39ee0362010-10-31 19:10:56 +0000932
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000933 // Collect singleton registers, if used.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000934 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
Chris Lattner1de88232010-11-01 01:47:07 +0000935 if (Record *Reg = II->getSingletonRegisterForToken(i, *this))
936 SingletonRegisters.insert(Reg);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000937 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000938
939 // Compute the require features.
Chris Lattner0f899c72010-10-30 19:38:20 +0000940 std::vector<Record*> Predicates =
941 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner6fa152c2010-10-30 20:15:02 +0000942 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
943 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
944 II->RequiredFeatures.push_back(Feature);
Daniel Dunbar54074b52010-07-19 05:44:09 +0000945
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000946 Instructions.push_back(II.take());
947 }
Chris Lattnerc240bb02010-11-01 04:03:32 +0000948
949
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000950 // Build info for the register classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000951 BuildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000952
953 // Build info for the user defined assembly operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000954 BuildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000955
956 // Build the instruction information.
957 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
958 ie = Instructions.end(); it != ie; ++it) {
959 InstructionInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000960
Chris Lattnere206fcf2010-09-06 21:01:37 +0000961 // The first token of the instruction is the mnemonic, which must be a
Chris Lattner02bcbc92010-11-01 01:37:30 +0000962 // simple string, not a $foo variable or a singleton register.
Chris Lattnere206fcf2010-09-06 21:01:37 +0000963 assert(!II->Tokens.empty() && "Instruction has no tokens?");
964 StringRef Mnemonic = II->Tokens[0];
Chris Lattner1de88232010-11-01 01:47:07 +0000965 if (Mnemonic[0] == '$' || II->getSingletonRegisterForToken(0, *this))
Chris Lattner02bcbc92010-11-01 01:37:30 +0000966 throw TGError(II->Instr->TheDef->getLoc(),
967 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Jim Grosbacha7c78222010-10-29 22:13:48 +0000968
Chris Lattnere206fcf2010-09-06 21:01:37 +0000969 // Parse the tokens after the mnemonic.
970 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000971 StringRef Token = II->Tokens[i];
972
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000973 // Check for singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +0000974 if (Record *RegRecord = II->getSingletonRegisterForToken(i, *this)) {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000975 InstructionInfo::Operand Op;
976 Op.Class = RegisterClasses[RegRecord];
977 Op.OperandInfo = 0;
978 assert(Op.Class && Op.Class->Registers.size() == 1 &&
979 "Unexpected class for singleton register");
980 II->Operands.push_back(Op);
981 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000982 }
983
Daniel Dunbar20927f22009-08-07 08:26:05 +0000984 // Check for simple tokens.
985 if (Token[0] != '$') {
986 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000987 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000988 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000989 II->Operands.push_back(Op);
990 continue;
991 }
992
993 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000994 StringRef OperandName;
995 if (Token[1] == '{')
996 OperandName = Token.substr(2, Token.size() - 3);
997 else
998 OperandName = Token.substr(1);
999
1000 // Map this token to an operand. FIXME: Move elsewhere.
1001 unsigned Idx;
Chris Lattnerc240bb02010-11-01 04:03:32 +00001002 if (!II->Instr->Operands.hasOperandNamed(OperandName, Idx))
Jim Grosbacha7c78222010-10-29 22:13:48 +00001003 throw std::string("error: unable to find operand: '" +
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001004 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001005
Daniel Dunbaraf616812010-02-10 08:15:48 +00001006 // FIXME: This is annoying, the named operand may be tied (e.g.,
1007 // XCHG8rm). What we want is the untied operand, which we now have to
1008 // grovel for. Only worry about this for single entry operands, we have to
1009 // clean this up anyway.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001010 const CGIOperandList::OperandInfo *OI = &II->Instr->Operands[Idx];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001011 if (OI->Constraints[0].isTied()) {
1012 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1013
1014 // The tied operand index is an MIOperand index, find the operand that
1015 // contains it.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001016 for (unsigned i = 0, e = II->Instr->Operands.size(); i != e; ++i) {
1017 if (II->Instr->Operands[i].MIOperandNo == TiedOp) {
1018 OI = &II->Instr->Operands[i];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001019 break;
1020 }
1021 }
1022
1023 assert(OI && "Unable to find tied operand target!");
1024 }
1025
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001026 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001027 Op.Class = getOperandClass(Token, *OI);
1028 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001029 II->Operands.push_back(Op);
1030 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001031 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001032
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001033 // Reorder classes so that classes preceed super classes.
1034 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001035}
1036
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001037static std::pair<unsigned, unsigned> *
1038GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1039 unsigned Index) {
1040 for (unsigned i = 0, e = List.size(); i != e; ++i)
1041 if (Index == List[i].first)
1042 return &List[i];
1043
1044 return 0;
1045}
1046
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001047static void EmitConvertToMCInst(CodeGenTarget &Target,
1048 std::vector<InstructionInfo*> &Infos,
1049 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001050 // Write the convert function to a separate stream, so we can drop it after
1051 // the enum.
1052 std::string ConvertFnBody;
1053 raw_string_ostream CvtOS(ConvertFnBody);
1054
Daniel Dunbar20927f22009-08-07 08:26:05 +00001055 // Function we have already generated.
1056 std::set<std::string> GeneratedFns;
1057
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001058 // Start the unified conversion function.
1059
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001060 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001061 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001062 << " const SmallVectorImpl<MCParsedAsmOperand*"
1063 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001064 CvtOS << " Inst.setOpcode(Opcode);\n";
1065 CvtOS << " switch (Kind) {\n";
1066 CvtOS << " default:\n";
1067
1068 // Start the enum, which we will generate inline.
1069
1070 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001071 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001072
Chris Lattner98986712010-01-14 22:21:20 +00001073 // TargetOperandClass - This is the target's operand class, like X86Operand.
1074 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001075
Daniel Dunbar20927f22009-08-07 08:26:05 +00001076 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1077 ie = Infos.end(); it != ie; ++it) {
1078 InstructionInfo &II = **it;
1079
1080 // Order the (class) operands by the order to convert them into an MCInst.
1081 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1082 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1083 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001084 if (Op.OperandInfo)
1085 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001086 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001087
1088 // Find any tied operands.
1089 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00001090 for (unsigned i = 0, e = II.Instr->Operands.size(); i != e; ++i) {
1091 const CGIOperandList::OperandInfo &OpInfo = II.Instr->Operands[i];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001092 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00001093 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001094 if (CI.isTied())
1095 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1096 CI.getTiedOperand()));
1097 }
1098 }
1099
Daniel Dunbar20927f22009-08-07 08:26:05 +00001100 std::sort(MIOperandList.begin(), MIOperandList.end());
1101
1102 // Compute the total number of operands.
1103 unsigned NumMIOperands = 0;
Chris Lattnerc240bb02010-11-01 04:03:32 +00001104 for (unsigned i = 0, e = II.Instr->Operands.size(); i != e; ++i) {
1105 const CGIOperandList::OperandInfo &OI = II.Instr->Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001106 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbar20927f22009-08-07 08:26:05 +00001107 OI.MIOperandNo + OI.MINumOperands);
1108 }
1109
1110 // Build the conversion function signature.
1111 std::string Signature = "Convert";
1112 unsigned CurIndex = 0;
1113 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1114 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001115 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001116 "Duplicate match for instruction operand!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001117
Daniel Dunbar20927f22009-08-07 08:26:05 +00001118 // Skip operands which weren't matched by anything, this occurs when the
1119 // .td file encodes "implicit" operands as explicit ones.
1120 //
1121 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001122 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001123 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1124 CurIndex);
1125 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001126 Signature += "__Imp";
1127 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001128 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001129 }
1130
1131 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001132
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001133 // Registers are always converted the same, don't duplicate the conversion
1134 // function based on them.
1135 //
1136 // FIXME: We could generalize this based on the render method, if it
1137 // mattered.
1138 if (Op.Class->isRegisterClass())
1139 Signature += "Reg";
1140 else
1141 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001142 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001143 Signature += "_" + utostr(MIOperandList[i].second);
1144
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001145 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001146 }
1147
1148 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001149 for (; CurIndex != NumMIOperands; ++CurIndex) {
1150 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1151 CurIndex);
1152 if (!Tie)
1153 Signature += "__Imp";
1154 else
1155 Signature += "__Tie" + utostr(Tie->second);
1156 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001157
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001158 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001159
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001160 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001161 if (!GeneratedFns.insert(Signature).second)
1162 continue;
1163
1164 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001165
1166 // Add to the enum list.
1167 OS << " " << Signature << ",\n";
1168
1169 // And to the convert function.
1170 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001171 CurIndex = 0;
1172 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1173 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1174
1175 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001176 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1177 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001178 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1179 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001180
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001181 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001182 // If not, this is some implicit operand. Just assume it is a register
1183 // for now.
1184 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1185 } else {
1186 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001187 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001188 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001189 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001190 }
1191 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001192
Chris Lattner98986712010-01-14 22:21:20 +00001193 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbacha7c78222010-10-29 22:13:48 +00001194 << MIOperandList[i].second
1195 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001196 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1197 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001198 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001199
Daniel Dunbar20927f22009-08-07 08:26:05 +00001200 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001201 for (; CurIndex != NumMIOperands; ++CurIndex) {
1202 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1203 CurIndex);
1204
1205 if (!Tie) {
1206 // If not, this is some implicit operand. Just assume it is a register
1207 // for now.
1208 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1209 } else {
1210 // Copy the tied operand.
1211 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1212 CvtOS << " Inst.addOperand(Inst.getOperand("
1213 << Tie->second << "));\n";
1214 }
1215 }
1216
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001217 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001218 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001219
1220 // Finish the convert function.
1221
1222 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001223 CvtOS << "}\n\n";
1224
1225 // Finish the enum, and drop the convert function after it.
1226
1227 OS << " NumConversionVariants\n";
1228 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001229
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001230 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001231}
1232
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001233/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1234static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1235 std::vector<ClassInfo*> &Infos,
1236 raw_ostream &OS) {
1237 OS << "namespace {\n\n";
1238
1239 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1240 << "/// instruction matching.\n";
1241 OS << "enum MatchClassKind {\n";
1242 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001243 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001244 ie = Infos.end(); it != ie; ++it) {
1245 ClassInfo &CI = **it;
1246 OS << " " << CI.Name << ", // ";
1247 if (CI.Kind == ClassInfo::Token) {
1248 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001249 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001250 if (!CI.ValueName.empty())
1251 OS << "register class '" << CI.ValueName << "'\n";
1252 else
1253 OS << "derived register class\n";
1254 } else {
1255 OS << "user defined class '" << CI.ValueName << "'\n";
1256 }
1257 }
1258 OS << " NumMatchClassKinds\n";
1259 OS << "};\n\n";
1260
1261 OS << "}\n\n";
1262}
1263
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001264/// EmitClassifyOperand - Emit the function to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001265static void EmitClassifyOperand(AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001266 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001267 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
Chris Lattner02bcbc92010-11-01 01:37:30 +00001268 << " " << Info.Target.getName() << "Operand &Operand = *("
1269 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001270
1271 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001272 OS << " if (Operand.isToken())\n";
1273 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001274
1275 // Classify registers.
1276 //
1277 // FIXME: Don't hardcode isReg, getReg.
1278 OS << " if (Operand.isReg()) {\n";
1279 OS << " switch (Operand.getReg()) {\n";
1280 OS << " default: return InvalidMatchClass;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001281 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001282 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1283 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001284 OS << " case " << Info.Target.getName() << "::"
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001285 << it->first->getName() << ": return " << it->second->Name << ";\n";
1286 OS << " }\n";
1287 OS << " }\n\n";
1288
1289 // Classify user defined operands.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001290 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001291 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001292 ClassInfo &CI = **it;
1293
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001294 if (!CI.isUserClass())
1295 continue;
1296
1297 OS << " // '" << CI.ClassName << "' class";
1298 if (!CI.SuperClasses.empty()) {
1299 OS << ", subclass of ";
1300 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1301 if (i) OS << ", ";
1302 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1303 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001304 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001305 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001306 OS << "\n";
1307
1308 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001309
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001310 // Validate subclass relationships.
1311 if (!CI.SuperClasses.empty()) {
1312 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1313 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1314 << "() && \"Invalid class relationship!\");\n";
1315 }
1316
1317 OS << " return " << CI.Name << ";\n";
1318 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001319 }
1320 OS << " return InvalidMatchClass;\n";
1321 OS << "}\n\n";
1322}
1323
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001324/// EmitIsSubclass - Emit the subclass predicate function.
1325static void EmitIsSubclass(CodeGenTarget &Target,
1326 std::vector<ClassInfo*> &Infos,
1327 raw_ostream &OS) {
1328 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1329 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1330 OS << " if (A == B)\n";
1331 OS << " return true;\n\n";
1332
1333 OS << " switch (A) {\n";
1334 OS << " default:\n";
1335 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001336 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001337 ie = Infos.end(); it != ie; ++it) {
1338 ClassInfo &A = **it;
1339
1340 if (A.Kind != ClassInfo::Token) {
1341 std::vector<StringRef> SuperClasses;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001342 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001343 ie = Infos.end(); it != ie; ++it) {
1344 ClassInfo &B = **it;
1345
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001346 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001347 SuperClasses.push_back(B.Name);
1348 }
1349
1350 if (SuperClasses.empty())
1351 continue;
1352
1353 OS << "\n case " << A.Name << ":\n";
1354
1355 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001356 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001357 continue;
1358 }
1359
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001360 OS << " switch (B) {\n";
1361 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001362 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001363 OS << " case " << SuperClasses[i] << ": return true;\n";
1364 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001365 }
1366 }
1367 OS << " }\n";
1368 OS << "}\n\n";
1369}
1370
Chris Lattner70add882009-08-08 20:02:57 +00001371
1372
Daniel Dunbar245f0582009-08-08 21:22:41 +00001373/// EmitMatchTokenString - Emit the function to match a token string to the
1374/// appropriate match class value.
1375static void EmitMatchTokenString(CodeGenTarget &Target,
1376 std::vector<ClassInfo*> &Infos,
1377 raw_ostream &OS) {
1378 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001379 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001380 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001381 ie = Infos.end(); it != ie; ++it) {
1382 ClassInfo &CI = **it;
1383
1384 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001385 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1386 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001387 }
1388
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001389 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001390
Chris Lattner5845e5c2010-09-06 02:01:51 +00001391 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001392
1393 OS << " return InvalidMatchClass;\n";
1394 OS << "}\n\n";
1395}
Chris Lattner70add882009-08-08 20:02:57 +00001396
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001397/// EmitMatchRegisterName - Emit the function to match a string to the target
1398/// specific register enum.
1399static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1400 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001401 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001402 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001403 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1404 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001405 if (Reg.TheDef->getValueAsString("AsmName").empty())
1406 continue;
1407
Chris Lattner5845e5c2010-09-06 02:01:51 +00001408 Matches.push_back(StringMatcher::StringPair(
1409 Reg.TheDef->getValueAsString("AsmName"),
1410 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001411 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001412
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001413 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001414
Chris Lattner5845e5c2010-09-06 02:01:51 +00001415 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001416
Daniel Dunbar245f0582009-08-08 21:22:41 +00001417 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001418 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001419}
Daniel Dunbara027d222009-07-31 02:32:59 +00001420
Daniel Dunbar54074b52010-07-19 05:44:09 +00001421/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1422/// definitions.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001423static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001424 raw_ostream &OS) {
1425 OS << "// Flags for subtarget features that participate in "
1426 << "instruction matching.\n";
1427 OS << "enum SubtargetFeatureFlag {\n";
1428 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1429 it = Info.SubtargetFeatures.begin(),
1430 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1431 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001432 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001433 }
1434 OS << " Feature_None = 0\n";
1435 OS << "};\n\n";
1436}
1437
1438/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1439/// available features given a subtarget.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001440static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001441 raw_ostream &OS) {
1442 std::string ClassName =
1443 Info.AsmParser->getValueAsString("AsmParserClassName");
1444
Chris Lattner02bcbc92010-11-01 01:37:30 +00001445 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1446 << "ComputeAvailableFeatures(const " << Info.Target.getName()
Daniel Dunbar54074b52010-07-19 05:44:09 +00001447 << "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 Lattner4a74ee72010-11-01 02:09:21 +00001467 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Chris Lattner693173f2010-10-30 19:23:13 +00001468
Chris Lattner4a74ee72010-11-01 02:09:21 +00001469 if (F == 0)
1470 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1471 "' is not marked as an AssemblerPredicate!");
1472
1473 if (NumFeatures)
1474 Result += '|';
1475
1476 Result += F->getEnumName();
1477 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00001478 }
1479
1480 if (NumFeatures > 1)
1481 Result = '(' + Result + ')';
1482 return Result;
1483}
1484
Chris Lattner674c1dc2010-10-30 17:36:36 +00001485/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001486/// emit a function for them and return true, otherwise return false.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001487static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattner674c1dc2010-10-30 17:36:36 +00001488 std::vector<Record*> Aliases =
1489 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001490 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001491
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001492 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1493 "unsigned Features) {\n";
1494
Chris Lattner4fd32c62010-10-30 18:56:12 +00001495 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1496 // iteration order of the map is stable.
1497 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1498
Chris Lattner674c1dc2010-10-30 17:36:36 +00001499 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1500 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001501 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001502 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001503
1504 // Process each alias a "from" mnemonic at a time, building the code executed
1505 // by the string remapper.
1506 std::vector<StringMatcher::StringPair> Cases;
1507 for (std::map<std::string, std::vector<Record*> >::iterator
1508 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1509 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00001510 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00001511
1512 // Loop through each alias and emit code that handles each case. If there
1513 // are two instructions without predicates, emit an error. If there is one,
1514 // emit it last.
1515 std::string MatchCode;
1516 int AliasWithNoPredicate = -1;
Chris Lattner4fd32c62010-10-30 18:56:12 +00001517
Chris Lattner693173f2010-10-30 19:23:13 +00001518 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1519 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00001520 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner693173f2010-10-30 19:23:13 +00001521
1522 // If this unconditionally matches, remember it for later and diagnose
1523 // duplicates.
1524 if (FeatureMask.empty()) {
1525 if (AliasWithNoPredicate != -1) {
1526 // We can't have two aliases from the same mnemonic with no predicate.
1527 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1528 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001529 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1530 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner693173f2010-10-30 19:23:13 +00001531 }
1532
1533 AliasWithNoPredicate = i;
1534 continue;
1535 }
1536
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001537 if (!MatchCode.empty())
1538 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00001539 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1540 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00001541 }
1542
Chris Lattner693173f2010-10-30 19:23:13 +00001543 if (AliasWithNoPredicate != -1) {
1544 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001545 if (!MatchCode.empty())
1546 MatchCode += "else\n ";
1547 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00001548 }
1549
1550 MatchCode += "return;";
1551
1552 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00001553 }
1554
Chris Lattner674c1dc2010-10-30 17:36:36 +00001555
1556 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner7fd44892010-10-30 18:48:18 +00001557 OS << "}\n";
1558
1559 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001560}
1561
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001562void AsmMatcherEmitter::run(raw_ostream &OS) {
1563 CodeGenTarget Target;
1564 Record *AsmParser = Target.getAsmParser();
1565 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1566
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001567 // Compute the information on the instructions to match.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001568 AsmMatcherInfo Info(AsmParser, Target);
1569 Info.BuildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00001570
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001571 // Sort the instruction table using the partial order on classes. We use
1572 // stable_sort to ensure that ambiguous instructions are still
1573 // deterministically ordered.
1574 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1575 less_ptr<InstructionInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001576
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001577 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001578 for (std::vector<InstructionInfo*>::iterator
1579 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001580 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001581 (*it)->dump();
1582 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001583
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001584 // Check for ambiguous instructions.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001585 DEBUG_WITH_TYPE("ambiguous_instrs", {
1586 unsigned NumAmbiguous = 0;
Chris Lattner87410362010-09-06 20:21:47 +00001587 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1588 for (unsigned j = i + 1; j != e; ++j) {
1589 InstructionInfo &A = *Info.Instructions[i];
1590 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001591
Chris Lattner87410362010-09-06 20:21:47 +00001592 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001593 errs() << "warning: ambiguous instruction match:\n";
1594 A.dump();
1595 errs() << "\nis incomparable with:\n";
1596 B.dump();
1597 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00001598 ++NumAmbiguous;
1599 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00001600 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001601 }
Chris Lattner87410362010-09-06 20:21:47 +00001602 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001603 errs() << "warning: " << NumAmbiguous
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001604 << " ambiguous instructions!\n";
1605 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001606
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001607 // Write the output.
1608
1609 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1610
Chris Lattner0692ee62010-09-06 19:11:01 +00001611 // Information for the class declaration.
1612 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1613 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001614 OS << " // This should be included into the middle of the declaration of \n";
1615 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001616 OS << " unsigned ComputeAvailableFeatures(const " <<
1617 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001618 OS << " enum MatchResultTy {\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001619 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1620 OS << " Match_MissingFeature\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001621 OS << " };\n";
Jim Grosbachbb168242010-10-08 18:13:57 +00001622 OS << " MatchResultTy MatchInstructionImpl(const "
1623 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattnerce4a3352010-09-06 22:11:18 +00001624 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001625 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1626
Jim Grosbacha7c78222010-10-29 22:13:48 +00001627
1628
1629
Chris Lattner0692ee62010-09-06 19:11:01 +00001630 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1631 OS << "#undef GET_REGISTER_MATCHER\n\n";
1632
Daniel Dunbar54074b52010-07-19 05:44:09 +00001633 // Emit the subtarget feature enumeration.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001634 EmitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001635
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001636 // Emit the function to match a register name to number.
1637 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001638
1639 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001640
Chris Lattner0692ee62010-09-06 19:11:01 +00001641
1642 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1643 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001644
Chris Lattner7fd44892010-10-30 18:48:18 +00001645 // Generate the function that remaps for mnemonic aliases.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001646 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner7fd44892010-10-30 18:48:18 +00001647
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001648 // Generate the unified function to convert operands into an MCInst.
1649 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001650
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001651 // Emit the enumeration for classes which participate in matching.
1652 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001653
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001654 // Emit the routine to match token strings to their match class.
1655 EmitMatchTokenString(Target, Info.Classes, OS);
1656
1657 // Emit the routine to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001658 EmitClassifyOperand(Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001659
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001660 // Emit the subclass predicate routine.
1661 EmitIsSubclass(Target, Info.Classes, OS);
1662
Daniel Dunbar54074b52010-07-19 05:44:09 +00001663 // Emit the available features compute function.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001664 EmitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001665
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001666
1667 size_t MaxNumOperands = 0;
1668 for (std::vector<InstructionInfo*>::const_iterator it =
1669 Info.Instructions.begin(), ie = Info.Instructions.end();
1670 it != ie; ++it)
1671 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001672
1673
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001674 // Emit the static match table; unused classes get initalized to 0 which is
1675 // guaranteed to be InvalidMatchClass.
1676 //
1677 // FIXME: We can reduce the size of this table very easily. First, we change
1678 // it so that store the kinds in separate bit-fields for each index, which
1679 // only needs to be the max width used for classes at that index (we also need
1680 // to reject based on this during classification). If we then make sure to
1681 // order the match kinds appropriately (putting mnemonics last), then we
1682 // should only end up using a few bits for each class, especially the ones
1683 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00001684 OS << "namespace {\n";
1685 OS << " struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001686 OS << " unsigned Opcode;\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001687 OS << " const char *Mnemonic;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001688 OS << " ConversionKind ConvertFn;\n";
1689 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001690 OS << " unsigned RequiredFeatures;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001691 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001692
Chris Lattner2b1f9432010-09-06 21:22:45 +00001693 OS << "// Predicate for searching for an opcode.\n";
1694 OS << " struct LessOpcode {\n";
1695 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1696 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1697 OS << " }\n";
1698 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1699 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1700 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00001701 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1702 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1703 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00001704 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001705
Chris Lattner96352e52010-09-06 21:08:38 +00001706 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001707
Chris Lattner96352e52010-09-06 21:08:38 +00001708 OS << "static const MatchEntry MatchTable["
1709 << Info.Instructions.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001710
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001711 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner96352e52010-09-06 21:08:38 +00001712 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001713 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001714 InstructionInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001715
Chris Lattner96352e52010-09-06 21:08:38 +00001716 OS << " { " << Target.getName() << "::" << II.InstrName
1717 << ", \"" << II.Tokens[0] << "\""
1718 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001719 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1720 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001721
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001722 if (i) OS << ", ";
1723 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001724 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001725 OS << " }, ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001726
Daniel Dunbar54074b52010-07-19 05:44:09 +00001727 // Write the required features mask.
1728 if (!II.RequiredFeatures.empty()) {
1729 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1730 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001731 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00001732 }
1733 } else
1734 OS << "0";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001735
Daniel Dunbar54074b52010-07-19 05:44:09 +00001736 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001737 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001738
Chris Lattner96352e52010-09-06 21:08:38 +00001739 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001740
Chris Lattner96352e52010-09-06 21:08:38 +00001741 // Finally, build the match function.
1742 OS << Target.getName() << ClassName << "::MatchResultTy "
1743 << Target.getName() << ClassName << "::\n"
1744 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1745 << " &Operands,\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001746 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001747
1748 // Emit code to get the available features.
1749 OS << " // Get the current feature set.\n";
1750 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1751
Chris Lattner674c1dc2010-10-30 17:36:36 +00001752 OS << " // Get the instruction mnemonic, which is the first token.\n";
1753 OS << " StringRef Mnemonic = ((" << Target.getName()
1754 << "Operand*)Operands[0])->getToken();\n\n";
1755
Chris Lattner7fd44892010-10-30 18:48:18 +00001756 if (HasMnemonicAliases) {
1757 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1758 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1759 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00001760
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001761 // Emit code to compute the class list for this operand vector.
1762 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001763 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1764 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1765 OS << " return Match_InvalidOperand;\n";
1766 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001767
1768 OS << " // Compute the class list for this operand vector.\n";
1769 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001770 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1771 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001772
1773 OS << " // Check for invalid operands before matching.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001774 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1775 OS << " ErrorInfo = i;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001776 OS << " return Match_InvalidOperand;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001777 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001778 OS << " }\n\n";
1779
1780 OS << " // Mark unused classes.\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001781 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001782 << "i != e; ++i)\n";
1783 OS << " Classes[i] = InvalidMatchClass;\n\n";
1784
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001785 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001786 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001787 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1788 OS << " // wrong for all instances of the instruction.\n";
1789 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001790
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001791 // Emit code to search the table.
1792 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001793 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1794 OS << " std::equal_range(MatchTable, MatchTable+"
1795 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001796
Chris Lattnera008e8a2010-09-06 21:54:15 +00001797 OS << " // Return a more specific error code if no mnemonics match.\n";
1798 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1799 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001800
Chris Lattner2b1f9432010-09-06 21:22:45 +00001801 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00001802 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001803 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001804
Gabor Greife53ee3b2010-09-07 06:06:06 +00001805 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattner44b0daa2010-09-06 21:25:43 +00001806 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001807
Daniel Dunbar54074b52010-07-19 05:44:09 +00001808 // Emit check that the subclasses match.
Chris Lattnerce4a3352010-09-06 22:11:18 +00001809 OS << " bool OperandsValid = true;\n";
1810 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1811 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1812 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001813 OS << " // If this operand is broken for all of the instances of this\n";
1814 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1815 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001816 OS << " ErrorInfo = i+1;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001817 OS << " else\n";
1818 OS << " ErrorInfo = ~0U;";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001819 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1820 OS << " OperandsValid = false;\n";
1821 OS << " break;\n";
1822 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001823
Chris Lattnerce4a3352010-09-06 22:11:18 +00001824 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00001825
1826 // Emit check that the required features are available.
1827 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1828 << "!= it->RequiredFeatures) {\n";
1829 OS << " HadMatchOtherThanFeatures = true;\n";
1830 OS << " continue;\n";
1831 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001832
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001833 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001834 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1835
1836 // Call the post-processing function, if used.
1837 std::string InsnCleanupFn =
1838 AsmParser->getValueAsString("AsmParserInstCleanup");
1839 if (!InsnCleanupFn.empty())
1840 OS << " " << InsnCleanupFn << "(Inst);\n";
1841
Chris Lattner79ed3f72010-09-06 19:22:17 +00001842 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001843 OS << " }\n\n";
1844
Chris Lattnerec6789f2010-09-06 20:08:02 +00001845 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1846 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001847 OS << " return Match_InvalidOperand;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001848 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001849
Chris Lattner0692ee62010-09-06 19:11:01 +00001850 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001851}