blob: d4fe6beca3bd10227148c7caf87c0ddff8b1a492 [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
Daniel Dunbar20927f22009-08-07 08:26:05 +0000172
173namespace {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000174 class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000175struct SubtargetFeatureInfo;
176
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000177/// ClassInfo - Helper class for storing the information about a particular
178/// class of operands which can be matched.
179struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000180 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000181 /// Invalid kind, for use as a sentinel value.
182 Invalid = 0,
183
184 /// The class for a particular token.
185 Token,
186
187 /// The (first) register class, subsequent register classes are
188 /// RegisterClass0+1, and so on.
189 RegisterClass0,
190
191 /// The (first) user defined class, subsequent user defined classes are
192 /// UserClass0+1, and so on.
193 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000194 };
195
196 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
197 /// N) for the Nth user defined class.
198 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000199
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000200 /// SuperClasses - The super classes of this class. Note that for simplicities
201 /// sake user operands only record their immediate super class, while register
202 /// operands include all superclasses.
203 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000204
Daniel Dunbar6745d422009-08-09 05:18:30 +0000205 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000206 std::string Name;
207
Daniel Dunbar6745d422009-08-09 05:18:30 +0000208 /// ClassName - The unadorned generic name for this class (e.g., Token).
209 std::string ClassName;
210
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000211 /// ValueName - The name of the value this class represents; for a token this
212 /// is the literal token string, for an operand it is the TableGen class (or
213 /// empty if this is a derived class).
214 std::string ValueName;
215
216 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000217 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000218 std::string PredicateMethod;
219
220 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000221 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000222 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000223
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000224 /// For register classes, the records for all the registers in this class.
225 std::set<Record*> Registers;
226
227public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000228 /// isRegisterClass() - Check if this is a register class.
229 bool isRegisterClass() const {
230 return Kind >= RegisterClass0 && Kind < UserClass0;
231 }
232
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000233 /// isUserClass() - Check if this is a user defined class.
234 bool isUserClass() const {
235 return Kind >= UserClass0;
236 }
237
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000238 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
239 /// are related if they are in the same class hierarchy.
240 bool isRelatedTo(const ClassInfo &RHS) const {
241 // Tokens are only related to tokens.
242 if (Kind == Token || RHS.Kind == Token)
243 return Kind == Token && RHS.Kind == Token;
244
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000245 // Registers classes are only related to registers classes, and only if
246 // their intersection is non-empty.
247 if (isRegisterClass() || RHS.isRegisterClass()) {
248 if (!isRegisterClass() || !RHS.isRegisterClass())
249 return false;
250
251 std::set<Record*> Tmp;
252 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000253 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000254 RHS.Registers.begin(), RHS.Registers.end(),
255 II);
256
257 return !Tmp.empty();
258 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000259
260 // Otherwise we have two users operands; they are related if they are in the
261 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000262 //
263 // FIXME: This is an oversimplification, they should only be related if they
264 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000265 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
266 const ClassInfo *Root = this;
267 while (!Root->SuperClasses.empty())
268 Root = Root->SuperClasses.front();
269
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000270 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000271 while (!RHSRoot->SuperClasses.empty())
272 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000273
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000274 return Root == RHSRoot;
275 }
276
Jim Grosbacha7c78222010-10-29 22:13:48 +0000277 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000278 bool isSubsetOf(const ClassInfo &RHS) const {
279 // This is a subset of RHS if it is the same class...
280 if (this == &RHS)
281 return true;
282
283 // ... or if any of its super classes are a subset of RHS.
284 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
285 ie = SuperClasses.end(); it != ie; ++it)
286 if ((*it)->isSubsetOf(RHS))
287 return true;
288
289 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000290 }
291
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000292 /// operator< - Compare two classes.
293 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000294 if (this == &RHS)
295 return false;
296
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000297 // Unrelated classes can be ordered by kind.
298 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000299 return Kind < RHS.Kind;
300
301 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000302 case Invalid:
303 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000304 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000305 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000306 //
307 // FIXME: Compare by enum value.
308 return ValueName < RHS.ValueName;
309
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000310 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000311 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000312 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000313 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000314 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000315 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000316
317 // Otherwise, order by name to ensure we have a total ordering.
318 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000319 }
320 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000321};
322
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000323/// InstructionInfo - Helper class for storing the necessary information for an
324/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000325struct InstructionInfo {
326 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000327 /// The unique class instance this operand should match.
328 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000329
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000330 /// The original operand this corresponds to, if any.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000331 const CGIOperandList::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000332 };
333
334 /// InstrName - The target name for this instruction.
335 std::string InstrName;
336
Chris Lattner5bc93872010-11-01 04:34:44 +0000337 Record *const TheDef;
338 const CGIOperandList &OperandList;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000339
340 /// AsmString - The assembly string for this instruction (with variants
341 /// removed).
342 std::string AsmString;
343
344 /// Tokens - The tokenized assembly pattern that this instruction matches.
345 SmallVector<StringRef, 4> Tokens;
346
347 /// Operands - The operands that this instruction matches.
348 SmallVector<Operand, 4> Operands;
349
Daniel Dunbar54074b52010-07-19 05:44:09 +0000350 /// Predicates - The required subtarget features to match this instruction.
351 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
352
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000353 /// ConversionFnKind - The enum value which is passed to the generated
354 /// ConvertToMCInst to convert parsed operands into an MCInst for this
355 /// function.
356 std::string ConversionFnKind;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000357
Chris Lattner5bc93872010-11-01 04:34:44 +0000358 InstructionInfo(const CodeGenInstruction &CGI, StringRef CommentDelimiter)
359 : TheDef(CGI.TheDef), OperandList(CGI.Operands) {
360 InstrName = TheDef->getName();
361 // TODO: Eventually support asmparser for Variant != 0.
362 AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, 0);
363
364 // Remove comments from the asm string. We know that the asmstring only
365 // has one line.
366 if (!CommentDelimiter.empty()) {
367 size_t Idx = StringRef(AsmString).find(CommentDelimiter);
368 if (Idx != StringRef::npos)
369 AsmString = AsmString.substr(0, Idx);
370 }
371
372 TokenizeAsmString(AsmString, Tokens);
373 }
374
375 /// isAssemblerInstruction - Return true if this matchable is a valid thing to
376 /// match against.
377 bool isAssemblerInstruction() const;
378
Chris Lattner02bcbc92010-11-01 01:37:30 +0000379 /// getSingletonRegisterForToken - If the specified token is a singleton
Chris Lattner1de88232010-11-01 01:47:07 +0000380 /// register, return the Record for it, otherwise return null.
381 Record *getSingletonRegisterForToken(unsigned i,
382 const AsmMatcherInfo &Info) const;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000383
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000384 /// operator< - Compare two instructions.
385 bool operator<(const InstructionInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000386 // The primary comparator is the instruction mnemonic.
387 if (Tokens[0] != RHS.Tokens[0])
388 return Tokens[0] < RHS.Tokens[0];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000389
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000390 if (Operands.size() != RHS.Operands.size())
391 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000392
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000393 // Compare lexicographically by operand. The matcher validates that other
394 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
395 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000396 if (*Operands[i].Class < *RHS.Operands[i].Class)
397 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000398 if (*RHS.Operands[i].Class < *Operands[i].Class)
399 return false;
400 }
401
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000402 return false;
403 }
404
Daniel Dunbar2b544812009-08-09 06:05:33 +0000405 /// CouldMatchAmiguouslyWith - Check whether this instruction could
406 /// ambiguously match the same set of operands as \arg RHS (without being a
407 /// strictly superior match).
408 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
409 // The number of operands is unambiguous.
410 if (Operands.size() != RHS.Operands.size())
411 return false;
412
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000413 // Otherwise, make sure the ordering of the two instructions is unambiguous
414 // by checking that either (a) a token or operand kind discriminates them,
415 // or (b) the ordering among equivalent kinds is consistent.
416
Daniel Dunbar2b544812009-08-09 06:05:33 +0000417 // Tokens and operand kinds are unambiguous (assuming a correct target
418 // specific parser).
419 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
420 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
421 Operands[i].Class->Kind == ClassInfo::Token)
422 if (*Operands[i].Class < *RHS.Operands[i].Class ||
423 *RHS.Operands[i].Class < *Operands[i].Class)
424 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000425
Daniel Dunbar2b544812009-08-09 06:05:33 +0000426 // Otherwise, this operand could commute if all operands are equivalent, or
427 // there is a pair of operands that compare less than and a pair that
428 // compare greater than.
429 bool HasLT = false, HasGT = false;
430 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
431 if (*Operands[i].Class < *RHS.Operands[i].Class)
432 HasLT = true;
433 if (*RHS.Operands[i].Class < *Operands[i].Class)
434 HasGT = true;
435 }
436
437 return !(HasLT ^ HasGT);
438 }
439
Daniel Dunbar20927f22009-08-07 08:26:05 +0000440 void dump();
441};
442
Daniel Dunbar54074b52010-07-19 05:44:09 +0000443/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
444/// feature which participates in instruction matching.
445struct SubtargetFeatureInfo {
446 /// \brief The predicate record for this feature.
447 Record *TheDef;
448
449 /// \brief An unique index assigned to represent this feature.
450 unsigned Index;
451
Chris Lattner0aed1e72010-10-30 20:07:57 +0000452 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
453
Daniel Dunbar54074b52010-07-19 05:44:09 +0000454 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000455 std::string getEnumName() const {
456 return "Feature_" + TheDef->getName();
457 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000458};
459
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000460class AsmMatcherInfo {
461public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000462 /// The tablegen AsmParser record.
463 Record *AsmParser;
464
Chris Lattner02bcbc92010-11-01 01:37:30 +0000465 /// Target - The target information.
466 CodeGenTarget &Target;
467
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000468 /// The AsmParser "CommentDelimiter" value.
469 std::string CommentDelimiter;
470
471 /// The AsmParser "RegisterPrefix" value.
472 std::string RegisterPrefix;
473
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000474 /// The classes which are needed for matching.
475 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000476
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000477 /// The information on the instruction to match.
478 std::vector<InstructionInfo*> Instructions;
479
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000480 /// Map of Register records to their class information.
481 std::map<Record*, ClassInfo*> RegisterClasses;
482
Daniel Dunbar54074b52010-07-19 05:44:09 +0000483 /// Map of Predicate records to their subtarget information.
484 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner6fa152c2010-10-30 20:15:02 +0000485
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000486private:
487 /// Map of token to class information which has already been constructed.
488 std::map<std::string, ClassInfo*> TokenClasses;
489
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000490 /// Map of RegisterClass records to their class information.
491 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000492
Daniel Dunbar338825c2009-08-10 18:41:10 +0000493 /// Map of AsmOperandClass records to their class information.
494 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000495
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000496private:
497 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000498 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000499
500 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000501 ClassInfo *getOperandClass(StringRef Token,
Chris Lattnerc240bb02010-11-01 04:03:32 +0000502 const CGIOperandList::OperandInfo &OI);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000503
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000504 /// BuildRegisterClasses - Build the ClassInfo* instances for register
505 /// classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000506 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000507
508 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
509 /// operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000510 void BuildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000511
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000512public:
Chris Lattner02bcbc92010-11-01 01:37:30 +0000513 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000514
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000515 /// BuildInfo - Construct the various tables used during matching.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000516 void BuildInfo();
Chris Lattner6fa152c2010-10-30 20:15:02 +0000517
518 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
519 /// given operand.
520 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
521 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
522 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
523 SubtargetFeatures.find(Def);
524 return I == SubtargetFeatures.end() ? 0 : I->second;
525 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000526};
527
Daniel Dunbar20927f22009-08-07 08:26:05 +0000528}
529
530void InstructionInfo::dump() {
531 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
532 << ", tokens:[";
533 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
534 errs() << Tokens[i];
535 if (i + 1 != e)
536 errs() << ", ";
537 }
538 errs() << "]\n";
539
540 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
541 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000542 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000543 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000544 errs() << '\"' << Tokens[i] << "\"\n";
545 continue;
546 }
547
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000548 if (!Op.OperandInfo) {
549 errs() << "(singleton register)\n";
550 continue;
551 }
552
Chris Lattnerc240bb02010-11-01 04:03:32 +0000553 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000554 errs() << OI.Name << " " << OI.Rec->getName()
555 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
556 }
557}
558
Chris Lattner02bcbc92010-11-01 01:37:30 +0000559/// getRegisterRecord - Get the register record for \arg name, or 0.
560static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
561 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
562 const CodeGenRegister &Reg = Target.getRegisters()[i];
563 if (Name == Reg.TheDef->getValueAsString("AsmName"))
564 return Reg.TheDef;
565 }
566
567 return 0;
568}
569
Chris Lattner5bc93872010-11-01 04:34:44 +0000570bool InstructionInfo::isAssemblerInstruction() const {
571 StringRef Name = InstrName;
572
573 // Reject instructions with no .s string.
574 if (AsmString.empty())
575 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
576
577 // Reject any instructions with a newline in them, they should be marked
578 // isCodeGenOnly if they are pseudo instructions.
579 if (AsmString.find('\n') != std::string::npos)
580 throw TGError(TheDef->getLoc(),
581 "multiline instruction is not valid for the asmparser, "
582 "mark it isCodeGenOnly");
583
584 // Reject instructions with attributes, these aren't something we can handle,
585 // the target should be refactored to use operands instead of modifiers.
586 //
587 // Also, check for instructions which reference the operand multiple times;
588 // this implies a constraint we would not honor.
589 std::set<std::string> OperandNames;
590 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
591 if (Tokens[i][0] == '$' && Tokens[i].find(':') != StringRef::npos)
592 throw TGError(TheDef->getLoc(),
593 "instruction with operand modifier '" + Tokens[i].str() +
594 "' not supported by asm matcher. Mark isCodeGenOnly!");
595
596 // FIXME: Should reject these. The ARM backend hits this with $lane in a
597 // bunch of instructions. It is unclear what the right answer is for this.
598 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
599 DEBUG({
600 errs() << "warning: '" << Name << "': "
601 << "ignoring instruction with tied operand '"
602 << Tokens[i].str() << "'\n";
603 });
604 return false;
605 }
606 }
607
608 return true;
609}
610
611
Chris Lattner02bcbc92010-11-01 01:37:30 +0000612/// getSingletonRegisterForToken - If the specified token is a singleton
613/// register, return the register name, otherwise return a null StringRef.
Chris Lattner1de88232010-11-01 01:47:07 +0000614Record *InstructionInfo::
Chris Lattner02bcbc92010-11-01 01:37:30 +0000615getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
616 StringRef Tok = Tokens[i];
617 if (!Tok.startswith(Info.RegisterPrefix))
Chris Lattner1de88232010-11-01 01:47:07 +0000618 return 0;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000619
620 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
Chris Lattner1de88232010-11-01 01:47:07 +0000621 if (Record *Rec = getRegisterRecord(Info.Target, RegName))
622 return Rec;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000623
Chris Lattner1de88232010-11-01 01:47:07 +0000624 // If there is no register prefix (i.e. "%" in "%eax"), then this may
625 // be some random non-register token, just ignore it.
626 if (Info.RegisterPrefix.empty())
627 return 0;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000628
Chris Lattner1de88232010-11-01 01:47:07 +0000629 std::string Err = "unable to find register for '" + RegName.str() +
630 "' (which matches register prefix)";
Chris Lattner5bc93872010-11-01 04:34:44 +0000631 throw TGError(TheDef->getLoc(), Err);
Chris Lattner02bcbc92010-11-01 01:37:30 +0000632}
633
634
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000635static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000636 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000637
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000638 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
639 switch (*it) {
640 case '*': Res += "_STAR_"; break;
641 case '%': Res += "_PCT_"; break;
642 case ':': Res += "_COLON_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000643 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000644 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000645 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000646 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000647 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000648 }
649 }
650
651 return Res;
652}
653
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000654ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000655 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000656
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000657 if (!Entry) {
658 Entry = new ClassInfo();
659 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000660 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000661 Entry->Name = "MCK_" + getEnumNameForToken(Token);
662 Entry->ValueName = Token;
663 Entry->PredicateMethod = "<invalid>";
664 Entry->RenderMethod = "<invalid>";
665 Classes.push_back(Entry);
666 }
667
668 return Entry;
669}
670
671ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000672AsmMatcherInfo::getOperandClass(StringRef Token,
Chris Lattnerc240bb02010-11-01 04:03:32 +0000673 const CGIOperandList::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000674 if (OI.Rec->isSubClassOf("RegisterClass")) {
675 ClassInfo *CI = RegisterClassClasses[OI.Rec];
676
677 if (!CI) {
678 PrintError(OI.Rec->getLoc(), "register class has no class info!");
679 throw std::string("ERROR: Missing register class!");
680 }
681
682 return CI;
683 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000684
Daniel Dunbar338825c2009-08-10 18:41:10 +0000685 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
686 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
687 ClassInfo *CI = AsmOperandClasses[MatchClass];
688
689 if (!CI) {
690 PrintError(OI.Rec->getLoc(), "operand has no match class!");
691 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000692 }
693
Daniel Dunbar338825c2009-08-10 18:41:10 +0000694 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000695}
696
Chris Lattner1de88232010-11-01 01:47:07 +0000697void AsmMatcherInfo::
698BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000699 std::vector<CodeGenRegisterClass> RegisterClasses;
700 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000701
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000702 RegisterClasses = Target.getRegisterClasses();
703 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000704
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000705 // The register sets used for matching.
706 std::set< std::set<Record*> > RegisterSets;
707
Jim Grosbacha7c78222010-10-29 22:13:48 +0000708 // Gather the defined sets.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000709 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
710 ie = RegisterClasses.end(); it != ie; ++it)
711 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
712 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000713
714 // Add any required singleton sets.
Chris Lattner1de88232010-11-01 01:47:07 +0000715 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
716 ie = SingletonRegisters.end(); it != ie; ++it) {
717 Record *Rec = *it;
718 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
719 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000720
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000721 // Introduce derived sets where necessary (when a register does not determine
722 // a unique register set class), and build the mapping of registers to the set
723 // they should classify to.
724 std::map<Record*, std::set<Record*> > RegisterMap;
725 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
726 ie = Registers.end(); it != ie; ++it) {
727 CodeGenRegister &CGR = *it;
728 // Compute the intersection of all sets containing this register.
729 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000730
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000731 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
732 ie = RegisterSets.end(); it != ie; ++it) {
733 if (!it->count(CGR.TheDef))
734 continue;
735
736 if (ContainingSet.empty()) {
737 ContainingSet = *it;
738 } else {
739 std::set<Record*> Tmp;
740 std::swap(Tmp, ContainingSet);
741 std::insert_iterator< std::set<Record*> > II(ContainingSet,
742 ContainingSet.begin());
743 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
744 II);
745 }
746 }
747
748 if (!ContainingSet.empty()) {
749 RegisterSets.insert(ContainingSet);
750 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
751 }
752 }
753
754 // Construct the register classes.
755 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
756 unsigned Index = 0;
757 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
758 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
759 ClassInfo *CI = new ClassInfo();
760 CI->Kind = ClassInfo::RegisterClass0 + Index;
761 CI->ClassName = "Reg" + utostr(Index);
762 CI->Name = "MCK_Reg" + utostr(Index);
763 CI->ValueName = "";
764 CI->PredicateMethod = ""; // unused
765 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000766 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000767 Classes.push_back(CI);
768 RegisterSetClasses.insert(std::make_pair(*it, CI));
769 }
770
771 // Find the superclasses; we could compute only the subgroup lattice edges,
772 // but there isn't really a point.
773 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
774 ie = RegisterSets.end(); it != ie; ++it) {
775 ClassInfo *CI = RegisterSetClasses[*it];
776 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
777 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000778 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000779 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
780 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
781 }
782
783 // Name the register classes which correspond to a user defined RegisterClass.
784 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
785 ie = RegisterClasses.end(); it != ie; ++it) {
786 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
787 it->Elements.end())];
788 if (CI->ValueName.empty()) {
789 CI->ClassName = it->getName();
790 CI->Name = "MCK_" + it->getName();
791 CI->ValueName = it->getName();
792 } else
793 CI->ValueName = CI->ValueName + "," + it->getName();
794
795 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
796 }
797
798 // Populate the map for individual registers.
799 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
800 ie = RegisterMap.end(); it != ie; ++it)
801 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000802
803 // Name the register classes which correspond to singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +0000804 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
805 ie = SingletonRegisters.end(); it != ie; ++it) {
806 Record *Rec = *it;
807 ClassInfo *CI = this->RegisterClasses[Rec];
808 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000809
Chris Lattner1de88232010-11-01 01:47:07 +0000810 if (CI->ValueName.empty()) {
811 CI->ClassName = Rec->getName();
812 CI->Name = "MCK_" + Rec->getName();
813 CI->ValueName = Rec->getName();
814 } else
815 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000816 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000817}
818
Chris Lattner02bcbc92010-11-01 01:37:30 +0000819void AsmMatcherInfo::BuildOperandClasses() {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000820 std::vector<Record*> AsmOperands;
821 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000822
823 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000824 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000825 ie = AsmOperands.end(); it != ie; ++it)
826 AsmOperandClasses[*it] = new ClassInfo();
827
Daniel Dunbar338825c2009-08-10 18:41:10 +0000828 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000829 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +0000830 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000831 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000832 CI->Kind = ClassInfo::UserClass0 + Index;
833
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000834 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
835 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
836 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
837 if (!DI) {
838 PrintError((*it)->getLoc(), "Invalid super class reference!");
839 continue;
840 }
841
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000842 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
843 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000844 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000845 else
846 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000847 }
848 CI->ClassName = (*it)->getValueAsString("Name");
849 CI->Name = "MCK_" + CI->ClassName;
850 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000851
852 // Get or construct the predicate method name.
853 Init *PMName = (*it)->getValueInit("PredicateMethod");
854 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
855 CI->PredicateMethod = SI->getValue();
856 } else {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000857 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000858 "Unexpected PredicateMethod field!");
859 CI->PredicateMethod = "is" + CI->ClassName;
860 }
861
862 // Get or construct the render method name.
863 Init *RMName = (*it)->getValueInit("RenderMethod");
864 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
865 CI->RenderMethod = SI->getValue();
866 } else {
867 assert(dynamic_cast<UnsetInit*>(RMName) &&
868 "Unexpected RenderMethod field!");
869 CI->RenderMethod = "add" + CI->ClassName + "Operands";
870 }
871
Daniel Dunbar338825c2009-08-10 18:41:10 +0000872 AsmOperandClasses[*it] = CI;
873 Classes.push_back(CI);
874 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000875}
876
Chris Lattner02bcbc92010-11-01 01:37:30 +0000877AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
878 : AsmParser(asmParser), Target(target),
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000879 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
880 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
881{
882}
883
Chris Lattner02bcbc92010-11-01 01:37:30 +0000884void AsmMatcherInfo::BuildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +0000885 // Build information about all of the AssemblerPredicates.
886 std::vector<Record*> AllPredicates =
887 Records.getAllDerivedDefinitions("Predicate");
888 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
889 Record *Pred = AllPredicates[i];
890 // Ignore predicates that are not intended for the assembler.
891 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
892 continue;
893
894 if (Pred->getName().empty()) {
895 PrintError(Pred->getLoc(), "Predicate has no name!");
896 throw std::string("ERROR: Predicate defs must be named");
897 }
898
899 unsigned FeatureNo = SubtargetFeatures.size();
900 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
901 assert(FeatureNo < 32 && "Too many subtarget features!");
902 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000903
Chris Lattner39ee0362010-10-31 19:10:56 +0000904 // Parse the instructions; we need to do this first so that we can gather the
905 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000906 SmallPtrSet<Record*, 16> SingletonRegisters;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000907 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
908 E = Target.inst_end(); I != E; ++I) {
909 const CodeGenInstruction &CGI = **I;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000910
Chris Lattner39ee0362010-10-31 19:10:56 +0000911 // If the tblgen -match-prefix option is specified (for tblgen hackers),
912 // filter the set of instructions we consider.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000913 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000914 continue;
915
Chris Lattner5bc93872010-11-01 04:34:44 +0000916 // Ignore "codegen only" instructions.
917 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
918 continue;
919
920 OwningPtr<InstructionInfo> II(new InstructionInfo(CGI, CommentDelimiter));
Daniel Dunbar20927f22009-08-07 08:26:05 +0000921
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000922 // Ignore instructions which shouldn't be matched and diagnose invalid
923 // instruction definitions with an error.
Chris Lattner5bc93872010-11-01 04:34:44 +0000924 if (!II->isAssemblerInstruction())
925 continue;
926
927 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
928 //
929 // FIXME: This is a total hack.
930 if (StringRef(II->InstrName).startswith("Int_") ||
931 StringRef(II->InstrName).endswith("_Int"))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000932 continue;
Chris Lattner39ee0362010-10-31 19:10:56 +0000933
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000934 // Collect singleton registers, if used.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000935 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
Chris Lattner1de88232010-11-01 01:47:07 +0000936 if (Record *Reg = II->getSingletonRegisterForToken(i, *this))
937 SingletonRegisters.insert(Reg);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000938 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000939
940 // Compute the require features.
Chris Lattner0f899c72010-10-30 19:38:20 +0000941 std::vector<Record*> Predicates =
942 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner6fa152c2010-10-30 20:15:02 +0000943 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
944 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
945 II->RequiredFeatures.push_back(Feature);
Daniel Dunbar54074b52010-07-19 05:44:09 +0000946
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000947 Instructions.push_back(II.take());
948 }
Chris Lattnerc240bb02010-11-01 04:03:32 +0000949
Chris Lattnerc76e80d2010-11-01 04:05:41 +0000950 // Parse all of the InstAlias definitions.
951 std::vector<Record*> AllInstAliases =
952 Records.getAllDerivedDefinitions("InstAlias");
953 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
954 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i]);
955
956
957 (void)Alias;
958 }
Chris Lattnerc240bb02010-11-01 04:03:32 +0000959
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000960 // Build info for the register classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000961 BuildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000962
963 // Build info for the user defined assembly operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000964 BuildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000965
966 // Build the instruction information.
967 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
968 ie = Instructions.end(); it != ie; ++it) {
969 InstructionInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000970
Chris Lattnere206fcf2010-09-06 21:01:37 +0000971 // The first token of the instruction is the mnemonic, which must be a
Chris Lattner02bcbc92010-11-01 01:37:30 +0000972 // simple string, not a $foo variable or a singleton register.
Chris Lattnere206fcf2010-09-06 21:01:37 +0000973 assert(!II->Tokens.empty() && "Instruction has no tokens?");
974 StringRef Mnemonic = II->Tokens[0];
Chris Lattner1de88232010-11-01 01:47:07 +0000975 if (Mnemonic[0] == '$' || II->getSingletonRegisterForToken(0, *this))
Chris Lattner5bc93872010-11-01 04:34:44 +0000976 throw TGError(II->TheDef->getLoc(),
Chris Lattner02bcbc92010-11-01 01:37:30 +0000977 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Jim Grosbacha7c78222010-10-29 22:13:48 +0000978
Chris Lattnere206fcf2010-09-06 21:01:37 +0000979 // Parse the tokens after the mnemonic.
980 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000981 StringRef Token = II->Tokens[i];
982
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000983 // Check for singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +0000984 if (Record *RegRecord = II->getSingletonRegisterForToken(i, *this)) {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000985 InstructionInfo::Operand Op;
986 Op.Class = RegisterClasses[RegRecord];
987 Op.OperandInfo = 0;
988 assert(Op.Class && Op.Class->Registers.size() == 1 &&
989 "Unexpected class for singleton register");
990 II->Operands.push_back(Op);
991 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000992 }
993
Daniel Dunbar20927f22009-08-07 08:26:05 +0000994 // Check for simple tokens.
995 if (Token[0] != '$') {
996 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000997 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000998 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000999 II->Operands.push_back(Op);
1000 continue;
1001 }
1002
1003 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001004 StringRef OperandName;
1005 if (Token[1] == '{')
1006 OperandName = Token.substr(2, Token.size() - 3);
1007 else
1008 OperandName = Token.substr(1);
1009
1010 // Map this token to an operand. FIXME: Move elsewhere.
1011 unsigned Idx;
Chris Lattner5bc93872010-11-01 04:34:44 +00001012 if (!II->OperandList.hasOperandNamed(OperandName, Idx))
Jim Grosbacha7c78222010-10-29 22:13:48 +00001013 throw std::string("error: unable to find operand: '" +
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001014 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001015
Daniel Dunbaraf616812010-02-10 08:15:48 +00001016 // FIXME: This is annoying, the named operand may be tied (e.g.,
1017 // XCHG8rm). What we want is the untied operand, which we now have to
1018 // grovel for. Only worry about this for single entry operands, we have to
1019 // clean this up anyway.
Chris Lattner5bc93872010-11-01 04:34:44 +00001020 const CGIOperandList::OperandInfo *OI = &II->OperandList[Idx];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001021 if (OI->Constraints[0].isTied()) {
1022 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1023
1024 // The tied operand index is an MIOperand index, find the operand that
1025 // contains it.
Chris Lattner5bc93872010-11-01 04:34:44 +00001026 for (unsigned i = 0, e = II->OperandList.size(); i != e; ++i) {
1027 if (II->OperandList[i].MIOperandNo == TiedOp) {
1028 OI = &II->OperandList[i];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001029 break;
1030 }
1031 }
1032
1033 assert(OI && "Unable to find tied operand target!");
1034 }
1035
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001036 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001037 Op.Class = getOperandClass(Token, *OI);
1038 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001039 II->Operands.push_back(Op);
1040 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001041 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001042
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001043 // Reorder classes so that classes preceed super classes.
1044 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001045}
1046
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001047static std::pair<unsigned, unsigned> *
1048GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1049 unsigned Index) {
1050 for (unsigned i = 0, e = List.size(); i != e; ++i)
1051 if (Index == List[i].first)
1052 return &List[i];
1053
1054 return 0;
1055}
1056
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001057static void EmitConvertToMCInst(CodeGenTarget &Target,
1058 std::vector<InstructionInfo*> &Infos,
1059 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001060 // Write the convert function to a separate stream, so we can drop it after
1061 // the enum.
1062 std::string ConvertFnBody;
1063 raw_string_ostream CvtOS(ConvertFnBody);
1064
Daniel Dunbar20927f22009-08-07 08:26:05 +00001065 // Function we have already generated.
1066 std::set<std::string> GeneratedFns;
1067
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001068 // Start the unified conversion function.
1069
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001070 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001071 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001072 << " const SmallVectorImpl<MCParsedAsmOperand*"
1073 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001074 CvtOS << " Inst.setOpcode(Opcode);\n";
1075 CvtOS << " switch (Kind) {\n";
1076 CvtOS << " default:\n";
1077
1078 // Start the enum, which we will generate inline.
1079
1080 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001081 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001082
Chris Lattner98986712010-01-14 22:21:20 +00001083 // TargetOperandClass - This is the target's operand class, like X86Operand.
1084 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001085
Daniel Dunbar20927f22009-08-07 08:26:05 +00001086 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1087 ie = Infos.end(); it != ie; ++it) {
1088 InstructionInfo &II = **it;
1089
1090 // Order the (class) operands by the order to convert them into an MCInst.
1091 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1092 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1093 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001094 if (Op.OperandInfo)
1095 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001096 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001097
1098 // Find any tied operands.
1099 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
Chris Lattner5bc93872010-11-01 04:34:44 +00001100 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1101 const CGIOperandList::OperandInfo &OpInfo = II.OperandList[i];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001102 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00001103 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j];
Daniel Dunbaraf616812010-02-10 08:15:48 +00001104 if (CI.isTied())
1105 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1106 CI.getTiedOperand()));
1107 }
1108 }
1109
Daniel Dunbar20927f22009-08-07 08:26:05 +00001110 std::sort(MIOperandList.begin(), MIOperandList.end());
1111
1112 // Compute the total number of operands.
1113 unsigned NumMIOperands = 0;
Chris Lattner5bc93872010-11-01 04:34:44 +00001114 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1115 const CGIOperandList::OperandInfo &OI = II.OperandList[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001116 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbar20927f22009-08-07 08:26:05 +00001117 OI.MIOperandNo + OI.MINumOperands);
1118 }
1119
1120 // Build the conversion function signature.
1121 std::string Signature = "Convert";
1122 unsigned CurIndex = 0;
1123 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1124 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001125 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001126 "Duplicate match for instruction operand!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001127
Daniel Dunbar20927f22009-08-07 08:26:05 +00001128 // Skip operands which weren't matched by anything, this occurs when the
1129 // .td file encodes "implicit" operands as explicit ones.
1130 //
1131 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001132 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001133 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1134 CurIndex);
1135 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001136 Signature += "__Imp";
1137 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001138 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001139 }
1140
1141 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001142
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001143 // Registers are always converted the same, don't duplicate the conversion
1144 // function based on them.
1145 //
1146 // FIXME: We could generalize this based on the render method, if it
1147 // mattered.
1148 if (Op.Class->isRegisterClass())
1149 Signature += "Reg";
1150 else
1151 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001152 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001153 Signature += "_" + utostr(MIOperandList[i].second);
1154
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001155 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001156 }
1157
1158 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001159 for (; CurIndex != NumMIOperands; ++CurIndex) {
1160 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1161 CurIndex);
1162 if (!Tie)
1163 Signature += "__Imp";
1164 else
1165 Signature += "__Tie" + utostr(Tie->second);
1166 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001167
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001168 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001169
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001170 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001171 if (!GeneratedFns.insert(Signature).second)
1172 continue;
1173
1174 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001175
1176 // Add to the enum list.
1177 OS << " " << Signature << ",\n";
1178
1179 // And to the convert function.
1180 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001181 CurIndex = 0;
1182 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1183 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1184
1185 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001186 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1187 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001188 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1189 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001190
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001191 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001192 // If not, this is some implicit operand. Just assume it is a register
1193 // for now.
1194 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1195 } else {
1196 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001197 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001198 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001199 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001200 }
1201 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001202
Chris Lattner98986712010-01-14 22:21:20 +00001203 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbacha7c78222010-10-29 22:13:48 +00001204 << MIOperandList[i].second
1205 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001206 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1207 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001208 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001209
Daniel Dunbar20927f22009-08-07 08:26:05 +00001210 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001211 for (; CurIndex != NumMIOperands; ++CurIndex) {
1212 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1213 CurIndex);
1214
1215 if (!Tie) {
1216 // If not, this is some implicit operand. Just assume it is a register
1217 // for now.
1218 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1219 } else {
1220 // Copy the tied operand.
1221 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1222 CvtOS << " Inst.addOperand(Inst.getOperand("
1223 << Tie->second << "));\n";
1224 }
1225 }
1226
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001227 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001228 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001229
1230 // Finish the convert function.
1231
1232 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001233 CvtOS << "}\n\n";
1234
1235 // Finish the enum, and drop the convert function after it.
1236
1237 OS << " NumConversionVariants\n";
1238 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001239
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001240 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001241}
1242
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001243/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1244static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1245 std::vector<ClassInfo*> &Infos,
1246 raw_ostream &OS) {
1247 OS << "namespace {\n\n";
1248
1249 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1250 << "/// instruction matching.\n";
1251 OS << "enum MatchClassKind {\n";
1252 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001253 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001254 ie = Infos.end(); it != ie; ++it) {
1255 ClassInfo &CI = **it;
1256 OS << " " << CI.Name << ", // ";
1257 if (CI.Kind == ClassInfo::Token) {
1258 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001259 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001260 if (!CI.ValueName.empty())
1261 OS << "register class '" << CI.ValueName << "'\n";
1262 else
1263 OS << "derived register class\n";
1264 } else {
1265 OS << "user defined class '" << CI.ValueName << "'\n";
1266 }
1267 }
1268 OS << " NumMatchClassKinds\n";
1269 OS << "};\n\n";
1270
1271 OS << "}\n\n";
1272}
1273
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001274/// EmitClassifyOperand - Emit the function to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001275static void EmitClassifyOperand(AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001276 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001277 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
Chris Lattner02bcbc92010-11-01 01:37:30 +00001278 << " " << Info.Target.getName() << "Operand &Operand = *("
1279 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001280
1281 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001282 OS << " if (Operand.isToken())\n";
1283 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001284
1285 // Classify registers.
1286 //
1287 // FIXME: Don't hardcode isReg, getReg.
1288 OS << " if (Operand.isReg()) {\n";
1289 OS << " switch (Operand.getReg()) {\n";
1290 OS << " default: return InvalidMatchClass;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001291 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001292 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1293 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001294 OS << " case " << Info.Target.getName() << "::"
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001295 << it->first->getName() << ": return " << it->second->Name << ";\n";
1296 OS << " }\n";
1297 OS << " }\n\n";
1298
1299 // Classify user defined operands.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001300 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001301 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001302 ClassInfo &CI = **it;
1303
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001304 if (!CI.isUserClass())
1305 continue;
1306
1307 OS << " // '" << CI.ClassName << "' class";
1308 if (!CI.SuperClasses.empty()) {
1309 OS << ", subclass of ";
1310 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1311 if (i) OS << ", ";
1312 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1313 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001314 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001315 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001316 OS << "\n";
1317
1318 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001319
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001320 // Validate subclass relationships.
1321 if (!CI.SuperClasses.empty()) {
1322 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1323 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1324 << "() && \"Invalid class relationship!\");\n";
1325 }
1326
1327 OS << " return " << CI.Name << ";\n";
1328 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001329 }
1330 OS << " return InvalidMatchClass;\n";
1331 OS << "}\n\n";
1332}
1333
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001334/// EmitIsSubclass - Emit the subclass predicate function.
1335static void EmitIsSubclass(CodeGenTarget &Target,
1336 std::vector<ClassInfo*> &Infos,
1337 raw_ostream &OS) {
1338 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1339 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1340 OS << " if (A == B)\n";
1341 OS << " return true;\n\n";
1342
1343 OS << " switch (A) {\n";
1344 OS << " default:\n";
1345 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001346 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001347 ie = Infos.end(); it != ie; ++it) {
1348 ClassInfo &A = **it;
1349
1350 if (A.Kind != ClassInfo::Token) {
1351 std::vector<StringRef> SuperClasses;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001352 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001353 ie = Infos.end(); it != ie; ++it) {
1354 ClassInfo &B = **it;
1355
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001356 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001357 SuperClasses.push_back(B.Name);
1358 }
1359
1360 if (SuperClasses.empty())
1361 continue;
1362
1363 OS << "\n case " << A.Name << ":\n";
1364
1365 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001366 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001367 continue;
1368 }
1369
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001370 OS << " switch (B) {\n";
1371 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001372 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001373 OS << " case " << SuperClasses[i] << ": return true;\n";
1374 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001375 }
1376 }
1377 OS << " }\n";
1378 OS << "}\n\n";
1379}
1380
Chris Lattner70add882009-08-08 20:02:57 +00001381
1382
Daniel Dunbar245f0582009-08-08 21:22:41 +00001383/// EmitMatchTokenString - Emit the function to match a token string to the
1384/// appropriate match class value.
1385static void EmitMatchTokenString(CodeGenTarget &Target,
1386 std::vector<ClassInfo*> &Infos,
1387 raw_ostream &OS) {
1388 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001389 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001390 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001391 ie = Infos.end(); it != ie; ++it) {
1392 ClassInfo &CI = **it;
1393
1394 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001395 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1396 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001397 }
1398
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001399 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001400
Chris Lattner5845e5c2010-09-06 02:01:51 +00001401 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001402
1403 OS << " return InvalidMatchClass;\n";
1404 OS << "}\n\n";
1405}
Chris Lattner70add882009-08-08 20:02:57 +00001406
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001407/// EmitMatchRegisterName - Emit the function to match a string to the target
1408/// specific register enum.
1409static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1410 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001411 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001412 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001413 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1414 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001415 if (Reg.TheDef->getValueAsString("AsmName").empty())
1416 continue;
1417
Chris Lattner5845e5c2010-09-06 02:01:51 +00001418 Matches.push_back(StringMatcher::StringPair(
1419 Reg.TheDef->getValueAsString("AsmName"),
1420 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001421 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001422
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001423 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001424
Chris Lattner5845e5c2010-09-06 02:01:51 +00001425 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001426
Daniel Dunbar245f0582009-08-08 21:22:41 +00001427 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001428 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001429}
Daniel Dunbara027d222009-07-31 02:32:59 +00001430
Daniel Dunbar54074b52010-07-19 05:44:09 +00001431/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1432/// definitions.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001433static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001434 raw_ostream &OS) {
1435 OS << "// Flags for subtarget features that participate in "
1436 << "instruction matching.\n";
1437 OS << "enum SubtargetFeatureFlag {\n";
1438 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1439 it = Info.SubtargetFeatures.begin(),
1440 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1441 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001442 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001443 }
1444 OS << " Feature_None = 0\n";
1445 OS << "};\n\n";
1446}
1447
1448/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1449/// available features given a subtarget.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001450static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001451 raw_ostream &OS) {
1452 std::string ClassName =
1453 Info.AsmParser->getValueAsString("AsmParserClassName");
1454
Chris Lattner02bcbc92010-11-01 01:37:30 +00001455 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1456 << "ComputeAvailableFeatures(const " << Info.Target.getName()
Daniel Dunbar54074b52010-07-19 05:44:09 +00001457 << "Subtarget *Subtarget) const {\n";
1458 OS << " unsigned Features = 0;\n";
1459 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1460 it = Info.SubtargetFeatures.begin(),
1461 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1462 SubtargetFeatureInfo &SFI = *it->second;
1463 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1464 << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001465 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001466 }
1467 OS << " return Features;\n";
1468 OS << "}\n\n";
1469}
1470
Chris Lattner6fa152c2010-10-30 20:15:02 +00001471static std::string GetAliasRequiredFeatures(Record *R,
1472 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00001473 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00001474 std::string Result;
1475 unsigned NumFeatures = 0;
1476 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner4a74ee72010-11-01 02:09:21 +00001477 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Chris Lattner693173f2010-10-30 19:23:13 +00001478
Chris Lattner4a74ee72010-11-01 02:09:21 +00001479 if (F == 0)
1480 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1481 "' is not marked as an AssemblerPredicate!");
1482
1483 if (NumFeatures)
1484 Result += '|';
1485
1486 Result += F->getEnumName();
1487 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00001488 }
1489
1490 if (NumFeatures > 1)
1491 Result = '(' + Result + ')';
1492 return Result;
1493}
1494
Chris Lattner674c1dc2010-10-30 17:36:36 +00001495/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001496/// emit a function for them and return true, otherwise return false.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001497static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattner674c1dc2010-10-30 17:36:36 +00001498 std::vector<Record*> Aliases =
1499 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001500 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001501
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001502 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1503 "unsigned Features) {\n";
1504
Chris Lattner4fd32c62010-10-30 18:56:12 +00001505 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1506 // iteration order of the map is stable.
1507 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1508
Chris Lattner674c1dc2010-10-30 17:36:36 +00001509 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1510 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001511 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001512 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001513
1514 // Process each alias a "from" mnemonic at a time, building the code executed
1515 // by the string remapper.
1516 std::vector<StringMatcher::StringPair> Cases;
1517 for (std::map<std::string, std::vector<Record*> >::iterator
1518 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1519 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00001520 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00001521
1522 // Loop through each alias and emit code that handles each case. If there
1523 // are two instructions without predicates, emit an error. If there is one,
1524 // emit it last.
1525 std::string MatchCode;
1526 int AliasWithNoPredicate = -1;
Chris Lattner4fd32c62010-10-30 18:56:12 +00001527
Chris Lattner693173f2010-10-30 19:23:13 +00001528 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1529 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00001530 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner693173f2010-10-30 19:23:13 +00001531
1532 // If this unconditionally matches, remember it for later and diagnose
1533 // duplicates.
1534 if (FeatureMask.empty()) {
1535 if (AliasWithNoPredicate != -1) {
1536 // We can't have two aliases from the same mnemonic with no predicate.
1537 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1538 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001539 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1540 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner693173f2010-10-30 19:23:13 +00001541 }
1542
1543 AliasWithNoPredicate = i;
1544 continue;
1545 }
1546
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001547 if (!MatchCode.empty())
1548 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00001549 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1550 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00001551 }
1552
Chris Lattner693173f2010-10-30 19:23:13 +00001553 if (AliasWithNoPredicate != -1) {
1554 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001555 if (!MatchCode.empty())
1556 MatchCode += "else\n ";
1557 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00001558 }
1559
1560 MatchCode += "return;";
1561
1562 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00001563 }
1564
Chris Lattner674c1dc2010-10-30 17:36:36 +00001565
1566 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner7fd44892010-10-30 18:48:18 +00001567 OS << "}\n";
1568
1569 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001570}
1571
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001572void AsmMatcherEmitter::run(raw_ostream &OS) {
1573 CodeGenTarget Target;
1574 Record *AsmParser = Target.getAsmParser();
1575 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1576
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001577 // Compute the information on the instructions to match.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001578 AsmMatcherInfo Info(AsmParser, Target);
1579 Info.BuildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00001580
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001581 // Sort the instruction table using the partial order on classes. We use
1582 // stable_sort to ensure that ambiguous instructions are still
1583 // deterministically ordered.
1584 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1585 less_ptr<InstructionInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001586
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001587 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001588 for (std::vector<InstructionInfo*>::iterator
1589 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001590 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001591 (*it)->dump();
1592 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001593
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001594 // Check for ambiguous instructions.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001595 DEBUG_WITH_TYPE("ambiguous_instrs", {
1596 unsigned NumAmbiguous = 0;
Chris Lattner87410362010-09-06 20:21:47 +00001597 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1598 for (unsigned j = i + 1; j != e; ++j) {
1599 InstructionInfo &A = *Info.Instructions[i];
1600 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001601
Chris Lattner87410362010-09-06 20:21:47 +00001602 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001603 errs() << "warning: ambiguous instruction match:\n";
1604 A.dump();
1605 errs() << "\nis incomparable with:\n";
1606 B.dump();
1607 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00001608 ++NumAmbiguous;
1609 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00001610 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001611 }
Chris Lattner87410362010-09-06 20:21:47 +00001612 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001613 errs() << "warning: " << NumAmbiguous
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001614 << " ambiguous instructions!\n";
1615 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001616
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001617 // Write the output.
1618
1619 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1620
Chris Lattner0692ee62010-09-06 19:11:01 +00001621 // Information for the class declaration.
1622 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1623 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001624 OS << " // This should be included into the middle of the declaration of \n";
1625 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001626 OS << " unsigned ComputeAvailableFeatures(const " <<
1627 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001628 OS << " enum MatchResultTy {\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001629 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1630 OS << " Match_MissingFeature\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001631 OS << " };\n";
Jim Grosbachbb168242010-10-08 18:13:57 +00001632 OS << " MatchResultTy MatchInstructionImpl(const "
1633 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattnerce4a3352010-09-06 22:11:18 +00001634 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001635 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1636
Jim Grosbacha7c78222010-10-29 22:13:48 +00001637
1638
1639
Chris Lattner0692ee62010-09-06 19:11:01 +00001640 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1641 OS << "#undef GET_REGISTER_MATCHER\n\n";
1642
Daniel Dunbar54074b52010-07-19 05:44:09 +00001643 // Emit the subtarget feature enumeration.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001644 EmitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001645
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001646 // Emit the function to match a register name to number.
1647 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001648
1649 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001650
Chris Lattner0692ee62010-09-06 19:11:01 +00001651
1652 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1653 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001654
Chris Lattner7fd44892010-10-30 18:48:18 +00001655 // Generate the function that remaps for mnemonic aliases.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001656 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner7fd44892010-10-30 18:48:18 +00001657
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001658 // Generate the unified function to convert operands into an MCInst.
1659 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001660
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001661 // Emit the enumeration for classes which participate in matching.
1662 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001663
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001664 // Emit the routine to match token strings to their match class.
1665 EmitMatchTokenString(Target, Info.Classes, OS);
1666
1667 // Emit the routine to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001668 EmitClassifyOperand(Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001669
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001670 // Emit the subclass predicate routine.
1671 EmitIsSubclass(Target, Info.Classes, OS);
1672
Daniel Dunbar54074b52010-07-19 05:44:09 +00001673 // Emit the available features compute function.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001674 EmitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001675
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001676
1677 size_t MaxNumOperands = 0;
1678 for (std::vector<InstructionInfo*>::const_iterator it =
1679 Info.Instructions.begin(), ie = Info.Instructions.end();
1680 it != ie; ++it)
1681 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001682
1683
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001684 // Emit the static match table; unused classes get initalized to 0 which is
1685 // guaranteed to be InvalidMatchClass.
1686 //
1687 // FIXME: We can reduce the size of this table very easily. First, we change
1688 // it so that store the kinds in separate bit-fields for each index, which
1689 // only needs to be the max width used for classes at that index (we also need
1690 // to reject based on this during classification). If we then make sure to
1691 // order the match kinds appropriately (putting mnemonics last), then we
1692 // should only end up using a few bits for each class, especially the ones
1693 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00001694 OS << "namespace {\n";
1695 OS << " struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001696 OS << " unsigned Opcode;\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001697 OS << " const char *Mnemonic;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001698 OS << " ConversionKind ConvertFn;\n";
1699 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001700 OS << " unsigned RequiredFeatures;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001701 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001702
Chris Lattner2b1f9432010-09-06 21:22:45 +00001703 OS << "// Predicate for searching for an opcode.\n";
1704 OS << " struct LessOpcode {\n";
1705 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1706 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1707 OS << " }\n";
1708 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1709 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1710 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00001711 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1712 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1713 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00001714 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001715
Chris Lattner96352e52010-09-06 21:08:38 +00001716 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001717
Chris Lattner96352e52010-09-06 21:08:38 +00001718 OS << "static const MatchEntry MatchTable["
1719 << Info.Instructions.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001720
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001721 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner96352e52010-09-06 21:08:38 +00001722 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001723 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001724 InstructionInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001725
Chris Lattner96352e52010-09-06 21:08:38 +00001726 OS << " { " << Target.getName() << "::" << II.InstrName
1727 << ", \"" << II.Tokens[0] << "\""
1728 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001729 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1730 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001731
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001732 if (i) OS << ", ";
1733 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001734 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001735 OS << " }, ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001736
Daniel Dunbar54074b52010-07-19 05:44:09 +00001737 // Write the required features mask.
1738 if (!II.RequiredFeatures.empty()) {
1739 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1740 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001741 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00001742 }
1743 } else
1744 OS << "0";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001745
Daniel Dunbar54074b52010-07-19 05:44:09 +00001746 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001747 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001748
Chris Lattner96352e52010-09-06 21:08:38 +00001749 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001750
Chris Lattner96352e52010-09-06 21:08:38 +00001751 // Finally, build the match function.
1752 OS << Target.getName() << ClassName << "::MatchResultTy "
1753 << Target.getName() << ClassName << "::\n"
1754 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1755 << " &Operands,\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001756 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001757
1758 // Emit code to get the available features.
1759 OS << " // Get the current feature set.\n";
1760 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1761
Chris Lattner674c1dc2010-10-30 17:36:36 +00001762 OS << " // Get the instruction mnemonic, which is the first token.\n";
1763 OS << " StringRef Mnemonic = ((" << Target.getName()
1764 << "Operand*)Operands[0])->getToken();\n\n";
1765
Chris Lattner7fd44892010-10-30 18:48:18 +00001766 if (HasMnemonicAliases) {
1767 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1768 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1769 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00001770
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001771 // Emit code to compute the class list for this operand vector.
1772 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001773 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1774 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1775 OS << " return Match_InvalidOperand;\n";
1776 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001777
1778 OS << " // Compute the class list for this operand vector.\n";
1779 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001780 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1781 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001782
1783 OS << " // Check for invalid operands before matching.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001784 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1785 OS << " ErrorInfo = i;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001786 OS << " return Match_InvalidOperand;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001787 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001788 OS << " }\n\n";
1789
1790 OS << " // Mark unused classes.\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001791 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001792 << "i != e; ++i)\n";
1793 OS << " Classes[i] = InvalidMatchClass;\n\n";
1794
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001795 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001796 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001797 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1798 OS << " // wrong for all instances of the instruction.\n";
1799 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001800
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001801 // Emit code to search the table.
1802 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001803 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1804 OS << " std::equal_range(MatchTable, MatchTable+"
1805 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001806
Chris Lattnera008e8a2010-09-06 21:54:15 +00001807 OS << " // Return a more specific error code if no mnemonics match.\n";
1808 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1809 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001810
Chris Lattner2b1f9432010-09-06 21:22:45 +00001811 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00001812 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001813 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001814
Gabor Greife53ee3b2010-09-07 06:06:06 +00001815 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattner44b0daa2010-09-06 21:25:43 +00001816 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001817
Daniel Dunbar54074b52010-07-19 05:44:09 +00001818 // Emit check that the subclasses match.
Chris Lattnerce4a3352010-09-06 22:11:18 +00001819 OS << " bool OperandsValid = true;\n";
1820 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1821 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1822 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001823 OS << " // If this operand is broken for all of the instances of this\n";
1824 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1825 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001826 OS << " ErrorInfo = i+1;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001827 OS << " else\n";
1828 OS << " ErrorInfo = ~0U;";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001829 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1830 OS << " OperandsValid = false;\n";
1831 OS << " break;\n";
1832 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001833
Chris Lattnerce4a3352010-09-06 22:11:18 +00001834 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00001835
1836 // Emit check that the required features are available.
1837 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1838 << "!= it->RequiredFeatures) {\n";
1839 OS << " HadMatchOtherThanFeatures = true;\n";
1840 OS << " continue;\n";
1841 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001842
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001843 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001844 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1845
1846 // Call the post-processing function, if used.
1847 std::string InsnCleanupFn =
1848 AsmParser->getValueAsString("AsmParserInstCleanup");
1849 if (!InsnCleanupFn.empty())
1850 OS << " " << InsnCleanupFn << "(Inst);\n";
1851
Chris Lattner79ed3f72010-09-06 19:22:17 +00001852 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001853 OS << " }\n\n";
1854
Chris Lattnerec6789f2010-09-06 20:08:02 +00001855 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1856 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001857 OS << " return Match_InvalidOperand;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001858 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001859
Chris Lattner0692ee62010-09-06 19:11:01 +00001860 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001861}