blob: e1aa2bc70f6c96d3bee8774c9e522d5bab85145a [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 Dunbarf26e3d12010-05-27 05:31:32 +0000391 if (this == &RHS)
392 return false;
393
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000394 // Unrelated classes can be ordered by kind.
395 if (!isRelatedTo(RHS))
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000396 return Kind < RHS.Kind;
397
398 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000399 case Invalid:
400 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000401 case Token:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000402 // Tokens are comparable by value.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000403 //
404 // FIXME: Compare by enum value.
405 return ValueName < RHS.ValueName;
406
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000407 default:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000408 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbarf26e3d12010-05-27 05:31:32 +0000409 if (isSubsetOf(RHS))
Duncan Sandsc2d3eee2010-07-12 08:16:59 +0000410 return true;
Daniel Dunbarf26e3d12010-05-27 05:31:32 +0000411 if (RHS.isSubsetOf(*this))
Duncan Sandsc2d3eee2010-07-12 08:16:59 +0000412 return false;
Daniel Dunbarf26e3d12010-05-27 05:31:32 +0000413
414 // Otherwise, order by name to ensure we have a total ordering.
415 return ValueName < RHS.ValueName;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000416 }
417 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000418};
419
Daniel Dunbarce82b992009-08-08 05:24:34 +0000420/// InstructionInfo - Helper class for storing the necessary information for an
421/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000422struct InstructionInfo {
423 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000424 /// The unique class instance this operand should match.
425 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000426
Daniel Dunbar378bee92009-08-08 07:50:56 +0000427 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000428 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000429 };
430
431 /// InstrName - The target name for this instruction.
432 std::string InstrName;
433
434 /// Instr - The instruction this matches.
435 const CodeGenInstruction *Instr;
436
437 /// AsmString - The assembly string for this instruction (with variants
438 /// removed).
439 std::string AsmString;
440
441 /// Tokens - The tokenized assembly pattern that this instruction matches.
442 SmallVector<StringRef, 4> Tokens;
443
444 /// Operands - The operands that this instruction matches.
445 SmallVector<Operand, 4> Operands;
446
Daniel Dunbarce82b992009-08-08 05:24:34 +0000447 /// ConversionFnKind - The enum value which is passed to the generated
448 /// ConvertToMCInst to convert parsed operands into an MCInst for this
449 /// function.
450 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000451
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000452 /// operator< - Compare two instructions.
453 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000454 if (Operands.size() != RHS.Operands.size())
455 return Operands.size() < RHS.Operands.size();
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000456
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000457 // Compare lexicographically by operand. The matcher validates that other
458 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
459 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000460 if (*Operands[i].Class < *RHS.Operands[i].Class)
461 return true;
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000462 if (*RHS.Operands[i].Class < *Operands[i].Class)
463 return false;
464 }
465
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000466 return false;
467 }
468
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000469 /// CouldMatchAmiguouslyWith - Check whether this instruction could
470 /// ambiguously match the same set of operands as \arg RHS (without being a
471 /// strictly superior match).
472 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
473 // The number of operands is unambiguous.
474 if (Operands.size() != RHS.Operands.size())
475 return false;
476
Daniel Dunbar24a7ad02010-01-23 00:26:16 +0000477 // Otherwise, make sure the ordering of the two instructions is unambiguous
478 // by checking that either (a) a token or operand kind discriminates them,
479 // or (b) the ordering among equivalent kinds is consistent.
480
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000481 // Tokens and operand kinds are unambiguous (assuming a correct target
482 // specific parser).
483 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
484 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
485 Operands[i].Class->Kind == ClassInfo::Token)
486 if (*Operands[i].Class < *RHS.Operands[i].Class ||
487 *RHS.Operands[i].Class < *Operands[i].Class)
488 return false;
489
490 // Otherwise, this operand could commute if all operands are equivalent, or
491 // there is a pair of operands that compare less than and a pair that
492 // compare greater than.
493 bool HasLT = false, HasGT = false;
494 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
495 if (*Operands[i].Class < *RHS.Operands[i].Class)
496 HasLT = true;
497 if (*RHS.Operands[i].Class < *Operands[i].Class)
498 HasGT = true;
499 }
500
501 return !(HasLT ^ HasGT);
502 }
503
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000504public:
505 void dump();
506};
507
Daniel Dunbar378bee92009-08-08 07:50:56 +0000508class AsmMatcherInfo {
509public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000510 /// The tablegen AsmParser record.
511 Record *AsmParser;
512
513 /// The AsmParser "CommentDelimiter" value.
514 std::string CommentDelimiter;
515
516 /// The AsmParser "RegisterPrefix" value.
517 std::string RegisterPrefix;
518
Daniel Dunbar378bee92009-08-08 07:50:56 +0000519 /// The classes which are needed for matching.
520 std::vector<ClassInfo*> Classes;
521
522 /// The information on the instruction to match.
523 std::vector<InstructionInfo*> Instructions;
524
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000525 /// Map of Register records to their class information.
526 std::map<Record*, ClassInfo*> RegisterClasses;
527
Daniel Dunbar378bee92009-08-08 07:50:56 +0000528private:
529 /// Map of token to class information which has already been constructed.
530 std::map<std::string, ClassInfo*> TokenClasses;
531
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000532 /// Map of RegisterClass records to their class information.
533 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000534
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000535 /// Map of AsmOperandClass records to their class information.
536 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000537
Daniel Dunbar378bee92009-08-08 07:50:56 +0000538private:
539 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner8b382002010-02-09 00:34:28 +0000540 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar378bee92009-08-08 07:50:56 +0000541
542 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattner8b382002010-02-09 00:34:28 +0000543 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbar378bee92009-08-08 07:50:56 +0000544 const CodeGenInstruction::OperandInfo &OI);
545
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000546 /// BuildRegisterClasses - Build the ClassInfo* instances for register
547 /// classes.
Daniel Dunbar35303e32009-08-11 23:23:44 +0000548 void BuildRegisterClasses(CodeGenTarget &Target,
549 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000550
551 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
552 /// operand classes.
553 void BuildOperandClasses(CodeGenTarget &Target);
554
Daniel Dunbar378bee92009-08-08 07:50:56 +0000555public:
Daniel Dunbara6d04732009-08-11 20:59:47 +0000556 AsmMatcherInfo(Record *_AsmParser);
557
Daniel Dunbar378bee92009-08-08 07:50:56 +0000558 /// BuildInfo - Construct the various tables used during matching.
559 void BuildInfo(CodeGenTarget &Target);
560};
561
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000562}
563
564void InstructionInfo::dump() {
565 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
566 << ", tokens:[";
567 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
568 errs() << Tokens[i];
569 if (i + 1 != e)
570 errs() << ", ";
571 }
572 errs() << "]\n";
573
574 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
575 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000576 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000577 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000578 errs() << '\"' << Tokens[i] << "\"\n";
579 continue;
580 }
581
Daniel Dunbar35303e32009-08-11 23:23:44 +0000582 if (!Op.OperandInfo) {
583 errs() << "(singleton register)\n";
584 continue;
585 }
586
Benjamin Kramer19afc502009-08-08 10:06:30 +0000587 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000588 errs() << OI.Name << " " << OI.Rec->getName()
589 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
590 }
591}
592
Chris Lattner8b382002010-02-09 00:34:28 +0000593static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000594 std::string Res;
595
596 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
597 switch (*it) {
598 case '*': Res += "_STAR_"; break;
599 case '%': Res += "_PCT_"; break;
600 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000601
Daniel Dunbar378bee92009-08-08 07:50:56 +0000602 default:
603 if (isalnum(*it)) {
604 Res += *it;
605 } else {
606 Res += "_" + utostr((unsigned) *it) + "_";
607 }
608 }
609 }
610
611 return Res;
612}
613
Daniel Dunbar35303e32009-08-11 23:23:44 +0000614/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattner8b382002010-02-09 00:34:28 +0000615static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000616 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
617 const CodeGenRegister &Reg = Target.getRegisters()[i];
618 if (Name == Reg.TheDef->getValueAsString("AsmName"))
619 return Reg.TheDef;
620 }
621
622 return 0;
623}
624
Chris Lattner8b382002010-02-09 00:34:28 +0000625ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000626 ClassInfo *&Entry = TokenClasses[Token];
627
628 if (!Entry) {
629 Entry = new ClassInfo();
630 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000631 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000632 Entry->Name = "MCK_" + getEnumNameForToken(Token);
633 Entry->ValueName = Token;
634 Entry->PredicateMethod = "<invalid>";
635 Entry->RenderMethod = "<invalid>";
636 Classes.push_back(Entry);
637 }
638
639 return Entry;
640}
641
642ClassInfo *
Chris Lattner8b382002010-02-09 00:34:28 +0000643AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbar378bee92009-08-08 07:50:56 +0000644 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000645 if (OI.Rec->isSubClassOf("RegisterClass")) {
646 ClassInfo *CI = RegisterClassClasses[OI.Rec];
647
648 if (!CI) {
649 PrintError(OI.Rec->getLoc(), "register class has no class info!");
650 throw std::string("ERROR: Missing register class!");
651 }
652
653 return CI;
654 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000655
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000656 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
657 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
658 ClassInfo *CI = AsmOperandClasses[MatchClass];
659
660 if (!CI) {
661 PrintError(OI.Rec->getLoc(), "operand has no match class!");
662 throw std::string("ERROR: Missing match class!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000663 }
664
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000665 return CI;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000666}
667
Daniel Dunbar35303e32009-08-11 23:23:44 +0000668void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
669 std::set<std::string>
670 &SingletonRegisterNames) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000671 std::vector<CodeGenRegisterClass> RegisterClasses;
672 std::vector<CodeGenRegister> Registers;
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000673
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000674 RegisterClasses = Target.getRegisterClasses();
675 Registers = Target.getRegisters();
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000676
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000677 // The register sets used for matching.
678 std::set< std::set<Record*> > RegisterSets;
679
680 // Gather the defined sets.
681 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
682 ie = RegisterClasses.end(); it != ie; ++it)
683 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
684 it->Elements.end()));
Daniel Dunbar35303e32009-08-11 23:23:44 +0000685
686 // Add any required singleton sets.
687 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
688 ie = SingletonRegisterNames.end(); it != ie; ++it)
689 if (Record *Rec = getRegisterRecord(Target, *it))
690 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
691
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000692 // Introduce derived sets where necessary (when a register does not determine
693 // a unique register set class), and build the mapping of registers to the set
694 // they should classify to.
695 std::map<Record*, std::set<Record*> > RegisterMap;
696 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
697 ie = Registers.end(); it != ie; ++it) {
698 CodeGenRegister &CGR = *it;
699 // Compute the intersection of all sets containing this register.
700 std::set<Record*> ContainingSet;
701
702 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
703 ie = RegisterSets.end(); it != ie; ++it) {
704 if (!it->count(CGR.TheDef))
705 continue;
706
707 if (ContainingSet.empty()) {
708 ContainingSet = *it;
709 } else {
710 std::set<Record*> Tmp;
711 std::swap(Tmp, ContainingSet);
712 std::insert_iterator< std::set<Record*> > II(ContainingSet,
713 ContainingSet.begin());
714 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
715 II);
716 }
717 }
718
719 if (!ContainingSet.empty()) {
720 RegisterSets.insert(ContainingSet);
721 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
722 }
723 }
724
725 // Construct the register classes.
726 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
727 unsigned Index = 0;
728 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
729 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
730 ClassInfo *CI = new ClassInfo();
731 CI->Kind = ClassInfo::RegisterClass0 + Index;
732 CI->ClassName = "Reg" + utostr(Index);
733 CI->Name = "MCK_Reg" + utostr(Index);
734 CI->ValueName = "";
735 CI->PredicateMethod = ""; // unused
736 CI->RenderMethod = "addRegOperands";
Daniel Dunbar1d606f62009-08-11 20:10:07 +0000737 CI->Registers = *it;
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000738 Classes.push_back(CI);
739 RegisterSetClasses.insert(std::make_pair(*it, CI));
740 }
741
742 // Find the superclasses; we could compute only the subgroup lattice edges,
743 // but there isn't really a point.
744 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
745 ie = RegisterSets.end(); it != ie; ++it) {
746 ClassInfo *CI = RegisterSetClasses[*it];
747 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
748 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
749 if (*it != *it2 &&
750 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
751 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
752 }
753
754 // Name the register classes which correspond to a user defined RegisterClass.
755 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
756 ie = RegisterClasses.end(); it != ie; ++it) {
757 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
758 it->Elements.end())];
759 if (CI->ValueName.empty()) {
760 CI->ClassName = it->getName();
761 CI->Name = "MCK_" + it->getName();
762 CI->ValueName = it->getName();
763 } else
764 CI->ValueName = CI->ValueName + "," + it->getName();
765
766 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
767 }
768
769 // Populate the map for individual registers.
770 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
771 ie = RegisterMap.end(); it != ie; ++it)
772 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar35303e32009-08-11 23:23:44 +0000773
774 // Name the register classes which correspond to singleton registers.
775 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
776 ie = SingletonRegisterNames.end(); it != ie; ++it) {
777 if (Record *Rec = getRegisterRecord(Target, *it)) {
778 ClassInfo *CI = this->RegisterClasses[Rec];
779 assert(CI && "Missing singleton register class info!");
780
781 if (CI->ValueName.empty()) {
782 CI->ClassName = Rec->getName();
783 CI->Name = "MCK_" + Rec->getName();
784 CI->ValueName = Rec->getName();
785 } else
786 CI->ValueName = CI->ValueName + "," + Rec->getName();
787 }
788 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000789}
790
791void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000792 std::vector<Record*> AsmOperands;
793 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarbbd99172010-01-30 01:02:37 +0000794
795 // Pre-populate AsmOperandClasses map.
796 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
797 ie = AsmOperands.end(); it != ie; ++it)
798 AsmOperandClasses[*it] = new ClassInfo();
799
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000800 unsigned Index = 0;
801 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
802 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbarbbd99172010-01-30 01:02:37 +0000803 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000804 CI->Kind = ClassInfo::UserClass0 + Index;
805
Daniel Dunbar0dad9b82010-05-22 21:02:29 +0000806 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
807 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
808 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
809 if (!DI) {
810 PrintError((*it)->getLoc(), "Invalid super class reference!");
811 continue;
812 }
813
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000814 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
815 if (!SC)
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000816 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000817 else
818 CI->SuperClasses.push_back(SC);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000819 }
820 CI->ClassName = (*it)->getValueAsString("Name");
821 CI->Name = "MCK_" + CI->ClassName;
822 CI->ValueName = (*it)->getName();
Daniel Dunbarb3413d82009-08-10 21:00:45 +0000823
824 // Get or construct the predicate method name.
825 Init *PMName = (*it)->getValueInit("PredicateMethod");
826 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
827 CI->PredicateMethod = SI->getValue();
828 } else {
829 assert(dynamic_cast<UnsetInit*>(PMName) &&
830 "Unexpected PredicateMethod field!");
831 CI->PredicateMethod = "is" + CI->ClassName;
832 }
833
834 // Get or construct the render method name.
835 Init *RMName = (*it)->getValueInit("RenderMethod");
836 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
837 CI->RenderMethod = SI->getValue();
838 } else {
839 assert(dynamic_cast<UnsetInit*>(RMName) &&
840 "Unexpected RenderMethod field!");
841 CI->RenderMethod = "add" + CI->ClassName + "Operands";
842 }
843
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000844 AsmOperandClasses[*it] = CI;
845 Classes.push_back(CI);
846 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000847}
848
Daniel Dunbara6d04732009-08-11 20:59:47 +0000849AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
850 : AsmParser(_AsmParser),
851 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
852 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
853{
854}
855
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000856void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000857 // Parse the instructions; we need to do this first so that we can gather the
858 // singleton register classes.
859 std::set<std::string> SingletonRegisterNames;
Chris Lattnera67d23d2010-03-19 00:18:23 +0000860
Chris Lattnera2e1d002010-03-19 00:34:35 +0000861 const std::vector<const CodeGenInstruction*> &InstrList =
862 Target.getInstructionsByEnumValue();
Chris Lattnera67d23d2010-03-19 00:18:23 +0000863
864 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
865 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000866
Chris Lattnera67d23d2010-03-19 00:18:23 +0000867 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000868 continue;
869
Chris Lattnera67d23d2010-03-19 00:18:23 +0000870 OwningPtr<InstructionInfo> II(new InstructionInfo());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000871
Chris Lattnera67d23d2010-03-19 00:18:23 +0000872 II->InstrName = CGI.TheDef->getName();
873 II->Instr = &CGI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000874 II->AsmString = FlattenVariants(CGI.AsmString, 0);
875
Daniel Dunbara6d04732009-08-11 20:59:47 +0000876 // Remove comments from the asm string.
877 if (!CommentDelimiter.empty()) {
878 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
879 if (Idx != StringRef::npos)
880 II->AsmString = II->AsmString.substr(0, Idx);
881 }
882
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000883 TokenizeAsmString(II->AsmString, II->Tokens);
884
885 // Ignore instructions which shouldn't be matched.
Chris Lattnera67d23d2010-03-19 00:18:23 +0000886 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000887 continue;
888
Daniel Dunbar35303e32009-08-11 23:23:44 +0000889 // Collect singleton registers, if used.
890 if (!RegisterPrefix.empty()) {
891 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
892 if (II->Tokens[i].startswith(RegisterPrefix)) {
893 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
894 Record *Rec = getRegisterRecord(Target, RegName);
895
896 if (!Rec) {
897 std::string Err = "unable to find register for '" + RegName.str() +
898 "' (which matches register prefix)";
899 throw TGError(CGI.TheDef->getLoc(), Err);
900 }
901
902 SingletonRegisterNames.insert(RegName);
903 }
904 }
905 }
906
907 Instructions.push_back(II.take());
908 }
909
910 // Build info for the register classes.
911 BuildRegisterClasses(Target, SingletonRegisterNames);
912
913 // Build info for the user defined assembly operand classes.
914 BuildOperandClasses(Target);
915
916 // Build the instruction information.
917 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
918 ie = Instructions.end(); it != ie; ++it) {
919 InstructionInfo *II = *it;
920
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000921 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
922 StringRef Token = II->Tokens[i];
923
Daniel Dunbar35303e32009-08-11 23:23:44 +0000924 // Check for singleton registers.
925 if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
926 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
927 InstructionInfo::Operand Op;
928 Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
929 Op.OperandInfo = 0;
930 assert(Op.Class && Op.Class->Registers.size() == 1 &&
931 "Unexpected class for singleton register");
932 II->Operands.push_back(Op);
933 continue;
934 }
935
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000936 // Check for simple tokens.
937 if (Token[0] != '$') {
938 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000939 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000940 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000941 II->Operands.push_back(Op);
942 continue;
943 }
944
945 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000946 StringRef OperandName;
947 if (Token[1] == '{')
948 OperandName = Token.substr(2, Token.size() - 3);
949 else
950 OperandName = Token.substr(1);
951
952 // Map this token to an operand. FIXME: Move elsewhere.
953 unsigned Idx;
954 try {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000955 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000956 } catch(...) {
Daniel Dunbar35303e32009-08-11 23:23:44 +0000957 throw std::string("error: unable to find operand: '" +
958 OperandName.str() + "'");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000959 }
960
Daniel Dunbar17fae482010-02-10 08:15:48 +0000961 // FIXME: This is annoying, the named operand may be tied (e.g.,
962 // XCHG8rm). What we want is the untied operand, which we now have to
963 // grovel for. Only worry about this for single entry operands, we have to
964 // clean this up anyway.
965 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
966 if (OI->Constraints[0].isTied()) {
967 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
968
969 // The tied operand index is an MIOperand index, find the operand that
970 // contains it.
971 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
972 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
973 OI = &II->Instr->OperandList[i];
974 break;
975 }
976 }
977
978 assert(OI && "Unable to find tied operand target!");
979 }
980
Daniel Dunbar378bee92009-08-08 07:50:56 +0000981 InstructionInfo::Operand Op;
Daniel Dunbar17fae482010-02-10 08:15:48 +0000982 Op.Class = getOperandClass(Token, *OI);
983 Op.OperandInfo = OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000984 II->Operands.push_back(Op);
985 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000986 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000987
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000988 // Reorder classes so that classes preceed super classes.
989 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000990}
991
Daniel Dunbarf9baff92010-02-12 01:46:54 +0000992static std::pair<unsigned, unsigned> *
993GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
994 unsigned Index) {
995 for (unsigned i = 0, e = List.size(); i != e; ++i)
996 if (Index == List[i].first)
997 return &List[i];
998
999 return 0;
1000}
1001
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001002static void EmitConvertToMCInst(CodeGenTarget &Target,
1003 std::vector<InstructionInfo*> &Infos,
1004 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +00001005 // Write the convert function to a separate stream, so we can drop it after
1006 // the enum.
1007 std::string ConvertFnBody;
1008 raw_string_ostream CvtOS(ConvertFnBody);
1009
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001010 // Function we have already generated.
1011 std::set<std::string> GeneratedFns;
1012
Daniel Dunbarce82b992009-08-08 05:24:34 +00001013 // Start the unified conversion function.
1014
Daniel Dunbar6757d762010-03-18 20:05:56 +00001015 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarce82b992009-08-08 05:24:34 +00001016 << "unsigned Opcode,\n"
Chris Lattner22f480d2010-01-14 22:21:20 +00001017 << " const SmallVectorImpl<MCParsedAsmOperand*"
1018 << "> &Operands) {\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +00001019 CvtOS << " Inst.setOpcode(Opcode);\n";
1020 CvtOS << " switch (Kind) {\n";
1021 CvtOS << " default:\n";
1022
1023 // Start the enum, which we will generate inline.
1024
1025 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +00001026 OS << "enum ConversionKind {\n";
1027
Chris Lattner22f480d2010-01-14 22:21:20 +00001028 // TargetOperandClass - This is the target's operand class, like X86Operand.
1029 std::string TargetOperandClass = Target.getName() + "Operand";
1030
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001031 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1032 ie = Infos.end(); it != ie; ++it) {
1033 InstructionInfo &II = **it;
1034
1035 // Order the (class) operands by the order to convert them into an MCInst.
1036 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1037 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1038 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +00001039 if (Op.OperandInfo)
1040 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001041 }
Daniel Dunbar17fae482010-02-10 08:15:48 +00001042
1043 // Find any tied operands.
1044 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1045 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1046 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1047 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1048 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1049 if (CI.isTied())
1050 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1051 CI.getTiedOperand()));
1052 }
1053 }
1054
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001055 std::sort(MIOperandList.begin(), MIOperandList.end());
1056
1057 // Compute the total number of operands.
1058 unsigned NumMIOperands = 0;
1059 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1060 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1061 NumMIOperands = std::max(NumMIOperands,
1062 OI.MIOperandNo + OI.MINumOperands);
1063 }
1064
1065 // Build the conversion function signature.
1066 std::string Signature = "Convert";
1067 unsigned CurIndex = 0;
1068 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1069 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +00001070 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001071 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001072
1073 // Skip operands which weren't matched by anything, this occurs when the
1074 // .td file encodes "implicit" operands as explicit ones.
1075 //
1076 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbar17fae482010-02-10 08:15:48 +00001077 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001078 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1079 CurIndex);
1080 if (!Tie)
Daniel Dunbar17fae482010-02-10 08:15:48 +00001081 Signature += "__Imp";
1082 else
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001083 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbar17fae482010-02-10 08:15:48 +00001084 }
1085
1086 Signature += "__";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001087
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001088 // Registers are always converted the same, don't duplicate the conversion
1089 // function based on them.
1090 //
1091 // FIXME: We could generalize this based on the render method, if it
1092 // mattered.
1093 if (Op.Class->isRegisterClass())
1094 Signature += "Reg";
1095 else
1096 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +00001097 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +00001098 Signature += "_" + utostr(MIOperandList[i].second);
1099
Benjamin Kramer19afc502009-08-08 10:06:30 +00001100 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001101 }
1102
1103 // Add any trailing implicit operands.
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001104 for (; CurIndex != NumMIOperands; ++CurIndex) {
1105 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1106 CurIndex);
1107 if (!Tie)
1108 Signature += "__Imp";
1109 else
1110 Signature += "__Tie" + utostr(Tie->second);
1111 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001112
Daniel Dunbarce82b992009-08-08 05:24:34 +00001113 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001114
Daniel Dunbarce82b992009-08-08 05:24:34 +00001115 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001116 if (!GeneratedFns.insert(Signature).second)
1117 continue;
1118
1119 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +00001120
1121 // Add to the enum list.
1122 OS << " " << Signature << ",\n";
1123
1124 // And to the convert function.
1125 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001126 CurIndex = 0;
1127 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1128 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1129
1130 // Add the implicit operands.
Daniel Dunbar17fae482010-02-10 08:15:48 +00001131 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1132 // See if this is a tied operand.
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001133 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1134 CurIndex);
Daniel Dunbar17fae482010-02-10 08:15:48 +00001135
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001136 if (!Tie) {
Daniel Dunbar17fae482010-02-10 08:15:48 +00001137 // If not, this is some implicit operand. Just assume it is a register
1138 // for now.
1139 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1140 } else {
1141 // Copy the tied operand.
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001142 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbar17fae482010-02-10 08:15:48 +00001143 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001144 << Tie->second << "));\n";
Daniel Dunbar17fae482010-02-10 08:15:48 +00001145 }
1146 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001147
Chris Lattner22f480d2010-01-14 22:21:20 +00001148 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1149 << MIOperandList[i].second
1150 << "])->" << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +00001151 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1152 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001153 }
1154
1155 // And add trailing implicit operands.
Daniel Dunbarf9baff92010-02-12 01:46:54 +00001156 for (; CurIndex != NumMIOperands; ++CurIndex) {
1157 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1158 CurIndex);
1159
1160 if (!Tie) {
1161 // If not, this is some implicit operand. Just assume it is a register
1162 // for now.
1163 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1164 } else {
1165 // Copy the tied operand.
1166 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1167 CvtOS << " Inst.addOperand(Inst.getOperand("
1168 << Tie->second << "));\n";
1169 }
1170 }
1171
Daniel Dunbar6757d762010-03-18 20:05:56 +00001172 CvtOS << " return;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001173 }
Daniel Dunbarce82b992009-08-08 05:24:34 +00001174
1175 // Finish the convert function.
1176
1177 CvtOS << " }\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +00001178 CvtOS << "}\n\n";
1179
1180 // Finish the enum, and drop the convert function after it.
1181
1182 OS << " NumConversionVariants\n";
1183 OS << "};\n\n";
1184
Daniel Dunbarce82b992009-08-08 05:24:34 +00001185 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +00001186}
1187
Daniel Dunbar378bee92009-08-08 07:50:56 +00001188/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1189static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1190 std::vector<ClassInfo*> &Infos,
1191 raw_ostream &OS) {
1192 OS << "namespace {\n\n";
1193
1194 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1195 << "/// instruction matching.\n";
1196 OS << "enum MatchClassKind {\n";
1197 OS << " InvalidMatchClass = 0,\n";
1198 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1199 ie = Infos.end(); it != ie; ++it) {
1200 ClassInfo &CI = **it;
1201 OS << " " << CI.Name << ", // ";
1202 if (CI.Kind == ClassInfo::Token) {
1203 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001204 } else if (CI.isRegisterClass()) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001205 if (!CI.ValueName.empty())
1206 OS << "register class '" << CI.ValueName << "'\n";
1207 else
1208 OS << "derived register class\n";
1209 } else {
1210 OS << "user defined class '" << CI.ValueName << "'\n";
1211 }
1212 }
1213 OS << " NumMatchClassKinds\n";
1214 OS << "};\n\n";
1215
1216 OS << "}\n\n";
1217}
1218
Daniel Dunbar378bee92009-08-08 07:50:56 +00001219/// EmitClassifyOperand - Emit the function to classify an operand.
1220static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001221 AsmMatcherInfo &Info,
Daniel Dunbar378bee92009-08-08 07:50:56 +00001222 raw_ostream &OS) {
Chris Lattner22f480d2010-01-14 22:21:20 +00001223 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1224 << " " << Target.getName() << "Operand &Operand = *("
1225 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001226
1227 // Classify tokens.
Daniel Dunbar378bee92009-08-08 07:50:56 +00001228 OS << " if (Operand.isToken())\n";
1229 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001230
1231 // Classify registers.
1232 //
1233 // FIXME: Don't hardcode isReg, getReg.
1234 OS << " if (Operand.isReg()) {\n";
1235 OS << " switch (Operand.getReg()) {\n";
1236 OS << " default: return InvalidMatchClass;\n";
1237 for (std::map<Record*, ClassInfo*>::iterator
1238 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1239 it != ie; ++it)
1240 OS << " case " << Target.getName() << "::"
1241 << it->first->getName() << ": return " << it->second->Name << ";\n";
1242 OS << " }\n";
1243 OS << " }\n\n";
1244
1245 // Classify user defined operands.
1246 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1247 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001248 ClassInfo &CI = **it;
1249
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001250 if (!CI.isUserClass())
1251 continue;
1252
1253 OS << " // '" << CI.ClassName << "' class";
1254 if (!CI.SuperClasses.empty()) {
1255 OS << ", subclass of ";
1256 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1257 if (i) OS << ", ";
1258 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1259 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar06d5cb62009-08-09 07:20:21 +00001260 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001261 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001262 OS << "\n";
1263
1264 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1265
1266 // Validate subclass relationships.
1267 if (!CI.SuperClasses.empty()) {
1268 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1269 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1270 << "() && \"Invalid class relationship!\");\n";
1271 }
1272
1273 OS << " return " << CI.Name << ";\n";
1274 OS << " }\n\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001275 }
1276 OS << " return InvalidMatchClass;\n";
1277 OS << "}\n\n";
1278}
1279
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001280/// EmitIsSubclass - Emit the subclass predicate function.
1281static void EmitIsSubclass(CodeGenTarget &Target,
1282 std::vector<ClassInfo*> &Infos,
1283 raw_ostream &OS) {
1284 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1285 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1286 OS << " if (A == B)\n";
1287 OS << " return true;\n\n";
1288
1289 OS << " switch (A) {\n";
1290 OS << " default:\n";
1291 OS << " return false;\n";
1292 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1293 ie = Infos.end(); it != ie; ++it) {
1294 ClassInfo &A = **it;
1295
1296 if (A.Kind != ClassInfo::Token) {
1297 std::vector<StringRef> SuperClasses;
1298 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1299 ie = Infos.end(); it != ie; ++it) {
1300 ClassInfo &B = **it;
1301
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001302 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001303 SuperClasses.push_back(B.Name);
1304 }
1305
1306 if (SuperClasses.empty())
1307 continue;
1308
1309 OS << "\n case " << A.Name << ":\n";
1310
1311 if (SuperClasses.size() == 1) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001312 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001313 continue;
1314 }
1315
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001316 OS << " switch (B) {\n";
1317 OS << " default: return false;\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001318 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001319 OS << " case " << SuperClasses[i] << ": return true;\n";
1320 OS << " }\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001321 }
1322 }
1323 OS << " }\n";
1324 OS << "}\n\n";
1325}
1326
Chris Lattner042926f2009-08-08 20:02:57 +00001327typedef std::pair<std::string, std::string> StringPair;
1328
1329/// FindFirstNonCommonLetter - Find the first character in the keys of the
1330/// string pairs that is not shared across the whole set of strings. All
1331/// strings are assumed to have the same length.
1332static unsigned
1333FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1334 assert(!Matches.empty());
1335 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1336 // Check to see if letter i is the same across the set.
1337 char Letter = Matches[0]->first[i];
1338
1339 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1340 if (Matches[str]->first[i] != Letter)
1341 return i;
1342 }
1343
1344 return Matches[0]->first.size();
1345}
1346
1347/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1348/// same length and whose characters leading up to CharNo are the same, emit
1349/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001350///
1351/// \return - True if control can leave the emitted code fragment.
1352static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +00001353 const std::vector<const StringPair*> &Matches,
1354 unsigned CharNo, unsigned IndentCount,
1355 raw_ostream &OS) {
1356 assert(!Matches.empty() && "Must have at least one string to match!");
1357 std::string Indent(IndentCount*2+4, ' ');
1358
1359 // If we have verified that the entire string matches, we're done: output the
1360 // matching code.
1361 if (CharNo == Matches[0]->first.size()) {
1362 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1363
1364 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1365 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1366 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001367 return false;
Chris Lattner042926f2009-08-08 20:02:57 +00001368 }
1369
1370 // Bucket the matches by the character we are comparing.
1371 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1372
1373 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1374 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1375
1376
1377 // If we have exactly one bucket to match, see how many characters are common
1378 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +00001379 if (MatchesByLetter.size() == 1) {
1380 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1381 unsigned NumChars = FirstNonCommonLetter-CharNo;
1382
Daniel Dunbar7906a642009-08-08 22:57:25 +00001383 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +00001384 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001385 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +00001386 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001387 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1388 << Matches[0]->first[CharNo] << "')\n";
1389 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001390 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001391 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +00001392 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001393 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1394 << NumChars << ") != \"";
1395 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +00001396 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001397 }
1398
Daniel Dunbar7906a642009-08-08 22:57:25 +00001399 return EmitStringMatcherForChar(StrVariableName, Matches,
1400 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001401 }
1402
1403 // Otherwise, we have multiple possible things, emit a switch on the
1404 // character.
1405 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1406 OS << Indent << "default: break;\n";
1407
1408 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1409 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1410 // TODO: escape hard stuff (like \n) if we ever care about it.
1411 OS << Indent << "case '" << LI->first << "':\t // "
1412 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001413 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1414 IndentCount+1, OS))
1415 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001416 }
1417
1418 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001419 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001420}
1421
1422
1423/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001424/// match, output a simple switch tree to classify the input string.
1425///
1426/// If a match is found, the code in Vals[i].second is executed; control must
1427/// not exit this code fragment. If nothing matches, execution falls through.
1428///
1429/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001430static void EmitStringMatcher(const std::string &StrVariableName,
1431 const std::vector<StringPair> &Matches,
1432 raw_ostream &OS) {
1433 // First level categorization: group strings by length.
1434 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1435
1436 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1437 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1438
1439 // Output a switch statement on length and categorize the elements within each
1440 // bin.
1441 OS << " switch (" << StrVariableName << ".size()) {\n";
1442 OS << " default: break;\n";
1443
Chris Lattner042926f2009-08-08 20:02:57 +00001444 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1445 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1446 OS << " case " << LI->first << ":\t // " << LI->second.size()
1447 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001448 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1449 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001450 }
1451
Chris Lattner042926f2009-08-08 20:02:57 +00001452 OS << " }\n";
1453}
1454
1455
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001456/// EmitMatchTokenString - Emit the function to match a token string to the
1457/// appropriate match class value.
1458static void EmitMatchTokenString(CodeGenTarget &Target,
1459 std::vector<ClassInfo*> &Infos,
1460 raw_ostream &OS) {
1461 // Construct the match list.
1462 std::vector<StringPair> Matches;
1463 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1464 ie = Infos.end(); it != ie; ++it) {
1465 ClassInfo &CI = **it;
1466
1467 if (CI.Kind == ClassInfo::Token)
1468 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1469 }
1470
Chris Lattner8b382002010-02-09 00:34:28 +00001471 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001472
1473 EmitStringMatcher("Name", Matches, OS);
1474
1475 OS << " return InvalidMatchClass;\n";
1476 OS << "}\n\n";
1477}
Chris Lattner042926f2009-08-08 20:02:57 +00001478
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001479/// EmitMatchRegisterName - Emit the function to match a string to the target
1480/// specific register enum.
1481static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1482 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001483 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001484 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001485 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1486 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001487 if (Reg.TheDef->getValueAsString("AsmName").empty())
1488 continue;
1489
Chris Lattner042926f2009-08-08 20:02:57 +00001490 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001491 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001492 }
Chris Lattner042926f2009-08-08 20:02:57 +00001493
Chris Lattner8b382002010-02-09 00:34:28 +00001494 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001495
Chris Lattner042926f2009-08-08 20:02:57 +00001496 EmitStringMatcher("Name", Matches, OS);
1497
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001498 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001499 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001500}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001501
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001502void AsmMatcherEmitter::run(raw_ostream &OS) {
1503 CodeGenTarget Target;
1504 Record *AsmParser = Target.getAsmParser();
1505 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1506
Daniel Dunbar378bee92009-08-08 07:50:56 +00001507 // Compute the information on the instructions to match.
Daniel Dunbara6d04732009-08-11 20:59:47 +00001508 AsmMatcherInfo Info(AsmParser);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001509 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001510
Daniel Dunbar75135552010-02-02 23:46:36 +00001511 // Sort the instruction table using the partial order on classes. We use
1512 // stable_sort to ensure that ambiguous instructions are still
1513 // deterministically ordered.
1514 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1515 less_ptr<InstructionInfo>());
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001516
Daniel Dunbarce82b992009-08-08 05:24:34 +00001517 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001518 for (std::vector<InstructionInfo*>::iterator
1519 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1520 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001521 (*it)->dump();
1522 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001523
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001524 // Check for ambiguous instructions.
1525 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001526 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1527 for (unsigned j = i + 1; j != e; ++j) {
1528 InstructionInfo &A = *Info.Instructions[i];
1529 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001530
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001531 if (A.CouldMatchAmiguouslyWith(B)) {
1532 DEBUG_WITH_TYPE("ambiguous_instrs", {
1533 errs() << "warning: ambiguous instruction match:\n";
1534 A.dump();
1535 errs() << "\nis incomparable with:\n";
1536 B.dump();
1537 errs() << "\n\n";
1538 });
1539 ++NumAmbiguous;
1540 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001541 }
1542 }
1543 if (NumAmbiguous)
1544 DEBUG_WITH_TYPE("ambiguous_instrs", {
1545 errs() << "warning: " << NumAmbiguous
1546 << " ambiguous instructions!\n";
1547 });
1548
Daniel Dunbar35303e32009-08-11 23:23:44 +00001549 // Write the output.
1550
1551 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1552
1553 // Emit the function to match a register name to number.
1554 EmitMatchRegisterName(Target, AsmParser, OS);
Sean Callananef372de2010-01-23 00:40:33 +00001555
1556 OS << "#ifndef REGISTERS_ONLY\n\n";
Daniel Dunbar35303e32009-08-11 23:23:44 +00001557
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001558 // Generate the unified function to convert operands into an MCInst.
1559 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001560
Daniel Dunbar378bee92009-08-08 07:50:56 +00001561 // Emit the enumeration for classes which participate in matching.
1562 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001563
Daniel Dunbar378bee92009-08-08 07:50:56 +00001564 // Emit the routine to match token strings to their match class.
1565 EmitMatchTokenString(Target, Info.Classes, OS);
1566
1567 // Emit the routine to classify an operand.
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001568 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001569
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001570 // Emit the subclass predicate routine.
1571 EmitIsSubclass(Target, Info.Classes, OS);
1572
Daniel Dunbar378bee92009-08-08 07:50:56 +00001573 // Finally, build the match function.
1574
1575 size_t MaxNumOperands = 0;
1576 for (std::vector<InstructionInfo*>::const_iterator it =
1577 Info.Instructions.begin(), ie = Info.Instructions.end();
1578 it != ie; ++it)
1579 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Daniel Dunbard9161322010-05-04 00:33:13 +00001580
1581 const std::string &MatchName =
1582 AsmParser->getValueAsString("MatchInstructionName");
1583 OS << "bool " << Target.getName() << ClassName << "::\n"
1584 << MatchName
1585 << "(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
1586 OS.indent(MatchName.size() + 1);
1587 OS << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001588
Daniel Dunbar378bee92009-08-08 07:50:56 +00001589 // Emit the static match table; unused classes get initalized to 0 which is
1590 // guaranteed to be InvalidMatchClass.
1591 //
1592 // FIXME: We can reduce the size of this table very easily. First, we change
1593 // it so that store the kinds in separate bit-fields for each index, which
1594 // only needs to be the max width used for classes at that index (we also need
1595 // to reject based on this during classification). If we then make sure to
1596 // order the match kinds appropriately (putting mnemonics last), then we
1597 // should only end up using a few bits for each class, especially the ones
1598 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001599 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001600 OS << " unsigned Opcode;\n";
1601 OS << " ConversionKind ConvertFn;\n";
1602 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1603 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1604
1605 for (std::vector<InstructionInfo*>::const_iterator it =
1606 Info.Instructions.begin(), ie = Info.Instructions.end();
1607 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001608 InstructionInfo &II = **it;
1609
Daniel Dunbar378bee92009-08-08 07:50:56 +00001610 OS << " { " << Target.getName() << "::" << II.InstrName
1611 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001612 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1613 InstructionInfo::Operand &Op = II.Operands[i];
1614
Daniel Dunbar378bee92009-08-08 07:50:56 +00001615 if (i) OS << ", ";
1616 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001617 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001618 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001619 }
1620
Daniel Dunbar378bee92009-08-08 07:50:56 +00001621 OS << " };\n\n";
1622
1623 // Emit code to compute the class list for this operand vector.
1624 OS << " // Eliminate obvious mismatches.\n";
1625 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1626 OS << " return true;\n\n";
1627
1628 OS << " // Compute the class list for this operand vector.\n";
1629 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1630 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1631 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1632
1633 OS << " // Check for invalid operands before matching.\n";
1634 OS << " if (Classes[i] == InvalidMatchClass)\n";
1635 OS << " return true;\n";
1636 OS << " }\n\n";
1637
1638 OS << " // Mark unused classes.\n";
1639 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1640 << "i != e; ++i)\n";
1641 OS << " Classes[i] = InvalidMatchClass;\n\n";
1642
1643 // Emit code to search the table.
1644 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001645 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001646 << "*ie = MatchTable + " << Info.Instructions.size()
1647 << "; it != ie; ++it) {\n";
1648 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001649 OS << " if (!IsSubclass(Classes["
1650 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001651 OS << " continue;\n";
1652 }
1653 OS << "\n";
Daniel Dunbar6757d762010-03-18 20:05:56 +00001654 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1655
1656 // Call the post-processing function, if used.
1657 std::string InsnCleanupFn =
1658 AsmParser->getValueAsString("AsmParserInstCleanup");
1659 if (!InsnCleanupFn.empty())
1660 OS << " " << InsnCleanupFn << "(Inst);\n";
1661
1662 OS << " return false;\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001663 OS << " }\n\n";
1664
Daniel Dunbara54716c2009-07-31 02:32:59 +00001665 OS << " return true;\n";
1666 OS << "}\n\n";
Sean Callananef372de2010-01-23 00:40:33 +00001667
1668 OS << "#endif // REGISTERS_ONLY\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001669}