blob: 122f12476b74011ff6dcbd30ce445f4081180fc2 [file] [log] [blame]
Daniel Dunbar3f6e3ff2009-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 Dunbarfe6759e2009-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 ...)
23// 'call' '*' %epc
24//
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 Dunbar3f6e3ff2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000079#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000080#include "llvm/ADT/SmallVector.h"
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000081#include "llvm/ADT/STLExtras.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000082#include "llvm/ADT/StringExtras.h"
83#include "llvm/Support/CommandLine.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000084#include "llvm/Support/Debug.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000085#include <list>
Daniel Dunbarce82b992009-08-08 05:24:34 +000086#include <map>
87#include <set>
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +000088using namespace llvm;
89
Daniel Dunbar62beebc2009-08-07 20:33:39 +000090static cl::opt<std::string>
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000091MatchPrefix("match-prefix", cl::init(""),
92 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000093
Daniel Dunbara54716c2009-07-31 02:32:59 +000094/// FlattenVariants - Flatten an .td file assembly string by selecting the
95/// variant at index \arg N.
96static std::string FlattenVariants(const std::string &AsmString,
97 unsigned N) {
98 StringRef Cur = AsmString;
99 std::string Res = "";
100
101 for (;;) {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000102 // Find the start of the next variant string.
103 size_t VariantsStart = 0;
104 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
105 if (Cur[VariantsStart] == '{' &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000106 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
107 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000108 break;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000109
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000110 // Add the prefix to the result.
111 Res += Cur.slice(0, VariantsStart);
112 if (VariantsStart == Cur.size())
Daniel Dunbara54716c2009-07-31 02:32:59 +0000113 break;
114
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000115 ++VariantsStart; // Skip the '{'.
116
117 // Scan to the end of the variants string.
118 size_t VariantsEnd = VariantsStart;
119 unsigned NestedBraces = 1;
120 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000121 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000122 if (--NestedBraces == 0)
123 break;
124 } else if (Cur[VariantsEnd] == '{')
125 ++NestedBraces;
126 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000127
128 // Select the Nth variant (or empty).
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000129 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000130 for (unsigned i = 0; i != N; ++i)
131 Selection = Selection.split('|').second;
132 Res += Selection.split('|').first;
133
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000134 assert(VariantsEnd != Cur.size() &&
135 "Unterminated variants in assembly string!");
136 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000137 }
138
139 return Res;
140}
141
142/// TokenizeAsmString - Tokenize a simplified assembly string.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000143static void TokenizeAsmString(const StringRef &AsmString,
Daniel Dunbara54716c2009-07-31 02:32:59 +0000144 SmallVectorImpl<StringRef> &Tokens) {
145 unsigned Prev = 0;
146 bool InTok = true;
147 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
148 switch (AsmString[i]) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000149 case '[':
150 case ']':
Daniel Dunbara54716c2009-07-31 02:32:59 +0000151 case '*':
152 case '!':
153 case ' ':
154 case '\t':
155 case ',':
156 if (InTok) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000157 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000158 InTok = false;
159 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000160 if (!isspace(AsmString[i]) && AsmString[i] != ',')
161 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000162 Prev = i + 1;
163 break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000164
165 case '\\':
166 if (InTok) {
167 Tokens.push_back(AsmString.slice(Prev, i));
168 InTok = false;
169 }
170 ++i;
171 assert(i != AsmString.size() && "Invalid quoted character");
172 Tokens.push_back(AsmString.substr(i, 1));
173 Prev = i + 1;
174 break;
175
176 case '$': {
177 // If this isn't "${", treat like a normal token.
178 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
179 if (InTok) {
180 Tokens.push_back(AsmString.slice(Prev, i));
181 InTok = false;
182 }
183 Prev = i;
184 break;
185 }
186
187 if (InTok) {
188 Tokens.push_back(AsmString.slice(Prev, i));
189 InTok = false;
190 }
191
192 StringRef::iterator End =
193 std::find(AsmString.begin() + i, AsmString.end(), '}');
194 assert(End != AsmString.end() && "Missing brace in operand reference!");
195 size_t EndPos = End - AsmString.begin();
196 Tokens.push_back(AsmString.slice(i, EndPos+1));
197 Prev = EndPos + 1;
198 i = EndPos;
199 break;
200 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000201
202 default:
203 InTok = true;
204 }
205 }
206 if (InTok && Prev != AsmString.size())
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000207 Tokens.push_back(AsmString.substr(Prev));
208}
209
210static bool IsAssemblerInstruction(const StringRef &Name,
211 const CodeGenInstruction &CGI,
212 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbara0e62002009-08-11 22:17:52 +0000213 // Ignore "codegen only" instructions.
214 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
215 return false;
216
217 // Ignore pseudo ops.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000218 //
Daniel Dunbara0e62002009-08-11 22:17:52 +0000219 // FIXME: This is a hack; can we convert these instructions to set the
220 // "codegen only" bit instead?
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000221 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
222 if (Form->getValue()->getAsString() == "Pseudo")
223 return false;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000224
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000225 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
226 //
227 // FIXME: This is a total hack.
228 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
229 return false;
230
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000231 // Ignore instructions with no .s string.
232 //
233 // FIXME: What are these?
234 if (CGI.AsmString.empty())
235 return false;
236
237 // FIXME: Hack; ignore any instructions with a newline in them.
238 if (std::find(CGI.AsmString.begin(),
239 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
240 return false;
241
242 // Ignore instructions with attributes, these are always fake instructions for
243 // simplifying codegen.
244 //
245 // FIXME: Is this true?
246 //
Daniel Dunbara0e62002009-08-11 22:17:52 +0000247 // Also, check for instructions which reference the operand multiple times;
248 // this implies a constraint we would not honor.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000249 std::set<std::string> OperandNames;
250 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251 if (Tokens[i][0] == '$' &&
252 std::find(Tokens[i].begin(),
253 Tokens[i].end(), ':') != Tokens[i].end()) {
254 DEBUG({
255 errs() << "warning: '" << Name << "': "
256 << "ignoring instruction; operand with attribute '"
Daniel Dunbara0e62002009-08-11 22:17:52 +0000257 << Tokens[i] << "'\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000258 });
259 return false;
260 }
261
262 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
Daniel Dunbara0e62002009-08-11 22:17:52 +0000263 std::string Err = "'" + Name.str() + "': " +
264 "invalid assembler instruction; tied operand '" + Tokens[i].str() + "'";
265 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000266 }
267 }
268
269 return true;
270}
271
272namespace {
273
Daniel Dunbar378bee92009-08-08 07:50:56 +0000274/// ClassInfo - Helper class for storing the information about a particular
275/// class of operands which can be matched.
276struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000277 enum ClassInfoKind {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000278 /// Invalid kind, for use as a sentinel value.
279 Invalid = 0,
280
281 /// The class for a particular token.
282 Token,
283
284 /// The (first) register class, subsequent register classes are
285 /// RegisterClass0+1, and so on.
286 RegisterClass0,
287
288 /// The (first) user defined class, subsequent user defined classes are
289 /// UserClass0+1, and so on.
290 UserClass0 = 1<<16
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000291 };
292
293 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
294 /// N) for the Nth user defined class.
295 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000296
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000297 /// SuperClasses - The super classes of this class. Note that for simplicities
298 /// sake user operands only record their immediate super class, while register
299 /// operands include all superclasses.
300 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000301
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000302 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000303 std::string Name;
304
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000305 /// ClassName - The unadorned generic name for this class (e.g., Token).
306 std::string ClassName;
307
Daniel Dunbar378bee92009-08-08 07:50:56 +0000308 /// ValueName - The name of the value this class represents; for a token this
309 /// is the literal token string, for an operand it is the TableGen class (or
310 /// empty if this is a derived class).
311 std::string ValueName;
312
313 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000314 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000315 std::string PredicateMethod;
316
317 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000318 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000319 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000320
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000321 /// For register classes, the records for all the registers in this class.
322 std::set<Record*> Registers;
323
324public:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000325 /// isRegisterClass() - Check if this is a register class.
326 bool isRegisterClass() const {
327 return Kind >= RegisterClass0 && Kind < UserClass0;
328 }
329
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000330 /// isUserClass() - Check if this is a user defined class.
331 bool isUserClass() const {
332 return Kind >= UserClass0;
333 }
334
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000335 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
336 /// are related if they are in the same class hierarchy.
337 bool isRelatedTo(const ClassInfo &RHS) const {
338 // Tokens are only related to tokens.
339 if (Kind == Token || RHS.Kind == Token)
340 return Kind == Token && RHS.Kind == Token;
341
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000342 // Registers classes are only related to registers classes, and only if
343 // their intersection is non-empty.
344 if (isRegisterClass() || RHS.isRegisterClass()) {
345 if (!isRegisterClass() || !RHS.isRegisterClass())
346 return false;
347
348 std::set<Record*> Tmp;
349 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
350 std::set_intersection(Registers.begin(), Registers.end(),
351 RHS.Registers.begin(), RHS.Registers.end(),
352 II);
353
354 return !Tmp.empty();
355 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000356
357 // Otherwise we have two users operands; they are related if they are in the
358 // same class hierarchy.
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000359 //
360 // FIXME: This is an oversimplification, they should only be related if they
361 // intersect, however we don't have that information.
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000362 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
363 const ClassInfo *Root = this;
364 while (!Root->SuperClasses.empty())
365 Root = Root->SuperClasses.front();
366
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000367 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000368 while (!RHSRoot->SuperClasses.empty())
369 RHSRoot = RHSRoot->SuperClasses.front();
370
371 return Root == RHSRoot;
372 }
373
374 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
375 bool isSubsetOf(const ClassInfo &RHS) const {
376 // This is a subset of RHS if it is the same class...
377 if (this == &RHS)
378 return true;
379
380 // ... or if any of its super classes are a subset of RHS.
381 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
382 ie = SuperClasses.end(); it != ie; ++it)
383 if ((*it)->isSubsetOf(RHS))
384 return true;
385
386 return false;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000387 }
388
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000389 /// operator< - Compare two classes.
390 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000391 // Unrelated classes can be ordered by kind.
392 if (!isRelatedTo(RHS))
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000393 return Kind < RHS.Kind;
394
395 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000396 case Invalid:
397 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000398 case Token:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000399 // Tokens are comparable by value.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000400 //
401 // FIXME: Compare by enum value.
402 return ValueName < RHS.ValueName;
403
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000404 default:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000405 // This class preceeds the RHS if it is a proper subset of the RHS.
406 return this != &RHS && isSubsetOf(RHS);
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000407 }
408 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000409};
410
Daniel Dunbarce82b992009-08-08 05:24:34 +0000411/// InstructionInfo - Helper class for storing the necessary information for an
412/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000413struct InstructionInfo {
414 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000415 /// The unique class instance this operand should match.
416 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000417
Daniel Dunbar378bee92009-08-08 07:50:56 +0000418 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000419 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000420 };
421
422 /// InstrName - The target name for this instruction.
423 std::string InstrName;
424
425 /// Instr - The instruction this matches.
426 const CodeGenInstruction *Instr;
427
428 /// AsmString - The assembly string for this instruction (with variants
429 /// removed).
430 std::string AsmString;
431
432 /// Tokens - The tokenized assembly pattern that this instruction matches.
433 SmallVector<StringRef, 4> Tokens;
434
435 /// Operands - The operands that this instruction matches.
436 SmallVector<Operand, 4> Operands;
437
Daniel Dunbarce82b992009-08-08 05:24:34 +0000438 /// ConversionFnKind - The enum value which is passed to the generated
439 /// ConvertToMCInst to convert parsed operands into an MCInst for this
440 /// function.
441 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000442
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000443 /// operator< - Compare two instructions.
444 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000445 if (Operands.size() != RHS.Operands.size())
446 return Operands.size() < RHS.Operands.size();
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000447
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000448 // Compare lexicographically by operand. The matcher validates that other
449 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
450 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000451 if (*Operands[i].Class < *RHS.Operands[i].Class)
452 return true;
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000453 if (*RHS.Operands[i].Class < *Operands[i].Class)
454 return false;
455 }
456
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000457 return false;
458 }
459
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000460 /// CouldMatchAmiguouslyWith - Check whether this instruction could
461 /// ambiguously match the same set of operands as \arg RHS (without being a
462 /// strictly superior match).
463 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
464 // The number of operands is unambiguous.
465 if (Operands.size() != RHS.Operands.size())
466 return false;
467
468 // Tokens and operand kinds are unambiguous (assuming a correct target
469 // specific parser).
470 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
471 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
472 Operands[i].Class->Kind == ClassInfo::Token)
473 if (*Operands[i].Class < *RHS.Operands[i].Class ||
474 *RHS.Operands[i].Class < *Operands[i].Class)
475 return false;
476
477 // Otherwise, this operand could commute if all operands are equivalent, or
478 // there is a pair of operands that compare less than and a pair that
479 // compare greater than.
480 bool HasLT = false, HasGT = false;
481 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
482 if (*Operands[i].Class < *RHS.Operands[i].Class)
483 HasLT = true;
484 if (*RHS.Operands[i].Class < *Operands[i].Class)
485 HasGT = true;
486 }
487
488 return !(HasLT ^ HasGT);
489 }
490
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000491public:
492 void dump();
493};
494
Daniel Dunbar378bee92009-08-08 07:50:56 +0000495class AsmMatcherInfo {
496public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000497 /// The tablegen AsmParser record.
498 Record *AsmParser;
499
500 /// The AsmParser "CommentDelimiter" value.
501 std::string CommentDelimiter;
502
503 /// The AsmParser "RegisterPrefix" value.
504 std::string RegisterPrefix;
505
Daniel Dunbar378bee92009-08-08 07:50:56 +0000506 /// The classes which are needed for matching.
507 std::vector<ClassInfo*> Classes;
508
509 /// The information on the instruction to match.
510 std::vector<InstructionInfo*> Instructions;
511
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000512 /// Map of Register records to their class information.
513 std::map<Record*, ClassInfo*> RegisterClasses;
514
Daniel Dunbar378bee92009-08-08 07:50:56 +0000515private:
516 /// Map of token to class information which has already been constructed.
517 std::map<std::string, ClassInfo*> TokenClasses;
518
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000519 /// Map of RegisterClass records to their class information.
520 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000521
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000522 /// Map of AsmOperandClass records to their class information.
523 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000524
Daniel Dunbar378bee92009-08-08 07:50:56 +0000525private:
526 /// getTokenClass - Lookup or create the class for the given token.
527 ClassInfo *getTokenClass(const StringRef &Token);
528
529 /// getOperandClass - Lookup or create the class for the given operand.
530 ClassInfo *getOperandClass(const StringRef &Token,
531 const CodeGenInstruction::OperandInfo &OI);
532
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000533 /// BuildRegisterClasses - Build the ClassInfo* instances for register
534 /// classes.
535 void BuildRegisterClasses(CodeGenTarget &Target);
536
537 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
538 /// operand classes.
539 void BuildOperandClasses(CodeGenTarget &Target);
540
Daniel Dunbar378bee92009-08-08 07:50:56 +0000541public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000542 AsmMatcherInfo(Record *_AsmParser);
543
Daniel Dunbar378bee92009-08-08 07:50:56 +0000544 /// BuildInfo - Construct the various tables used during matching.
545 void BuildInfo(CodeGenTarget &Target);
546};
547
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000548}
549
550void InstructionInfo::dump() {
551 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
552 << ", tokens:[";
553 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
554 errs() << Tokens[i];
555 if (i + 1 != e)
556 errs() << ", ";
557 }
558 errs() << "]\n";
559
560 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
561 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000562 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000563 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000564 errs() << '\"' << Tokens[i] << "\"\n";
565 continue;
566 }
567
Benjamin Kramer19afc502009-08-08 10:06:30 +0000568 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000569 errs() << OI.Name << " " << OI.Rec->getName()
570 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
571 }
572}
573
Daniel Dunbar378bee92009-08-08 07:50:56 +0000574static std::string getEnumNameForToken(const StringRef &Str) {
575 std::string Res;
576
577 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
578 switch (*it) {
579 case '*': Res += "_STAR_"; break;
580 case '%': Res += "_PCT_"; break;
581 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000582
Daniel Dunbar378bee92009-08-08 07:50:56 +0000583 default:
584 if (isalnum(*it)) {
585 Res += *it;
586 } else {
587 Res += "_" + utostr((unsigned) *it) + "_";
588 }
589 }
590 }
591
592 return Res;
593}
594
595ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
596 ClassInfo *&Entry = TokenClasses[Token];
597
598 if (!Entry) {
599 Entry = new ClassInfo();
600 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000601 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000602 Entry->Name = "MCK_" + getEnumNameForToken(Token);
603 Entry->ValueName = Token;
604 Entry->PredicateMethod = "<invalid>";
605 Entry->RenderMethod = "<invalid>";
606 Classes.push_back(Entry);
607 }
608
609 return Entry;
610}
611
612ClassInfo *
613AsmMatcherInfo::getOperandClass(const StringRef &Token,
614 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000615 if (OI.Rec->isSubClassOf("RegisterClass")) {
616 ClassInfo *CI = RegisterClassClasses[OI.Rec];
617
618 if (!CI) {
619 PrintError(OI.Rec->getLoc(), "register class has no class info!");
620 throw std::string("ERROR: Missing register class!");
621 }
622
623 return CI;
624 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000625
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000626 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
627 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
628 ClassInfo *CI = AsmOperandClasses[MatchClass];
629
630 if (!CI) {
631 PrintError(OI.Rec->getLoc(), "operand has no match class!");
632 throw std::string("ERROR: Missing match class!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000633 }
634
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000635 return CI;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000636}
637
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000638void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
639 std::vector<CodeGenRegisterClass> RegisterClasses;
640 std::vector<CodeGenRegister> Registers;
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000641
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000642 RegisterClasses = Target.getRegisterClasses();
643 Registers = Target.getRegisters();
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000644
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000645 // The register sets used for matching.
646 std::set< std::set<Record*> > RegisterSets;
647
648 // Gather the defined sets.
649 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
650 ie = RegisterClasses.end(); it != ie; ++it)
651 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
652 it->Elements.end()));
653
654 // Introduce derived sets where necessary (when a register does not determine
655 // a unique register set class), and build the mapping of registers to the set
656 // they should classify to.
657 std::map<Record*, std::set<Record*> > RegisterMap;
658 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
659 ie = Registers.end(); it != ie; ++it) {
660 CodeGenRegister &CGR = *it;
661 // Compute the intersection of all sets containing this register.
662 std::set<Record*> ContainingSet;
663
664 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
665 ie = RegisterSets.end(); it != ie; ++it) {
666 if (!it->count(CGR.TheDef))
667 continue;
668
669 if (ContainingSet.empty()) {
670 ContainingSet = *it;
671 } else {
672 std::set<Record*> Tmp;
673 std::swap(Tmp, ContainingSet);
674 std::insert_iterator< std::set<Record*> > II(ContainingSet,
675 ContainingSet.begin());
676 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
677 II);
678 }
679 }
680
681 if (!ContainingSet.empty()) {
682 RegisterSets.insert(ContainingSet);
683 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
684 }
685 }
686
687 // Construct the register classes.
688 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
689 unsigned Index = 0;
690 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
691 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
692 ClassInfo *CI = new ClassInfo();
693 CI->Kind = ClassInfo::RegisterClass0 + Index;
694 CI->ClassName = "Reg" + utostr(Index);
695 CI->Name = "MCK_Reg" + utostr(Index);
696 CI->ValueName = "";
697 CI->PredicateMethod = ""; // unused
698 CI->RenderMethod = "addRegOperands";
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000699 CI->Registers = *it;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000700 Classes.push_back(CI);
701 RegisterSetClasses.insert(std::make_pair(*it, CI));
702 }
703
704 // Find the superclasses; we could compute only the subgroup lattice edges,
705 // but there isn't really a point.
706 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
707 ie = RegisterSets.end(); it != ie; ++it) {
708 ClassInfo *CI = RegisterSetClasses[*it];
709 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
710 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
711 if (*it != *it2 &&
712 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
713 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
714 }
715
716 // Name the register classes which correspond to a user defined RegisterClass.
717 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
718 ie = RegisterClasses.end(); it != ie; ++it) {
719 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
720 it->Elements.end())];
721 if (CI->ValueName.empty()) {
722 CI->ClassName = it->getName();
723 CI->Name = "MCK_" + it->getName();
724 CI->ValueName = it->getName();
725 } else
726 CI->ValueName = CI->ValueName + "," + it->getName();
727
728 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
729 }
730
731 // Populate the map for individual registers.
732 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
733 ie = RegisterMap.end(); it != ie; ++it)
734 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
735}
736
737void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000738 std::vector<Record*> AsmOperands;
739 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
740 unsigned Index = 0;
741 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
742 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
743 ClassInfo *CI = new ClassInfo();
744 CI->Kind = ClassInfo::UserClass0 + Index;
745
746 Init *Super = (*it)->getValueInit("SuperClass");
747 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000748 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
749 if (!SC)
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000750 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000751 else
752 CI->SuperClasses.push_back(SC);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000753 } else {
754 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000755 }
756 CI->ClassName = (*it)->getValueAsString("Name");
757 CI->Name = "MCK_" + CI->ClassName;
758 CI->ValueName = (*it)->getName();
Daniel Dunbarb3413d82009-08-10 21:00:45 +0000759
760 // Get or construct the predicate method name.
761 Init *PMName = (*it)->getValueInit("PredicateMethod");
762 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
763 CI->PredicateMethod = SI->getValue();
764 } else {
765 assert(dynamic_cast<UnsetInit*>(PMName) &&
766 "Unexpected PredicateMethod field!");
767 CI->PredicateMethod = "is" + CI->ClassName;
768 }
769
770 // Get or construct the render method name.
771 Init *RMName = (*it)->getValueInit("RenderMethod");
772 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
773 CI->RenderMethod = SI->getValue();
774 } else {
775 assert(dynamic_cast<UnsetInit*>(RMName) &&
776 "Unexpected RenderMethod field!");
777 CI->RenderMethod = "add" + CI->ClassName + "Operands";
778 }
779
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000780 AsmOperandClasses[*it] = CI;
781 Classes.push_back(CI);
782 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000783}
784
Daniel Dunbara6d04732009-08-11 20:59:47 +0000785AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
786 : AsmParser(_AsmParser),
787 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
788 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
789{
790}
791
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000792void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
793 // Build info for the register classes.
794 BuildRegisterClasses(Target);
795
796 // Build info for the user defined assembly operand classes.
797 BuildOperandClasses(Target);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000798
799 // Build the instruction information.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000800 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000801 it = Target.getInstructions().begin(),
802 ie = Target.getInstructions().end();
803 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000804 const CodeGenInstruction &CGI = it->second;
805
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000806 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000807 continue;
808
809 OwningPtr<InstructionInfo> II(new InstructionInfo);
810
811 II->InstrName = it->first;
812 II->Instr = &it->second;
813 II->AsmString = FlattenVariants(CGI.AsmString, 0);
814
Daniel Dunbara6d04732009-08-11 20:59:47 +0000815 // Remove comments from the asm string.
816 if (!CommentDelimiter.empty()) {
817 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
818 if (Idx != StringRef::npos)
819 II->AsmString = II->AsmString.substr(0, Idx);
820 }
821
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000822 TokenizeAsmString(II->AsmString, II->Tokens);
823
824 // Ignore instructions which shouldn't be matched.
825 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
826 continue;
827
828 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
829 StringRef Token = II->Tokens[i];
830
831 // Check for simple tokens.
832 if (Token[0] != '$') {
833 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000834 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000835 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000836 II->Operands.push_back(Op);
837 continue;
838 }
839
840 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000841 StringRef OperandName;
842 if (Token[1] == '{')
843 OperandName = Token.substr(2, Token.size() - 3);
844 else
845 OperandName = Token.substr(1);
846
847 // Map this token to an operand. FIXME: Move elsewhere.
848 unsigned Idx;
849 try {
850 Idx = CGI.getOperandNamed(OperandName);
851 } catch(...) {
852 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
853 break;
854 }
855
856 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000857 InstructionInfo::Operand Op;
858 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000859 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000860 II->Operands.push_back(Op);
861 }
862
863 // If we broke out, ignore the instruction.
864 if (II->Operands.size() != II->Tokens.size())
865 continue;
866
Daniel Dunbar378bee92009-08-08 07:50:56 +0000867 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000868 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000869
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000870 // Reorder classes so that classes preceed super classes.
871 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000872}
873
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000874static void EmitConvertToMCInst(CodeGenTarget &Target,
875 std::vector<InstructionInfo*> &Infos,
876 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000877 // Write the convert function to a separate stream, so we can drop it after
878 // the enum.
879 std::string ConvertFnBody;
880 raw_string_ostream CvtOS(ConvertFnBody);
881
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000882 // Function we have already generated.
883 std::set<std::string> GeneratedFns;
884
Daniel Dunbarce82b992009-08-08 05:24:34 +0000885 // Start the unified conversion function.
886
887 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
888 << "unsigned Opcode,\n"
889 << " SmallVectorImpl<"
890 << Target.getName() << "Operand> &Operands) {\n";
891 CvtOS << " Inst.setOpcode(Opcode);\n";
892 CvtOS << " switch (Kind) {\n";
893 CvtOS << " default:\n";
894
895 // Start the enum, which we will generate inline.
896
897 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000898 OS << "enum ConversionKind {\n";
899
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000900 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
901 ie = Infos.end(); it != ie; ++it) {
902 InstructionInfo &II = **it;
903
904 // Order the (class) operands by the order to convert them into an MCInst.
905 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
906 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
907 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000908 if (Op.OperandInfo)
909 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000910 }
911 std::sort(MIOperandList.begin(), MIOperandList.end());
912
913 // Compute the total number of operands.
914 unsigned NumMIOperands = 0;
915 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
916 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
917 NumMIOperands = std::max(NumMIOperands,
918 OI.MIOperandNo + OI.MINumOperands);
919 }
920
921 // Build the conversion function signature.
922 std::string Signature = "Convert";
923 unsigned CurIndex = 0;
924 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
925 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000926 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000927 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000928
Daniel Dunbarce82b992009-08-08 05:24:34 +0000929 Signature += "_";
930
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000931 // Skip operands which weren't matched by anything, this occurs when the
932 // .td file encodes "implicit" operands as explicit ones.
933 //
934 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000935 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000936 Signature += "Imp";
937
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000938 // Registers are always converted the same, don't duplicate the conversion
939 // function based on them.
940 //
941 // FIXME: We could generalize this based on the render method, if it
942 // mattered.
943 if (Op.Class->isRegisterClass())
944 Signature += "Reg";
945 else
946 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000947 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000948 Signature += "_" + utostr(MIOperandList[i].second);
949
Benjamin Kramer19afc502009-08-08 10:06:30 +0000950 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000951 }
952
953 // Add any trailing implicit operands.
954 for (; CurIndex != NumMIOperands; ++CurIndex)
955 Signature += "Imp";
956
Daniel Dunbarce82b992009-08-08 05:24:34 +0000957 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000958
Daniel Dunbarce82b992009-08-08 05:24:34 +0000959 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000960 if (!GeneratedFns.insert(Signature).second)
961 continue;
962
963 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000964
965 // Add to the enum list.
966 OS << " " << Signature << ",\n";
967
968 // And to the convert function.
969 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000970 CurIndex = 0;
971 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
972 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
973
974 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000975 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000976 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000977
Daniel Dunbarce82b992009-08-08 05:24:34 +0000978 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000979 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000980 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
981 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000982 }
983
984 // And add trailing implicit operands.
985 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000986 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
987 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000988 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000989
990 // Finish the convert function.
991
992 CvtOS << " }\n";
993 CvtOS << " return false;\n";
994 CvtOS << "}\n\n";
995
996 // Finish the enum, and drop the convert function after it.
997
998 OS << " NumConversionVariants\n";
999 OS << "};\n\n";
1000
Daniel Dunbarce82b992009-08-08 05:24:34 +00001001 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +00001002}
1003
Daniel Dunbar378bee92009-08-08 07:50:56 +00001004/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1005static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1006 std::vector<ClassInfo*> &Infos,
1007 raw_ostream &OS) {
1008 OS << "namespace {\n\n";
1009
1010 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1011 << "/// instruction matching.\n";
1012 OS << "enum MatchClassKind {\n";
1013 OS << " InvalidMatchClass = 0,\n";
1014 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1015 ie = Infos.end(); it != ie; ++it) {
1016 ClassInfo &CI = **it;
1017 OS << " " << CI.Name << ", // ";
1018 if (CI.Kind == ClassInfo::Token) {
1019 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001020 } else if (CI.isRegisterClass()) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001021 if (!CI.ValueName.empty())
1022 OS << "register class '" << CI.ValueName << "'\n";
1023 else
1024 OS << "derived register class\n";
1025 } else {
1026 OS << "user defined class '" << CI.ValueName << "'\n";
1027 }
1028 }
1029 OS << " NumMatchClassKinds\n";
1030 OS << "};\n\n";
1031
1032 OS << "}\n\n";
1033}
1034
Daniel Dunbar378bee92009-08-08 07:50:56 +00001035/// EmitClassifyOperand - Emit the function to classify an operand.
1036static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001037 AsmMatcherInfo &Info,
Daniel Dunbar378bee92009-08-08 07:50:56 +00001038 raw_ostream &OS) {
1039 OS << "static MatchClassKind ClassifyOperand("
1040 << Target.getName() << "Operand &Operand) {\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001041
1042 // Classify tokens.
Daniel Dunbar378bee92009-08-08 07:50:56 +00001043 OS << " if (Operand.isToken())\n";
1044 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001045
1046 // Classify registers.
1047 //
1048 // FIXME: Don't hardcode isReg, getReg.
1049 OS << " if (Operand.isReg()) {\n";
1050 OS << " switch (Operand.getReg()) {\n";
1051 OS << " default: return InvalidMatchClass;\n";
1052 for (std::map<Record*, ClassInfo*>::iterator
1053 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1054 it != ie; ++it)
1055 OS << " case " << Target.getName() << "::"
1056 << it->first->getName() << ": return " << it->second->Name << ";\n";
1057 OS << " }\n";
1058 OS << " }\n\n";
1059
1060 // Classify user defined operands.
1061 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1062 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001063 ClassInfo &CI = **it;
1064
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001065 if (!CI.isUserClass())
1066 continue;
1067
1068 OS << " // '" << CI.ClassName << "' class";
1069 if (!CI.SuperClasses.empty()) {
1070 OS << ", subclass of ";
1071 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1072 if (i) OS << ", ";
1073 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1074 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar06d5cb62009-08-09 07:20:21 +00001075 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001076 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001077 OS << "\n";
1078
1079 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1080
1081 // Validate subclass relationships.
1082 if (!CI.SuperClasses.empty()) {
1083 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1084 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1085 << "() && \"Invalid class relationship!\");\n";
1086 }
1087
1088 OS << " return " << CI.Name << ";\n";
1089 OS << " }\n\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001090 }
1091 OS << " return InvalidMatchClass;\n";
1092 OS << "}\n\n";
1093}
1094
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001095/// EmitIsSubclass - Emit the subclass predicate function.
1096static void EmitIsSubclass(CodeGenTarget &Target,
1097 std::vector<ClassInfo*> &Infos,
1098 raw_ostream &OS) {
1099 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1100 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1101 OS << " if (A == B)\n";
1102 OS << " return true;\n\n";
1103
1104 OS << " switch (A) {\n";
1105 OS << " default:\n";
1106 OS << " return false;\n";
1107 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1108 ie = Infos.end(); it != ie; ++it) {
1109 ClassInfo &A = **it;
1110
1111 if (A.Kind != ClassInfo::Token) {
1112 std::vector<StringRef> SuperClasses;
1113 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1114 ie = Infos.end(); it != ie; ++it) {
1115 ClassInfo &B = **it;
1116
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001117 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001118 SuperClasses.push_back(B.Name);
1119 }
1120
1121 if (SuperClasses.empty())
1122 continue;
1123
1124 OS << "\n case " << A.Name << ":\n";
1125
1126 if (SuperClasses.size() == 1) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001127 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001128 continue;
1129 }
1130
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001131 OS << " switch (B) {\n";
1132 OS << " default: return false;\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001133 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001134 OS << " case " << SuperClasses[i] << ": return true;\n";
1135 OS << " }\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001136 }
1137 }
1138 OS << " }\n";
1139 OS << "}\n\n";
1140}
1141
Chris Lattner042926f2009-08-08 20:02:57 +00001142typedef std::pair<std::string, std::string> StringPair;
1143
1144/// FindFirstNonCommonLetter - Find the first character in the keys of the
1145/// string pairs that is not shared across the whole set of strings. All
1146/// strings are assumed to have the same length.
1147static unsigned
1148FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1149 assert(!Matches.empty());
1150 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1151 // Check to see if letter i is the same across the set.
1152 char Letter = Matches[0]->first[i];
1153
1154 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1155 if (Matches[str]->first[i] != Letter)
1156 return i;
1157 }
1158
1159 return Matches[0]->first.size();
1160}
1161
1162/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1163/// same length and whose characters leading up to CharNo are the same, emit
1164/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001165///
1166/// \return - True if control can leave the emitted code fragment.
1167static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +00001168 const std::vector<const StringPair*> &Matches,
1169 unsigned CharNo, unsigned IndentCount,
1170 raw_ostream &OS) {
1171 assert(!Matches.empty() && "Must have at least one string to match!");
1172 std::string Indent(IndentCount*2+4, ' ');
1173
1174 // If we have verified that the entire string matches, we're done: output the
1175 // matching code.
1176 if (CharNo == Matches[0]->first.size()) {
1177 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1178
1179 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1180 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1181 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001182 return false;
Chris Lattner042926f2009-08-08 20:02:57 +00001183 }
1184
1185 // Bucket the matches by the character we are comparing.
1186 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1187
1188 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1189 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1190
1191
1192 // If we have exactly one bucket to match, see how many characters are common
1193 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +00001194 if (MatchesByLetter.size() == 1) {
1195 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1196 unsigned NumChars = FirstNonCommonLetter-CharNo;
1197
Daniel Dunbar7906a642009-08-08 22:57:25 +00001198 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +00001199 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001200 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +00001201 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001202 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1203 << Matches[0]->first[CharNo] << "')\n";
1204 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001205 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001206 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +00001207 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001208 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1209 << NumChars << ") != \"";
1210 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +00001211 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001212 }
1213
Daniel Dunbar7906a642009-08-08 22:57:25 +00001214 return EmitStringMatcherForChar(StrVariableName, Matches,
1215 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001216 }
1217
1218 // Otherwise, we have multiple possible things, emit a switch on the
1219 // character.
1220 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1221 OS << Indent << "default: break;\n";
1222
1223 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1224 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1225 // TODO: escape hard stuff (like \n) if we ever care about it.
1226 OS << Indent << "case '" << LI->first << "':\t // "
1227 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001228 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1229 IndentCount+1, OS))
1230 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001231 }
1232
1233 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001234 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001235}
1236
1237
1238/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001239/// match, output a simple switch tree to classify the input string.
1240///
1241/// If a match is found, the code in Vals[i].second is executed; control must
1242/// not exit this code fragment. If nothing matches, execution falls through.
1243///
1244/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001245static void EmitStringMatcher(const std::string &StrVariableName,
1246 const std::vector<StringPair> &Matches,
1247 raw_ostream &OS) {
1248 // First level categorization: group strings by length.
1249 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1250
1251 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1252 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1253
1254 // Output a switch statement on length and categorize the elements within each
1255 // bin.
1256 OS << " switch (" << StrVariableName << ".size()) {\n";
1257 OS << " default: break;\n";
1258
Chris Lattner042926f2009-08-08 20:02:57 +00001259 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1260 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1261 OS << " case " << LI->first << ":\t // " << LI->second.size()
1262 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001263 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1264 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001265 }
1266
Chris Lattner042926f2009-08-08 20:02:57 +00001267 OS << " }\n";
1268}
1269
1270
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001271/// EmitMatchTokenString - Emit the function to match a token string to the
1272/// appropriate match class value.
1273static void EmitMatchTokenString(CodeGenTarget &Target,
1274 std::vector<ClassInfo*> &Infos,
1275 raw_ostream &OS) {
1276 // Construct the match list.
1277 std::vector<StringPair> Matches;
1278 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1279 ie = Infos.end(); it != ie; ++it) {
1280 ClassInfo &CI = **it;
1281
1282 if (CI.Kind == ClassInfo::Token)
1283 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1284 }
1285
1286 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1287
1288 EmitStringMatcher("Name", Matches, OS);
1289
1290 OS << " return InvalidMatchClass;\n";
1291 OS << "}\n\n";
1292}
Chris Lattner042926f2009-08-08 20:02:57 +00001293
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001294/// EmitMatchRegisterName - Emit the function to match a string to the target
1295/// specific register enum.
1296static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1297 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001298 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001299 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001300 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1301 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001302 if (Reg.TheDef->getValueAsString("AsmName").empty())
1303 continue;
1304
Chris Lattner042926f2009-08-08 20:02:57 +00001305 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001306 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001307 }
Chris Lattner042926f2009-08-08 20:02:57 +00001308
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001309 OS << "unsigned " << Target.getName()
1310 << AsmParser->getValueAsString("AsmParserClassName")
1311 << "::MatchRegisterName(const StringRef &Name) {\n";
1312
Chris Lattner042926f2009-08-08 20:02:57 +00001313 EmitStringMatcher("Name", Matches, OS);
1314
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001315 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001316 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001317}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001318
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001319void AsmMatcherEmitter::run(raw_ostream &OS) {
1320 CodeGenTarget Target;
1321 Record *AsmParser = Target.getAsmParser();
1322 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1323
1324 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1325
1326 // Emit the function to match a register name to number.
1327 EmitMatchRegisterName(Target, AsmParser, OS);
1328
Daniel Dunbar378bee92009-08-08 07:50:56 +00001329 // Compute the information on the instructions to match.
Daniel Dunbara6d04732009-08-11 20:59:47 +00001330 AsmMatcherInfo Info(AsmParser);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001331 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001332
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001333 // Sort the instruction table using the partial order on classes.
1334 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1335 less_ptr<InstructionInfo>());
1336
Daniel Dunbarce82b992009-08-08 05:24:34 +00001337 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001338 for (std::vector<InstructionInfo*>::iterator
1339 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1340 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001341 (*it)->dump();
1342 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001343
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001344 // Check for ambiguous instructions.
1345 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001346 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1347 for (unsigned j = i + 1; j != e; ++j) {
1348 InstructionInfo &A = *Info.Instructions[i];
1349 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001350
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001351 if (A.CouldMatchAmiguouslyWith(B)) {
1352 DEBUG_WITH_TYPE("ambiguous_instrs", {
1353 errs() << "warning: ambiguous instruction match:\n";
1354 A.dump();
1355 errs() << "\nis incomparable with:\n";
1356 B.dump();
1357 errs() << "\n\n";
1358 });
1359 ++NumAmbiguous;
1360 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001361 }
1362 }
1363 if (NumAmbiguous)
1364 DEBUG_WITH_TYPE("ambiguous_instrs", {
1365 errs() << "warning: " << NumAmbiguous
1366 << " ambiguous instructions!\n";
1367 });
1368
1369 // Generate the unified function to convert operands into an MCInst.
1370 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001371
Daniel Dunbar378bee92009-08-08 07:50:56 +00001372 // Emit the enumeration for classes which participate in matching.
1373 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001374
Daniel Dunbar378bee92009-08-08 07:50:56 +00001375 // Emit the routine to match token strings to their match class.
1376 EmitMatchTokenString(Target, Info.Classes, OS);
1377
1378 // Emit the routine to classify an operand.
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001379 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001380
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001381 // Emit the subclass predicate routine.
1382 EmitIsSubclass(Target, Info.Classes, OS);
1383
Daniel Dunbar378bee92009-08-08 07:50:56 +00001384 // Finally, build the match function.
1385
1386 size_t MaxNumOperands = 0;
1387 for (std::vector<InstructionInfo*>::const_iterator it =
1388 Info.Instructions.begin(), ie = Info.Instructions.end();
1389 it != ie; ++it)
1390 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1391
Daniel Dunbara54716c2009-07-31 02:32:59 +00001392 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001393 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001394 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1395 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001396
Daniel Dunbar378bee92009-08-08 07:50:56 +00001397 // Emit the static match table; unused classes get initalized to 0 which is
1398 // guaranteed to be InvalidMatchClass.
1399 //
1400 // FIXME: We can reduce the size of this table very easily. First, we change
1401 // it so that store the kinds in separate bit-fields for each index, which
1402 // only needs to be the max width used for classes at that index (we also need
1403 // to reject based on this during classification). If we then make sure to
1404 // order the match kinds appropriately (putting mnemonics last), then we
1405 // should only end up using a few bits for each class, especially the ones
1406 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001407 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001408 OS << " unsigned Opcode;\n";
1409 OS << " ConversionKind ConvertFn;\n";
1410 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1411 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1412
1413 for (std::vector<InstructionInfo*>::const_iterator it =
1414 Info.Instructions.begin(), ie = Info.Instructions.end();
1415 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001416 InstructionInfo &II = **it;
1417
Daniel Dunbar378bee92009-08-08 07:50:56 +00001418 OS << " { " << Target.getName() << "::" << II.InstrName
1419 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001420 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1421 InstructionInfo::Operand &Op = II.Operands[i];
1422
Daniel Dunbar378bee92009-08-08 07:50:56 +00001423 if (i) OS << ", ";
1424 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001425 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001426 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001427 }
1428
Daniel Dunbar378bee92009-08-08 07:50:56 +00001429 OS << " };\n\n";
1430
1431 // Emit code to compute the class list for this operand vector.
1432 OS << " // Eliminate obvious mismatches.\n";
1433 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1434 OS << " return true;\n\n";
1435
1436 OS << " // Compute the class list for this operand vector.\n";
1437 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1438 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1439 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1440
1441 OS << " // Check for invalid operands before matching.\n";
1442 OS << " if (Classes[i] == InvalidMatchClass)\n";
1443 OS << " return true;\n";
1444 OS << " }\n\n";
1445
1446 OS << " // Mark unused classes.\n";
1447 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1448 << "i != e; ++i)\n";
1449 OS << " Classes[i] = InvalidMatchClass;\n\n";
1450
1451 // Emit code to search the table.
1452 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001453 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001454 << "*ie = MatchTable + " << Info.Instructions.size()
1455 << "; it != ie; ++it) {\n";
1456 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001457 OS << " if (!IsSubclass(Classes["
1458 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001459 OS << " continue;\n";
1460 }
1461 OS << "\n";
1462 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1463 << "it->Opcode, Operands);\n";
1464 OS << " }\n\n";
1465
Daniel Dunbara54716c2009-07-31 02:32:59 +00001466 OS << " return true;\n";
1467 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001468}