blob: 5b5dd2bef0b2e913cba2a2bfed05e25ac5c41d9f [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.
Chris Lattner8b382002010-02-09 00:34:28 +0000143static void TokenizeAsmString(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
Chris Lattner8b382002010-02-09 00:34:28 +0000210static bool IsAssemblerInstruction(StringRef Name,
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000211 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
Daniel Dunbar24a7ad02010-01-23 00:26:16 +0000468 // Otherwise, make sure the ordering of the two instructions is unambiguous
469 // by checking that either (a) a token or operand kind discriminates them,
470 // or (b) the ordering among equivalent kinds is consistent.
471
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000472 // Tokens and operand kinds are unambiguous (assuming a correct target
473 // specific parser).
474 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
475 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
476 Operands[i].Class->Kind == ClassInfo::Token)
477 if (*Operands[i].Class < *RHS.Operands[i].Class ||
478 *RHS.Operands[i].Class < *Operands[i].Class)
479 return false;
480
481 // Otherwise, this operand could commute if all operands are equivalent, or
482 // there is a pair of operands that compare less than and a pair that
483 // compare greater than.
484 bool HasLT = false, HasGT = false;
485 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
486 if (*Operands[i].Class < *RHS.Operands[i].Class)
487 HasLT = true;
488 if (*RHS.Operands[i].Class < *Operands[i].Class)
489 HasGT = true;
490 }
491
492 return !(HasLT ^ HasGT);
493 }
494
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000495public:
496 void dump();
497};
498
Daniel Dunbar378bee92009-08-08 07:50:56 +0000499class AsmMatcherInfo {
500public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000501 /// The tablegen AsmParser record.
502 Record *AsmParser;
503
504 /// The AsmParser "CommentDelimiter" value.
505 std::string CommentDelimiter;
506
507 /// The AsmParser "RegisterPrefix" value.
508 std::string RegisterPrefix;
509
Daniel Dunbar378bee92009-08-08 07:50:56 +0000510 /// The classes which are needed for matching.
511 std::vector<ClassInfo*> Classes;
512
513 /// The information on the instruction to match.
514 std::vector<InstructionInfo*> Instructions;
515
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000516 /// Map of Register records to their class information.
517 std::map<Record*, ClassInfo*> RegisterClasses;
518
Daniel Dunbar378bee92009-08-08 07:50:56 +0000519private:
520 /// Map of token to class information which has already been constructed.
521 std::map<std::string, ClassInfo*> TokenClasses;
522
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000523 /// Map of RegisterClass records to their class information.
524 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000525
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000526 /// Map of AsmOperandClass records to their class information.
527 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000528
Daniel Dunbar378bee92009-08-08 07:50:56 +0000529private:
530 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner8b382002010-02-09 00:34:28 +0000531 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar378bee92009-08-08 07:50:56 +0000532
533 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattner8b382002010-02-09 00:34:28 +0000534 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbar378bee92009-08-08 07:50:56 +0000535 const CodeGenInstruction::OperandInfo &OI);
536
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000537 /// BuildRegisterClasses - Build the ClassInfo* instances for register
538 /// classes.
Daniel Dunbar35303e32009-08-11 23:23:44 +0000539 void BuildRegisterClasses(CodeGenTarget &Target,
540 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000541
542 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
543 /// operand classes.
544 void BuildOperandClasses(CodeGenTarget &Target);
545
Daniel Dunbar378bee92009-08-08 07:50:56 +0000546public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000547 AsmMatcherInfo(Record *_AsmParser);
548
Daniel Dunbar378bee92009-08-08 07:50:56 +0000549 /// BuildInfo - Construct the various tables used during matching.
550 void BuildInfo(CodeGenTarget &Target);
551};
552
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000553}
554
555void InstructionInfo::dump() {
556 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
557 << ", tokens:[";
558 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
559 errs() << Tokens[i];
560 if (i + 1 != e)
561 errs() << ", ";
562 }
563 errs() << "]\n";
564
565 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
566 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000567 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000568 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000569 errs() << '\"' << Tokens[i] << "\"\n";
570 continue;
571 }
572
Daniel Dunbar35303e32009-08-11 23:23:44 +0000573 if (!Op.OperandInfo) {
574 errs() << "(singleton register)\n";
575 continue;
576 }
577
Benjamin Kramer19afc502009-08-08 10:06:30 +0000578 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000579 errs() << OI.Name << " " << OI.Rec->getName()
580 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
581 }
582}
583
Chris Lattner8b382002010-02-09 00:34:28 +0000584static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000585 std::string Res;
586
587 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
588 switch (*it) {
589 case '*': Res += "_STAR_"; break;
590 case '%': Res += "_PCT_"; break;
591 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000592
Daniel Dunbar378bee92009-08-08 07:50:56 +0000593 default:
594 if (isalnum(*it)) {
595 Res += *it;
596 } else {
597 Res += "_" + utostr((unsigned) *it) + "_";
598 }
599 }
600 }
601
602 return Res;
603}
604
Daniel Dunbar35303e32009-08-11 23:23:44 +0000605/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattner8b382002010-02-09 00:34:28 +0000606static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000607 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
608 const CodeGenRegister &Reg = Target.getRegisters()[i];
609 if (Name == Reg.TheDef->getValueAsString("AsmName"))
610 return Reg.TheDef;
611 }
612
613 return 0;
614}
615
Chris Lattner8b382002010-02-09 00:34:28 +0000616ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000617 ClassInfo *&Entry = TokenClasses[Token];
618
619 if (!Entry) {
620 Entry = new ClassInfo();
621 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000622 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000623 Entry->Name = "MCK_" + getEnumNameForToken(Token);
624 Entry->ValueName = Token;
625 Entry->PredicateMethod = "<invalid>";
626 Entry->RenderMethod = "<invalid>";
627 Classes.push_back(Entry);
628 }
629
630 return Entry;
631}
632
633ClassInfo *
Chris Lattner8b382002010-02-09 00:34:28 +0000634AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbar378bee92009-08-08 07:50:56 +0000635 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000636 if (OI.Rec->isSubClassOf("RegisterClass")) {
637 ClassInfo *CI = RegisterClassClasses[OI.Rec];
638
639 if (!CI) {
640 PrintError(OI.Rec->getLoc(), "register class has no class info!");
641 throw std::string("ERROR: Missing register class!");
642 }
643
644 return CI;
645 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000646
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000647 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
648 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
649 ClassInfo *CI = AsmOperandClasses[MatchClass];
650
651 if (!CI) {
652 PrintError(OI.Rec->getLoc(), "operand has no match class!");
653 throw std::string("ERROR: Missing match class!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000654 }
655
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000656 return CI;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000657}
658
Daniel Dunbar35303e32009-08-11 23:23:44 +0000659void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
660 std::set<std::string>
661 &SingletonRegisterNames) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000662 std::vector<CodeGenRegisterClass> RegisterClasses;
663 std::vector<CodeGenRegister> Registers;
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000664
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000665 RegisterClasses = Target.getRegisterClasses();
666 Registers = Target.getRegisters();
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000667
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000668 // The register sets used for matching.
669 std::set< std::set<Record*> > RegisterSets;
670
671 // Gather the defined sets.
672 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
673 ie = RegisterClasses.end(); it != ie; ++it)
674 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
675 it->Elements.end()));
Daniel Dunbar35303e32009-08-11 23:23:44 +0000676
677 // Add any required singleton sets.
678 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
679 ie = SingletonRegisterNames.end(); it != ie; ++it)
680 if (Record *Rec = getRegisterRecord(Target, *it))
681 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
682
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000683 // Introduce derived sets where necessary (when a register does not determine
684 // a unique register set class), and build the mapping of registers to the set
685 // they should classify to.
686 std::map<Record*, std::set<Record*> > RegisterMap;
687 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
688 ie = Registers.end(); it != ie; ++it) {
689 CodeGenRegister &CGR = *it;
690 // Compute the intersection of all sets containing this register.
691 std::set<Record*> ContainingSet;
692
693 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
694 ie = RegisterSets.end(); it != ie; ++it) {
695 if (!it->count(CGR.TheDef))
696 continue;
697
698 if (ContainingSet.empty()) {
699 ContainingSet = *it;
700 } else {
701 std::set<Record*> Tmp;
702 std::swap(Tmp, ContainingSet);
703 std::insert_iterator< std::set<Record*> > II(ContainingSet,
704 ContainingSet.begin());
705 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
706 II);
707 }
708 }
709
710 if (!ContainingSet.empty()) {
711 RegisterSets.insert(ContainingSet);
712 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
713 }
714 }
715
716 // Construct the register classes.
717 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
718 unsigned Index = 0;
719 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
720 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
721 ClassInfo *CI = new ClassInfo();
722 CI->Kind = ClassInfo::RegisterClass0 + Index;
723 CI->ClassName = "Reg" + utostr(Index);
724 CI->Name = "MCK_Reg" + utostr(Index);
725 CI->ValueName = "";
726 CI->PredicateMethod = ""; // unused
727 CI->RenderMethod = "addRegOperands";
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000728 CI->Registers = *it;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000729 Classes.push_back(CI);
730 RegisterSetClasses.insert(std::make_pair(*it, CI));
731 }
732
733 // Find the superclasses; we could compute only the subgroup lattice edges,
734 // but there isn't really a point.
735 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
736 ie = RegisterSets.end(); it != ie; ++it) {
737 ClassInfo *CI = RegisterSetClasses[*it];
738 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
739 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
740 if (*it != *it2 &&
741 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
742 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
743 }
744
745 // Name the register classes which correspond to a user defined RegisterClass.
746 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
747 ie = RegisterClasses.end(); it != ie; ++it) {
748 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
749 it->Elements.end())];
750 if (CI->ValueName.empty()) {
751 CI->ClassName = it->getName();
752 CI->Name = "MCK_" + it->getName();
753 CI->ValueName = it->getName();
754 } else
755 CI->ValueName = CI->ValueName + "," + it->getName();
756
757 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
758 }
759
760 // Populate the map for individual registers.
761 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
762 ie = RegisterMap.end(); it != ie; ++it)
763 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar35303e32009-08-11 23:23:44 +0000764
765 // Name the register classes which correspond to singleton registers.
766 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
767 ie = SingletonRegisterNames.end(); it != ie; ++it) {
768 if (Record *Rec = getRegisterRecord(Target, *it)) {
769 ClassInfo *CI = this->RegisterClasses[Rec];
770 assert(CI && "Missing singleton register class info!");
771
772 if (CI->ValueName.empty()) {
773 CI->ClassName = Rec->getName();
774 CI->Name = "MCK_" + Rec->getName();
775 CI->ValueName = Rec->getName();
776 } else
777 CI->ValueName = CI->ValueName + "," + Rec->getName();
778 }
779 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000780}
781
782void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000783 std::vector<Record*> AsmOperands;
784 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarbbd99172010-01-30 01:02:37 +0000785
786 // Pre-populate AsmOperandClasses map.
787 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
788 ie = AsmOperands.end(); it != ie; ++it)
789 AsmOperandClasses[*it] = new ClassInfo();
790
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000791 unsigned Index = 0;
792 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
793 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbarbbd99172010-01-30 01:02:37 +0000794 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000795 CI->Kind = ClassInfo::UserClass0 + Index;
796
797 Init *Super = (*it)->getValueInit("SuperClass");
798 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000799 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
800 if (!SC)
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000801 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000802 else
803 CI->SuperClasses.push_back(SC);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000804 } else {
805 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000806 }
807 CI->ClassName = (*it)->getValueAsString("Name");
808 CI->Name = "MCK_" + CI->ClassName;
809 CI->ValueName = (*it)->getName();
Daniel Dunbarb3413d82009-08-10 21:00:45 +0000810
811 // Get or construct the predicate method name.
812 Init *PMName = (*it)->getValueInit("PredicateMethod");
813 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
814 CI->PredicateMethod = SI->getValue();
815 } else {
816 assert(dynamic_cast<UnsetInit*>(PMName) &&
817 "Unexpected PredicateMethod field!");
818 CI->PredicateMethod = "is" + CI->ClassName;
819 }
820
821 // Get or construct the render method name.
822 Init *RMName = (*it)->getValueInit("RenderMethod");
823 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
824 CI->RenderMethod = SI->getValue();
825 } else {
826 assert(dynamic_cast<UnsetInit*>(RMName) &&
827 "Unexpected RenderMethod field!");
828 CI->RenderMethod = "add" + CI->ClassName + "Operands";
829 }
830
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000831 AsmOperandClasses[*it] = CI;
832 Classes.push_back(CI);
833 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000834}
835
Daniel Dunbara6d04732009-08-11 20:59:47 +0000836AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
837 : AsmParser(_AsmParser),
838 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
839 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
840{
841}
842
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000843void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000844 // Parse the instructions; we need to do this first so that we can gather the
845 // singleton register classes.
846 std::set<std::string> SingletonRegisterNames;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000847 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000848 it = Target.getInstructions().begin(),
849 ie = Target.getInstructions().end();
850 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000851 const CodeGenInstruction &CGI = it->second;
852
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000853 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000854 continue;
855
856 OwningPtr<InstructionInfo> II(new InstructionInfo);
857
858 II->InstrName = it->first;
859 II->Instr = &it->second;
860 II->AsmString = FlattenVariants(CGI.AsmString, 0);
861
Daniel Dunbara6d04732009-08-11 20:59:47 +0000862 // Remove comments from the asm string.
863 if (!CommentDelimiter.empty()) {
864 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
865 if (Idx != StringRef::npos)
866 II->AsmString = II->AsmString.substr(0, Idx);
867 }
868
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000869 TokenizeAsmString(II->AsmString, II->Tokens);
870
871 // Ignore instructions which shouldn't be matched.
872 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
873 continue;
874
Daniel Dunbar35303e32009-08-11 23:23:44 +0000875 // Collect singleton registers, if used.
876 if (!RegisterPrefix.empty()) {
877 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
878 if (II->Tokens[i].startswith(RegisterPrefix)) {
879 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
880 Record *Rec = getRegisterRecord(Target, RegName);
881
882 if (!Rec) {
883 std::string Err = "unable to find register for '" + RegName.str() +
884 "' (which matches register prefix)";
885 throw TGError(CGI.TheDef->getLoc(), Err);
886 }
887
888 SingletonRegisterNames.insert(RegName);
889 }
890 }
891 }
892
893 Instructions.push_back(II.take());
894 }
895
896 // Build info for the register classes.
897 BuildRegisterClasses(Target, SingletonRegisterNames);
898
899 // Build info for the user defined assembly operand classes.
900 BuildOperandClasses(Target);
901
902 // Build the instruction information.
903 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
904 ie = Instructions.end(); it != ie; ++it) {
905 InstructionInfo *II = *it;
906
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000907 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
908 StringRef Token = II->Tokens[i];
909
Daniel Dunbar35303e32009-08-11 23:23:44 +0000910 // Check for singleton registers.
911 if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
912 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
913 InstructionInfo::Operand Op;
914 Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
915 Op.OperandInfo = 0;
916 assert(Op.Class && Op.Class->Registers.size() == 1 &&
917 "Unexpected class for singleton register");
918 II->Operands.push_back(Op);
919 continue;
920 }
921
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000922 // Check for simple tokens.
923 if (Token[0] != '$') {
924 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000925 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000926 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000927 II->Operands.push_back(Op);
928 continue;
929 }
930
931 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000932 StringRef OperandName;
933 if (Token[1] == '{')
934 OperandName = Token.substr(2, Token.size() - 3);
935 else
936 OperandName = Token.substr(1);
937
938 // Map this token to an operand. FIXME: Move elsewhere.
939 unsigned Idx;
940 try {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000941 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000942 } catch(...) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000943 throw std::string("error: unable to find operand: '" +
944 OperandName.str() + "'");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000945 }
946
Daniel Dunbar17fae482010-02-10 08:15:48 +0000947 // FIXME: This is annoying, the named operand may be tied (e.g.,
948 // XCHG8rm). What we want is the untied operand, which we now have to
949 // grovel for. Only worry about this for single entry operands, we have to
950 // clean this up anyway.
951 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
952 if (OI->Constraints[0].isTied()) {
953 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
954
955 // The tied operand index is an MIOperand index, find the operand that
956 // contains it.
957 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
958 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
959 OI = &II->Instr->OperandList[i];
960 break;
961 }
962 }
963
964 assert(OI && "Unable to find tied operand target!");
965 }
966
Daniel Dunbar378bee92009-08-08 07:50:56 +0000967 InstructionInfo::Operand Op;
Daniel Dunbar17fae482010-02-10 08:15:48 +0000968 Op.Class = getOperandClass(Token, *OI);
969 Op.OperandInfo = OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000970 II->Operands.push_back(Op);
971 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000972 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000973
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000974 // Reorder classes so that classes preceed super classes.
975 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000976}
977
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000978static void EmitConvertToMCInst(CodeGenTarget &Target,
979 std::vector<InstructionInfo*> &Infos,
980 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000981 // Write the convert function to a separate stream, so we can drop it after
982 // the enum.
983 std::string ConvertFnBody;
984 raw_string_ostream CvtOS(ConvertFnBody);
985
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000986 // Function we have already generated.
987 std::set<std::string> GeneratedFns;
988
Daniel Dunbarce82b992009-08-08 05:24:34 +0000989 // Start the unified conversion function.
990
991 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
992 << "unsigned Opcode,\n"
Chris Lattner22f480d2010-01-14 22:21:20 +0000993 << " const SmallVectorImpl<MCParsedAsmOperand*"
994 << "> &Operands) {\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000995 CvtOS << " Inst.setOpcode(Opcode);\n";
996 CvtOS << " switch (Kind) {\n";
997 CvtOS << " default:\n";
998
999 // Start the enum, which we will generate inline.
1000
1001 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +00001002 OS << "enum ConversionKind {\n";
1003
Chris Lattner22f480d2010-01-14 22:21:20 +00001004 // TargetOperandClass - This is the target's operand class, like X86Operand.
1005 std::string TargetOperandClass = Target.getName() + "Operand";
1006
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001007 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1008 ie = Infos.end(); it != ie; ++it) {
1009 InstructionInfo &II = **it;
1010
1011 // Order the (class) operands by the order to convert them into an MCInst.
1012 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1013 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1014 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +00001015 if (Op.OperandInfo)
1016 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001017 }
Daniel Dunbar17fae482010-02-10 08:15:48 +00001018
1019 // Find any tied operands.
1020 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1021 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1022 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1023 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1024 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1025 if (CI.isTied())
1026 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1027 CI.getTiedOperand()));
1028 }
1029 }
1030
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001031 std::sort(MIOperandList.begin(), MIOperandList.end());
1032
1033 // Compute the total number of operands.
1034 unsigned NumMIOperands = 0;
1035 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1036 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1037 NumMIOperands = std::max(NumMIOperands,
1038 OI.MIOperandNo + OI.MINumOperands);
1039 }
1040
1041 // Build the conversion function signature.
1042 std::string Signature = "Convert";
1043 unsigned CurIndex = 0;
1044 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1045 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +00001046 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001047 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001048
1049 // Skip operands which weren't matched by anything, this occurs when the
1050 // .td file encodes "implicit" operands as explicit ones.
1051 //
1052 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbar17fae482010-02-10 08:15:48 +00001053 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1054 // See if this is a tied operand.
1055 unsigned i, e = TiedOperands.size();
1056 for (i = 0; i != e; ++i)
1057 if (CurIndex == TiedOperands[i].first)
1058 break;
1059 if (i == e)
1060 Signature += "__Imp";
1061 else
1062 Signature += "__Tie" + utostr(TiedOperands[i].second);
1063 }
1064
1065 Signature += "__";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001066
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001067 // Registers are always converted the same, don't duplicate the conversion
1068 // function based on them.
1069 //
1070 // FIXME: We could generalize this based on the render method, if it
1071 // mattered.
1072 if (Op.Class->isRegisterClass())
1073 Signature += "Reg";
1074 else
1075 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +00001076 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +00001077 Signature += "_" + utostr(MIOperandList[i].second);
1078
Benjamin Kramer19afc502009-08-08 10:06:30 +00001079 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001080 }
1081
1082 // Add any trailing implicit operands.
1083 for (; CurIndex != NumMIOperands; ++CurIndex)
1084 Signature += "Imp";
1085
Daniel Dunbarce82b992009-08-08 05:24:34 +00001086 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001087
Daniel Dunbarce82b992009-08-08 05:24:34 +00001088 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001089 if (!GeneratedFns.insert(Signature).second)
1090 continue;
1091
1092 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +00001093
1094 // Add to the enum list.
1095 OS << " " << Signature << ",\n";
1096
1097 // And to the convert function.
1098 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001099 CurIndex = 0;
1100 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1101 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1102
1103 // Add the implicit operands.
Daniel Dunbar17fae482010-02-10 08:15:48 +00001104 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1105 // See if this is a tied operand.
1106 unsigned i, e = TiedOperands.size();
1107 for (i = 0; i != e; ++i)
1108 if (CurIndex == TiedOperands[i].first)
1109 break;
1110
1111 if (i == e) {
1112 // If not, this is some implicit operand. Just assume it is a register
1113 // for now.
1114 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1115 } else {
1116 // Copy the tied operand.
1117 assert(TiedOperands[i].first > TiedOperands[i].second &&
1118 "Tied operand preceeds its target!");
1119 CvtOS << " Inst.addOperand(Inst.getOperand("
1120 << TiedOperands[i].second << "));\n";
1121 }
1122 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001123
Chris Lattner22f480d2010-01-14 22:21:20 +00001124 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1125 << MIOperandList[i].second
1126 << "])->" << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +00001127 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1128 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001129 }
1130
1131 // And add trailing implicit operands.
1132 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +00001133 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1134 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001135 }
Daniel Dunbarce82b992009-08-08 05:24:34 +00001136
1137 // Finish the convert function.
1138
1139 CvtOS << " }\n";
1140 CvtOS << " return false;\n";
1141 CvtOS << "}\n\n";
1142
1143 // Finish the enum, and drop the convert function after it.
1144
1145 OS << " NumConversionVariants\n";
1146 OS << "};\n\n";
1147
Daniel Dunbarce82b992009-08-08 05:24:34 +00001148 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +00001149}
1150
Daniel Dunbar378bee92009-08-08 07:50:56 +00001151/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1152static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1153 std::vector<ClassInfo*> &Infos,
1154 raw_ostream &OS) {
1155 OS << "namespace {\n\n";
1156
1157 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1158 << "/// instruction matching.\n";
1159 OS << "enum MatchClassKind {\n";
1160 OS << " InvalidMatchClass = 0,\n";
1161 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1162 ie = Infos.end(); it != ie; ++it) {
1163 ClassInfo &CI = **it;
1164 OS << " " << CI.Name << ", // ";
1165 if (CI.Kind == ClassInfo::Token) {
1166 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001167 } else if (CI.isRegisterClass()) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001168 if (!CI.ValueName.empty())
1169 OS << "register class '" << CI.ValueName << "'\n";
1170 else
1171 OS << "derived register class\n";
1172 } else {
1173 OS << "user defined class '" << CI.ValueName << "'\n";
1174 }
1175 }
1176 OS << " NumMatchClassKinds\n";
1177 OS << "};\n\n";
1178
1179 OS << "}\n\n";
1180}
1181
Daniel Dunbar378bee92009-08-08 07:50:56 +00001182/// EmitClassifyOperand - Emit the function to classify an operand.
1183static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001184 AsmMatcherInfo &Info,
Daniel Dunbar378bee92009-08-08 07:50:56 +00001185 raw_ostream &OS) {
Chris Lattner22f480d2010-01-14 22:21:20 +00001186 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1187 << " " << Target.getName() << "Operand &Operand = *("
1188 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001189
1190 // Classify tokens.
Daniel Dunbar378bee92009-08-08 07:50:56 +00001191 OS << " if (Operand.isToken())\n";
1192 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001193
1194 // Classify registers.
1195 //
1196 // FIXME: Don't hardcode isReg, getReg.
1197 OS << " if (Operand.isReg()) {\n";
1198 OS << " switch (Operand.getReg()) {\n";
1199 OS << " default: return InvalidMatchClass;\n";
1200 for (std::map<Record*, ClassInfo*>::iterator
1201 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1202 it != ie; ++it)
1203 OS << " case " << Target.getName() << "::"
1204 << it->first->getName() << ": return " << it->second->Name << ";\n";
1205 OS << " }\n";
1206 OS << " }\n\n";
1207
1208 // Classify user defined operands.
1209 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1210 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001211 ClassInfo &CI = **it;
1212
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001213 if (!CI.isUserClass())
1214 continue;
1215
1216 OS << " // '" << CI.ClassName << "' class";
1217 if (!CI.SuperClasses.empty()) {
1218 OS << ", subclass of ";
1219 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1220 if (i) OS << ", ";
1221 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1222 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar06d5cb62009-08-09 07:20:21 +00001223 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001224 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001225 OS << "\n";
1226
1227 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1228
1229 // Validate subclass relationships.
1230 if (!CI.SuperClasses.empty()) {
1231 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1232 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1233 << "() && \"Invalid class relationship!\");\n";
1234 }
1235
1236 OS << " return " << CI.Name << ";\n";
1237 OS << " }\n\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001238 }
1239 OS << " return InvalidMatchClass;\n";
1240 OS << "}\n\n";
1241}
1242
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001243/// EmitIsSubclass - Emit the subclass predicate function.
1244static void EmitIsSubclass(CodeGenTarget &Target,
1245 std::vector<ClassInfo*> &Infos,
1246 raw_ostream &OS) {
1247 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1248 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1249 OS << " if (A == B)\n";
1250 OS << " return true;\n\n";
1251
1252 OS << " switch (A) {\n";
1253 OS << " default:\n";
1254 OS << " return false;\n";
1255 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1256 ie = Infos.end(); it != ie; ++it) {
1257 ClassInfo &A = **it;
1258
1259 if (A.Kind != ClassInfo::Token) {
1260 std::vector<StringRef> SuperClasses;
1261 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1262 ie = Infos.end(); it != ie; ++it) {
1263 ClassInfo &B = **it;
1264
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001265 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001266 SuperClasses.push_back(B.Name);
1267 }
1268
1269 if (SuperClasses.empty())
1270 continue;
1271
1272 OS << "\n case " << A.Name << ":\n";
1273
1274 if (SuperClasses.size() == 1) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001275 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001276 continue;
1277 }
1278
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001279 OS << " switch (B) {\n";
1280 OS << " default: return false;\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001281 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001282 OS << " case " << SuperClasses[i] << ": return true;\n";
1283 OS << " }\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001284 }
1285 }
1286 OS << " }\n";
1287 OS << "}\n\n";
1288}
1289
Chris Lattner042926f2009-08-08 20:02:57 +00001290typedef std::pair<std::string, std::string> StringPair;
1291
1292/// FindFirstNonCommonLetter - Find the first character in the keys of the
1293/// string pairs that is not shared across the whole set of strings. All
1294/// strings are assumed to have the same length.
1295static unsigned
1296FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1297 assert(!Matches.empty());
1298 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1299 // Check to see if letter i is the same across the set.
1300 char Letter = Matches[0]->first[i];
1301
1302 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1303 if (Matches[str]->first[i] != Letter)
1304 return i;
1305 }
1306
1307 return Matches[0]->first.size();
1308}
1309
1310/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1311/// same length and whose characters leading up to CharNo are the same, emit
1312/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001313///
1314/// \return - True if control can leave the emitted code fragment.
1315static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +00001316 const std::vector<const StringPair*> &Matches,
1317 unsigned CharNo, unsigned IndentCount,
1318 raw_ostream &OS) {
1319 assert(!Matches.empty() && "Must have at least one string to match!");
1320 std::string Indent(IndentCount*2+4, ' ');
1321
1322 // If we have verified that the entire string matches, we're done: output the
1323 // matching code.
1324 if (CharNo == Matches[0]->first.size()) {
1325 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1326
1327 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1328 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1329 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001330 return false;
Chris Lattner042926f2009-08-08 20:02:57 +00001331 }
1332
1333 // Bucket the matches by the character we are comparing.
1334 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1335
1336 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1337 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1338
1339
1340 // If we have exactly one bucket to match, see how many characters are common
1341 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +00001342 if (MatchesByLetter.size() == 1) {
1343 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1344 unsigned NumChars = FirstNonCommonLetter-CharNo;
1345
Daniel Dunbar7906a642009-08-08 22:57:25 +00001346 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +00001347 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001348 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +00001349 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001350 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1351 << Matches[0]->first[CharNo] << "')\n";
1352 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001353 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001354 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +00001355 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001356 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1357 << NumChars << ") != \"";
1358 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +00001359 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001360 }
1361
Daniel Dunbar7906a642009-08-08 22:57:25 +00001362 return EmitStringMatcherForChar(StrVariableName, Matches,
1363 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001364 }
1365
1366 // Otherwise, we have multiple possible things, emit a switch on the
1367 // character.
1368 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1369 OS << Indent << "default: break;\n";
1370
1371 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1372 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1373 // TODO: escape hard stuff (like \n) if we ever care about it.
1374 OS << Indent << "case '" << LI->first << "':\t // "
1375 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001376 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1377 IndentCount+1, OS))
1378 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001379 }
1380
1381 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001382 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001383}
1384
1385
1386/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001387/// match, output a simple switch tree to classify the input string.
1388///
1389/// If a match is found, the code in Vals[i].second is executed; control must
1390/// not exit this code fragment. If nothing matches, execution falls through.
1391///
1392/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001393static void EmitStringMatcher(const std::string &StrVariableName,
1394 const std::vector<StringPair> &Matches,
1395 raw_ostream &OS) {
1396 // First level categorization: group strings by length.
1397 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1398
1399 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1400 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1401
1402 // Output a switch statement on length and categorize the elements within each
1403 // bin.
1404 OS << " switch (" << StrVariableName << ".size()) {\n";
1405 OS << " default: break;\n";
1406
Chris Lattner042926f2009-08-08 20:02:57 +00001407 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1408 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1409 OS << " case " << LI->first << ":\t // " << LI->second.size()
1410 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001411 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1412 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001413 }
1414
Chris Lattner042926f2009-08-08 20:02:57 +00001415 OS << " }\n";
1416}
1417
1418
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001419/// EmitMatchTokenString - Emit the function to match a token string to the
1420/// appropriate match class value.
1421static void EmitMatchTokenString(CodeGenTarget &Target,
1422 std::vector<ClassInfo*> &Infos,
1423 raw_ostream &OS) {
1424 // Construct the match list.
1425 std::vector<StringPair> Matches;
1426 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1427 ie = Infos.end(); it != ie; ++it) {
1428 ClassInfo &CI = **it;
1429
1430 if (CI.Kind == ClassInfo::Token)
1431 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1432 }
1433
Chris Lattner8b382002010-02-09 00:34:28 +00001434 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001435
1436 EmitStringMatcher("Name", Matches, OS);
1437
1438 OS << " return InvalidMatchClass;\n";
1439 OS << "}\n\n";
1440}
Chris Lattner042926f2009-08-08 20:02:57 +00001441
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001442/// EmitMatchRegisterName - Emit the function to match a string to the target
1443/// specific register enum.
1444static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1445 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001446 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001447 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001448 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1449 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001450 if (Reg.TheDef->getValueAsString("AsmName").empty())
1451 continue;
1452
Chris Lattner042926f2009-08-08 20:02:57 +00001453 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001454 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001455 }
Chris Lattner042926f2009-08-08 20:02:57 +00001456
Chris Lattner8b382002010-02-09 00:34:28 +00001457 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001458
Chris Lattner042926f2009-08-08 20:02:57 +00001459 EmitStringMatcher("Name", Matches, OS);
1460
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001461 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001462 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001463}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001464
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001465void AsmMatcherEmitter::run(raw_ostream &OS) {
1466 CodeGenTarget Target;
1467 Record *AsmParser = Target.getAsmParser();
1468 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1469
Daniel Dunbar378bee92009-08-08 07:50:56 +00001470 // Compute the information on the instructions to match.
Daniel Dunbara6d04732009-08-11 20:59:47 +00001471 AsmMatcherInfo Info(AsmParser);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001472 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001473
Daniel Dunbar75135552010-02-02 23:46:36 +00001474 // Sort the instruction table using the partial order on classes. We use
1475 // stable_sort to ensure that ambiguous instructions are still
1476 // deterministically ordered.
1477 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1478 less_ptr<InstructionInfo>());
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001479
Daniel Dunbarce82b992009-08-08 05:24:34 +00001480 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001481 for (std::vector<InstructionInfo*>::iterator
1482 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1483 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001484 (*it)->dump();
1485 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001486
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001487 // Check for ambiguous instructions.
1488 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001489 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1490 for (unsigned j = i + 1; j != e; ++j) {
1491 InstructionInfo &A = *Info.Instructions[i];
1492 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001493
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001494 if (A.CouldMatchAmiguouslyWith(B)) {
1495 DEBUG_WITH_TYPE("ambiguous_instrs", {
1496 errs() << "warning: ambiguous instruction match:\n";
1497 A.dump();
1498 errs() << "\nis incomparable with:\n";
1499 B.dump();
1500 errs() << "\n\n";
1501 });
1502 ++NumAmbiguous;
1503 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001504 }
1505 }
1506 if (NumAmbiguous)
1507 DEBUG_WITH_TYPE("ambiguous_instrs", {
1508 errs() << "warning: " << NumAmbiguous
1509 << " ambiguous instructions!\n";
1510 });
1511
Daniel Dunbar35303e32009-08-11 23:23:44 +00001512 // Write the output.
1513
1514 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1515
1516 // Emit the function to match a register name to number.
1517 EmitMatchRegisterName(Target, AsmParser, OS);
Sean Callananef372de2010-01-23 00:40:33 +00001518
1519 OS << "#ifndef REGISTERS_ONLY\n\n";
Daniel Dunbar35303e32009-08-11 23:23:44 +00001520
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001521 // Generate the unified function to convert operands into an MCInst.
1522 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001523
Daniel Dunbar378bee92009-08-08 07:50:56 +00001524 // Emit the enumeration for classes which participate in matching.
1525 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001526
Daniel Dunbar378bee92009-08-08 07:50:56 +00001527 // Emit the routine to match token strings to their match class.
1528 EmitMatchTokenString(Target, Info.Classes, OS);
1529
1530 // Emit the routine to classify an operand.
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001531 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001532
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001533 // Emit the subclass predicate routine.
1534 EmitIsSubclass(Target, Info.Classes, OS);
1535
Daniel Dunbar378bee92009-08-08 07:50:56 +00001536 // Finally, build the match function.
1537
1538 size_t MaxNumOperands = 0;
1539 for (std::vector<InstructionInfo*>::const_iterator it =
1540 Info.Instructions.begin(), ie = Info.Instructions.end();
1541 it != ie; ++it)
1542 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1543
Daniel Dunbara54716c2009-07-31 02:32:59 +00001544 OS << "bool " << Target.getName() << ClassName
Chris Lattner22f480d2010-01-14 22:21:20 +00001545 << "::\nMatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> "
1546 "&Operands,\n MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001547
Daniel Dunbar378bee92009-08-08 07:50:56 +00001548 // Emit the static match table; unused classes get initalized to 0 which is
1549 // guaranteed to be InvalidMatchClass.
1550 //
1551 // FIXME: We can reduce the size of this table very easily. First, we change
1552 // it so that store the kinds in separate bit-fields for each index, which
1553 // only needs to be the max width used for classes at that index (we also need
1554 // to reject based on this during classification). If we then make sure to
1555 // order the match kinds appropriately (putting mnemonics last), then we
1556 // should only end up using a few bits for each class, especially the ones
1557 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001558 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001559 OS << " unsigned Opcode;\n";
1560 OS << " ConversionKind ConvertFn;\n";
1561 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1562 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1563
1564 for (std::vector<InstructionInfo*>::const_iterator it =
1565 Info.Instructions.begin(), ie = Info.Instructions.end();
1566 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001567 InstructionInfo &II = **it;
1568
Daniel Dunbar378bee92009-08-08 07:50:56 +00001569 OS << " { " << Target.getName() << "::" << II.InstrName
1570 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001571 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1572 InstructionInfo::Operand &Op = II.Operands[i];
1573
Daniel Dunbar378bee92009-08-08 07:50:56 +00001574 if (i) OS << ", ";
1575 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001576 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001577 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001578 }
1579
Daniel Dunbar378bee92009-08-08 07:50:56 +00001580 OS << " };\n\n";
1581
1582 // Emit code to compute the class list for this operand vector.
1583 OS << " // Eliminate obvious mismatches.\n";
1584 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1585 OS << " return true;\n\n";
1586
1587 OS << " // Compute the class list for this operand vector.\n";
1588 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1589 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1590 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1591
1592 OS << " // Check for invalid operands before matching.\n";
1593 OS << " if (Classes[i] == InvalidMatchClass)\n";
1594 OS << " return true;\n";
1595 OS << " }\n\n";
1596
1597 OS << " // Mark unused classes.\n";
1598 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1599 << "i != e; ++i)\n";
1600 OS << " Classes[i] = InvalidMatchClass;\n\n";
1601
1602 // Emit code to search the table.
1603 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001604 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001605 << "*ie = MatchTable + " << Info.Instructions.size()
1606 << "; it != ie; ++it) {\n";
1607 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001608 OS << " if (!IsSubclass(Classes["
1609 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001610 OS << " continue;\n";
1611 }
1612 OS << "\n";
1613 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1614 << "it->Opcode, Operands);\n";
1615 OS << " }\n\n";
1616
Daniel Dunbara54716c2009-07-31 02:32:59 +00001617 OS << " return true;\n";
1618 OS << "}\n\n";
Sean Callananef372de2010-01-23 00:40:33 +00001619
1620 OS << "#endif // REGISTERS_ONLY\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001621}