blob: 57b93b1d2700b04dd05f991aacd8950c75bd70fd [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) {
213 // Ignore psuedo ops.
214 //
215 // FIXME: This is a hack.
216 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
217 if (Form->getValue()->getAsString() == "Pseudo")
218 return false;
219
220 // Ignore "PHI" node.
221 //
222 // FIXME: This is also a hack.
223 if (Name == "PHI")
224 return false;
225
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000226 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227 //
228 // FIXME: This is a total hack.
229 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
230 return false;
231
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000232 // Ignore instructions with no .s string.
233 //
234 // FIXME: What are these?
235 if (CGI.AsmString.empty())
236 return false;
237
238 // FIXME: Hack; ignore any instructions with a newline in them.
239 if (std::find(CGI.AsmString.begin(),
240 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
241 return false;
242
243 // Ignore instructions with attributes, these are always fake instructions for
244 // simplifying codegen.
245 //
246 // FIXME: Is this true?
247 //
248 // Also, we ignore instructions which reference the operand multiple times;
249 // this implies a constraint we would not currently honor. These are
250 // currently always fake instructions for simplifying codegen.
251 //
252 // FIXME: Encode this assumption in the .td, so we can error out here.
253 std::set<std::string> OperandNames;
254 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255 if (Tokens[i][0] == '$' &&
256 std::find(Tokens[i].begin(),
257 Tokens[i].end(), ':') != Tokens[i].end()) {
258 DEBUG({
259 errs() << "warning: '" << Name << "': "
260 << "ignoring instruction; operand with attribute '"
261 << Tokens[i] << "', \n";
262 });
263 return false;
264 }
265
266 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
267 DEBUG({
268 errs() << "warning: '" << Name << "': "
269 << "ignoring instruction; tied operand '"
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000270 << Tokens[i] << "'\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000271 });
272 return false;
273 }
274 }
275
276 return true;
277}
278
279namespace {
280
Daniel Dunbar378bee92009-08-08 07:50:56 +0000281/// ClassInfo - Helper class for storing the information about a particular
282/// class of operands which can be matched.
283struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000284 enum ClassInfoKind {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000285 /// Invalid kind, for use as a sentinel value.
286 Invalid = 0,
287
288 /// The class for a particular token.
289 Token,
290
291 /// The (first) register class, subsequent register classes are
292 /// RegisterClass0+1, and so on.
293 RegisterClass0,
294
295 /// The (first) user defined class, subsequent user defined classes are
296 /// UserClass0+1, and so on.
297 UserClass0 = 1<<16
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000298 };
299
300 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
301 /// N) for the Nth user defined class.
302 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000303
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000304 /// SuperClasses - The super classes of this class. Note that for simplicities
305 /// sake user operands only record their immediate super class, while register
306 /// operands include all superclasses.
307 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000308
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000309 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000310 std::string Name;
311
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000312 /// ClassName - The unadorned generic name for this class (e.g., Token).
313 std::string ClassName;
314
Daniel Dunbar378bee92009-08-08 07:50:56 +0000315 /// ValueName - The name of the value this class represents; for a token this
316 /// is the literal token string, for an operand it is the TableGen class (or
317 /// empty if this is a derived class).
318 std::string ValueName;
319
320 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000321 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000322 std::string PredicateMethod;
323
324 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000325 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000326 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000327
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000328 /// For register classes, the records for all the registers in this class.
329 std::set<Record*> Registers;
330
331public:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000332 /// isRegisterClass() - Check if this is a register class.
333 bool isRegisterClass() const {
334 return Kind >= RegisterClass0 && Kind < UserClass0;
335 }
336
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000337 /// isUserClass() - Check if this is a user defined class.
338 bool isUserClass() const {
339 return Kind >= UserClass0;
340 }
341
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000342 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
343 /// are related if they are in the same class hierarchy.
344 bool isRelatedTo(const ClassInfo &RHS) const {
345 // Tokens are only related to tokens.
346 if (Kind == Token || RHS.Kind == Token)
347 return Kind == Token && RHS.Kind == Token;
348
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000349 // Registers classes are only related to registers classes, and only if
350 // their intersection is non-empty.
351 if (isRegisterClass() || RHS.isRegisterClass()) {
352 if (!isRegisterClass() || !RHS.isRegisterClass())
353 return false;
354
355 std::set<Record*> Tmp;
356 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
357 std::set_intersection(Registers.begin(), Registers.end(),
358 RHS.Registers.begin(), RHS.Registers.end(),
359 II);
360
361 return !Tmp.empty();
362 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000363
364 // Otherwise we have two users operands; they are related if they are in the
365 // same class hierarchy.
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000366 //
367 // FIXME: This is an oversimplification, they should only be related if they
368 // intersect, however we don't have that information.
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000369 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
370 const ClassInfo *Root = this;
371 while (!Root->SuperClasses.empty())
372 Root = Root->SuperClasses.front();
373
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000374 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000375 while (!RHSRoot->SuperClasses.empty())
376 RHSRoot = RHSRoot->SuperClasses.front();
377
378 return Root == RHSRoot;
379 }
380
381 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
382 bool isSubsetOf(const ClassInfo &RHS) const {
383 // This is a subset of RHS if it is the same class...
384 if (this == &RHS)
385 return true;
386
387 // ... or if any of its super classes are a subset of RHS.
388 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
389 ie = SuperClasses.end(); it != ie; ++it)
390 if ((*it)->isSubsetOf(RHS))
391 return true;
392
393 return false;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000394 }
395
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000396 /// operator< - Compare two classes.
397 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000398 // Unrelated classes can be ordered by kind.
399 if (!isRelatedTo(RHS))
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000400 return Kind < RHS.Kind;
401
402 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000403 case Invalid:
404 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000405 case Token:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000406 // Tokens are comparable by value.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000407 //
408 // FIXME: Compare by enum value.
409 return ValueName < RHS.ValueName;
410
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000411 default:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000412 // This class preceeds the RHS if it is a proper subset of the RHS.
413 return this != &RHS && isSubsetOf(RHS);
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000414 }
415 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000416};
417
Daniel Dunbarce82b992009-08-08 05:24:34 +0000418/// InstructionInfo - Helper class for storing the necessary information for an
419/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000420struct InstructionInfo {
421 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000422 /// The unique class instance this operand should match.
423 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000424
Daniel Dunbar378bee92009-08-08 07:50:56 +0000425 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000426 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000427 };
428
429 /// InstrName - The target name for this instruction.
430 std::string InstrName;
431
432 /// Instr - The instruction this matches.
433 const CodeGenInstruction *Instr;
434
435 /// AsmString - The assembly string for this instruction (with variants
436 /// removed).
437 std::string AsmString;
438
439 /// Tokens - The tokenized assembly pattern that this instruction matches.
440 SmallVector<StringRef, 4> Tokens;
441
442 /// Operands - The operands that this instruction matches.
443 SmallVector<Operand, 4> Operands;
444
Daniel Dunbarce82b992009-08-08 05:24:34 +0000445 /// ConversionFnKind - The enum value which is passed to the generated
446 /// ConvertToMCInst to convert parsed operands into an MCInst for this
447 /// function.
448 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000449
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000450 /// operator< - Compare two instructions.
451 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000452 if (Operands.size() != RHS.Operands.size())
453 return Operands.size() < RHS.Operands.size();
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000454
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000455 // Compare lexicographically by operand. The matcher validates that other
456 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
457 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000458 if (*Operands[i].Class < *RHS.Operands[i].Class)
459 return true;
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000460 if (*RHS.Operands[i].Class < *Operands[i].Class)
461 return false;
462 }
463
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000464 return false;
465 }
466
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000467 /// CouldMatchAmiguouslyWith - Check whether this instruction could
468 /// ambiguously match the same set of operands as \arg RHS (without being a
469 /// strictly superior match).
470 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
471 // The number of operands is unambiguous.
472 if (Operands.size() != RHS.Operands.size())
473 return false;
474
475 // Tokens and operand kinds are unambiguous (assuming a correct target
476 // specific parser).
477 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
478 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
479 Operands[i].Class->Kind == ClassInfo::Token)
480 if (*Operands[i].Class < *RHS.Operands[i].Class ||
481 *RHS.Operands[i].Class < *Operands[i].Class)
482 return false;
483
484 // Otherwise, this operand could commute if all operands are equivalent, or
485 // there is a pair of operands that compare less than and a pair that
486 // compare greater than.
487 bool HasLT = false, HasGT = false;
488 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
489 if (*Operands[i].Class < *RHS.Operands[i].Class)
490 HasLT = true;
491 if (*RHS.Operands[i].Class < *Operands[i].Class)
492 HasGT = true;
493 }
494
495 return !(HasLT ^ HasGT);
496 }
497
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000498public:
499 void dump();
500};
501
Daniel Dunbar378bee92009-08-08 07:50:56 +0000502class AsmMatcherInfo {
503public:
504 /// The classes which are needed for matching.
505 std::vector<ClassInfo*> Classes;
506
507 /// The information on the instruction to match.
508 std::vector<InstructionInfo*> Instructions;
509
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000510 /// Map of Register records to their class information.
511 std::map<Record*, ClassInfo*> RegisterClasses;
512
Daniel Dunbar378bee92009-08-08 07:50:56 +0000513private:
514 /// Map of token to class information which has already been constructed.
515 std::map<std::string, ClassInfo*> TokenClasses;
516
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000517 /// Map of RegisterClass records to their class information.
518 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000519
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000520 /// Map of AsmOperandClass records to their class information.
521 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000522
Daniel Dunbar378bee92009-08-08 07:50:56 +0000523private:
524 /// getTokenClass - Lookup or create the class for the given token.
525 ClassInfo *getTokenClass(const StringRef &Token);
526
527 /// getOperandClass - Lookup or create the class for the given operand.
528 ClassInfo *getOperandClass(const StringRef &Token,
529 const CodeGenInstruction::OperandInfo &OI);
530
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000531 /// BuildRegisterClasses - Build the ClassInfo* instances for register
532 /// classes.
533 void BuildRegisterClasses(CodeGenTarget &Target);
534
535 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
536 /// operand classes.
537 void BuildOperandClasses(CodeGenTarget &Target);
538
Daniel Dunbar378bee92009-08-08 07:50:56 +0000539public:
540 /// BuildInfo - Construct the various tables used during matching.
541 void BuildInfo(CodeGenTarget &Target);
542};
543
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000544}
545
546void InstructionInfo::dump() {
547 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
548 << ", tokens:[";
549 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
550 errs() << Tokens[i];
551 if (i + 1 != e)
552 errs() << ", ";
553 }
554 errs() << "]\n";
555
556 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
557 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000558 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000559 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000560 errs() << '\"' << Tokens[i] << "\"\n";
561 continue;
562 }
563
Benjamin Kramer19afc502009-08-08 10:06:30 +0000564 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000565 errs() << OI.Name << " " << OI.Rec->getName()
566 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
567 }
568}
569
Daniel Dunbar378bee92009-08-08 07:50:56 +0000570static std::string getEnumNameForToken(const StringRef &Str) {
571 std::string Res;
572
573 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
574 switch (*it) {
575 case '*': Res += "_STAR_"; break;
576 case '%': Res += "_PCT_"; break;
577 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000578
Daniel Dunbar378bee92009-08-08 07:50:56 +0000579 default:
580 if (isalnum(*it)) {
581 Res += *it;
582 } else {
583 Res += "_" + utostr((unsigned) *it) + "_";
584 }
585 }
586 }
587
588 return Res;
589}
590
591ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
592 ClassInfo *&Entry = TokenClasses[Token];
593
594 if (!Entry) {
595 Entry = new ClassInfo();
596 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000597 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000598 Entry->Name = "MCK_" + getEnumNameForToken(Token);
599 Entry->ValueName = Token;
600 Entry->PredicateMethod = "<invalid>";
601 Entry->RenderMethod = "<invalid>";
602 Classes.push_back(Entry);
603 }
604
605 return Entry;
606}
607
608ClassInfo *
609AsmMatcherInfo::getOperandClass(const StringRef &Token,
610 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000611 if (OI.Rec->isSubClassOf("RegisterClass")) {
612 ClassInfo *CI = RegisterClassClasses[OI.Rec];
613
614 if (!CI) {
615 PrintError(OI.Rec->getLoc(), "register class has no class info!");
616 throw std::string("ERROR: Missing register class!");
617 }
618
619 return CI;
620 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000621
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000622 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
623 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
624 ClassInfo *CI = AsmOperandClasses[MatchClass];
625
626 if (!CI) {
627 PrintError(OI.Rec->getLoc(), "operand has no match class!");
628 throw std::string("ERROR: Missing match class!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000629 }
630
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000631 return CI;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000632}
633
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000634void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
635 std::vector<CodeGenRegisterClass> RegisterClasses;
636 std::vector<CodeGenRegister> Registers;
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000637
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000638 RegisterClasses = Target.getRegisterClasses();
639 Registers = Target.getRegisters();
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000640
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000641 // The register sets used for matching.
642 std::set< std::set<Record*> > RegisterSets;
643
644 // Gather the defined sets.
645 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
646 ie = RegisterClasses.end(); it != ie; ++it)
647 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
648 it->Elements.end()));
649
650 // Introduce derived sets where necessary (when a register does not determine
651 // a unique register set class), and build the mapping of registers to the set
652 // they should classify to.
653 std::map<Record*, std::set<Record*> > RegisterMap;
654 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
655 ie = Registers.end(); it != ie; ++it) {
656 CodeGenRegister &CGR = *it;
657 // Compute the intersection of all sets containing this register.
658 std::set<Record*> ContainingSet;
659
660 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
661 ie = RegisterSets.end(); it != ie; ++it) {
662 if (!it->count(CGR.TheDef))
663 continue;
664
665 if (ContainingSet.empty()) {
666 ContainingSet = *it;
667 } else {
668 std::set<Record*> Tmp;
669 std::swap(Tmp, ContainingSet);
670 std::insert_iterator< std::set<Record*> > II(ContainingSet,
671 ContainingSet.begin());
672 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
673 II);
674 }
675 }
676
677 if (!ContainingSet.empty()) {
678 RegisterSets.insert(ContainingSet);
679 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
680 }
681 }
682
683 // Construct the register classes.
684 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
685 unsigned Index = 0;
686 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
687 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
688 ClassInfo *CI = new ClassInfo();
689 CI->Kind = ClassInfo::RegisterClass0 + Index;
690 CI->ClassName = "Reg" + utostr(Index);
691 CI->Name = "MCK_Reg" + utostr(Index);
692 CI->ValueName = "";
693 CI->PredicateMethod = ""; // unused
694 CI->RenderMethod = "addRegOperands";
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000695 CI->Registers = *it;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000696 Classes.push_back(CI);
697 RegisterSetClasses.insert(std::make_pair(*it, CI));
698 }
699
700 // Find the superclasses; we could compute only the subgroup lattice edges,
701 // but there isn't really a point.
702 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
703 ie = RegisterSets.end(); it != ie; ++it) {
704 ClassInfo *CI = RegisterSetClasses[*it];
705 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
706 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
707 if (*it != *it2 &&
708 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
709 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
710 }
711
712 // Name the register classes which correspond to a user defined RegisterClass.
713 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
714 ie = RegisterClasses.end(); it != ie; ++it) {
715 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
716 it->Elements.end())];
717 if (CI->ValueName.empty()) {
718 CI->ClassName = it->getName();
719 CI->Name = "MCK_" + it->getName();
720 CI->ValueName = it->getName();
721 } else
722 CI->ValueName = CI->ValueName + "," + it->getName();
723
724 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
725 }
726
727 // Populate the map for individual registers.
728 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
729 ie = RegisterMap.end(); it != ie; ++it)
730 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
731}
732
733void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000734 std::vector<Record*> AsmOperands;
735 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
736 unsigned Index = 0;
737 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
738 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
739 ClassInfo *CI = new ClassInfo();
740 CI->Kind = ClassInfo::UserClass0 + Index;
741
742 Init *Super = (*it)->getValueInit("SuperClass");
743 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000744 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
745 if (!SC)
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000746 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000747 else
748 CI->SuperClasses.push_back(SC);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000749 } else {
750 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000751 }
752 CI->ClassName = (*it)->getValueAsString("Name");
753 CI->Name = "MCK_" + CI->ClassName;
754 CI->ValueName = (*it)->getName();
Daniel Dunbarb3413d82009-08-10 21:00:45 +0000755
756 // Get or construct the predicate method name.
757 Init *PMName = (*it)->getValueInit("PredicateMethod");
758 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
759 CI->PredicateMethod = SI->getValue();
760 } else {
761 assert(dynamic_cast<UnsetInit*>(PMName) &&
762 "Unexpected PredicateMethod field!");
763 CI->PredicateMethod = "is" + CI->ClassName;
764 }
765
766 // Get or construct the render method name.
767 Init *RMName = (*it)->getValueInit("RenderMethod");
768 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
769 CI->RenderMethod = SI->getValue();
770 } else {
771 assert(dynamic_cast<UnsetInit*>(RMName) &&
772 "Unexpected RenderMethod field!");
773 CI->RenderMethod = "add" + CI->ClassName + "Operands";
774 }
775
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000776 AsmOperandClasses[*it] = CI;
777 Classes.push_back(CI);
778 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000779}
780
781void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
782 // Build info for the register classes.
783 BuildRegisterClasses(Target);
784
785 // Build info for the user defined assembly operand classes.
786 BuildOperandClasses(Target);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000787
788 // Build the instruction information.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000789 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000790 it = Target.getInstructions().begin(),
791 ie = Target.getInstructions().end();
792 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000793 const CodeGenInstruction &CGI = it->second;
794
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000795 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000796 continue;
797
798 OwningPtr<InstructionInfo> II(new InstructionInfo);
799
800 II->InstrName = it->first;
801 II->Instr = &it->second;
802 II->AsmString = FlattenVariants(CGI.AsmString, 0);
803
804 TokenizeAsmString(II->AsmString, II->Tokens);
805
806 // Ignore instructions which shouldn't be matched.
807 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
808 continue;
809
810 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
811 StringRef Token = II->Tokens[i];
812
813 // Check for simple tokens.
814 if (Token[0] != '$') {
815 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000816 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000817 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000818 II->Operands.push_back(Op);
819 continue;
820 }
821
822 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000823 StringRef OperandName;
824 if (Token[1] == '{')
825 OperandName = Token.substr(2, Token.size() - 3);
826 else
827 OperandName = Token.substr(1);
828
829 // Map this token to an operand. FIXME: Move elsewhere.
830 unsigned Idx;
831 try {
832 Idx = CGI.getOperandNamed(OperandName);
833 } catch(...) {
834 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
835 break;
836 }
837
838 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000839 InstructionInfo::Operand Op;
840 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000841 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000842 II->Operands.push_back(Op);
843 }
844
845 // If we broke out, ignore the instruction.
846 if (II->Operands.size() != II->Tokens.size())
847 continue;
848
Daniel Dunbar378bee92009-08-08 07:50:56 +0000849 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000850 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000851
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000852 // Reorder classes so that classes preceed super classes.
853 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000854}
855
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000856static void EmitConvertToMCInst(CodeGenTarget &Target,
857 std::vector<InstructionInfo*> &Infos,
858 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000859 // Write the convert function to a separate stream, so we can drop it after
860 // the enum.
861 std::string ConvertFnBody;
862 raw_string_ostream CvtOS(ConvertFnBody);
863
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000864 // Function we have already generated.
865 std::set<std::string> GeneratedFns;
866
Daniel Dunbarce82b992009-08-08 05:24:34 +0000867 // Start the unified conversion function.
868
869 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
870 << "unsigned Opcode,\n"
871 << " SmallVectorImpl<"
872 << Target.getName() << "Operand> &Operands) {\n";
873 CvtOS << " Inst.setOpcode(Opcode);\n";
874 CvtOS << " switch (Kind) {\n";
875 CvtOS << " default:\n";
876
877 // Start the enum, which we will generate inline.
878
879 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000880 OS << "enum ConversionKind {\n";
881
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000882 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
883 ie = Infos.end(); it != ie; ++it) {
884 InstructionInfo &II = **it;
885
886 // Order the (class) operands by the order to convert them into an MCInst.
887 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
888 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
889 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000890 if (Op.OperandInfo)
891 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000892 }
893 std::sort(MIOperandList.begin(), MIOperandList.end());
894
895 // Compute the total number of operands.
896 unsigned NumMIOperands = 0;
897 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
898 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
899 NumMIOperands = std::max(NumMIOperands,
900 OI.MIOperandNo + OI.MINumOperands);
901 }
902
903 // Build the conversion function signature.
904 std::string Signature = "Convert";
905 unsigned CurIndex = 0;
906 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
907 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000908 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000909 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000910
Daniel Dunbarce82b992009-08-08 05:24:34 +0000911 Signature += "_";
912
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000913 // Skip operands which weren't matched by anything, this occurs when the
914 // .td file encodes "implicit" operands as explicit ones.
915 //
916 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000917 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000918 Signature += "Imp";
919
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000920 // Registers are always converted the same, don't duplicate the conversion
921 // function based on them.
922 //
923 // FIXME: We could generalize this based on the render method, if it
924 // mattered.
925 if (Op.Class->isRegisterClass())
926 Signature += "Reg";
927 else
928 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000929 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000930 Signature += "_" + utostr(MIOperandList[i].second);
931
Benjamin Kramer19afc502009-08-08 10:06:30 +0000932 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000933 }
934
935 // Add any trailing implicit operands.
936 for (; CurIndex != NumMIOperands; ++CurIndex)
937 Signature += "Imp";
938
Daniel Dunbarce82b992009-08-08 05:24:34 +0000939 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000940
Daniel Dunbarce82b992009-08-08 05:24:34 +0000941 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000942 if (!GeneratedFns.insert(Signature).second)
943 continue;
944
945 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000946
947 // Add to the enum list.
948 OS << " " << Signature << ",\n";
949
950 // And to the convert function.
951 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000952 CurIndex = 0;
953 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
954 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
955
956 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000957 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000958 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000959
Daniel Dunbarce82b992009-08-08 05:24:34 +0000960 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000961 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000962 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
963 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000964 }
965
966 // And add trailing implicit operands.
967 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000968 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
969 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000970 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000971
972 // Finish the convert function.
973
974 CvtOS << " }\n";
975 CvtOS << " return false;\n";
976 CvtOS << "}\n\n";
977
978 // Finish the enum, and drop the convert function after it.
979
980 OS << " NumConversionVariants\n";
981 OS << "};\n\n";
982
Daniel Dunbarce82b992009-08-08 05:24:34 +0000983 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +0000984}
985
Daniel Dunbar378bee92009-08-08 07:50:56 +0000986/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
987static void EmitMatchClassEnumeration(CodeGenTarget &Target,
988 std::vector<ClassInfo*> &Infos,
989 raw_ostream &OS) {
990 OS << "namespace {\n\n";
991
992 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
993 << "/// instruction matching.\n";
994 OS << "enum MatchClassKind {\n";
995 OS << " InvalidMatchClass = 0,\n";
996 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
997 ie = Infos.end(); it != ie; ++it) {
998 ClassInfo &CI = **it;
999 OS << " " << CI.Name << ", // ";
1000 if (CI.Kind == ClassInfo::Token) {
1001 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001002 } else if (CI.isRegisterClass()) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001003 if (!CI.ValueName.empty())
1004 OS << "register class '" << CI.ValueName << "'\n";
1005 else
1006 OS << "derived register class\n";
1007 } else {
1008 OS << "user defined class '" << CI.ValueName << "'\n";
1009 }
1010 }
1011 OS << " NumMatchClassKinds\n";
1012 OS << "};\n\n";
1013
1014 OS << "}\n\n";
1015}
1016
Daniel Dunbar378bee92009-08-08 07:50:56 +00001017/// EmitClassifyOperand - Emit the function to classify an operand.
1018static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001019 AsmMatcherInfo &Info,
Daniel Dunbar378bee92009-08-08 07:50:56 +00001020 raw_ostream &OS) {
1021 OS << "static MatchClassKind ClassifyOperand("
1022 << Target.getName() << "Operand &Operand) {\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001023
1024 // Classify tokens.
Daniel Dunbar378bee92009-08-08 07:50:56 +00001025 OS << " if (Operand.isToken())\n";
1026 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001027
1028 // Classify registers.
1029 //
1030 // FIXME: Don't hardcode isReg, getReg.
1031 OS << " if (Operand.isReg()) {\n";
1032 OS << " switch (Operand.getReg()) {\n";
1033 OS << " default: return InvalidMatchClass;\n";
1034 for (std::map<Record*, ClassInfo*>::iterator
1035 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1036 it != ie; ++it)
1037 OS << " case " << Target.getName() << "::"
1038 << it->first->getName() << ": return " << it->second->Name << ";\n";
1039 OS << " }\n";
1040 OS << " }\n\n";
1041
1042 // Classify user defined operands.
1043 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1044 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001045 ClassInfo &CI = **it;
1046
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001047 if (!CI.isUserClass())
1048 continue;
1049
1050 OS << " // '" << CI.ClassName << "' class";
1051 if (!CI.SuperClasses.empty()) {
1052 OS << ", subclass of ";
1053 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1054 if (i) OS << ", ";
1055 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1056 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar06d5cb62009-08-09 07:20:21 +00001057 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001058 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001059 OS << "\n";
1060
1061 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1062
1063 // Validate subclass relationships.
1064 if (!CI.SuperClasses.empty()) {
1065 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1066 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1067 << "() && \"Invalid class relationship!\");\n";
1068 }
1069
1070 OS << " return " << CI.Name << ";\n";
1071 OS << " }\n\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001072 }
1073 OS << " return InvalidMatchClass;\n";
1074 OS << "}\n\n";
1075}
1076
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001077/// EmitIsSubclass - Emit the subclass predicate function.
1078static void EmitIsSubclass(CodeGenTarget &Target,
1079 std::vector<ClassInfo*> &Infos,
1080 raw_ostream &OS) {
1081 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1082 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1083 OS << " if (A == B)\n";
1084 OS << " return true;\n\n";
1085
1086 OS << " switch (A) {\n";
1087 OS << " default:\n";
1088 OS << " return false;\n";
1089 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1090 ie = Infos.end(); it != ie; ++it) {
1091 ClassInfo &A = **it;
1092
1093 if (A.Kind != ClassInfo::Token) {
1094 std::vector<StringRef> SuperClasses;
1095 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1096 ie = Infos.end(); it != ie; ++it) {
1097 ClassInfo &B = **it;
1098
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001099 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001100 SuperClasses.push_back(B.Name);
1101 }
1102
1103 if (SuperClasses.empty())
1104 continue;
1105
1106 OS << "\n case " << A.Name << ":\n";
1107
1108 if (SuperClasses.size() == 1) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001109 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001110 continue;
1111 }
1112
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001113 OS << " switch (B) {\n";
1114 OS << " default: return false;\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001115 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001116 OS << " case " << SuperClasses[i] << ": return true;\n";
1117 OS << " }\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001118 }
1119 }
1120 OS << " }\n";
1121 OS << "}\n\n";
1122}
1123
Chris Lattner042926f2009-08-08 20:02:57 +00001124typedef std::pair<std::string, std::string> StringPair;
1125
1126/// FindFirstNonCommonLetter - Find the first character in the keys of the
1127/// string pairs that is not shared across the whole set of strings. All
1128/// strings are assumed to have the same length.
1129static unsigned
1130FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1131 assert(!Matches.empty());
1132 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1133 // Check to see if letter i is the same across the set.
1134 char Letter = Matches[0]->first[i];
1135
1136 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1137 if (Matches[str]->first[i] != Letter)
1138 return i;
1139 }
1140
1141 return Matches[0]->first.size();
1142}
1143
1144/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1145/// same length and whose characters leading up to CharNo are the same, emit
1146/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001147///
1148/// \return - True if control can leave the emitted code fragment.
1149static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +00001150 const std::vector<const StringPair*> &Matches,
1151 unsigned CharNo, unsigned IndentCount,
1152 raw_ostream &OS) {
1153 assert(!Matches.empty() && "Must have at least one string to match!");
1154 std::string Indent(IndentCount*2+4, ' ');
1155
1156 // If we have verified that the entire string matches, we're done: output the
1157 // matching code.
1158 if (CharNo == Matches[0]->first.size()) {
1159 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1160
1161 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1162 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1163 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001164 return false;
Chris Lattner042926f2009-08-08 20:02:57 +00001165 }
1166
1167 // Bucket the matches by the character we are comparing.
1168 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1169
1170 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1171 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1172
1173
1174 // If we have exactly one bucket to match, see how many characters are common
1175 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +00001176 if (MatchesByLetter.size() == 1) {
1177 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1178 unsigned NumChars = FirstNonCommonLetter-CharNo;
1179
Daniel Dunbar7906a642009-08-08 22:57:25 +00001180 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +00001181 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001182 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +00001183 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001184 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1185 << Matches[0]->first[CharNo] << "')\n";
1186 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001187 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001188 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +00001189 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001190 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1191 << NumChars << ") != \"";
1192 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +00001193 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001194 }
1195
Daniel Dunbar7906a642009-08-08 22:57:25 +00001196 return EmitStringMatcherForChar(StrVariableName, Matches,
1197 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001198 }
1199
1200 // Otherwise, we have multiple possible things, emit a switch on the
1201 // character.
1202 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1203 OS << Indent << "default: break;\n";
1204
1205 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1206 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1207 // TODO: escape hard stuff (like \n) if we ever care about it.
1208 OS << Indent << "case '" << LI->first << "':\t // "
1209 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001210 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1211 IndentCount+1, OS))
1212 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001213 }
1214
1215 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001216 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001217}
1218
1219
1220/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001221/// match, output a simple switch tree to classify the input string.
1222///
1223/// If a match is found, the code in Vals[i].second is executed; control must
1224/// not exit this code fragment. If nothing matches, execution falls through.
1225///
1226/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001227static void EmitStringMatcher(const std::string &StrVariableName,
1228 const std::vector<StringPair> &Matches,
1229 raw_ostream &OS) {
1230 // First level categorization: group strings by length.
1231 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1232
1233 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1234 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1235
1236 // Output a switch statement on length and categorize the elements within each
1237 // bin.
1238 OS << " switch (" << StrVariableName << ".size()) {\n";
1239 OS << " default: break;\n";
1240
Chris Lattner042926f2009-08-08 20:02:57 +00001241 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1242 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1243 OS << " case " << LI->first << ":\t // " << LI->second.size()
1244 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001245 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1246 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001247 }
1248
Chris Lattner042926f2009-08-08 20:02:57 +00001249 OS << " }\n";
1250}
1251
1252
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001253/// EmitMatchTokenString - Emit the function to match a token string to the
1254/// appropriate match class value.
1255static void EmitMatchTokenString(CodeGenTarget &Target,
1256 std::vector<ClassInfo*> &Infos,
1257 raw_ostream &OS) {
1258 // Construct the match list.
1259 std::vector<StringPair> Matches;
1260 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1261 ie = Infos.end(); it != ie; ++it) {
1262 ClassInfo &CI = **it;
1263
1264 if (CI.Kind == ClassInfo::Token)
1265 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1266 }
1267
1268 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1269
1270 EmitStringMatcher("Name", Matches, OS);
1271
1272 OS << " return InvalidMatchClass;\n";
1273 OS << "}\n\n";
1274}
Chris Lattner042926f2009-08-08 20:02:57 +00001275
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001276/// EmitMatchRegisterName - Emit the function to match a string to the target
1277/// specific register enum.
1278static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1279 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001280 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001281 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001282 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1283 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001284 if (Reg.TheDef->getValueAsString("AsmName").empty())
1285 continue;
1286
Chris Lattner042926f2009-08-08 20:02:57 +00001287 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001288 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001289 }
Chris Lattner042926f2009-08-08 20:02:57 +00001290
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001291 OS << "unsigned " << Target.getName()
1292 << AsmParser->getValueAsString("AsmParserClassName")
1293 << "::MatchRegisterName(const StringRef &Name) {\n";
1294
Chris Lattner042926f2009-08-08 20:02:57 +00001295 EmitStringMatcher("Name", Matches, OS);
1296
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001297 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001298 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001299}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001300
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001301void AsmMatcherEmitter::run(raw_ostream &OS) {
1302 CodeGenTarget Target;
1303 Record *AsmParser = Target.getAsmParser();
1304 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1305
1306 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1307
1308 // Emit the function to match a register name to number.
1309 EmitMatchRegisterName(Target, AsmParser, OS);
1310
Daniel Dunbar378bee92009-08-08 07:50:56 +00001311 // Compute the information on the instructions to match.
1312 AsmMatcherInfo Info;
1313 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001314
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001315 // Sort the instruction table using the partial order on classes.
1316 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1317 less_ptr<InstructionInfo>());
1318
Daniel Dunbarce82b992009-08-08 05:24:34 +00001319 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001320 for (std::vector<InstructionInfo*>::iterator
1321 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1322 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001323 (*it)->dump();
1324 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001325
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001326 // Check for ambiguous instructions.
1327 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001328 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1329 for (unsigned j = i + 1; j != e; ++j) {
1330 InstructionInfo &A = *Info.Instructions[i];
1331 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001332
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001333 if (A.CouldMatchAmiguouslyWith(B)) {
1334 DEBUG_WITH_TYPE("ambiguous_instrs", {
1335 errs() << "warning: ambiguous instruction match:\n";
1336 A.dump();
1337 errs() << "\nis incomparable with:\n";
1338 B.dump();
1339 errs() << "\n\n";
1340 });
1341 ++NumAmbiguous;
1342 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001343 }
1344 }
1345 if (NumAmbiguous)
1346 DEBUG_WITH_TYPE("ambiguous_instrs", {
1347 errs() << "warning: " << NumAmbiguous
1348 << " ambiguous instructions!\n";
1349 });
1350
1351 // Generate the unified function to convert operands into an MCInst.
1352 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001353
Daniel Dunbar378bee92009-08-08 07:50:56 +00001354 // Emit the enumeration for classes which participate in matching.
1355 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001356
Daniel Dunbar378bee92009-08-08 07:50:56 +00001357 // Emit the routine to match token strings to their match class.
1358 EmitMatchTokenString(Target, Info.Classes, OS);
1359
1360 // Emit the routine to classify an operand.
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001361 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001362
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001363 // Emit the subclass predicate routine.
1364 EmitIsSubclass(Target, Info.Classes, OS);
1365
Daniel Dunbar378bee92009-08-08 07:50:56 +00001366 // Finally, build the match function.
1367
1368 size_t MaxNumOperands = 0;
1369 for (std::vector<InstructionInfo*>::const_iterator it =
1370 Info.Instructions.begin(), ie = Info.Instructions.end();
1371 it != ie; ++it)
1372 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1373
Daniel Dunbara54716c2009-07-31 02:32:59 +00001374 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001375 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001376 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1377 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001378
Daniel Dunbar378bee92009-08-08 07:50:56 +00001379 // Emit the static match table; unused classes get initalized to 0 which is
1380 // guaranteed to be InvalidMatchClass.
1381 //
1382 // FIXME: We can reduce the size of this table very easily. First, we change
1383 // it so that store the kinds in separate bit-fields for each index, which
1384 // only needs to be the max width used for classes at that index (we also need
1385 // to reject based on this during classification). If we then make sure to
1386 // order the match kinds appropriately (putting mnemonics last), then we
1387 // should only end up using a few bits for each class, especially the ones
1388 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001389 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001390 OS << " unsigned Opcode;\n";
1391 OS << " ConversionKind ConvertFn;\n";
1392 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1393 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1394
1395 for (std::vector<InstructionInfo*>::const_iterator it =
1396 Info.Instructions.begin(), ie = Info.Instructions.end();
1397 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001398 InstructionInfo &II = **it;
1399
Daniel Dunbar378bee92009-08-08 07:50:56 +00001400 OS << " { " << Target.getName() << "::" << II.InstrName
1401 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001402 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1403 InstructionInfo::Operand &Op = II.Operands[i];
1404
Daniel Dunbar378bee92009-08-08 07:50:56 +00001405 if (i) OS << ", ";
1406 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001407 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001408 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001409 }
1410
Daniel Dunbar378bee92009-08-08 07:50:56 +00001411 OS << " };\n\n";
1412
1413 // Emit code to compute the class list for this operand vector.
1414 OS << " // Eliminate obvious mismatches.\n";
1415 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1416 OS << " return true;\n\n";
1417
1418 OS << " // Compute the class list for this operand vector.\n";
1419 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1420 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1421 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1422
1423 OS << " // Check for invalid operands before matching.\n";
1424 OS << " if (Classes[i] == InvalidMatchClass)\n";
1425 OS << " return true;\n";
1426 OS << " }\n\n";
1427
1428 OS << " // Mark unused classes.\n";
1429 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1430 << "i != e; ++i)\n";
1431 OS << " Classes[i] = InvalidMatchClass;\n\n";
1432
1433 // Emit code to search the table.
1434 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001435 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001436 << "*ie = MatchTable + " << Info.Instructions.size()
1437 << "; it != ie; ++it) {\n";
1438 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001439 OS << " if (!IsSubclass(Classes["
1440 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001441 OS << " continue;\n";
1442 }
1443 OS << "\n";
1444 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1445 << "it->Opcode, Operands);\n";
1446 OS << " }\n\n";
1447
Daniel Dunbara54716c2009-07-31 02:32:59 +00001448 OS << " return true;\n";
1449 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001450}