blob: cbe214d3f31a3e41b7c8643c558734518aa8d7f2 [file] [log] [blame]
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
11// assembly operands in the MCInst structures.
12//
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000013// The input to the target specific matcher is a list of literal tokens and
14// operands. The target specific parser should generally eliminate any syntax
15// which is not relevant for matching; for example, comma tokens should have
16// already been consumed and eliminated by the parser. Most instructions will
17// end up with a single literal token (the instruction name) and some number of
18// operands.
19//
20// Some example inputs, for X86:
21// 'addl' (immediate ...) (register ...)
22// 'add' (immediate ...) (memory ...)
23// 'call' '*' %epc
24//
25// The assembly matcher is responsible for converting this input into a precise
26// machine instruction (i.e., an instruction with a well defined encoding). This
27// mapping has several properties which complicate matching:
28//
29// - It may be ambiguous; many architectures can legally encode particular
30// variants of an instruction in different ways (for example, using a smaller
31// encoding for small immediates). Such ambiguities should never be
32// arbitrarily resolved by the assembler, the assembler is always responsible
33// for choosing the "best" available instruction.
34//
35// - It may depend on the subtarget or the assembler context. Instructions
36// which are invalid for the current mode, but otherwise unambiguous (e.g.,
37// an SSE instruction in a file being assembled for i486) should be accepted
38// and rejected by the assembler front end. However, if the proper encoding
39// for an instruction is dependent on the assembler context then the matcher
40// is responsible for selecting the correct machine instruction for the
41// current mode.
42//
43// The core matching algorithm attempts to exploit the regularity in most
44// instruction sets to quickly determine the set of possibly matching
45// instructions, and the simplify the generated code. Additionally, this helps
46// to ensure that the ambiguities are intentionally resolved by the user.
47//
48// The matching is divided into two distinct phases:
49//
50// 1. Classification: Each operand is mapped to the unique set which (a)
51// contains it, and (b) is the largest such subset for which a single
52// instruction could match all members.
53//
54// For register classes, we can generate these subgroups automatically. For
55// arbitrary operands, we expect the user to define the classes and their
56// relations to one another (for example, 8-bit signed immediates as a
57// subset of 32-bit immediates).
58//
59// By partitioning the operands in this way, we guarantee that for any
60// tuple of classes, any single instruction must match either all or none
61// of the sets of operands which could classify to that tuple.
62//
63// In addition, the subset relation amongst classes induces a partial order
64// on such tuples, which we use to resolve ambiguities.
65//
66// FIXME: What do we do if a crazy case shows up where this is the wrong
67// resolution?
68//
69// 2. The input can now be treated as a tuple of classes (static tokens are
70// simple singleton sets). Each such tuple should generally map to a single
71// instruction (we currently ignore cases where this isn't true, whee!!!),
72// which we can emit a simple matcher for.
73//
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000079#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000080#include "llvm/ADT/SmallVector.h"
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000081#include "llvm/ADT/STLExtras.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000082#include "llvm/ADT/StringExtras.h"
83#include "llvm/Support/CommandLine.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000084#include "llvm/Support/Debug.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000085#include <list>
Daniel Dunbarce82b992009-08-08 05:24:34 +000086#include <map>
87#include <set>
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +000088using namespace llvm;
89
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000090namespace {
Daniel Dunbar62beebc2009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000094}
95
Daniel Dunbara54716c2009-07-31 02:32:59 +000096/// FlattenVariants - Flatten an .td file assembly string by selecting the
97/// variant at index \arg N.
98static std::string FlattenVariants(const std::string &AsmString,
99 unsigned N) {
100 StringRef Cur = AsmString;
101 std::string Res = "";
102
103 for (;;) {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000104 // Find the start of the next variant string.
105 size_t VariantsStart = 0;
106 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
107 if (Cur[VariantsStart] == '{' &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000108 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
109 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000110 break;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000111
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000112 // Add the prefix to the result.
113 Res += Cur.slice(0, VariantsStart);
114 if (VariantsStart == Cur.size())
Daniel Dunbara54716c2009-07-31 02:32:59 +0000115 break;
116
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000117 ++VariantsStart; // Skip the '{'.
118
119 // Scan to the end of the variants string.
120 size_t VariantsEnd = VariantsStart;
121 unsigned NestedBraces = 1;
122 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000123 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000124 if (--NestedBraces == 0)
125 break;
126 } else if (Cur[VariantsEnd] == '{')
127 ++NestedBraces;
128 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000129
130 // Select the Nth variant (or empty).
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000131 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000132 for (unsigned i = 0; i != N; ++i)
133 Selection = Selection.split('|').second;
134 Res += Selection.split('|').first;
135
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000136 assert(VariantsEnd != Cur.size() &&
137 "Unterminated variants in assembly string!");
138 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000139 }
140
141 return Res;
142}
143
144/// TokenizeAsmString - Tokenize a simplified assembly string.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000145static void TokenizeAsmString(const StringRef &AsmString,
Daniel Dunbara54716c2009-07-31 02:32:59 +0000146 SmallVectorImpl<StringRef> &Tokens) {
147 unsigned Prev = 0;
148 bool InTok = true;
149 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
150 switch (AsmString[i]) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000151 case '[':
152 case ']':
Daniel Dunbara54716c2009-07-31 02:32:59 +0000153 case '*':
154 case '!':
155 case ' ':
156 case '\t':
157 case ',':
158 if (InTok) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000159 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000160 InTok = false;
161 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000162 if (!isspace(AsmString[i]) && AsmString[i] != ',')
163 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000164 Prev = i + 1;
165 break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000166
167 case '\\':
168 if (InTok) {
169 Tokens.push_back(AsmString.slice(Prev, i));
170 InTok = false;
171 }
172 ++i;
173 assert(i != AsmString.size() && "Invalid quoted character");
174 Tokens.push_back(AsmString.substr(i, 1));
175 Prev = i + 1;
176 break;
177
178 case '$': {
179 // If this isn't "${", treat like a normal token.
180 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
181 if (InTok) {
182 Tokens.push_back(AsmString.slice(Prev, i));
183 InTok = false;
184 }
185 Prev = i;
186 break;
187 }
188
189 if (InTok) {
190 Tokens.push_back(AsmString.slice(Prev, i));
191 InTok = false;
192 }
193
194 StringRef::iterator End =
195 std::find(AsmString.begin() + i, AsmString.end(), '}');
196 assert(End != AsmString.end() && "Missing brace in operand reference!");
197 size_t EndPos = End - AsmString.begin();
198 Tokens.push_back(AsmString.slice(i, EndPos+1));
199 Prev = EndPos + 1;
200 i = EndPos;
201 break;
202 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000203
204 default:
205 InTok = true;
206 }
207 }
208 if (InTok && Prev != AsmString.size())
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000209 Tokens.push_back(AsmString.substr(Prev));
210}
211
212static bool IsAssemblerInstruction(const StringRef &Name,
213 const CodeGenInstruction &CGI,
214 const SmallVectorImpl<StringRef> &Tokens) {
215 // Ignore psuedo ops.
216 //
217 // FIXME: This is a hack.
218 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
219 if (Form->getValue()->getAsString() == "Pseudo")
220 return false;
221
222 // Ignore "PHI" node.
223 //
224 // FIXME: This is also a hack.
225 if (Name == "PHI")
226 return false;
227
228 // Ignore instructions with no .s string.
229 //
230 // FIXME: What are these?
231 if (CGI.AsmString.empty())
232 return false;
233
234 // FIXME: Hack; ignore any instructions with a newline in them.
235 if (std::find(CGI.AsmString.begin(),
236 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
237 return false;
238
239 // Ignore instructions with attributes, these are always fake instructions for
240 // simplifying codegen.
241 //
242 // FIXME: Is this true?
243 //
244 // Also, we ignore instructions which reference the operand multiple times;
245 // this implies a constraint we would not currently honor. These are
246 // currently always fake instructions for simplifying codegen.
247 //
248 // FIXME: Encode this assumption in the .td, so we can error out here.
249 std::set<std::string> OperandNames;
250 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251 if (Tokens[i][0] == '$' &&
252 std::find(Tokens[i].begin(),
253 Tokens[i].end(), ':') != Tokens[i].end()) {
254 DEBUG({
255 errs() << "warning: '" << Name << "': "
256 << "ignoring instruction; operand with attribute '"
257 << Tokens[i] << "', \n";
258 });
259 return false;
260 }
261
262 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
263 DEBUG({
264 errs() << "warning: '" << Name << "': "
265 << "ignoring instruction; tied operand '"
266 << Tokens[i] << "', \n";
267 });
268 return false;
269 }
270 }
271
272 return true;
273}
274
275namespace {
276
Daniel Dunbar378bee92009-08-08 07:50:56 +0000277/// ClassInfo - Helper class for storing the information about a particular
278/// class of operands which can be matched.
279struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000280 enum ClassInfoKind {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000281 Invalid = 0, ///< Invalid kind, for use as a sentinel value.
282 Token, ///< The class for a particular token.
283 Register, ///< A register class.
284 UserClass0 ///< The (first) user defined class, subsequent user defined
285 /// classes are UserClass0+1, and so on.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000286 };
287
288 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
289 /// N) for the Nth user defined class.
290 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000291
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000292 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000293 std::string Name;
294
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000295 /// ClassName - The unadorned generic name for this class (e.g., Token).
296 std::string ClassName;
297
Daniel Dunbar378bee92009-08-08 07:50:56 +0000298 /// ValueName - The name of the value this class represents; for a token this
299 /// is the literal token string, for an operand it is the TableGen class (or
300 /// empty if this is a derived class).
301 std::string ValueName;
302
303 /// PredicateMethod - The name of the operand method to test whether the
304 /// operand matches this class; this is not valid for Token kinds.
305 std::string PredicateMethod;
306
307 /// RenderMethod - The name of the operand method to add this operand to an
308 /// MCInst; this is not valid for Token kinds.
309 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000310
311 /// operator< - Compare two classes.
312 bool operator<(const ClassInfo &RHS) const {
313 // Incompatible kinds are comparable.
314 if (Kind != RHS.Kind)
315 return Kind < RHS.Kind;
316
317 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000318 case Invalid:
319 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000320 case Token:
321 // Tokens are always comparable.
322 //
323 // FIXME: Compare by enum value.
324 return ValueName < RHS.ValueName;
325
326 case Register:
327 // FIXME: Compare by subset relation.
328 return false;
329
330 default:
331 // FIXME: Allow user defined relation.
332 return false;
333 }
334 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000335};
336
Daniel Dunbarce82b992009-08-08 05:24:34 +0000337/// InstructionInfo - Helper class for storing the necessary information for an
338/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000339struct InstructionInfo {
340 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000341 /// The unique class instance this operand should match.
342 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000343
Daniel Dunbar378bee92009-08-08 07:50:56 +0000344 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000345 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000346 };
347
348 /// InstrName - The target name for this instruction.
349 std::string InstrName;
350
351 /// Instr - The instruction this matches.
352 const CodeGenInstruction *Instr;
353
354 /// AsmString - The assembly string for this instruction (with variants
355 /// removed).
356 std::string AsmString;
357
358 /// Tokens - The tokenized assembly pattern that this instruction matches.
359 SmallVector<StringRef, 4> Tokens;
360
361 /// Operands - The operands that this instruction matches.
362 SmallVector<Operand, 4> Operands;
363
Daniel Dunbarce82b992009-08-08 05:24:34 +0000364 /// ConversionFnKind - The enum value which is passed to the generated
365 /// ConvertToMCInst to convert parsed operands into an MCInst for this
366 /// function.
367 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000368
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000369 /// operator< - Compare two instructions.
370 bool operator<(const InstructionInfo &RHS) const {
371 // Order first by the number of operands (which is unambiguous).
372 if (Operands.size() != RHS.Operands.size())
373 return Operands.size() < RHS.Operands.size();
374
375 // Otherwise, order by lexicographic comparison of tokens and operand kinds
376 // (these can never be ambiguous).
377 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
378 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
379 Operands[i].Class->Kind == ClassInfo::Token)
380 if (*Operands[i].Class < *RHS.Operands[i].Class)
381 return true;
382
383 // Finally, order by the component wise comparison of operand classes. We
384 // don't want to rely on the lexigraphic ordering of elements, so we define
385 // only define the ordering when it is unambiguous. That is, when some pair
386 // compares less than and no pair compares greater than.
387
388 // Check that no pair compares greater than.
389 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
390 if (*RHS.Operands[i].Class < *Operands[i].Class)
391 return false;
392
393 // Otherwise, return true if some pair compares less than.
394 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
395 if (*Operands[i].Class < *RHS.Operands[i].Class)
396 return true;
397
398 return false;
399 }
400
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000401public:
402 void dump();
403};
404
Daniel Dunbar378bee92009-08-08 07:50:56 +0000405class AsmMatcherInfo {
406public:
407 /// The classes which are needed for matching.
408 std::vector<ClassInfo*> Classes;
409
410 /// The information on the instruction to match.
411 std::vector<InstructionInfo*> Instructions;
412
413private:
414 /// Map of token to class information which has already been constructed.
415 std::map<std::string, ClassInfo*> TokenClasses;
416
417 /// Map of operand name to class information which has already been
418 /// constructed.
419 std::map<std::string, ClassInfo*> OperandClasses;
420
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000421 /// Map of user class names to kind value.
422 std::map<std::string, unsigned> UserClasses;
423
Daniel Dunbar378bee92009-08-08 07:50:56 +0000424private:
425 /// getTokenClass - Lookup or create the class for the given token.
426 ClassInfo *getTokenClass(const StringRef &Token);
427
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000428 /// getUserClassKind - Lookup or create the kind value for the given class
429 /// name.
430 unsigned getUserClassKind(const StringRef &Name);
431
Daniel Dunbar378bee92009-08-08 07:50:56 +0000432 /// getOperandClass - Lookup or create the class for the given operand.
433 ClassInfo *getOperandClass(const StringRef &Token,
434 const CodeGenInstruction::OperandInfo &OI);
435
436public:
437 /// BuildInfo - Construct the various tables used during matching.
438 void BuildInfo(CodeGenTarget &Target);
439};
440
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000441}
442
443void InstructionInfo::dump() {
444 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
445 << ", tokens:[";
446 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
447 errs() << Tokens[i];
448 if (i + 1 != e)
449 errs() << ", ";
450 }
451 errs() << "]\n";
452
453 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
454 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000455 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000456 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000457 errs() << '\"' << Tokens[i] << "\"\n";
458 continue;
459 }
460
Benjamin Kramer19afc502009-08-08 10:06:30 +0000461 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000462 errs() << OI.Name << " " << OI.Rec->getName()
463 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
464 }
465}
466
Daniel Dunbar378bee92009-08-08 07:50:56 +0000467static std::string getEnumNameForToken(const StringRef &Str) {
468 std::string Res;
469
470 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
471 switch (*it) {
472 case '*': Res += "_STAR_"; break;
473 case '%': Res += "_PCT_"; break;
474 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000475
Daniel Dunbar378bee92009-08-08 07:50:56 +0000476 default:
477 if (isalnum(*it)) {
478 Res += *it;
479 } else {
480 Res += "_" + utostr((unsigned) *it) + "_";
481 }
482 }
483 }
484
485 return Res;
486}
487
488ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
489 ClassInfo *&Entry = TokenClasses[Token];
490
491 if (!Entry) {
492 Entry = new ClassInfo();
493 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000494 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000495 Entry->Name = "MCK_" + getEnumNameForToken(Token);
496 Entry->ValueName = Token;
497 Entry->PredicateMethod = "<invalid>";
498 Entry->RenderMethod = "<invalid>";
499 Classes.push_back(Entry);
500 }
501
502 return Entry;
503}
504
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000505unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
506 unsigned &Entry = UserClasses[Name];
507
508 if (!Entry)
509 Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
510
511 return Entry;
512}
513
Daniel Dunbar378bee92009-08-08 07:50:56 +0000514ClassInfo *
515AsmMatcherInfo::getOperandClass(const StringRef &Token,
516 const CodeGenInstruction::OperandInfo &OI) {
517 std::string ClassName;
518 if (OI.Rec->isSubClassOf("RegisterClass")) {
519 ClassName = "Reg";
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000520 } else {
521 try {
522 ClassName = OI.Rec->getValueAsString("ParserMatchClass");
523 assert(ClassName != "Reg" && "'Reg' class name is reserved!");
524 } catch(...) {
525 PrintError(OI.Rec->getLoc(), "operand has no match class!");
526 ClassName = "Invalid";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000527 }
528 }
529
530 ClassInfo *&Entry = OperandClasses[ClassName];
531
532 if (!Entry) {
533 Entry = new ClassInfo();
534 // FIXME: Hack.
535 if (ClassName == "Reg") {
536 Entry->Kind = ClassInfo::Register;
537 } else {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000538 Entry->Kind = getUserClassKind(ClassName);
Daniel Dunbar378bee92009-08-08 07:50:56 +0000539 }
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000540 Entry->ClassName = ClassName;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000541 Entry->Name = "MCK_" + ClassName;
542 Entry->ValueName = OI.Rec->getName();
543 Entry->PredicateMethod = "is" + ClassName;
544 Entry->RenderMethod = "add" + ClassName + "Operands";
545 Classes.push_back(Entry);
546 }
547
548 return Entry;
549}
550
551void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000552 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000553 it = Target.getInstructions().begin(),
554 ie = Target.getInstructions().end();
555 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000556 const CodeGenInstruction &CGI = it->second;
557
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000558 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000559 continue;
560
561 OwningPtr<InstructionInfo> II(new InstructionInfo);
562
563 II->InstrName = it->first;
564 II->Instr = &it->second;
565 II->AsmString = FlattenVariants(CGI.AsmString, 0);
566
567 TokenizeAsmString(II->AsmString, II->Tokens);
568
569 // Ignore instructions which shouldn't be matched.
570 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
571 continue;
572
573 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
574 StringRef Token = II->Tokens[i];
575
576 // Check for simple tokens.
577 if (Token[0] != '$') {
578 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000579 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000580 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000581 II->Operands.push_back(Op);
582 continue;
583 }
584
585 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000586 StringRef OperandName;
587 if (Token[1] == '{')
588 OperandName = Token.substr(2, Token.size() - 3);
589 else
590 OperandName = Token.substr(1);
591
592 // Map this token to an operand. FIXME: Move elsewhere.
593 unsigned Idx;
594 try {
595 Idx = CGI.getOperandNamed(OperandName);
596 } catch(...) {
597 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
598 break;
599 }
600
601 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000602 InstructionInfo::Operand Op;
603 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000604 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000605 II->Operands.push_back(Op);
606 }
607
608 // If we broke out, ignore the instruction.
609 if (II->Operands.size() != II->Tokens.size())
610 continue;
611
Daniel Dunbar378bee92009-08-08 07:50:56 +0000612 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000613 }
614}
615
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000616static void EmitConvertToMCInst(CodeGenTarget &Target,
617 std::vector<InstructionInfo*> &Infos,
618 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000619 // Write the convert function to a separate stream, so we can drop it after
620 // the enum.
621 std::string ConvertFnBody;
622 raw_string_ostream CvtOS(ConvertFnBody);
623
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000624 // Function we have already generated.
625 std::set<std::string> GeneratedFns;
626
Daniel Dunbarce82b992009-08-08 05:24:34 +0000627 // Start the unified conversion function.
628
629 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
630 << "unsigned Opcode,\n"
631 << " SmallVectorImpl<"
632 << Target.getName() << "Operand> &Operands) {\n";
633 CvtOS << " Inst.setOpcode(Opcode);\n";
634 CvtOS << " switch (Kind) {\n";
635 CvtOS << " default:\n";
636
637 // Start the enum, which we will generate inline.
638
639 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000640 OS << "enum ConversionKind {\n";
641
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000642 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
643 ie = Infos.end(); it != ie; ++it) {
644 InstructionInfo &II = **it;
645
646 // Order the (class) operands by the order to convert them into an MCInst.
647 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
648 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
649 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000650 if (Op.OperandInfo)
651 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000652 }
653 std::sort(MIOperandList.begin(), MIOperandList.end());
654
655 // Compute the total number of operands.
656 unsigned NumMIOperands = 0;
657 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
658 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
659 NumMIOperands = std::max(NumMIOperands,
660 OI.MIOperandNo + OI.MINumOperands);
661 }
662
663 // Build the conversion function signature.
664 std::string Signature = "Convert";
665 unsigned CurIndex = 0;
666 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
667 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000668 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000669 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000670
Daniel Dunbarce82b992009-08-08 05:24:34 +0000671 Signature += "_";
672
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000673 // Skip operands which weren't matched by anything, this occurs when the
674 // .td file encodes "implicit" operands as explicit ones.
675 //
676 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000677 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000678 Signature += "Imp";
679
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000680 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000681 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000682 Signature += "_" + utostr(MIOperandList[i].second);
683
Benjamin Kramer19afc502009-08-08 10:06:30 +0000684 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000685 }
686
687 // Add any trailing implicit operands.
688 for (; CurIndex != NumMIOperands; ++CurIndex)
689 Signature += "Imp";
690
Daniel Dunbarce82b992009-08-08 05:24:34 +0000691 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000692
Daniel Dunbarce82b992009-08-08 05:24:34 +0000693 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000694 if (!GeneratedFns.insert(Signature).second)
695 continue;
696
697 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000698
699 // Add to the enum list.
700 OS << " " << Signature << ",\n";
701
702 // And to the convert function.
703 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000704 CurIndex = 0;
705 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
706 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
707
708 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000709 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000710 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000711
Daniel Dunbarce82b992009-08-08 05:24:34 +0000712 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000713 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000714 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
715 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000716 }
717
718 // And add trailing implicit operands.
719 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000720 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
721 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000722 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000723
724 // Finish the convert function.
725
726 CvtOS << " }\n";
727 CvtOS << " return false;\n";
728 CvtOS << "}\n\n";
729
730 // Finish the enum, and drop the convert function after it.
731
732 OS << " NumConversionVariants\n";
733 OS << "};\n\n";
734
Daniel Dunbarce82b992009-08-08 05:24:34 +0000735 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +0000736}
737
Daniel Dunbar378bee92009-08-08 07:50:56 +0000738/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
739static void EmitMatchClassEnumeration(CodeGenTarget &Target,
740 std::vector<ClassInfo*> &Infos,
741 raw_ostream &OS) {
742 OS << "namespace {\n\n";
743
744 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
745 << "/// instruction matching.\n";
746 OS << "enum MatchClassKind {\n";
747 OS << " InvalidMatchClass = 0,\n";
748 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
749 ie = Infos.end(); it != ie; ++it) {
750 ClassInfo &CI = **it;
751 OS << " " << CI.Name << ", // ";
752 if (CI.Kind == ClassInfo::Token) {
753 OS << "'" << CI.ValueName << "'\n";
754 } else if (CI.Kind == ClassInfo::Register) {
755 if (!CI.ValueName.empty())
756 OS << "register class '" << CI.ValueName << "'\n";
757 else
758 OS << "derived register class\n";
759 } else {
760 OS << "user defined class '" << CI.ValueName << "'\n";
761 }
762 }
763 OS << " NumMatchClassKinds\n";
764 OS << "};\n\n";
765
766 OS << "}\n\n";
767}
768
Daniel Dunbar378bee92009-08-08 07:50:56 +0000769/// EmitClassifyOperand - Emit the function to classify an operand.
770static void EmitClassifyOperand(CodeGenTarget &Target,
771 std::vector<ClassInfo*> &Infos,
772 raw_ostream &OS) {
773 OS << "static MatchClassKind ClassifyOperand("
774 << Target.getName() << "Operand &Operand) {\n";
775 OS << " if (Operand.isToken())\n";
776 OS << " return MatchTokenString(Operand.getToken());\n\n";
777 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
778 ie = Infos.end(); it != ie; ++it) {
779 ClassInfo &CI = **it;
780
781 if (CI.Kind != ClassInfo::Token) {
782 OS << " if (Operand." << CI.PredicateMethod << "())\n";
783 OS << " return " << CI.Name << ";\n\n";
784 }
785 }
786 OS << " return InvalidMatchClass;\n";
787 OS << "}\n\n";
788}
789
Chris Lattner042926f2009-08-08 20:02:57 +0000790typedef std::pair<std::string, std::string> StringPair;
791
792/// FindFirstNonCommonLetter - Find the first character in the keys of the
793/// string pairs that is not shared across the whole set of strings. All
794/// strings are assumed to have the same length.
795static unsigned
796FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
797 assert(!Matches.empty());
798 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
799 // Check to see if letter i is the same across the set.
800 char Letter = Matches[0]->first[i];
801
802 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
803 if (Matches[str]->first[i] != Letter)
804 return i;
805 }
806
807 return Matches[0]->first.size();
808}
809
810/// EmitStringMatcherForChar - Given a set of strings that are known to be the
811/// same length and whose characters leading up to CharNo are the same, emit
812/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000813///
814/// \return - True if control can leave the emitted code fragment.
815static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +0000816 const std::vector<const StringPair*> &Matches,
817 unsigned CharNo, unsigned IndentCount,
818 raw_ostream &OS) {
819 assert(!Matches.empty() && "Must have at least one string to match!");
820 std::string Indent(IndentCount*2+4, ' ');
821
822 // If we have verified that the entire string matches, we're done: output the
823 // matching code.
824 if (CharNo == Matches[0]->first.size()) {
825 assert(Matches.size() == 1 && "Had duplicate keys to match on");
826
827 // FIXME: If Matches[0].first has embeded \n, this will be bad.
828 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
829 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000830 return false;
Chris Lattner042926f2009-08-08 20:02:57 +0000831 }
832
833 // Bucket the matches by the character we are comparing.
834 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
835
836 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
837 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
838
839
840 // If we have exactly one bucket to match, see how many characters are common
841 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +0000842 if (MatchesByLetter.size() == 1) {
843 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
844 unsigned NumChars = FirstNonCommonLetter-CharNo;
845
Daniel Dunbar7906a642009-08-08 22:57:25 +0000846 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +0000847 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000848 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +0000849 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000850 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
851 << Matches[0]->first[CharNo] << "')\n";
852 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000853 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000854 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +0000855 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000856 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
857 << NumChars << ") != \"";
858 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +0000859 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000860 }
861
Daniel Dunbar7906a642009-08-08 22:57:25 +0000862 return EmitStringMatcherForChar(StrVariableName, Matches,
863 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +0000864 }
865
866 // Otherwise, we have multiple possible things, emit a switch on the
867 // character.
868 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
869 OS << Indent << "default: break;\n";
870
871 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
872 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
873 // TODO: escape hard stuff (like \n) if we ever care about it.
874 OS << Indent << "case '" << LI->first << "':\t // "
875 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000876 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
877 IndentCount+1, OS))
878 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000879 }
880
881 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000882 return true;
Chris Lattner042926f2009-08-08 20:02:57 +0000883}
884
885
886/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +0000887/// match, output a simple switch tree to classify the input string.
888///
889/// If a match is found, the code in Vals[i].second is executed; control must
890/// not exit this code fragment. If nothing matches, execution falls through.
891///
892/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +0000893static void EmitStringMatcher(const std::string &StrVariableName,
894 const std::vector<StringPair> &Matches,
895 raw_ostream &OS) {
896 // First level categorization: group strings by length.
897 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
898
899 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
900 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
901
902 // Output a switch statement on length and categorize the elements within each
903 // bin.
904 OS << " switch (" << StrVariableName << ".size()) {\n";
905 OS << " default: break;\n";
906
Chris Lattner042926f2009-08-08 20:02:57 +0000907 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
908 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
909 OS << " case " << LI->first << ":\t // " << LI->second.size()
910 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000911 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
912 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000913 }
914
Chris Lattner042926f2009-08-08 20:02:57 +0000915 OS << " }\n";
916}
917
918
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000919/// EmitMatchTokenString - Emit the function to match a token string to the
920/// appropriate match class value.
921static void EmitMatchTokenString(CodeGenTarget &Target,
922 std::vector<ClassInfo*> &Infos,
923 raw_ostream &OS) {
924 // Construct the match list.
925 std::vector<StringPair> Matches;
926 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
927 ie = Infos.end(); it != ie; ++it) {
928 ClassInfo &CI = **it;
929
930 if (CI.Kind == ClassInfo::Token)
931 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
932 }
933
934 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
935
936 EmitStringMatcher("Name", Matches, OS);
937
938 OS << " return InvalidMatchClass;\n";
939 OS << "}\n\n";
940}
Chris Lattner042926f2009-08-08 20:02:57 +0000941
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000942/// EmitMatchRegisterName - Emit the function to match a string to the target
943/// specific register enum.
944static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
945 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000946 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +0000947 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000948 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
949 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +0000950 if (Reg.TheDef->getValueAsString("AsmName").empty())
951 continue;
952
Chris Lattner042926f2009-08-08 20:02:57 +0000953 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000954 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +0000955 }
Chris Lattner042926f2009-08-08 20:02:57 +0000956
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000957 OS << "unsigned " << Target.getName()
958 << AsmParser->getValueAsString("AsmParserClassName")
959 << "::MatchRegisterName(const StringRef &Name) {\n";
960
Chris Lattner042926f2009-08-08 20:02:57 +0000961 EmitStringMatcher("Name", Matches, OS);
962
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000963 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000964 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000965}
Daniel Dunbara54716c2009-07-31 02:32:59 +0000966
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000967void AsmMatcherEmitter::run(raw_ostream &OS) {
968 CodeGenTarget Target;
969 Record *AsmParser = Target.getAsmParser();
970 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
971
972 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
973
974 // Emit the function to match a register name to number.
975 EmitMatchRegisterName(Target, AsmParser, OS);
976
Daniel Dunbar378bee92009-08-08 07:50:56 +0000977 // Compute the information on the instructions to match.
978 AsmMatcherInfo Info;
979 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000980
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000981 // Sort the instruction table using the partial order on classes.
982 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
983 less_ptr<InstructionInfo>());
984
Daniel Dunbarce82b992009-08-08 05:24:34 +0000985 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000986 for (std::vector<InstructionInfo*>::iterator
987 it = Info.Instructions.begin(), ie = Info.Instructions.end();
988 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000989 (*it)->dump();
990 });
Daniel Dunbara54716c2009-07-31 02:32:59 +0000991
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000992 // Check for ambiguous instructions.
993 unsigned NumAmbiguous = 0;
994 for (std::vector<InstructionInfo*>::const_iterator it =
995 Info.Instructions.begin(), ie = Info.Instructions.end() - 1;
996 it != ie;) {
997 InstructionInfo &II = **it;
998 ++it;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000999
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001000 InstructionInfo &Next = **it;
1001
1002 if (!(II < Next)){
1003 DEBUG_WITH_TYPE("ambiguous_instrs", {
1004 errs() << "warning: ambiguous instruction match:\n";
1005 II.dump();
1006 errs() << "\nis incomparable with:\n";
1007 Next.dump();
1008 errs() << "\n\n";
1009 });
1010 ++NumAmbiguous;
1011 }
1012 }
1013 if (NumAmbiguous)
1014 DEBUG_WITH_TYPE("ambiguous_instrs", {
1015 errs() << "warning: " << NumAmbiguous
1016 << " ambiguous instructions!\n";
1017 });
1018
1019 // Generate the unified function to convert operands into an MCInst.
1020 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001021
Daniel Dunbar378bee92009-08-08 07:50:56 +00001022 // Emit the enumeration for classes which participate in matching.
1023 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001024
Daniel Dunbar378bee92009-08-08 07:50:56 +00001025 // Emit the routine to match token strings to their match class.
1026 EmitMatchTokenString(Target, Info.Classes, OS);
1027
1028 // Emit the routine to classify an operand.
1029 EmitClassifyOperand(Target, Info.Classes, OS);
1030
1031 // Finally, build the match function.
1032
1033 size_t MaxNumOperands = 0;
1034 for (std::vector<InstructionInfo*>::const_iterator it =
1035 Info.Instructions.begin(), ie = Info.Instructions.end();
1036 it != ie; ++it)
1037 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1038
Daniel Dunbara54716c2009-07-31 02:32:59 +00001039 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001040 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001041 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1042 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001043
Daniel Dunbar378bee92009-08-08 07:50:56 +00001044 // Emit the static match table; unused classes get initalized to 0 which is
1045 // guaranteed to be InvalidMatchClass.
1046 //
1047 // FIXME: We can reduce the size of this table very easily. First, we change
1048 // it so that store the kinds in separate bit-fields for each index, which
1049 // only needs to be the max width used for classes at that index (we also need
1050 // to reject based on this during classification). If we then make sure to
1051 // order the match kinds appropriately (putting mnemonics last), then we
1052 // should only end up using a few bits for each class, especially the ones
1053 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001054 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001055 OS << " unsigned Opcode;\n";
1056 OS << " ConversionKind ConvertFn;\n";
1057 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1058 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1059
1060 for (std::vector<InstructionInfo*>::const_iterator it =
1061 Info.Instructions.begin(), ie = Info.Instructions.end();
1062 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001063 InstructionInfo &II = **it;
1064
Daniel Dunbar378bee92009-08-08 07:50:56 +00001065 OS << " { " << Target.getName() << "::" << II.InstrName
1066 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001067 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1068 InstructionInfo::Operand &Op = II.Operands[i];
1069
Daniel Dunbar378bee92009-08-08 07:50:56 +00001070 if (i) OS << ", ";
1071 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001072 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001073 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001074 }
1075
Daniel Dunbar378bee92009-08-08 07:50:56 +00001076 OS << " };\n\n";
1077
1078 // Emit code to compute the class list for this operand vector.
1079 OS << " // Eliminate obvious mismatches.\n";
1080 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1081 OS << " return true;\n\n";
1082
1083 OS << " // Compute the class list for this operand vector.\n";
1084 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1085 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1086 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1087
1088 OS << " // Check for invalid operands before matching.\n";
1089 OS << " if (Classes[i] == InvalidMatchClass)\n";
1090 OS << " return true;\n";
1091 OS << " }\n\n";
1092
1093 OS << " // Mark unused classes.\n";
1094 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1095 << "i != e; ++i)\n";
1096 OS << " Classes[i] = InvalidMatchClass;\n\n";
1097
1098 // Emit code to search the table.
1099 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001100 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001101 << "*ie = MatchTable + " << Info.Instructions.size()
1102 << "; it != ie; ++it) {\n";
1103 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1104 OS << " if (Classes[" << i << "] != it->Classes[" << i << "])\n";
1105 OS << " continue;\n";
1106 }
1107 OS << "\n";
1108 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1109 << "it->Opcode, Operands);\n";
1110 OS << " }\n\n";
1111
Daniel Dunbara54716c2009-07-31 02:32:59 +00001112 OS << " return true;\n";
1113 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001114}