blob: 0fad96edde3786cff3821c0999fd6e1703e404d6 [file] [log] [blame]
Daniel Dunbar3085b572009-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 Dunbare10787e2009-08-07 08:26:05 +000013// The input to the target specific matcher is a list of literal tokens and
14// operands. The target specific parser should generally eliminate any syntax
15// which is not relevant for matching; for example, comma tokens should have
16// already been consumed and eliminated by the parser. Most instructions will
17// end up with a single literal token (the instruction name) and some number of
18// operands.
19//
20// Some example inputs, for X86:
21// 'addl' (immediate ...) (register ...)
22// 'add' (immediate ...) (memory ...)
Jim Grosbach0eccfc22010-10-29 22:13:48 +000023// 'call' '*' %epc
Daniel Dunbare10787e2009-08-07 08:26:05 +000024//
25// The assembly matcher is responsible for converting this input into a precise
26// machine instruction (i.e., an instruction with a well defined encoding). This
27// mapping has several properties which complicate matching:
28//
29// - It may be ambiguous; many architectures can legally encode particular
30// variants of an instruction in different ways (for example, using a smaller
31// encoding for small immediates). Such ambiguities should never be
32// arbitrarily resolved by the assembler, the assembler is always responsible
33// for choosing the "best" available instruction.
34//
35// - It may depend on the subtarget or the assembler context. Instructions
36// which are invalid for the current mode, but otherwise unambiguous (e.g.,
37// an SSE instruction in a file being assembled for i486) should be accepted
38// and rejected by the assembler front end. However, if the proper encoding
39// for an instruction is dependent on the assembler context then the matcher
40// is responsible for selecting the correct machine instruction for the
41// current mode.
42//
43// The core matching algorithm attempts to exploit the regularity in most
44// instruction sets to quickly determine the set of possibly matching
45// instructions, and the simplify the generated code. Additionally, this helps
46// to ensure that the ambiguities are intentionally resolved by the user.
47//
48// The matching is divided into two distinct phases:
49//
50// 1. Classification: Each operand is mapped to the unique set which (a)
51// contains it, and (b) is the largest such subset for which a single
52// instruction could match all members.
53//
54// For register classes, we can generate these subgroups automatically. For
55// arbitrary operands, we expect the user to define the classes and their
56// relations to one another (for example, 8-bit signed immediates as a
57// subset of 32-bit immediates).
58//
59// By partitioning the operands in this way, we guarantee that for any
60// tuple of classes, any single instruction must match either all or none
61// of the sets of operands which could classify to that tuple.
62//
63// In addition, the subset relation amongst classes induces a partial order
64// on such tuples, which we use to resolve ambiguities.
65//
66// FIXME: What do we do if a crazy case shows up where this is the wrong
67// resolution?
68//
69// 2. The input can now be treated as a tuple of classes (static tokens are
70// simple singleton sets). Each such tuple should generally map to a single
71// instruction (we currently ignore cases where this isn't true, whee!!!),
72// which we can emit a simple matcher for.
73//
Daniel Dunbar3085b572009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Chris Lattnerca5a3552010-09-06 02:01:51 +000079#include "StringMatcher.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +000080#include "llvm/ADT/OwningPtr.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000081#include "llvm/ADT/SmallVector.h"
Daniel Dunbar3239f022009-08-09 04:00:06 +000082#include "llvm/ADT/STLExtras.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +000083#include "llvm/ADT/StringExtras.h"
84#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000085#include "llvm/Support/Debug.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000086#include <list>
Daniel Dunbar71330282009-08-08 05:24:34 +000087#include <map>
88#include <set>
Daniel Dunbar3085b572009-07-11 19:39:44 +000089using namespace llvm;
90
Daniel Dunbar15b80372009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar3239f022009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbare10787e2009-08-07 08:26:05 +000094
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000095/// FlattenVariants - Flatten an .td file assembly string by selecting the
96/// variant at index \arg N.
97static std::string FlattenVariants(const std::string &AsmString,
98 unsigned N) {
99 StringRef Cur = AsmString;
100 std::string Res = "";
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000101
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000102 for (;;) {
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000103 // Find the start of the next variant string.
104 size_t VariantsStart = 0;
105 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000106 if (Cur[VariantsStart] == '{' &&
Daniel Dunbare10787e2009-08-07 08:26:05 +0000107 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
108 Cur[VariantsStart-1] != '\\')))
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000109 break;
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000110
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000111 // Add the prefix to the result.
112 Res += Cur.slice(0, VariantsStart);
113 if (VariantsStart == Cur.size())
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000114 break;
115
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000116 ++VariantsStart; // Skip the '{'.
117
118 // Scan to the end of the variants string.
119 size_t VariantsEnd = VariantsStart;
120 unsigned NestedBraces = 1;
121 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000122 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000123 if (--NestedBraces == 0)
124 break;
125 } else if (Cur[VariantsEnd] == '{')
126 ++NestedBraces;
127 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000128
129 // Select the Nth variant (or empty).
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000130 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000131 for (unsigned i = 0; i != N; ++i)
132 Selection = Selection.split('|').second;
133 Res += Selection.split('|').first;
134
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000135 assert(VariantsEnd != Cur.size() &&
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000136 "Unterminated variants in assembly string!");
137 Cur = Cur.substr(VariantsEnd + 1);
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000138 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000139
140 return Res;
141}
142
143/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000144static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000145 SmallVectorImpl<StringRef> &Tokens) {
146 unsigned Prev = 0;
147 bool InTok = true;
148 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
149 switch (AsmString[i]) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000150 case '[':
151 case ']':
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000152 case '*':
153 case '!':
154 case ' ':
155 case '\t':
156 case ',':
157 if (InTok) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000158 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000159 InTok = false;
160 }
Daniel Dunbare10787e2009-08-07 08:26:05 +0000161 if (!isspace(AsmString[i]) && AsmString[i] != ',')
162 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000163 Prev = i + 1;
164 break;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000165
Daniel Dunbare10787e2009-08-07 08:26:05 +0000166 case '\\':
167 if (InTok) {
168 Tokens.push_back(AsmString.slice(Prev, i));
169 InTok = false;
170 }
171 ++i;
172 assert(i != AsmString.size() && "Invalid quoted character");
173 Tokens.push_back(AsmString.substr(i, 1));
174 Prev = i + 1;
175 break;
176
177 case '$': {
178 // If this isn't "${", treat like a normal token.
179 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
180 if (InTok) {
181 Tokens.push_back(AsmString.slice(Prev, i));
182 InTok = false;
183 }
184 Prev = i;
185 break;
186 }
187
188 if (InTok) {
189 Tokens.push_back(AsmString.slice(Prev, i));
190 InTok = false;
191 }
192
193 StringRef::iterator End =
194 std::find(AsmString.begin() + i, AsmString.end(), '}');
195 assert(End != AsmString.end() && "Missing brace in operand reference!");
196 size_t EndPos = End - AsmString.begin();
197 Tokens.push_back(AsmString.slice(i, EndPos+1));
198 Prev = EndPos + 1;
199 i = EndPos;
200 break;
201 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000202
Daniel Dunbar69f024b2010-08-11 06:36:59 +0000203 case '.':
204 if (InTok) {
205 Tokens.push_back(AsmString.slice(Prev, i));
206 }
207 Prev = i;
208 InTok = true;
209 break;
210
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000211 default:
212 InTok = true;
213 }
214 }
215 if (InTok && Prev != AsmString.size())
Daniel Dunbare10787e2009-08-07 08:26:05 +0000216 Tokens.push_back(AsmString.substr(Prev));
217}
218
Chris Lattner60db0a62010-02-09 00:34:28 +0000219static bool IsAssemblerInstruction(StringRef Name,
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000220 const CodeGenInstruction &CGI,
Daniel Dunbare10787e2009-08-07 08:26:05 +0000221 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbarc4f8ea42009-08-11 22:17:52 +0000222 // Ignore "codegen only" instructions.
223 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
224 return false;
225
226 // Ignore pseudo ops.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000227 //
Chris Lattner9492c172010-10-31 19:15:18 +0000228 // FIXME: This is a hack [for X86]; can we convert these instructions to set
229 // the "codegen only" bit instead?
Daniel Dunbare10787e2009-08-07 08:26:05 +0000230 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
231 if (Form->getValue()->getAsString() == "Pseudo")
232 return false;
Chris Lattner9492c172010-10-31 19:15:18 +0000233
234 // FIXME: This is a hack [for ARM]; can we convert these instructions to set
235 // the "codegen only" bit instead?
236 if (const RecordVal *Form = CGI.TheDef->getValue("F"))
237 if (Form->getValue()->getAsString() == "Pseudo")
238 return false;
239
Daniel Dunbare10787e2009-08-07 08:26:05 +0000240
Daniel Dunbare0891c22009-08-09 08:19:00 +0000241 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
242 //
243 // FIXME: This is a total hack.
244 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
245 return false;
246
Daniel Dunbare10787e2009-08-07 08:26:05 +0000247 // Ignore instructions with no .s string.
248 //
249 // FIXME: What are these?
Chris Lattner9492c172010-10-31 19:15:18 +0000250 if (CGI.AsmString.empty()) {
251 PrintError(CGI.TheDef->getLoc(),
252 "instruction with empty asm string");
253 throw std::string("ERROR: Invalid instruction for asm matcher");
254 }
Daniel Dunbare10787e2009-08-07 08:26:05 +0000255
256 // FIXME: Hack; ignore any instructions with a newline in them.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000257 if (std::find(CGI.AsmString.begin(),
Daniel Dunbare10787e2009-08-07 08:26:05 +0000258 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
259 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000260
Chris Lattner9492c172010-10-31 19:15:18 +0000261 // Reject instructions with attributes, these aren't something we can handle,
262 // the target should be refactored to use operands instead of modifiers.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000263 //
Daniel Dunbarc4f8ea42009-08-11 22:17:52 +0000264 // Also, check for instructions which reference the operand multiple times;
265 // this implies a constraint we would not honor.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000266 std::set<std::string> OperandNames;
267 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
Chris Lattnere59eef32010-10-31 19:05:32 +0000268 if (Tokens[i][0] == '$' &&
Chris Lattner33fc3e02010-10-31 19:10:56 +0000269 Tokens[i].find(':') != StringRef::npos) {
270 PrintError(CGI.TheDef->getLoc(),
271 "instruction with operand modifier '" + Tokens[i].str() +
272 "' not supported by asm matcher. Mark isCodeGenOnly!");
273 throw std::string("ERROR: Invalid instruction");
Chris Lattnere59eef32010-10-31 19:05:32 +0000274 }
Chris Lattner33fc3e02010-10-31 19:10:56 +0000275
Chris Lattnere59eef32010-10-31 19:05:32 +0000276 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
277 DEBUG({
Chris Lattner33fc3e02010-10-31 19:10:56 +0000278 errs() << "warning: '" << Name << "': "
279 << "ignoring instruction with tied operand '"
280 << Tokens[i].str() << "'\n";
281 });
Chris Lattnere59eef32010-10-31 19:05:32 +0000282 return false;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000283 }
284 }
Chris Lattner33fc3e02010-10-31 19:10:56 +0000285
Daniel Dunbare10787e2009-08-07 08:26:05 +0000286 return true;
287}
288
289namespace {
290
Daniel Dunbareefe8612010-07-19 05:44:09 +0000291struct SubtargetFeatureInfo;
292
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000293/// ClassInfo - Helper class for storing the information about a particular
294/// class of operands which can be matched.
295struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000296 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000297 /// Invalid kind, for use as a sentinel value.
298 Invalid = 0,
299
300 /// The class for a particular token.
301 Token,
302
303 /// The (first) register class, subsequent register classes are
304 /// RegisterClass0+1, and so on.
305 RegisterClass0,
306
307 /// The (first) user defined class, subsequent user defined classes are
308 /// UserClass0+1, and so on.
309 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000310 };
311
312 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
313 /// N) for the Nth user defined class.
314 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000315
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000316 /// SuperClasses - The super classes of this class. Note that for simplicities
317 /// sake user operands only record their immediate super class, while register
318 /// operands include all superclasses.
319 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000320
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000321 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000322 std::string Name;
323
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000324 /// ClassName - The unadorned generic name for this class (e.g., Token).
325 std::string ClassName;
326
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000327 /// ValueName - The name of the value this class represents; for a token this
328 /// is the literal token string, for an operand it is the TableGen class (or
329 /// empty if this is a derived class).
330 std::string ValueName;
331
332 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000333 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000334 std::string PredicateMethod;
335
336 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000337 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000338 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000339
Daniel Dunbar34c87912009-08-11 20:10:07 +0000340 /// For register classes, the records for all the registers in this class.
341 std::set<Record*> Registers;
342
343public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000344 /// isRegisterClass() - Check if this is a register class.
345 bool isRegisterClass() const {
346 return Kind >= RegisterClass0 && Kind < UserClass0;
347 }
348
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000349 /// isUserClass() - Check if this is a user defined class.
350 bool isUserClass() const {
351 return Kind >= UserClass0;
352 }
353
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000354 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
355 /// are related if they are in the same class hierarchy.
356 bool isRelatedTo(const ClassInfo &RHS) const {
357 // Tokens are only related to tokens.
358 if (Kind == Token || RHS.Kind == Token)
359 return Kind == Token && RHS.Kind == Token;
360
Daniel Dunbar34c87912009-08-11 20:10:07 +0000361 // Registers classes are only related to registers classes, and only if
362 // their intersection is non-empty.
363 if (isRegisterClass() || RHS.isRegisterClass()) {
364 if (!isRegisterClass() || !RHS.isRegisterClass())
365 return false;
366
367 std::set<Record*> Tmp;
368 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000369 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000370 RHS.Registers.begin(), RHS.Registers.end(),
371 II);
372
373 return !Tmp.empty();
374 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000375
376 // Otherwise we have two users operands; they are related if they are in the
377 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000378 //
379 // FIXME: This is an oversimplification, they should only be related if they
380 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000381 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
382 const ClassInfo *Root = this;
383 while (!Root->SuperClasses.empty())
384 Root = Root->SuperClasses.front();
385
Daniel Dunbar34c87912009-08-11 20:10:07 +0000386 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000387 while (!RHSRoot->SuperClasses.empty())
388 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000389
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000390 return Root == RHSRoot;
391 }
392
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000393 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000394 bool isSubsetOf(const ClassInfo &RHS) const {
395 // This is a subset of RHS if it is the same class...
396 if (this == &RHS)
397 return true;
398
399 // ... or if any of its super classes are a subset of RHS.
400 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
401 ie = SuperClasses.end(); it != ie; ++it)
402 if ((*it)->isSubsetOf(RHS))
403 return true;
404
405 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000406 }
407
Daniel Dunbar3239f022009-08-09 04:00:06 +0000408 /// operator< - Compare two classes.
409 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000410 if (this == &RHS)
411 return false;
412
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000413 // Unrelated classes can be ordered by kind.
414 if (!isRelatedTo(RHS))
Daniel Dunbar3239f022009-08-09 04:00:06 +0000415 return Kind < RHS.Kind;
416
417 switch (Kind) {
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000418 case Invalid:
419 assert(0 && "Invalid kind!");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000420 case Token:
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000421 // Tokens are comparable by value.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000422 //
423 // FIXME: Compare by enum value.
424 return ValueName < RHS.ValueName;
425
Daniel Dunbar3239f022009-08-09 04:00:06 +0000426 default:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000427 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000428 if (isSubsetOf(RHS))
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000429 return true;
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000430 if (RHS.isSubsetOf(*this))
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000431 return false;
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000432
433 // Otherwise, order by name to ensure we have a total ordering.
434 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000435 }
436 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000437};
438
Daniel Dunbar71330282009-08-08 05:24:34 +0000439/// InstructionInfo - Helper class for storing the necessary information for an
440/// instruction which is capable of being matched.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000441struct InstructionInfo {
442 struct Operand {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000443 /// The unique class instance this operand should match.
444 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000445
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000446 /// The original operand this corresponds to, if any.
Benjamin Kramer61130712009-08-08 10:06:30 +0000447 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000448 };
449
450 /// InstrName - The target name for this instruction.
451 std::string InstrName;
452
453 /// Instr - The instruction this matches.
454 const CodeGenInstruction *Instr;
455
456 /// AsmString - The assembly string for this instruction (with variants
457 /// removed).
458 std::string AsmString;
459
460 /// Tokens - The tokenized assembly pattern that this instruction matches.
461 SmallVector<StringRef, 4> Tokens;
462
463 /// Operands - The operands that this instruction matches.
464 SmallVector<Operand, 4> Operands;
465
Daniel Dunbareefe8612010-07-19 05:44:09 +0000466 /// Predicates - The required subtarget features to match this instruction.
467 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
468
Daniel Dunbar71330282009-08-08 05:24:34 +0000469 /// ConversionFnKind - The enum value which is passed to the generated
470 /// ConvertToMCInst to convert parsed operands into an MCInst for this
471 /// function.
472 std::string ConversionFnKind;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000473
Daniel Dunbar3239f022009-08-09 04:00:06 +0000474 /// operator< - Compare two instructions.
475 bool operator<(const InstructionInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000476 // The primary comparator is the instruction mnemonic.
477 if (Tokens[0] != RHS.Tokens[0])
478 return Tokens[0] < RHS.Tokens[0];
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000479
Daniel Dunbar3239f022009-08-09 04:00:06 +0000480 if (Operands.size() != RHS.Operands.size())
481 return Operands.size() < RHS.Operands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000482
Daniel Dunbard9631912009-08-09 08:23:23 +0000483 // Compare lexicographically by operand. The matcher validates that other
484 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
485 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000486 if (*Operands[i].Class < *RHS.Operands[i].Class)
487 return true;
Daniel Dunbard9631912009-08-09 08:23:23 +0000488 if (*RHS.Operands[i].Class < *Operands[i].Class)
489 return false;
490 }
491
Daniel Dunbar3239f022009-08-09 04:00:06 +0000492 return false;
493 }
494
Daniel Dunbarf573b562009-08-09 06:05:33 +0000495 /// CouldMatchAmiguouslyWith - Check whether this instruction could
496 /// ambiguously match the same set of operands as \arg RHS (without being a
497 /// strictly superior match).
498 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
499 // The number of operands is unambiguous.
500 if (Operands.size() != RHS.Operands.size())
501 return false;
502
Daniel Dunbare1974092010-01-23 00:26:16 +0000503 // Otherwise, make sure the ordering of the two instructions is unambiguous
504 // by checking that either (a) a token or operand kind discriminates them,
505 // or (b) the ordering among equivalent kinds is consistent.
506
Daniel Dunbarf573b562009-08-09 06:05:33 +0000507 // Tokens and operand kinds are unambiguous (assuming a correct target
508 // specific parser).
509 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
510 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
511 Operands[i].Class->Kind == ClassInfo::Token)
512 if (*Operands[i].Class < *RHS.Operands[i].Class ||
513 *RHS.Operands[i].Class < *Operands[i].Class)
514 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000515
Daniel Dunbarf573b562009-08-09 06:05:33 +0000516 // Otherwise, this operand could commute if all operands are equivalent, or
517 // there is a pair of operands that compare less than and a pair that
518 // compare greater than.
519 bool HasLT = false, HasGT = false;
520 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
521 if (*Operands[i].Class < *RHS.Operands[i].Class)
522 HasLT = true;
523 if (*RHS.Operands[i].Class < *Operands[i].Class)
524 HasGT = true;
525 }
526
527 return !(HasLT ^ HasGT);
528 }
529
Daniel Dunbare10787e2009-08-07 08:26:05 +0000530public:
531 void dump();
532};
533
Daniel Dunbareefe8612010-07-19 05:44:09 +0000534/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
535/// feature which participates in instruction matching.
536struct SubtargetFeatureInfo {
537 /// \brief The predicate record for this feature.
538 Record *TheDef;
539
540 /// \brief An unique index assigned to represent this feature.
541 unsigned Index;
542
Chris Lattnera0e87192010-10-30 20:07:57 +0000543 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
544
Daniel Dunbareefe8612010-07-19 05:44:09 +0000545 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattnera0e87192010-10-30 20:07:57 +0000546 std::string getEnumName() const {
547 return "Feature_" + TheDef->getName();
548 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000549};
550
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000551class AsmMatcherInfo {
552public:
Daniel Dunbare4318712009-08-11 20:59:47 +0000553 /// The tablegen AsmParser record.
554 Record *AsmParser;
555
556 /// The AsmParser "CommentDelimiter" value.
557 std::string CommentDelimiter;
558
559 /// The AsmParser "RegisterPrefix" value.
560 std::string RegisterPrefix;
561
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000562 /// The classes which are needed for matching.
563 std::vector<ClassInfo*> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000564
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000565 /// The information on the instruction to match.
566 std::vector<InstructionInfo*> Instructions;
567
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000568 /// Map of Register records to their class information.
569 std::map<Record*, ClassInfo*> RegisterClasses;
570
Daniel Dunbareefe8612010-07-19 05:44:09 +0000571 /// Map of Predicate records to their subtarget information.
572 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner43690072010-10-30 20:15:02 +0000573
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000574private:
575 /// Map of token to class information which has already been constructed.
576 std::map<std::string, ClassInfo*> TokenClasses;
577
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000578 /// Map of RegisterClass records to their class information.
579 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000580
Daniel Dunbar17410a42009-08-10 18:41:10 +0000581 /// Map of AsmOperandClass records to their class information.
582 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000583
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000584private:
585 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000586 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000587
588 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattner60db0a62010-02-09 00:34:28 +0000589 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000590 const CodeGenInstruction::OperandInfo &OI);
591
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000592 /// BuildRegisterClasses - Build the ClassInfo* instances for register
593 /// classes.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000594 void BuildRegisterClasses(CodeGenTarget &Target,
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000595 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000596
597 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
598 /// operand classes.
599 void BuildOperandClasses(CodeGenTarget &Target);
600
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000601public:
Daniel Dunbare4318712009-08-11 20:59:47 +0000602 AsmMatcherInfo(Record *_AsmParser);
603
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000604 /// BuildInfo - Construct the various tables used during matching.
605 void BuildInfo(CodeGenTarget &Target);
Chris Lattner43690072010-10-30 20:15:02 +0000606
607 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
608 /// given operand.
609 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
610 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
611 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
612 SubtargetFeatures.find(Def);
613 return I == SubtargetFeatures.end() ? 0 : I->second;
614 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000615};
616
Daniel Dunbare10787e2009-08-07 08:26:05 +0000617}
618
619void InstructionInfo::dump() {
620 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
621 << ", tokens:[";
622 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
623 errs() << Tokens[i];
624 if (i + 1 != e)
625 errs() << ", ";
626 }
627 errs() << "]\n";
628
629 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
630 Operand &Op = Operands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000631 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000632 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000633 errs() << '\"' << Tokens[i] << "\"\n";
634 continue;
635 }
636
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000637 if (!Op.OperandInfo) {
638 errs() << "(singleton register)\n";
639 continue;
640 }
641
Benjamin Kramer61130712009-08-08 10:06:30 +0000642 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000643 errs() << OI.Name << " " << OI.Rec->getName()
644 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
645 }
646}
647
Chris Lattner60db0a62010-02-09 00:34:28 +0000648static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000649 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000650
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000651 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
652 switch (*it) {
653 case '*': Res += "_STAR_"; break;
654 case '%': Res += "_PCT_"; break;
655 case ':': Res += "_COLON_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000656 default:
Chris Lattner33fc3e02010-10-31 19:10:56 +0000657 if (isalnum(*it))
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000658 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +0000659 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000660 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000661 }
662 }
663
664 return Res;
665}
666
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000667/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattner60db0a62010-02-09 00:34:28 +0000668static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000669 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
670 const CodeGenRegister &Reg = Target.getRegisters()[i];
671 if (Name == Reg.TheDef->getValueAsString("AsmName"))
672 return Reg.TheDef;
673 }
674
675 return 0;
676}
677
Chris Lattner60db0a62010-02-09 00:34:28 +0000678ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000679 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000680
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000681 if (!Entry) {
682 Entry = new ClassInfo();
683 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000684 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000685 Entry->Name = "MCK_" + getEnumNameForToken(Token);
686 Entry->ValueName = Token;
687 Entry->PredicateMethod = "<invalid>";
688 Entry->RenderMethod = "<invalid>";
689 Classes.push_back(Entry);
690 }
691
692 return Entry;
693}
694
695ClassInfo *
Chris Lattner60db0a62010-02-09 00:34:28 +0000696AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000697 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000698 if (OI.Rec->isSubClassOf("RegisterClass")) {
699 ClassInfo *CI = RegisterClassClasses[OI.Rec];
700
701 if (!CI) {
702 PrintError(OI.Rec->getLoc(), "register class has no class info!");
703 throw std::string("ERROR: Missing register class!");
704 }
705
706 return CI;
707 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000708
Daniel Dunbar17410a42009-08-10 18:41:10 +0000709 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
710 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
711 ClassInfo *CI = AsmOperandClasses[MatchClass];
712
713 if (!CI) {
714 PrintError(OI.Rec->getLoc(), "operand has no match class!");
715 throw std::string("ERROR: Missing match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000716 }
717
Daniel Dunbar17410a42009-08-10 18:41:10 +0000718 return CI;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000719}
720
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000721void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
722 std::set<std::string>
723 &SingletonRegisterNames) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000724 std::vector<CodeGenRegisterClass> RegisterClasses;
725 std::vector<CodeGenRegister> Registers;
Daniel Dunbar17410a42009-08-10 18:41:10 +0000726
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000727 RegisterClasses = Target.getRegisterClasses();
728 Registers = Target.getRegisters();
Daniel Dunbar17410a42009-08-10 18:41:10 +0000729
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000730 // The register sets used for matching.
731 std::set< std::set<Record*> > RegisterSets;
732
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000733 // Gather the defined sets.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000734 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
735 ie = RegisterClasses.end(); it != ie; ++it)
736 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
737 it->Elements.end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000738
739 // Add any required singleton sets.
740 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
741 ie = SingletonRegisterNames.end(); it != ie; ++it)
742 if (Record *Rec = getRegisterRecord(Target, *it))
743 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000744
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000745 // Introduce derived sets where necessary (when a register does not determine
746 // a unique register set class), and build the mapping of registers to the set
747 // they should classify to.
748 std::map<Record*, std::set<Record*> > RegisterMap;
749 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
750 ie = Registers.end(); it != ie; ++it) {
751 CodeGenRegister &CGR = *it;
752 // Compute the intersection of all sets containing this register.
753 std::set<Record*> ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000754
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000755 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
756 ie = RegisterSets.end(); it != ie; ++it) {
757 if (!it->count(CGR.TheDef))
758 continue;
759
760 if (ContainingSet.empty()) {
761 ContainingSet = *it;
762 } else {
763 std::set<Record*> Tmp;
764 std::swap(Tmp, ContainingSet);
765 std::insert_iterator< std::set<Record*> > II(ContainingSet,
766 ContainingSet.begin());
767 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
768 II);
769 }
770 }
771
772 if (!ContainingSet.empty()) {
773 RegisterSets.insert(ContainingSet);
774 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
775 }
776 }
777
778 // Construct the register classes.
779 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
780 unsigned Index = 0;
781 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
782 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
783 ClassInfo *CI = new ClassInfo();
784 CI->Kind = ClassInfo::RegisterClass0 + Index;
785 CI->ClassName = "Reg" + utostr(Index);
786 CI->Name = "MCK_Reg" + utostr(Index);
787 CI->ValueName = "";
788 CI->PredicateMethod = ""; // unused
789 CI->RenderMethod = "addRegOperands";
Daniel Dunbar34c87912009-08-11 20:10:07 +0000790 CI->Registers = *it;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000791 Classes.push_back(CI);
792 RegisterSetClasses.insert(std::make_pair(*it, CI));
793 }
794
795 // Find the superclasses; we could compute only the subgroup lattice edges,
796 // but there isn't really a point.
797 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
798 ie = RegisterSets.end(); it != ie; ++it) {
799 ClassInfo *CI = RegisterSetClasses[*it];
800 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
801 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000802 if (*it != *it2 &&
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000803 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
804 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
805 }
806
807 // Name the register classes which correspond to a user defined RegisterClass.
808 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
809 ie = RegisterClasses.end(); it != ie; ++it) {
810 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
811 it->Elements.end())];
812 if (CI->ValueName.empty()) {
813 CI->ClassName = it->getName();
814 CI->Name = "MCK_" + it->getName();
815 CI->ValueName = it->getName();
816 } else
817 CI->ValueName = CI->ValueName + "," + it->getName();
818
819 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
820 }
821
822 // Populate the map for individual registers.
823 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
824 ie = RegisterMap.end(); it != ie; ++it)
825 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000826
827 // Name the register classes which correspond to singleton registers.
828 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
829 ie = SingletonRegisterNames.end(); it != ie; ++it) {
830 if (Record *Rec = getRegisterRecord(Target, *it)) {
831 ClassInfo *CI = this->RegisterClasses[Rec];
832 assert(CI && "Missing singleton register class info!");
833
834 if (CI->ValueName.empty()) {
835 CI->ClassName = Rec->getName();
836 CI->Name = "MCK_" + Rec->getName();
837 CI->ValueName = Rec->getName();
838 } else
839 CI->ValueName = CI->ValueName + "," + Rec->getName();
840 }
841 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000842}
843
844void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar17410a42009-08-10 18:41:10 +0000845 std::vector<Record*> AsmOperands;
846 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +0000847
848 // Pre-populate AsmOperandClasses map.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000849 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbarcf181532010-01-30 01:02:37 +0000850 ie = AsmOperands.end(); it != ie; ++it)
851 AsmOperandClasses[*it] = new ClassInfo();
852
Daniel Dunbar17410a42009-08-10 18:41:10 +0000853 unsigned Index = 0;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000854 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar17410a42009-08-10 18:41:10 +0000855 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbarcf181532010-01-30 01:02:37 +0000856 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar17410a42009-08-10 18:41:10 +0000857 CI->Kind = ClassInfo::UserClass0 + Index;
858
Daniel Dunbar346782c2010-05-22 21:02:29 +0000859 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
860 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
861 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
862 if (!DI) {
863 PrintError((*it)->getLoc(), "Invalid super class reference!");
864 continue;
865 }
866
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000867 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
868 if (!SC)
Daniel Dunbar17410a42009-08-10 18:41:10 +0000869 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000870 else
871 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +0000872 }
873 CI->ClassName = (*it)->getValueAsString("Name");
874 CI->Name = "MCK_" + CI->ClassName;
875 CI->ValueName = (*it)->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +0000876
877 // Get or construct the predicate method name.
878 Init *PMName = (*it)->getValueInit("PredicateMethod");
879 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
880 CI->PredicateMethod = SI->getValue();
881 } else {
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000882 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +0000883 "Unexpected PredicateMethod field!");
884 CI->PredicateMethod = "is" + CI->ClassName;
885 }
886
887 // Get or construct the render method name.
888 Init *RMName = (*it)->getValueInit("RenderMethod");
889 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
890 CI->RenderMethod = SI->getValue();
891 } else {
892 assert(dynamic_cast<UnsetInit*>(RMName) &&
893 "Unexpected RenderMethod field!");
894 CI->RenderMethod = "add" + CI->ClassName + "Operands";
895 }
896
Daniel Dunbar17410a42009-08-10 18:41:10 +0000897 AsmOperandClasses[*it] = CI;
898 Classes.push_back(CI);
899 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000900}
901
Chris Lattnera0e87192010-10-30 20:07:57 +0000902AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
903 : AsmParser(asmParser),
Daniel Dunbare4318712009-08-11 20:59:47 +0000904 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
905 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
906{
907}
908
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000909void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Chris Lattnera0e87192010-10-30 20:07:57 +0000910 // Build information about all of the AssemblerPredicates.
911 std::vector<Record*> AllPredicates =
912 Records.getAllDerivedDefinitions("Predicate");
913 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
914 Record *Pred = AllPredicates[i];
915 // Ignore predicates that are not intended for the assembler.
916 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
917 continue;
918
919 if (Pred->getName().empty()) {
920 PrintError(Pred->getLoc(), "Predicate has no name!");
921 throw std::string("ERROR: Predicate defs must be named");
922 }
923
924 unsigned FeatureNo = SubtargetFeatures.size();
925 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
926 assert(FeatureNo < 32 && "Too many subtarget features!");
927 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000928
Chris Lattner33fc3e02010-10-31 19:10:56 +0000929 // Parse the instructions; we need to do this first so that we can gather the
930 // singleton register classes.
931 std::set<std::string> SingletonRegisterNames;
932 const std::vector<const CodeGenInstruction*> &InstrList =
933 Target.getInstructionsByEnumValue();
Chris Lattner70eb8972010-03-19 00:18:23 +0000934 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
935 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbare10787e2009-08-07 08:26:05 +0000936
Chris Lattner33fc3e02010-10-31 19:10:56 +0000937 // If the tblgen -match-prefix option is specified (for tblgen hackers),
938 // filter the set of instructions we consider.
Chris Lattner70eb8972010-03-19 00:18:23 +0000939 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbare10787e2009-08-07 08:26:05 +0000940 continue;
941
Chris Lattner70eb8972010-03-19 00:18:23 +0000942 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000943
Chris Lattner70eb8972010-03-19 00:18:23 +0000944 II->InstrName = CGI.TheDef->getName();
945 II->Instr = &CGI;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000946 II->AsmString = FlattenVariants(CGI.AsmString, 0);
947
Chris Lattner33fc3e02010-10-31 19:10:56 +0000948 // Remove comments from the asm string. We know that the asmstring only
949 // has one line.
Daniel Dunbare4318712009-08-11 20:59:47 +0000950 if (!CommentDelimiter.empty()) {
951 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
952 if (Idx != StringRef::npos)
953 II->AsmString = II->AsmString.substr(0, Idx);
954 }
955
Daniel Dunbare10787e2009-08-07 08:26:05 +0000956 TokenizeAsmString(II->AsmString, II->Tokens);
957
958 // Ignore instructions which shouldn't be matched.
Chris Lattner70eb8972010-03-19 00:18:23 +0000959 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbare10787e2009-08-07 08:26:05 +0000960 continue;
Chris Lattner33fc3e02010-10-31 19:10:56 +0000961
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000962 // Collect singleton registers, if used.
Chris Lattner1be06972010-10-28 21:28:42 +0000963 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
964 if (!II->Tokens[i].startswith(RegisterPrefix))
965 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000966
Chris Lattner1be06972010-10-28 21:28:42 +0000967 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
968 Record *Rec = getRegisterRecord(Target, RegName);
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000969
Chris Lattner1be06972010-10-28 21:28:42 +0000970 if (!Rec) {
971 // If there is no register prefix (i.e. "%" in "%eax"), then this may
972 // be some random non-register token, just ignore it.
973 if (RegisterPrefix.empty())
974 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000975
976 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner1be06972010-10-28 21:28:42 +0000977 "' (which matches register prefix)";
978 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000979 }
Chris Lattner1be06972010-10-28 21:28:42 +0000980
981 SingletonRegisterNames.insert(RegName);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000982 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000983
984 // Compute the require features.
Chris Lattneraac142c2010-10-30 19:38:20 +0000985 std::vector<Record*> Predicates =
986 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner43690072010-10-30 20:15:02 +0000987 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
988 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
989 II->RequiredFeatures.push_back(Feature);
Daniel Dunbareefe8612010-07-19 05:44:09 +0000990
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000991 Instructions.push_back(II.take());
992 }
993
994 // Build info for the register classes.
995 BuildRegisterClasses(Target, SingletonRegisterNames);
996
997 // Build info for the user defined assembly operand classes.
998 BuildOperandClasses(Target);
999
1000 // Build the instruction information.
1001 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
1002 ie = Instructions.end(); it != ie; ++it) {
1003 InstructionInfo *II = *it;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001004
Chris Lattner82d88ce2010-09-06 21:01:37 +00001005 // The first token of the instruction is the mnemonic, which must be a
1006 // simple string.
1007 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1008 StringRef Mnemonic = II->Tokens[0];
1009 assert(Mnemonic[0] != '$' &&
1010 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001011
Chris Lattner82d88ce2010-09-06 21:01:37 +00001012 // Parse the tokens after the mnemonic.
1013 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbare10787e2009-08-07 08:26:05 +00001014 StringRef Token = II->Tokens[i];
1015
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001016 // Check for singleton registers.
Chris Lattner1be06972010-10-28 21:28:42 +00001017 if (Token.startswith(RegisterPrefix)) {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001018 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
Chris Lattner1be06972010-10-28 21:28:42 +00001019 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1020 InstructionInfo::Operand Op;
1021 Op.Class = RegisterClasses[RegRecord];
1022 Op.OperandInfo = 0;
1023 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1024 "Unexpected class for singleton register");
1025 II->Operands.push_back(Op);
1026 continue;
1027 }
1028
1029 if (!RegisterPrefix.empty()) {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001030 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner1be06972010-10-28 21:28:42 +00001031 "' (which matches register prefix)";
1032 throw TGError(II->Instr->TheDef->getLoc(), Err);
1033 }
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001034 }
1035
Daniel Dunbare10787e2009-08-07 08:26:05 +00001036 // Check for simple tokens.
1037 if (Token[0] != '$') {
1038 InstructionInfo::Operand Op;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001039 Op.Class = getTokenClass(Token);
Benjamin Kramer61130712009-08-08 10:06:30 +00001040 Op.OperandInfo = 0;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001041 II->Operands.push_back(Op);
1042 continue;
1043 }
1044
1045 // Otherwise this is an operand reference.
Daniel Dunbare10787e2009-08-07 08:26:05 +00001046 StringRef OperandName;
1047 if (Token[1] == '{')
1048 OperandName = Token.substr(2, Token.size() - 3);
1049 else
1050 OperandName = Token.substr(1);
1051
1052 // Map this token to an operand. FIXME: Move elsewhere.
1053 unsigned Idx;
1054 try {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001055 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001056 } catch(...) {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001057 throw std::string("error: unable to find operand: '" +
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001058 OperandName.str() + "'");
Daniel Dunbare10787e2009-08-07 08:26:05 +00001059 }
1060
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001061 // FIXME: This is annoying, the named operand may be tied (e.g.,
1062 // XCHG8rm). What we want is the untied operand, which we now have to
1063 // grovel for. Only worry about this for single entry operands, we have to
1064 // clean this up anyway.
1065 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1066 if (OI->Constraints[0].isTied()) {
1067 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1068
1069 // The tied operand index is an MIOperand index, find the operand that
1070 // contains it.
1071 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1072 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1073 OI = &II->Instr->OperandList[i];
1074 break;
1075 }
1076 }
1077
1078 assert(OI && "Unable to find tied operand target!");
1079 }
1080
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001081 InstructionInfo::Operand Op;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001082 Op.Class = getOperandClass(Token, *OI);
1083 Op.OperandInfo = OI;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001084 II->Operands.push_back(Op);
1085 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001086 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001087
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001088 // Reorder classes so that classes preceed super classes.
1089 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbare10787e2009-08-07 08:26:05 +00001090}
1091
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001092static std::pair<unsigned, unsigned> *
1093GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1094 unsigned Index) {
1095 for (unsigned i = 0, e = List.size(); i != e; ++i)
1096 if (Index == List[i].first)
1097 return &List[i];
1098
1099 return 0;
1100}
1101
Daniel Dunbar3239f022009-08-09 04:00:06 +00001102static void EmitConvertToMCInst(CodeGenTarget &Target,
1103 std::vector<InstructionInfo*> &Infos,
1104 raw_ostream &OS) {
Daniel Dunbar71330282009-08-08 05:24:34 +00001105 // Write the convert function to a separate stream, so we can drop it after
1106 // the enum.
1107 std::string ConvertFnBody;
1108 raw_string_ostream CvtOS(ConvertFnBody);
1109
Daniel Dunbare10787e2009-08-07 08:26:05 +00001110 // Function we have already generated.
1111 std::set<std::string> GeneratedFns;
1112
Daniel Dunbar71330282009-08-08 05:24:34 +00001113 // Start the unified conversion function.
1114
Daniel Dunbar451a4352010-03-18 20:05:56 +00001115 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbar71330282009-08-08 05:24:34 +00001116 << "unsigned Opcode,\n"
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001117 << " const SmallVectorImpl<MCParsedAsmOperand*"
1118 << "> &Operands) {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001119 CvtOS << " Inst.setOpcode(Opcode);\n";
1120 CvtOS << " switch (Kind) {\n";
1121 CvtOS << " default:\n";
1122
1123 // Start the enum, which we will generate inline.
1124
1125 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001126 OS << "enum ConversionKind {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001127
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001128 // TargetOperandClass - This is the target's operand class, like X86Operand.
1129 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001130
Daniel Dunbare10787e2009-08-07 08:26:05 +00001131 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1132 ie = Infos.end(); it != ie; ++it) {
1133 InstructionInfo &II = **it;
1134
1135 // Order the (class) operands by the order to convert them into an MCInst.
1136 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1137 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1138 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer61130712009-08-08 10:06:30 +00001139 if (Op.OperandInfo)
1140 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbare10787e2009-08-07 08:26:05 +00001141 }
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001142
1143 // Find any tied operands.
1144 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1145 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1146 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1147 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1148 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1149 if (CI.isTied())
1150 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1151 CI.getTiedOperand()));
1152 }
1153 }
1154
Daniel Dunbare10787e2009-08-07 08:26:05 +00001155 std::sort(MIOperandList.begin(), MIOperandList.end());
1156
1157 // Compute the total number of operands.
1158 unsigned NumMIOperands = 0;
1159 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1160 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001161 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbare10787e2009-08-07 08:26:05 +00001162 OI.MIOperandNo + OI.MINumOperands);
1163 }
1164
1165 // Build the conversion function signature.
1166 std::string Signature = "Convert";
1167 unsigned CurIndex = 0;
1168 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1169 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer61130712009-08-08 10:06:30 +00001170 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbare10787e2009-08-07 08:26:05 +00001171 "Duplicate match for instruction operand!");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001172
Daniel Dunbare10787e2009-08-07 08:26:05 +00001173 // Skip operands which weren't matched by anything, this occurs when the
1174 // .td file encodes "implicit" operands as explicit ones.
1175 //
1176 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001177 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001178 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1179 CurIndex);
1180 if (!Tie)
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001181 Signature += "__Imp";
1182 else
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001183 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001184 }
1185
1186 Signature += "__";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001187
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001188 // Registers are always converted the same, don't duplicate the conversion
1189 // function based on them.
1190 //
1191 // FIXME: We could generalize this based on the render method, if it
1192 // mattered.
1193 if (Op.Class->isRegisterClass())
1194 Signature += "Reg";
1195 else
1196 Signature += Op.Class->ClassName;
Benjamin Kramer61130712009-08-08 10:06:30 +00001197 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbar71330282009-08-08 05:24:34 +00001198 Signature += "_" + utostr(MIOperandList[i].second);
1199
Benjamin Kramer61130712009-08-08 10:06:30 +00001200 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001201 }
1202
1203 // Add any trailing implicit operands.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001204 for (; CurIndex != NumMIOperands; ++CurIndex) {
1205 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1206 CurIndex);
1207 if (!Tie)
1208 Signature += "__Imp";
1209 else
1210 Signature += "__Tie" + utostr(Tie->second);
1211 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001212
Daniel Dunbar71330282009-08-08 05:24:34 +00001213 II.ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001214
Daniel Dunbar71330282009-08-08 05:24:34 +00001215 // Check if we have already generated this signature.
Daniel Dunbare10787e2009-08-07 08:26:05 +00001216 if (!GeneratedFns.insert(Signature).second)
1217 continue;
1218
1219 // If not, emit it now.
Daniel Dunbar71330282009-08-08 05:24:34 +00001220
1221 // Add to the enum list.
1222 OS << " " << Signature << ",\n";
1223
1224 // And to the convert function.
1225 CvtOS << " case " << Signature << ":\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001226 CurIndex = 0;
1227 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1228 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1229
1230 // Add the implicit operands.
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001231 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1232 // See if this is a tied operand.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001233 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1234 CurIndex);
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001235
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001236 if (!Tie) {
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001237 // If not, this is some implicit operand. Just assume it is a register
1238 // for now.
1239 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1240 } else {
1241 // Copy the tied operand.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001242 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001243 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001244 << Tie->second << "));\n";
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001245 }
1246 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001247
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001248 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001249 << MIOperandList[i].second
1250 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramer61130712009-08-08 10:06:30 +00001251 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1252 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001253 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001254
Daniel Dunbare10787e2009-08-07 08:26:05 +00001255 // And add trailing implicit operands.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001256 for (; CurIndex != NumMIOperands; ++CurIndex) {
1257 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1258 CurIndex);
1259
1260 if (!Tie) {
1261 // If not, this is some implicit operand. Just assume it is a register
1262 // for now.
1263 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1264 } else {
1265 // Copy the tied operand.
1266 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1267 CvtOS << " Inst.addOperand(Inst.getOperand("
1268 << Tie->second << "));\n";
1269 }
1270 }
1271
Daniel Dunbar451a4352010-03-18 20:05:56 +00001272 CvtOS << " return;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001273 }
Daniel Dunbar71330282009-08-08 05:24:34 +00001274
1275 // Finish the convert function.
1276
1277 CvtOS << " }\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001278 CvtOS << "}\n\n";
1279
1280 // Finish the enum, and drop the convert function after it.
1281
1282 OS << " NumConversionVariants\n";
1283 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001284
Daniel Dunbar71330282009-08-08 05:24:34 +00001285 OS << CvtOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001286}
1287
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001288/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1289static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1290 std::vector<ClassInfo*> &Infos,
1291 raw_ostream &OS) {
1292 OS << "namespace {\n\n";
1293
1294 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1295 << "/// instruction matching.\n";
1296 OS << "enum MatchClassKind {\n";
1297 OS << " InvalidMatchClass = 0,\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001298 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001299 ie = Infos.end(); it != ie; ++it) {
1300 ClassInfo &CI = **it;
1301 OS << " " << CI.Name << ", // ";
1302 if (CI.Kind == ClassInfo::Token) {
1303 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001304 } else if (CI.isRegisterClass()) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001305 if (!CI.ValueName.empty())
1306 OS << "register class '" << CI.ValueName << "'\n";
1307 else
1308 OS << "derived register class\n";
1309 } else {
1310 OS << "user defined class '" << CI.ValueName << "'\n";
1311 }
1312 }
1313 OS << " NumMatchClassKinds\n";
1314 OS << "};\n\n";
1315
1316 OS << "}\n\n";
1317}
1318
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001319/// EmitClassifyOperand - Emit the function to classify an operand.
1320static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001321 AsmMatcherInfo &Info,
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001322 raw_ostream &OS) {
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001323 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1324 << " " << Target.getName() << "Operand &Operand = *("
1325 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001326
1327 // Classify tokens.
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001328 OS << " if (Operand.isToken())\n";
1329 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001330
1331 // Classify registers.
1332 //
1333 // FIXME: Don't hardcode isReg, getReg.
1334 OS << " if (Operand.isReg()) {\n";
1335 OS << " switch (Operand.getReg()) {\n";
1336 OS << " default: return InvalidMatchClass;\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001337 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001338 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1339 it != ie; ++it)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001340 OS << " case " << Target.getName() << "::"
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001341 << it->first->getName() << ": return " << it->second->Name << ";\n";
1342 OS << " }\n";
1343 OS << " }\n\n";
1344
1345 // Classify user defined operands.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001346 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001347 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001348 ClassInfo &CI = **it;
1349
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001350 if (!CI.isUserClass())
1351 continue;
1352
1353 OS << " // '" << CI.ClassName << "' class";
1354 if (!CI.SuperClasses.empty()) {
1355 OS << ", subclass of ";
1356 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1357 if (i) OS << ", ";
1358 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1359 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001360 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001361 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001362 OS << "\n";
1363
1364 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001365
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001366 // Validate subclass relationships.
1367 if (!CI.SuperClasses.empty()) {
1368 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1369 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1370 << "() && \"Invalid class relationship!\");\n";
1371 }
1372
1373 OS << " return " << CI.Name << ";\n";
1374 OS << " }\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001375 }
1376 OS << " return InvalidMatchClass;\n";
1377 OS << "}\n\n";
1378}
1379
Daniel Dunbar2587b612009-08-10 16:05:47 +00001380/// EmitIsSubclass - Emit the subclass predicate function.
1381static void EmitIsSubclass(CodeGenTarget &Target,
1382 std::vector<ClassInfo*> &Infos,
1383 raw_ostream &OS) {
1384 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1385 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1386 OS << " if (A == B)\n";
1387 OS << " return true;\n\n";
1388
1389 OS << " switch (A) {\n";
1390 OS << " default:\n";
1391 OS << " return false;\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001392 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar2587b612009-08-10 16:05:47 +00001393 ie = Infos.end(); it != ie; ++it) {
1394 ClassInfo &A = **it;
1395
1396 if (A.Kind != ClassInfo::Token) {
1397 std::vector<StringRef> SuperClasses;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001398 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar2587b612009-08-10 16:05:47 +00001399 ie = Infos.end(); it != ie; ++it) {
1400 ClassInfo &B = **it;
1401
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001402 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar2587b612009-08-10 16:05:47 +00001403 SuperClasses.push_back(B.Name);
1404 }
1405
1406 if (SuperClasses.empty())
1407 continue;
1408
1409 OS << "\n case " << A.Name << ":\n";
1410
1411 if (SuperClasses.size() == 1) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001412 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001413 continue;
1414 }
1415
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001416 OS << " switch (B) {\n";
1417 OS << " default: return false;\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001418 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001419 OS << " case " << SuperClasses[i] << ": return true;\n";
1420 OS << " }\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001421 }
1422 }
1423 OS << " }\n";
1424 OS << "}\n\n";
1425}
1426
Chris Lattner00e2e742009-08-08 20:02:57 +00001427
1428
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001429/// EmitMatchTokenString - Emit the function to match a token string to the
1430/// appropriate match class value.
1431static void EmitMatchTokenString(CodeGenTarget &Target,
1432 std::vector<ClassInfo*> &Infos,
1433 raw_ostream &OS) {
1434 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00001435 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001436 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001437 ie = Infos.end(); it != ie; ++it) {
1438 ClassInfo &CI = **it;
1439
1440 if (CI.Kind == ClassInfo::Token)
Chris Lattnerca5a3552010-09-06 02:01:51 +00001441 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1442 "return " + CI.Name + ";"));
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001443 }
1444
Chris Lattner60db0a62010-02-09 00:34:28 +00001445 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001446
Chris Lattnerca5a3552010-09-06 02:01:51 +00001447 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001448
1449 OS << " return InvalidMatchClass;\n";
1450 OS << "}\n\n";
1451}
Chris Lattner00e2e742009-08-08 20:02:57 +00001452
Daniel Dunbard0470d72009-08-07 21:01:44 +00001453/// EmitMatchRegisterName - Emit the function to match a string to the target
1454/// specific register enum.
1455static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1456 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001457 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00001458 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001459 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1460 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbare2eec052009-07-17 18:51:11 +00001461 if (Reg.TheDef->getValueAsString("AsmName").empty())
1462 continue;
1463
Chris Lattnerca5a3552010-09-06 02:01:51 +00001464 Matches.push_back(StringMatcher::StringPair(
1465 Reg.TheDef->getValueAsString("AsmName"),
1466 "return " + utostr(i + 1) + ";"));
Daniel Dunbare2eec052009-07-17 18:51:11 +00001467 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001468
Chris Lattner60db0a62010-02-09 00:34:28 +00001469 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001470
Chris Lattnerca5a3552010-09-06 02:01:51 +00001471 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001472
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001473 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001474 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00001475}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001476
Daniel Dunbareefe8612010-07-19 05:44:09 +00001477/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1478/// definitions.
1479static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1480 AsmMatcherInfo &Info,
1481 raw_ostream &OS) {
1482 OS << "// Flags for subtarget features that participate in "
1483 << "instruction matching.\n";
1484 OS << "enum SubtargetFeatureFlag {\n";
1485 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1486 it = Info.SubtargetFeatures.begin(),
1487 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1488 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattnera0e87192010-10-30 20:07:57 +00001489 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001490 }
1491 OS << " Feature_None = 0\n";
1492 OS << "};\n\n";
1493}
1494
1495/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1496/// available features given a subtarget.
1497static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1498 AsmMatcherInfo &Info,
1499 raw_ostream &OS) {
1500 std::string ClassName =
1501 Info.AsmParser->getValueAsString("AsmParserClassName");
1502
1503 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1504 << "ComputeAvailableFeatures(const " << Target.getName()
1505 << "Subtarget *Subtarget) const {\n";
1506 OS << " unsigned Features = 0;\n";
1507 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1508 it = Info.SubtargetFeatures.begin(),
1509 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1510 SubtargetFeatureInfo &SFI = *it->second;
1511 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1512 << ")\n";
Chris Lattnera0e87192010-10-30 20:07:57 +00001513 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001514 }
1515 OS << " return Features;\n";
1516 OS << "}\n\n";
1517}
1518
Chris Lattner43690072010-10-30 20:15:02 +00001519static std::string GetAliasRequiredFeatures(Record *R,
1520 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00001521 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00001522 std::string Result;
1523 unsigned NumFeatures = 0;
1524 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner43690072010-10-30 20:15:02 +00001525 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1526 if (NumFeatures)
1527 Result += '|';
Chris Lattner2cb092d2010-10-30 19:23:13 +00001528
Chris Lattner43690072010-10-30 20:15:02 +00001529 Result += F->getEnumName();
1530 ++NumFeatures;
1531 }
Chris Lattner2cb092d2010-10-30 19:23:13 +00001532 }
1533
1534 if (NumFeatures > 1)
1535 Result = '(' + Result + ')';
1536 return Result;
1537}
1538
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001539/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner477fba4f2010-10-30 18:48:18 +00001540/// emit a function for them and return true, otherwise return false.
Chris Lattnera0e87192010-10-30 20:07:57 +00001541static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001542 std::vector<Record*> Aliases =
1543 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner477fba4f2010-10-30 18:48:18 +00001544 if (Aliases.empty()) return false;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001545
Chris Lattnerec563972010-10-30 18:57:07 +00001546 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1547 "unsigned Features) {\n";
1548
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001549 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1550 // iteration order of the map is stable.
1551 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1552
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001553 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1554 Record *R = Aliases[i];
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001555 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001556 }
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001557
1558 // Process each alias a "from" mnemonic at a time, building the code executed
1559 // by the string remapper.
1560 std::vector<StringMatcher::StringPair> Cases;
1561 for (std::map<std::string, std::vector<Record*> >::iterator
1562 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1563 I != E; ++I) {
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001564 const std::vector<Record*> &ToVec = I->second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00001565
1566 // Loop through each alias and emit code that handles each case. If there
1567 // are two instructions without predicates, emit an error. If there is one,
1568 // emit it last.
1569 std::string MatchCode;
1570 int AliasWithNoPredicate = -1;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001571
Chris Lattner2cb092d2010-10-30 19:23:13 +00001572 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1573 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00001574 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner2cb092d2010-10-30 19:23:13 +00001575
1576 // If this unconditionally matches, remember it for later and diagnose
1577 // duplicates.
1578 if (FeatureMask.empty()) {
1579 if (AliasWithNoPredicate != -1) {
1580 // We can't have two aliases from the same mnemonic with no predicate.
1581 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1582 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001583 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1584 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner2cb092d2010-10-30 19:23:13 +00001585 }
1586
1587 AliasWithNoPredicate = i;
1588 continue;
1589 }
1590
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001591 if (!MatchCode.empty())
1592 MatchCode += "else ";
Chris Lattner2cb092d2010-10-30 19:23:13 +00001593 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1594 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001595 }
1596
Chris Lattner2cb092d2010-10-30 19:23:13 +00001597 if (AliasWithNoPredicate != -1) {
1598 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001599 if (!MatchCode.empty())
1600 MatchCode += "else\n ";
1601 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00001602 }
1603
1604 MatchCode += "return;";
1605
1606 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001607 }
1608
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001609
1610 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner477fba4f2010-10-30 18:48:18 +00001611 OS << "}\n";
1612
1613 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001614}
1615
Daniel Dunbard0470d72009-08-07 21:01:44 +00001616void AsmMatcherEmitter::run(raw_ostream &OS) {
1617 CodeGenTarget Target;
1618 Record *AsmParser = Target.getAsmParser();
1619 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1620
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001621 // Compute the information on the instructions to match.
Daniel Dunbare4318712009-08-11 20:59:47 +00001622 AsmMatcherInfo Info(AsmParser);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001623 Info.BuildInfo(Target);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001624
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00001625 // Sort the instruction table using the partial order on classes. We use
1626 // stable_sort to ensure that ambiguous instructions are still
1627 // deterministically ordered.
1628 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1629 less_ptr<InstructionInfo>());
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001630
Daniel Dunbar71330282009-08-08 05:24:34 +00001631 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001632 for (std::vector<InstructionInfo*>::iterator
1633 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001634 it != ie; ++it)
Daniel Dunbare10787e2009-08-07 08:26:05 +00001635 (*it)->dump();
1636 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001637
Daniel Dunbar3239f022009-08-09 04:00:06 +00001638 // Check for ambiguous instructions.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001639 DEBUG_WITH_TYPE("ambiguous_instrs", {
1640 unsigned NumAmbiguous = 0;
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001641 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1642 for (unsigned j = i + 1; j != e; ++j) {
1643 InstructionInfo &A = *Info.Instructions[i];
1644 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001645
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001646 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001647 errs() << "warning: ambiguous instruction match:\n";
1648 A.dump();
1649 errs() << "\nis incomparable with:\n";
1650 B.dump();
1651 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001652 ++NumAmbiguous;
1653 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00001654 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00001655 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001656 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001657 errs() << "warning: " << NumAmbiguous
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001658 << " ambiguous instructions!\n";
1659 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00001660
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001661 // Write the output.
1662
1663 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1664
Chris Lattner3e4582a2010-09-06 19:11:01 +00001665 // Information for the class declaration.
1666 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1667 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001668 OS << " // This should be included into the middle of the declaration of \n";
1669 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner3e4582a2010-09-06 19:11:01 +00001670 OS << " unsigned ComputeAvailableFeatures(const " <<
1671 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001672 OS << " enum MatchResultTy {\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001673 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1674 OS << " Match_MissingFeature\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001675 OS << " };\n";
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00001676 OS << " MatchResultTy MatchInstructionImpl(const "
1677 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattner339cc7b2010-09-06 22:11:18 +00001678 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner3e4582a2010-09-06 19:11:01 +00001679 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1680
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001681
1682
1683
Chris Lattner3e4582a2010-09-06 19:11:01 +00001684 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1685 OS << "#undef GET_REGISTER_MATCHER\n\n";
1686
Daniel Dunbareefe8612010-07-19 05:44:09 +00001687 // Emit the subtarget feature enumeration.
1688 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1689
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001690 // Emit the function to match a register name to number.
1691 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00001692
1693 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001694
Chris Lattner3e4582a2010-09-06 19:11:01 +00001695
1696 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1697 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001698
Chris Lattner477fba4f2010-10-30 18:48:18 +00001699 // Generate the function that remaps for mnemonic aliases.
Chris Lattnera0e87192010-10-30 20:07:57 +00001700 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner477fba4f2010-10-30 18:48:18 +00001701
Daniel Dunbar3239f022009-08-09 04:00:06 +00001702 // Generate the unified function to convert operands into an MCInst.
1703 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001704
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001705 // Emit the enumeration for classes which participate in matching.
1706 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001707
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001708 // Emit the routine to match token strings to their match class.
1709 EmitMatchTokenString(Target, Info.Classes, OS);
1710
1711 // Emit the routine to classify an operand.
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001712 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001713
Daniel Dunbar2587b612009-08-10 16:05:47 +00001714 // Emit the subclass predicate routine.
1715 EmitIsSubclass(Target, Info.Classes, OS);
1716
Daniel Dunbareefe8612010-07-19 05:44:09 +00001717 // Emit the available features compute function.
1718 EmitComputeAvailableFeatures(Target, Info, OS);
1719
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001720
1721 size_t MaxNumOperands = 0;
1722 for (std::vector<InstructionInfo*>::const_iterator it =
1723 Info.Instructions.begin(), ie = Info.Instructions.end();
1724 it != ie; ++it)
1725 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001726
1727
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001728 // Emit the static match table; unused classes get initalized to 0 which is
1729 // guaranteed to be InvalidMatchClass.
1730 //
1731 // FIXME: We can reduce the size of this table very easily. First, we change
1732 // it so that store the kinds in separate bit-fields for each index, which
1733 // only needs to be the max width used for classes at that index (we also need
1734 // to reject based on this during classification). If we then make sure to
1735 // order the match kinds appropriately (putting mnemonics last), then we
1736 // should only end up using a few bits for each class, especially the ones
1737 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001738 OS << "namespace {\n";
1739 OS << " struct MatchEntry {\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001740 OS << " unsigned Opcode;\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001741 OS << " const char *Mnemonic;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001742 OS << " ConversionKind ConvertFn;\n";
1743 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001744 OS << " unsigned RequiredFeatures;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001745 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001746
Chris Lattner81301972010-09-06 21:22:45 +00001747 OS << "// Predicate for searching for an opcode.\n";
1748 OS << " struct LessOpcode {\n";
1749 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1750 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1751 OS << " }\n";
1752 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1753 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1754 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00001755 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1756 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1757 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001758 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001759
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001760 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001761
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001762 OS << "static const MatchEntry MatchTable["
1763 << Info.Instructions.size() << "] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001764
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001765 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001766 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001767 it != ie; ++it) {
Daniel Dunbare10787e2009-08-07 08:26:05 +00001768 InstructionInfo &II = **it;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001769
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001770 OS << " { " << Target.getName() << "::" << II.InstrName
1771 << ", \"" << II.Tokens[0] << "\""
1772 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001773 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1774 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001775
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001776 if (i) OS << ", ";
1777 OS << Op.Class->Name;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001778 }
Daniel Dunbareefe8612010-07-19 05:44:09 +00001779 OS << " }, ";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001780
Daniel Dunbareefe8612010-07-19 05:44:09 +00001781 // Write the required features mask.
1782 if (!II.RequiredFeatures.empty()) {
1783 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1784 if (i) OS << "|";
Chris Lattnera0e87192010-10-30 20:07:57 +00001785 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbareefe8612010-07-19 05:44:09 +00001786 }
1787 } else
1788 OS << "0";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001789
Daniel Dunbareefe8612010-07-19 05:44:09 +00001790 OS << "},\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001791 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001792
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001793 OS << "};\n\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001794
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001795 // Finally, build the match function.
1796 OS << Target.getName() << ClassName << "::MatchResultTy "
1797 << Target.getName() << ClassName << "::\n"
1798 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1799 << " &Operands,\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001800 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001801
1802 // Emit code to get the available features.
1803 OS << " // Get the current feature set.\n";
1804 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1805
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001806 OS << " // Get the instruction mnemonic, which is the first token.\n";
1807 OS << " StringRef Mnemonic = ((" << Target.getName()
1808 << "Operand*)Operands[0])->getToken();\n\n";
1809
Chris Lattner477fba4f2010-10-30 18:48:18 +00001810 if (HasMnemonicAliases) {
1811 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1812 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1813 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001814
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001815 // Emit code to compute the class list for this operand vector.
1816 OS << " // Eliminate obvious mismatches.\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001817 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1818 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1819 OS << " return Match_InvalidOperand;\n";
1820 OS << " }\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001821
1822 OS << " // Compute the class list for this operand vector.\n";
1823 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001824 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1825 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001826
1827 OS << " // Check for invalid operands before matching.\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001828 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1829 OS << " ErrorInfo = i;\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001830 OS << " return Match_InvalidOperand;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001831 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001832 OS << " }\n\n";
1833
1834 OS << " // Mark unused classes.\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001835 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001836 << "i != e; ++i)\n";
1837 OS << " Classes[i] = InvalidMatchClass;\n\n";
1838
Chris Lattnerabfe4222010-09-06 23:37:39 +00001839 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner81301972010-09-06 21:22:45 +00001840 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001841 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1842 OS << " // wrong for all instances of the instruction.\n";
1843 OS << " ErrorInfo = ~0U;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001844
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001845 // Emit code to search the table.
1846 OS << " // Search the table.\n";
Chris Lattner81301972010-09-06 21:22:45 +00001847 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1848 OS << " std::equal_range(MatchTable, MatchTable+"
1849 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001850
Chris Lattner628fbec2010-09-06 21:54:15 +00001851 OS << " // Return a more specific error code if no mnemonics match.\n";
1852 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1853 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001854
Chris Lattner81301972010-09-06 21:22:45 +00001855 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00001856 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001857 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001858
Gabor Greif7f3ce252010-09-07 06:06:06 +00001859 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattnerc4521d12010-09-06 21:25:43 +00001860 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001861
Daniel Dunbareefe8612010-07-19 05:44:09 +00001862 // Emit check that the subclasses match.
Chris Lattner339cc7b2010-09-06 22:11:18 +00001863 OS << " bool OperandsValid = true;\n";
1864 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1865 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1866 OS << " continue;\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001867 OS << " // If this operand is broken for all of the instances of this\n";
1868 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1869 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001870 OS << " ErrorInfo = i+1;\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001871 OS << " else\n";
1872 OS << " ErrorInfo = ~0U;";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001873 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1874 OS << " OperandsValid = false;\n";
1875 OS << " break;\n";
1876 OS << " }\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001877
Chris Lattner339cc7b2010-09-06 22:11:18 +00001878 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00001879
1880 // Emit check that the required features are available.
1881 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1882 << "!= it->RequiredFeatures) {\n";
1883 OS << " HadMatchOtherThanFeatures = true;\n";
1884 OS << " continue;\n";
1885 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001886
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001887 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00001888 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1889
1890 // Call the post-processing function, if used.
1891 std::string InsnCleanupFn =
1892 AsmParser->getValueAsString("AsmParserInstCleanup");
1893 if (!InsnCleanupFn.empty())
1894 OS << " " << InsnCleanupFn << "(Inst);\n";
1895
Chris Lattnera22a3682010-09-06 19:22:17 +00001896 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001897 OS << " }\n\n";
1898
Chris Lattnerb4be28f2010-09-06 20:08:02 +00001899 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1900 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001901 OS << " return Match_InvalidOperand;\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001902 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001903
Chris Lattner3e4582a2010-09-06 19:11:01 +00001904 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00001905}