1 //===- 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. It also emits a matcher for
12 // custom operand parsing.
13 //
14 // Converting assembly operands into MCInst structures
15 // ---------------------------------------------------
16 //
17 // The input to the target specific matcher is a list of literal tokens and
18 // operands. The target specific parser should generally eliminate any syntax
19 // which is not relevant for matching; for example, comma tokens should have
20 // already been consumed and eliminated by the parser. Most instructions will
21 // end up with a single literal token (the instruction name) and some number of
22 // operands.
23 //
24 // Some example inputs, for X86:
25 // 'addl' (immediate ...) (register ...)
26 // 'add' (immediate ...) (memory ...)
27 // 'call' '*' %epc
28 //
29 // The assembly matcher is responsible for converting this input into a precise
30 // machine instruction (i.e., an instruction with a well defined encoding). This
31 // mapping has several properties which complicate matching:
32 //
33 // - It may be ambiguous; many architectures can legally encode particular
34 // variants of an instruction in different ways (for example, using a smaller
35 // encoding for small immediates). Such ambiguities should never be
36 // arbitrarily resolved by the assembler, the assembler is always responsible
37 // for choosing the "best" available instruction.
38 //
39 // - It may depend on the subtarget or the assembler context. Instructions
40 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
41 // an SSE instruction in a file being assembled for i486) should be accepted
42 // and rejected by the assembler front end. However, if the proper encoding
43 // for an instruction is dependent on the assembler context then the matcher
44 // is responsible for selecting the correct machine instruction for the
45 // current mode.
46 //
47 // The core matching algorithm attempts to exploit the regularity in most
48 // instruction sets to quickly determine the set of possibly matching
49 // instructions, and the simplify the generated code. Additionally, this helps
50 // to ensure that the ambiguities are intentionally resolved by the user.
51 //
52 // The matching is divided into two distinct phases:
53 //
54 // 1. Classification: Each operand is mapped to the unique set which (a)
55 // contains it, and (b) is the largest such subset for which a single
56 // instruction could match all members.
57 //
58 // For register classes, we can generate these subgroups automatically. For
59 // arbitrary operands, we expect the user to define the classes and their
60 // relations to one another (for example, 8-bit signed immediates as a
61 // subset of 32-bit immediates).
62 //
63 // By partitioning the operands in this way, we guarantee that for any
64 // tuple of classes, any single instruction must match either all or none
65 // of the sets of operands which could classify to that tuple.
66 //
67 // In addition, the subset relation amongst classes induces a partial order
68 // on such tuples, which we use to resolve ambiguities.
69 //
70 // 2. The input can now be treated as a tuple of classes (static tokens are
71 // simple singleton sets). Each such tuple should generally map to a single
72 // instruction (we currently ignore cases where this isn't true, whee!!!),
73 // which we can emit a simple matcher for.
74 //
75 // Custom Operand Parsing
76 // ----------------------
77 //
78 // Some targets need a custom way to parse operands, some specific instructions
79 // can contain arguments that can represent processor flags and other kinds of
80 // identifiers that need to be mapped to specific valeus in the final encoded
81 // instructions. The target specific custom operand parsing works in the
82 // following way:
83 //
84 // 1. A operand match table is built, each entry contains a mnemonic, an
85 // operand class, a mask for all operand positions for that same
86 // class/mnemonic and target features to be checked while trying to match.
87 //
88 // 2. The operand matcher will try every possible entry with the same
89 // mnemonic and will check if the target feature for this mnemonic also
90 // matches. After that, if the operand to be matched has its index
91 // present in the mask, a successful match occurs. Otherwise, fallback
92 // to the regular operand parsing.
93 //
94 // 3. For a match success, each operand class that has a 'ParserMethod'
95 // becomes part of a switch from where the custom method is called.
96 //
97 //===----------------------------------------------------------------------===//
98
99 #include "AsmMatcherEmitter.h"
100 #include "CodeGenTarget.h"
101 #include "StringMatcher.h"
102 #include "StringToOffsetTable.h"
103 #include "llvm/ADT/OwningPtr.h"
104 #include "llvm/ADT/PointerUnion.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallVector.h"
107 #include "llvm/ADT/STLExtras.h"
108 #include "llvm/ADT/StringExtras.h"
109 #include "llvm/Support/CommandLine.h"
110 #include "llvm/Support/Debug.h"
111 #include "llvm/Support/ErrorHandling.h"
112 #include "llvm/TableGen/Error.h"
113 #include "llvm/TableGen/Record.h"
114 #include <map>
115 #include <set>
116 using namespace llvm;
117
118 static cl::opt<std::string>
119 MatchPrefix("match-prefix", cl::init(""),
120 cl::desc("Only match instructions with the given prefix"));
121
122 namespace {
123 class AsmMatcherInfo;
124 struct SubtargetFeatureInfo;
125
126 /// ClassInfo - Helper class for storing the information about a particular
127 /// class of operands which can be matched.
128 struct ClassInfo {
129 enum ClassInfoKind {
130 /// Invalid kind, for use as a sentinel value.
131 Invalid = 0,
132
133 /// The class for a particular token.
134 Token,
135
136 /// The (first) register class, subsequent register classes are
137 /// RegisterClass0+1, and so on.
138 RegisterClass0,
139
140 /// The (first) user defined class, subsequent user defined classes are
141 /// UserClass0+1, and so on.
142 UserClass0 = 1<<16
143 };
144
145 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
146 /// N) for the Nth user defined class.
147 unsigned Kind;
148
149 /// SuperClasses - The super classes of this class. Note that for simplicities
150 /// sake user operands only record their immediate super class, while register
151 /// operands include all superclasses.
152 std::vector<ClassInfo*> SuperClasses;
153
154 /// Name - The full class name, suitable for use in an enum.
155 std::string Name;
156
157 /// ClassName - The unadorned generic name for this class (e.g., Token).
158 std::string ClassName;
159
160 /// ValueName - The name of the value this class represents; for a token this
161 /// is the literal token string, for an operand it is the TableGen class (or
162 /// empty if this is a derived class).
163 std::string ValueName;
164
165 /// PredicateMethod - The name of the operand method to test whether the
166 /// operand matches this class; this is not valid for Token or register kinds.
167 std::string PredicateMethod;
168
169 /// RenderMethod - The name of the operand method to add this operand to an
170 /// MCInst; this is not valid for Token or register kinds.
171 std::string RenderMethod;
172
173 /// ParserMethod - The name of the operand method to do a target specific
174 /// parsing on the operand.
175 std::string ParserMethod;
176
177 /// For register classes, the records for all the registers in this class.
178 std::set<Record*> Registers;
179
180 public:
181 /// isRegisterClass() - Check if this is a register class.
isRegisterClass__anon6b53c0400111::ClassInfo182 bool isRegisterClass() const {
183 return Kind >= RegisterClass0 && Kind < UserClass0;
184 }
185
186 /// isUserClass() - Check if this is a user defined class.
isUserClass__anon6b53c0400111::ClassInfo187 bool isUserClass() const {
188 return Kind >= UserClass0;
189 }
190
191 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
192 /// are related if they are in the same class hierarchy.
isRelatedTo__anon6b53c0400111::ClassInfo193 bool isRelatedTo(const ClassInfo &RHS) const {
194 // Tokens are only related to tokens.
195 if (Kind == Token || RHS.Kind == Token)
196 return Kind == Token && RHS.Kind == Token;
197
198 // Registers classes are only related to registers classes, and only if
199 // their intersection is non-empty.
200 if (isRegisterClass() || RHS.isRegisterClass()) {
201 if (!isRegisterClass() || !RHS.isRegisterClass())
202 return false;
203
204 std::set<Record*> Tmp;
205 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
206 std::set_intersection(Registers.begin(), Registers.end(),
207 RHS.Registers.begin(), RHS.Registers.end(),
208 II);
209
210 return !Tmp.empty();
211 }
212
213 // Otherwise we have two users operands; they are related if they are in the
214 // same class hierarchy.
215 //
216 // FIXME: This is an oversimplification, they should only be related if they
217 // intersect, however we don't have that information.
218 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
219 const ClassInfo *Root = this;
220 while (!Root->SuperClasses.empty())
221 Root = Root->SuperClasses.front();
222
223 const ClassInfo *RHSRoot = &RHS;
224 while (!RHSRoot->SuperClasses.empty())
225 RHSRoot = RHSRoot->SuperClasses.front();
226
227 return Root == RHSRoot;
228 }
229
230 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
isSubsetOf__anon6b53c0400111::ClassInfo231 bool isSubsetOf(const ClassInfo &RHS) const {
232 // This is a subset of RHS if it is the same class...
233 if (this == &RHS)
234 return true;
235
236 // ... or if any of its super classes are a subset of RHS.
237 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
238 ie = SuperClasses.end(); it != ie; ++it)
239 if ((*it)->isSubsetOf(RHS))
240 return true;
241
242 return false;
243 }
244
245 /// operator< - Compare two classes.
operator <__anon6b53c0400111::ClassInfo246 bool operator<(const ClassInfo &RHS) const {
247 if (this == &RHS)
248 return false;
249
250 // Unrelated classes can be ordered by kind.
251 if (!isRelatedTo(RHS))
252 return Kind < RHS.Kind;
253
254 switch (Kind) {
255 case Invalid:
256 llvm_unreachable("Invalid kind!");
257
258 default:
259 // This class precedes the RHS if it is a proper subset of the RHS.
260 if (isSubsetOf(RHS))
261 return true;
262 if (RHS.isSubsetOf(*this))
263 return false;
264
265 // Otherwise, order by name to ensure we have a total ordering.
266 return ValueName < RHS.ValueName;
267 }
268 }
269 };
270
271 /// MatchableInfo - Helper class for storing the necessary information for an
272 /// instruction or alias which is capable of being matched.
273 struct MatchableInfo {
274 struct AsmOperand {
275 /// Token - This is the token that the operand came from.
276 StringRef Token;
277
278 /// The unique class instance this operand should match.
279 ClassInfo *Class;
280
281 /// The operand name this is, if anything.
282 StringRef SrcOpName;
283
284 /// The suboperand index within SrcOpName, or -1 for the entire operand.
285 int SubOpIdx;
286
287 /// Register record if this token is singleton register.
288 Record *SingletonReg;
289
AsmOperand__anon6b53c0400111::MatchableInfo::AsmOperand290 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
291 SingletonReg(0) {}
292 };
293
294 /// ResOperand - This represents a single operand in the result instruction
295 /// generated by the match. In cases (like addressing modes) where a single
296 /// assembler operand expands to multiple MCOperands, this represents the
297 /// single assembler operand, not the MCOperand.
298 struct ResOperand {
299 enum {
300 /// RenderAsmOperand - This represents an operand result that is
301 /// generated by calling the render method on the assembly operand. The
302 /// corresponding AsmOperand is specified by AsmOperandNum.
303 RenderAsmOperand,
304
305 /// TiedOperand - This represents a result operand that is a duplicate of
306 /// a previous result operand.
307 TiedOperand,
308
309 /// ImmOperand - This represents an immediate value that is dumped into
310 /// the operand.
311 ImmOperand,
312
313 /// RegOperand - This represents a fixed register that is dumped in.
314 RegOperand
315 } Kind;
316
317 union {
318 /// This is the operand # in the AsmOperands list that this should be
319 /// copied from.
320 unsigned AsmOperandNum;
321
322 /// TiedOperandNum - This is the (earlier) result operand that should be
323 /// copied from.
324 unsigned TiedOperandNum;
325
326 /// ImmVal - This is the immediate value added to the instruction.
327 int64_t ImmVal;
328
329 /// Register - This is the register record.
330 Record *Register;
331 };
332
333 /// MINumOperands - The number of MCInst operands populated by this
334 /// operand.
335 unsigned MINumOperands;
336
getRenderedOp__anon6b53c0400111::MatchableInfo::ResOperand337 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
338 ResOperand X;
339 X.Kind = RenderAsmOperand;
340 X.AsmOperandNum = AsmOpNum;
341 X.MINumOperands = NumOperands;
342 return X;
343 }
344
getTiedOp__anon6b53c0400111::MatchableInfo::ResOperand345 static ResOperand getTiedOp(unsigned TiedOperandNum) {
346 ResOperand X;
347 X.Kind = TiedOperand;
348 X.TiedOperandNum = TiedOperandNum;
349 X.MINumOperands = 1;
350 return X;
351 }
352
getImmOp__anon6b53c0400111::MatchableInfo::ResOperand353 static ResOperand getImmOp(int64_t Val) {
354 ResOperand X;
355 X.Kind = ImmOperand;
356 X.ImmVal = Val;
357 X.MINumOperands = 1;
358 return X;
359 }
360
getRegOp__anon6b53c0400111::MatchableInfo::ResOperand361 static ResOperand getRegOp(Record *Reg) {
362 ResOperand X;
363 X.Kind = RegOperand;
364 X.Register = Reg;
365 X.MINumOperands = 1;
366 return X;
367 }
368 };
369
370 /// AsmVariantID - Target's assembly syntax variant no.
371 int AsmVariantID;
372
373 /// TheDef - This is the definition of the instruction or InstAlias that this
374 /// matchable came from.
375 Record *const TheDef;
376
377 /// DefRec - This is the definition that it came from.
378 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
379
getResultInst__anon6b53c0400111::MatchableInfo380 const CodeGenInstruction *getResultInst() const {
381 if (DefRec.is<const CodeGenInstruction*>())
382 return DefRec.get<const CodeGenInstruction*>();
383 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
384 }
385
386 /// ResOperands - This is the operand list that should be built for the result
387 /// MCInst.
388 std::vector<ResOperand> ResOperands;
389
390 /// AsmString - The assembly string for this instruction (with variants
391 /// removed), e.g. "movsx $src, $dst".
392 std::string AsmString;
393
394 /// Mnemonic - This is the first token of the matched instruction, its
395 /// mnemonic.
396 StringRef Mnemonic;
397
398 /// AsmOperands - The textual operands that this instruction matches,
399 /// annotated with a class and where in the OperandList they were defined.
400 /// This directly corresponds to the tokenized AsmString after the mnemonic is
401 /// removed.
402 SmallVector<AsmOperand, 4> AsmOperands;
403
404 /// Predicates - The required subtarget features to match this instruction.
405 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
406
407 /// ConversionFnKind - The enum value which is passed to the generated
408 /// ConvertToMCInst to convert parsed operands into an MCInst for this
409 /// function.
410 std::string ConversionFnKind;
411
MatchableInfo__anon6b53c0400111::MatchableInfo412 MatchableInfo(const CodeGenInstruction &CGI)
413 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
414 AsmString(CGI.AsmString) {
415 }
416
MatchableInfo__anon6b53c0400111::MatchableInfo417 MatchableInfo(const CodeGenInstAlias *Alias)
418 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
419 AsmString(Alias->AsmString) {
420 }
421
422 void Initialize(const AsmMatcherInfo &Info,
423 SmallPtrSet<Record*, 16> &SingletonRegisters,
424 int AsmVariantNo, std::string &RegisterPrefix);
425
426 /// Validate - Return true if this matchable is a valid thing to match against
427 /// and perform a bunch of validity checking.
428 bool Validate(StringRef CommentDelimiter, bool Hack) const;
429
430 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
431 /// if present, from specified token.
432 void
433 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
434 std::string &RegisterPrefix);
435
436 /// FindAsmOperand - Find the AsmOperand with the specified name and
437 /// suboperand index.
FindAsmOperand__anon6b53c0400111::MatchableInfo438 int FindAsmOperand(StringRef N, int SubOpIdx) const {
439 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
440 if (N == AsmOperands[i].SrcOpName &&
441 SubOpIdx == AsmOperands[i].SubOpIdx)
442 return i;
443 return -1;
444 }
445
446 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
447 /// This does not check the suboperand index.
FindAsmOperandNamed__anon6b53c0400111::MatchableInfo448 int FindAsmOperandNamed(StringRef N) const {
449 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
450 if (N == AsmOperands[i].SrcOpName)
451 return i;
452 return -1;
453 }
454
455 void BuildInstructionResultOperands();
456 void BuildAliasResultOperands();
457
458 /// operator< - Compare two matchables.
operator <__anon6b53c0400111::MatchableInfo459 bool operator<(const MatchableInfo &RHS) const {
460 // The primary comparator is the instruction mnemonic.
461 if (Mnemonic != RHS.Mnemonic)
462 return Mnemonic < RHS.Mnemonic;
463
464 if (AsmOperands.size() != RHS.AsmOperands.size())
465 return AsmOperands.size() < RHS.AsmOperands.size();
466
467 // Compare lexicographically by operand. The matcher validates that other
468 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
469 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
470 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
471 return true;
472 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
473 return false;
474 }
475
476 return false;
477 }
478
479 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
480 /// ambiguously match the same set of operands as \arg RHS (without being a
481 /// strictly superior match).
CouldMatchAmbiguouslyWith__anon6b53c0400111::MatchableInfo482 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
483 // The primary comparator is the instruction mnemonic.
484 if (Mnemonic != RHS.Mnemonic)
485 return false;
486
487 // The number of operands is unambiguous.
488 if (AsmOperands.size() != RHS.AsmOperands.size())
489 return false;
490
491 // Otherwise, make sure the ordering of the two instructions is unambiguous
492 // by checking that either (a) a token or operand kind discriminates them,
493 // or (b) the ordering among equivalent kinds is consistent.
494
495 // Tokens and operand kinds are unambiguous (assuming a correct target
496 // specific parser).
497 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
498 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
499 AsmOperands[i].Class->Kind == ClassInfo::Token)
500 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
501 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
502 return false;
503
504 // Otherwise, this operand could commute if all operands are equivalent, or
505 // there is a pair of operands that compare less than and a pair that
506 // compare greater than.
507 bool HasLT = false, HasGT = false;
508 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
509 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
510 HasLT = true;
511 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
512 HasGT = true;
513 }
514
515 return !(HasLT ^ HasGT);
516 }
517
518 void dump();
519
520 private:
521 void TokenizeAsmString(const AsmMatcherInfo &Info);
522 };
523
524 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
525 /// feature which participates in instruction matching.
526 struct SubtargetFeatureInfo {
527 /// \brief The predicate record for this feature.
528 Record *TheDef;
529
530 /// \brief An unique index assigned to represent this feature.
531 unsigned Index;
532
SubtargetFeatureInfo__anon6b53c0400111::SubtargetFeatureInfo533 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
534
535 /// \brief The name of the enumerated constant identifying this feature.
getEnumName__anon6b53c0400111::SubtargetFeatureInfo536 std::string getEnumName() const {
537 return "Feature_" + TheDef->getName();
538 }
539 };
540
541 struct OperandMatchEntry {
542 unsigned OperandMask;
543 MatchableInfo* MI;
544 ClassInfo *CI;
545
Create__anon6b53c0400111::OperandMatchEntry546 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
547 unsigned opMask) {
548 OperandMatchEntry X;
549 X.OperandMask = opMask;
550 X.CI = ci;
551 X.MI = mi;
552 return X;
553 }
554 };
555
556
557 class AsmMatcherInfo {
558 public:
559 /// Tracked Records
560 RecordKeeper &Records;
561
562 /// The tablegen AsmParser record.
563 Record *AsmParser;
564
565 /// Target - The target information.
566 CodeGenTarget &Target;
567
568 /// The classes which are needed for matching.
569 std::vector<ClassInfo*> Classes;
570
571 /// The information on the matchables to match.
572 std::vector<MatchableInfo*> Matchables;
573
574 /// Info for custom matching operands by user defined methods.
575 std::vector<OperandMatchEntry> OperandMatchInfo;
576
577 /// Map of Register records to their class information.
578 std::map<Record*, ClassInfo*> RegisterClasses;
579
580 /// Map of Predicate records to their subtarget information.
581 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
582
583 private:
584 /// Map of token to class information which has already been constructed.
585 std::map<std::string, ClassInfo*> TokenClasses;
586
587 /// Map of RegisterClass records to their class information.
588 std::map<Record*, ClassInfo*> RegisterClassClasses;
589
590 /// Map of AsmOperandClass records to their class information.
591 std::map<Record*, ClassInfo*> AsmOperandClasses;
592
593 private:
594 /// getTokenClass - Lookup or create the class for the given token.
595 ClassInfo *getTokenClass(StringRef Token);
596
597 /// getOperandClass - Lookup or create the class for the given operand.
598 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
599 int SubOpIdx);
600 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
601
602 /// BuildRegisterClasses - Build the ClassInfo* instances for register
603 /// classes.
604 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
605
606 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
607 /// operand classes.
608 void BuildOperandClasses();
609
610 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
611 unsigned AsmOpIdx);
612 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
613 MatchableInfo::AsmOperand &Op);
614
615 public:
616 AsmMatcherInfo(Record *AsmParser,
617 CodeGenTarget &Target,
618 RecordKeeper &Records);
619
620 /// BuildInfo - Construct the various tables used during matching.
621 void BuildInfo();
622
623 /// BuildOperandMatchInfo - Build the necessary information to handle user
624 /// defined operand parsing methods.
625 void BuildOperandMatchInfo();
626
627 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
628 /// given operand.
getSubtargetFeature(Record * Def) const629 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
630 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
631 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
632 SubtargetFeatures.find(Def);
633 return I == SubtargetFeatures.end() ? 0 : I->second;
634 }
635
getRecords() const636 RecordKeeper &getRecords() const {
637 return Records;
638 }
639 };
640
641 }
642
dump()643 void MatchableInfo::dump() {
644 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
645
646 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
647 AsmOperand &Op = AsmOperands[i];
648 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
649 errs() << '\"' << Op.Token << "\"\n";
650 }
651 }
652
Initialize(const AsmMatcherInfo & Info,SmallPtrSet<Record *,16> & SingletonRegisters,int AsmVariantNo,std::string & RegisterPrefix)653 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
654 SmallPtrSet<Record*, 16> &SingletonRegisters,
655 int AsmVariantNo, std::string &RegisterPrefix) {
656 AsmVariantID = AsmVariantNo;
657 AsmString =
658 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
659
660 TokenizeAsmString(Info);
661
662 // Compute the require features.
663 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
664 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
665 if (SubtargetFeatureInfo *Feature =
666 Info.getSubtargetFeature(Predicates[i]))
667 RequiredFeatures.push_back(Feature);
668
669 // Collect singleton registers, if used.
670 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
671 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
672 if (Record *Reg = AsmOperands[i].SingletonReg)
673 SingletonRegisters.insert(Reg);
674 }
675 }
676
677 /// TokenizeAsmString - Tokenize a simplified assembly string.
TokenizeAsmString(const AsmMatcherInfo & Info)678 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
679 StringRef String = AsmString;
680 unsigned Prev = 0;
681 bool InTok = true;
682 for (unsigned i = 0, e = String.size(); i != e; ++i) {
683 switch (String[i]) {
684 case '[':
685 case ']':
686 case '*':
687 case '!':
688 case ' ':
689 case '\t':
690 case ',':
691 if (InTok) {
692 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
693 InTok = false;
694 }
695 if (!isspace(String[i]) && String[i] != ',')
696 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
697 Prev = i + 1;
698 break;
699
700 case '\\':
701 if (InTok) {
702 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
703 InTok = false;
704 }
705 ++i;
706 assert(i != String.size() && "Invalid quoted character");
707 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
708 Prev = i + 1;
709 break;
710
711 case '$': {
712 if (InTok) {
713 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
714 InTok = false;
715 }
716
717 // If this isn't "${", treat like a normal token.
718 if (i + 1 == String.size() || String[i + 1] != '{') {
719 Prev = i;
720 break;
721 }
722
723 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
724 assert(End != String.end() && "Missing brace in operand reference!");
725 size_t EndPos = End - String.begin();
726 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
727 Prev = EndPos + 1;
728 i = EndPos;
729 break;
730 }
731
732 case '.':
733 if (InTok)
734 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
735 Prev = i;
736 InTok = true;
737 break;
738
739 default:
740 InTok = true;
741 }
742 }
743 if (InTok && Prev != String.size())
744 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
745
746 // The first token of the instruction is the mnemonic, which must be a
747 // simple string, not a $foo variable or a singleton register.
748 if (AsmOperands.empty())
749 throw TGError(TheDef->getLoc(),
750 "Instruction '" + TheDef->getName() + "' has no tokens");
751 Mnemonic = AsmOperands[0].Token;
752 // FIXME : Check and raise an error if it is a register.
753 if (Mnemonic[0] == '$')
754 throw TGError(TheDef->getLoc(),
755 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
756
757 // Remove the first operand, it is tracked in the mnemonic field.
758 AsmOperands.erase(AsmOperands.begin());
759 }
760
Validate(StringRef CommentDelimiter,bool Hack) const761 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
762 // Reject matchables with no .s string.
763 if (AsmString.empty())
764 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
765
766 // Reject any matchables with a newline in them, they should be marked
767 // isCodeGenOnly if they are pseudo instructions.
768 if (AsmString.find('\n') != std::string::npos)
769 throw TGError(TheDef->getLoc(),
770 "multiline instruction is not valid for the asmparser, "
771 "mark it isCodeGenOnly");
772
773 // Remove comments from the asm string. We know that the asmstring only
774 // has one line.
775 if (!CommentDelimiter.empty() &&
776 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
777 throw TGError(TheDef->getLoc(),
778 "asmstring for instruction has comment character in it, "
779 "mark it isCodeGenOnly");
780
781 // Reject matchables with operand modifiers, these aren't something we can
782 // handle, the target should be refactored to use operands instead of
783 // modifiers.
784 //
785 // Also, check for instructions which reference the operand multiple times;
786 // this implies a constraint we would not honor.
787 std::set<std::string> OperandNames;
788 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
789 StringRef Tok = AsmOperands[i].Token;
790 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
791 throw TGError(TheDef->getLoc(),
792 "matchable with operand modifier '" + Tok.str() +
793 "' not supported by asm matcher. Mark isCodeGenOnly!");
794
795 // Verify that any operand is only mentioned once.
796 // We reject aliases and ignore instructions for now.
797 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
798 if (!Hack)
799 throw TGError(TheDef->getLoc(),
800 "ERROR: matchable with tied operand '" + Tok.str() +
801 "' can never be matched!");
802 // FIXME: Should reject these. The ARM backend hits this with $lane in a
803 // bunch of instructions. It is unclear what the right answer is.
804 DEBUG({
805 errs() << "warning: '" << TheDef->getName() << "': "
806 << "ignoring instruction with tied operand '"
807 << Tok.str() << "'\n";
808 });
809 return false;
810 }
811 }
812
813 return true;
814 }
815
816 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
817 /// if present, from specified token.
818 void MatchableInfo::
extractSingletonRegisterForAsmOperand(unsigned OperandNo,const AsmMatcherInfo & Info,std::string & RegisterPrefix)819 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
820 const AsmMatcherInfo &Info,
821 std::string &RegisterPrefix) {
822 StringRef Tok = AsmOperands[OperandNo].Token;
823 if (RegisterPrefix.empty()) {
824 std::string LoweredTok = Tok.lower();
825 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
826 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
827 return;
828 }
829
830 if (!Tok.startswith(RegisterPrefix))
831 return;
832
833 StringRef RegName = Tok.substr(RegisterPrefix.size());
834 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
835 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
836
837 // If there is no register prefix (i.e. "%" in "%eax"), then this may
838 // be some random non-register token, just ignore it.
839 return;
840 }
841
getEnumNameForToken(StringRef Str)842 static std::string getEnumNameForToken(StringRef Str) {
843 std::string Res;
844
845 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
846 switch (*it) {
847 case '*': Res += "_STAR_"; break;
848 case '%': Res += "_PCT_"; break;
849 case ':': Res += "_COLON_"; break;
850 case '!': Res += "_EXCLAIM_"; break;
851 case '.': Res += "_DOT_"; break;
852 default:
853 if (isalnum(*it))
854 Res += *it;
855 else
856 Res += "_" + utostr((unsigned) *it) + "_";
857 }
858 }
859
860 return Res;
861 }
862
getTokenClass(StringRef Token)863 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
864 ClassInfo *&Entry = TokenClasses[Token];
865
866 if (!Entry) {
867 Entry = new ClassInfo();
868 Entry->Kind = ClassInfo::Token;
869 Entry->ClassName = "Token";
870 Entry->Name = "MCK_" + getEnumNameForToken(Token);
871 Entry->ValueName = Token;
872 Entry->PredicateMethod = "<invalid>";
873 Entry->RenderMethod = "<invalid>";
874 Entry->ParserMethod = "";
875 Classes.push_back(Entry);
876 }
877
878 return Entry;
879 }
880
881 ClassInfo *
getOperandClass(const CGIOperandList::OperandInfo & OI,int SubOpIdx)882 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
883 int SubOpIdx) {
884 Record *Rec = OI.Rec;
885 if (SubOpIdx != -1)
886 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
887 return getOperandClass(Rec, SubOpIdx);
888 }
889
890 ClassInfo *
getOperandClass(Record * Rec,int SubOpIdx)891 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
892 if (Rec->isSubClassOf("RegisterOperand")) {
893 // RegisterOperand may have an associated ParserMatchClass. If it does,
894 // use it, else just fall back to the underlying register class.
895 const RecordVal *R = Rec->getValue("ParserMatchClass");
896 if (R == 0 || R->getValue() == 0)
897 throw "Record `" + Rec->getName() +
898 "' does not have a ParserMatchClass!\n";
899
900 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
901 Record *MatchClass = DI->getDef();
902 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
903 return CI;
904 }
905
906 // No custom match class. Just use the register class.
907 Record *ClassRec = Rec->getValueAsDef("RegClass");
908 if (!ClassRec)
909 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
910 "' has no associated register class!\n");
911 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
912 return CI;
913 throw TGError(Rec->getLoc(), "register class has no class info!");
914 }
915
916
917 if (Rec->isSubClassOf("RegisterClass")) {
918 if (ClassInfo *CI = RegisterClassClasses[Rec])
919 return CI;
920 throw TGError(Rec->getLoc(), "register class has no class info!");
921 }
922
923 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
924 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
925 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
926 return CI;
927
928 throw TGError(Rec->getLoc(), "operand has no match class!");
929 }
930
931 void AsmMatcherInfo::
BuildRegisterClasses(SmallPtrSet<Record *,16> & SingletonRegisters)932 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
933 const std::vector<CodeGenRegister*> &Registers =
934 Target.getRegBank().getRegisters();
935 ArrayRef<CodeGenRegisterClass*> RegClassList =
936 Target.getRegBank().getRegClasses();
937
938 // The register sets used for matching.
939 std::set< std::set<Record*> > RegisterSets;
940
941 // Gather the defined sets.
942 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
943 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
944 RegisterSets.insert(std::set<Record*>(
945 (*it)->getOrder().begin(), (*it)->getOrder().end()));
946
947 // Add any required singleton sets.
948 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
949 ie = SingletonRegisters.end(); it != ie; ++it) {
950 Record *Rec = *it;
951 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
952 }
953
954 // Introduce derived sets where necessary (when a register does not determine
955 // a unique register set class), and build the mapping of registers to the set
956 // they should classify to.
957 std::map<Record*, std::set<Record*> > RegisterMap;
958 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
959 ie = Registers.end(); it != ie; ++it) {
960 const CodeGenRegister &CGR = **it;
961 // Compute the intersection of all sets containing this register.
962 std::set<Record*> ContainingSet;
963
964 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
965 ie = RegisterSets.end(); it != ie; ++it) {
966 if (!it->count(CGR.TheDef))
967 continue;
968
969 if (ContainingSet.empty()) {
970 ContainingSet = *it;
971 continue;
972 }
973
974 std::set<Record*> Tmp;
975 std::swap(Tmp, ContainingSet);
976 std::insert_iterator< std::set<Record*> > II(ContainingSet,
977 ContainingSet.begin());
978 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
979 }
980
981 if (!ContainingSet.empty()) {
982 RegisterSets.insert(ContainingSet);
983 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
984 }
985 }
986
987 // Construct the register classes.
988 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
989 unsigned Index = 0;
990 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
991 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
992 ClassInfo *CI = new ClassInfo();
993 CI->Kind = ClassInfo::RegisterClass0 + Index;
994 CI->ClassName = "Reg" + utostr(Index);
995 CI->Name = "MCK_Reg" + utostr(Index);
996 CI->ValueName = "";
997 CI->PredicateMethod = ""; // unused
998 CI->RenderMethod = "addRegOperands";
999 CI->Registers = *it;
1000 Classes.push_back(CI);
1001 RegisterSetClasses.insert(std::make_pair(*it, CI));
1002 }
1003
1004 // Find the superclasses; we could compute only the subgroup lattice edges,
1005 // but there isn't really a point.
1006 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1007 ie = RegisterSets.end(); it != ie; ++it) {
1008 ClassInfo *CI = RegisterSetClasses[*it];
1009 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1010 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1011 if (*it != *it2 &&
1012 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1013 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1014 }
1015
1016 // Name the register classes which correspond to a user defined RegisterClass.
1017 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1018 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1019 const CodeGenRegisterClass &RC = **it;
1020 // Def will be NULL for non-user defined register classes.
1021 Record *Def = RC.getDef();
1022 if (!Def)
1023 continue;
1024 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1025 RC.getOrder().end())];
1026 if (CI->ValueName.empty()) {
1027 CI->ClassName = RC.getName();
1028 CI->Name = "MCK_" + RC.getName();
1029 CI->ValueName = RC.getName();
1030 } else
1031 CI->ValueName = CI->ValueName + "," + RC.getName();
1032
1033 RegisterClassClasses.insert(std::make_pair(Def, CI));
1034 }
1035
1036 // Populate the map for individual registers.
1037 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1038 ie = RegisterMap.end(); it != ie; ++it)
1039 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1040
1041 // Name the register classes which correspond to singleton registers.
1042 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1043 ie = SingletonRegisters.end(); it != ie; ++it) {
1044 Record *Rec = *it;
1045 ClassInfo *CI = RegisterClasses[Rec];
1046 assert(CI && "Missing singleton register class info!");
1047
1048 if (CI->ValueName.empty()) {
1049 CI->ClassName = Rec->getName();
1050 CI->Name = "MCK_" + Rec->getName();
1051 CI->ValueName = Rec->getName();
1052 } else
1053 CI->ValueName = CI->ValueName + "," + Rec->getName();
1054 }
1055 }
1056
BuildOperandClasses()1057 void AsmMatcherInfo::BuildOperandClasses() {
1058 std::vector<Record*> AsmOperands =
1059 Records.getAllDerivedDefinitions("AsmOperandClass");
1060
1061 // Pre-populate AsmOperandClasses map.
1062 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1063 ie = AsmOperands.end(); it != ie; ++it)
1064 AsmOperandClasses[*it] = new ClassInfo();
1065
1066 unsigned Index = 0;
1067 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1068 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1069 ClassInfo *CI = AsmOperandClasses[*it];
1070 CI->Kind = ClassInfo::UserClass0 + Index;
1071
1072 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1073 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1074 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1075 if (!DI) {
1076 PrintError((*it)->getLoc(), "Invalid super class reference!");
1077 continue;
1078 }
1079
1080 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1081 if (!SC)
1082 PrintError((*it)->getLoc(), "Invalid super class reference!");
1083 else
1084 CI->SuperClasses.push_back(SC);
1085 }
1086 CI->ClassName = (*it)->getValueAsString("Name");
1087 CI->Name = "MCK_" + CI->ClassName;
1088 CI->ValueName = (*it)->getName();
1089
1090 // Get or construct the predicate method name.
1091 Init *PMName = (*it)->getValueInit("PredicateMethod");
1092 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1093 CI->PredicateMethod = SI->getValue();
1094 } else {
1095 assert(dynamic_cast<UnsetInit*>(PMName) &&
1096 "Unexpected PredicateMethod field!");
1097 CI->PredicateMethod = "is" + CI->ClassName;
1098 }
1099
1100 // Get or construct the render method name.
1101 Init *RMName = (*it)->getValueInit("RenderMethod");
1102 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1103 CI->RenderMethod = SI->getValue();
1104 } else {
1105 assert(dynamic_cast<UnsetInit*>(RMName) &&
1106 "Unexpected RenderMethod field!");
1107 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1108 }
1109
1110 // Get the parse method name or leave it as empty.
1111 Init *PRMName = (*it)->getValueInit("ParserMethod");
1112 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1113 CI->ParserMethod = SI->getValue();
1114
1115 AsmOperandClasses[*it] = CI;
1116 Classes.push_back(CI);
1117 }
1118 }
1119
AsmMatcherInfo(Record * asmParser,CodeGenTarget & target,RecordKeeper & records)1120 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1121 CodeGenTarget &target,
1122 RecordKeeper &records)
1123 : Records(records), AsmParser(asmParser), Target(target) {
1124 }
1125
1126 /// BuildOperandMatchInfo - Build the necessary information to handle user
1127 /// defined operand parsing methods.
BuildOperandMatchInfo()1128 void AsmMatcherInfo::BuildOperandMatchInfo() {
1129
1130 /// Map containing a mask with all operands indices that can be found for
1131 /// that class inside a instruction.
1132 std::map<ClassInfo*, unsigned> OpClassMask;
1133
1134 for (std::vector<MatchableInfo*>::const_iterator it =
1135 Matchables.begin(), ie = Matchables.end();
1136 it != ie; ++it) {
1137 MatchableInfo &II = **it;
1138 OpClassMask.clear();
1139
1140 // Keep track of all operands of this instructions which belong to the
1141 // same class.
1142 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1143 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1144 if (Op.Class->ParserMethod.empty())
1145 continue;
1146 unsigned &OperandMask = OpClassMask[Op.Class];
1147 OperandMask |= (1 << i);
1148 }
1149
1150 // Generate operand match info for each mnemonic/operand class pair.
1151 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1152 iie = OpClassMask.end(); iit != iie; ++iit) {
1153 unsigned OpMask = iit->second;
1154 ClassInfo *CI = iit->first;
1155 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1156 }
1157 }
1158 }
1159
BuildInfo()1160 void AsmMatcherInfo::BuildInfo() {
1161 // Build information about all of the AssemblerPredicates.
1162 std::vector<Record*> AllPredicates =
1163 Records.getAllDerivedDefinitions("Predicate");
1164 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1165 Record *Pred = AllPredicates[i];
1166 // Ignore predicates that are not intended for the assembler.
1167 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1168 continue;
1169
1170 if (Pred->getName().empty())
1171 throw TGError(Pred->getLoc(), "Predicate has no name!");
1172
1173 unsigned FeatureNo = SubtargetFeatures.size();
1174 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1175 assert(FeatureNo < 32 && "Too many subtarget features!");
1176 }
1177
1178 // Parse the instructions; we need to do this first so that we can gather the
1179 // singleton register classes.
1180 SmallPtrSet<Record*, 16> SingletonRegisters;
1181 unsigned VariantCount = Target.getAsmParserVariantCount();
1182 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1183 Record *AsmVariant = Target.getAsmParserVariant(VC);
1184 std::string CommentDelimiter =
1185 AsmVariant->getValueAsString("CommentDelimiter");
1186 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1187 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1188
1189 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1190 E = Target.inst_end(); I != E; ++I) {
1191 const CodeGenInstruction &CGI = **I;
1192
1193 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1194 // filter the set of instructions we consider.
1195 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1196 continue;
1197
1198 // Ignore "codegen only" instructions.
1199 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1200 continue;
1201
1202 // Validate the operand list to ensure we can handle this instruction.
1203 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1204 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1205
1206 // Validate tied operands.
1207 if (OI.getTiedRegister() != -1) {
1208 // If we have a tied operand that consists of multiple MCOperands,
1209 // reject it. We reject aliases and ignore instructions for now.
1210 if (OI.MINumOperands != 1) {
1211 // FIXME: Should reject these. The ARM backend hits this with $lane
1212 // in a bunch of instructions. The right answer is unclear.
1213 DEBUG({
1214 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1215 << "ignoring instruction with multi-operand tied operand '"
1216 << OI.Name << "'\n";
1217 });
1218 continue;
1219 }
1220 }
1221 }
1222
1223 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1224
1225 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1226
1227 // Ignore instructions which shouldn't be matched and diagnose invalid
1228 // instruction definitions with an error.
1229 if (!II->Validate(CommentDelimiter, true))
1230 continue;
1231
1232 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1233 //
1234 // FIXME: This is a total hack.
1235 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1236 StringRef(II->TheDef->getName()).endswith("_Int"))
1237 continue;
1238
1239 Matchables.push_back(II.take());
1240 }
1241
1242 // Parse all of the InstAlias definitions and stick them in the list of
1243 // matchables.
1244 std::vector<Record*> AllInstAliases =
1245 Records.getAllDerivedDefinitions("InstAlias");
1246 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1247 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1248
1249 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1250 // filter the set of instruction aliases we consider, based on the target
1251 // instruction.
1252 if (!StringRef(Alias->ResultInst->TheDef->getName())
1253 .startswith( MatchPrefix))
1254 continue;
1255
1256 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1257
1258 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1259
1260 // Validate the alias definitions.
1261 II->Validate(CommentDelimiter, false);
1262
1263 Matchables.push_back(II.take());
1264 }
1265 }
1266
1267 // Build info for the register classes.
1268 BuildRegisterClasses(SingletonRegisters);
1269
1270 // Build info for the user defined assembly operand classes.
1271 BuildOperandClasses();
1272
1273 // Build the information about matchables, now that we have fully formed
1274 // classes.
1275 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1276 ie = Matchables.end(); it != ie; ++it) {
1277 MatchableInfo *II = *it;
1278
1279 // Parse the tokens after the mnemonic.
1280 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1281 // don't precompute the loop bound.
1282 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1283 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1284 StringRef Token = Op.Token;
1285
1286 // Check for singleton registers.
1287 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1288 Op.Class = RegisterClasses[RegRecord];
1289 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1290 "Unexpected class for singleton register");
1291 continue;
1292 }
1293
1294 // Check for simple tokens.
1295 if (Token[0] != '$') {
1296 Op.Class = getTokenClass(Token);
1297 continue;
1298 }
1299
1300 if (Token.size() > 1 && isdigit(Token[1])) {
1301 Op.Class = getTokenClass(Token);
1302 continue;
1303 }
1304
1305 // Otherwise this is an operand reference.
1306 StringRef OperandName;
1307 if (Token[1] == '{')
1308 OperandName = Token.substr(2, Token.size() - 3);
1309 else
1310 OperandName = Token.substr(1);
1311
1312 if (II->DefRec.is<const CodeGenInstruction*>())
1313 BuildInstructionOperandReference(II, OperandName, i);
1314 else
1315 BuildAliasOperandReference(II, OperandName, Op);
1316 }
1317
1318 if (II->DefRec.is<const CodeGenInstruction*>())
1319 II->BuildInstructionResultOperands();
1320 else
1321 II->BuildAliasResultOperands();
1322 }
1323
1324 // Process token alias definitions and set up the associated superclass
1325 // information.
1326 std::vector<Record*> AllTokenAliases =
1327 Records.getAllDerivedDefinitions("TokenAlias");
1328 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1329 Record *Rec = AllTokenAliases[i];
1330 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1331 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1332 if (FromClass == ToClass)
1333 throw TGError(Rec->getLoc(),
1334 "error: Destination value identical to source value.");
1335 FromClass->SuperClasses.push_back(ToClass);
1336 }
1337
1338 // Reorder classes so that classes precede super classes.
1339 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1340 }
1341
1342 /// BuildInstructionOperandReference - The specified operand is a reference to a
1343 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1344 void AsmMatcherInfo::
BuildInstructionOperandReference(MatchableInfo * II,StringRef OperandName,unsigned AsmOpIdx)1345 BuildInstructionOperandReference(MatchableInfo *II,
1346 StringRef OperandName,
1347 unsigned AsmOpIdx) {
1348 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1349 const CGIOperandList &Operands = CGI.Operands;
1350 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1351
1352 // Map this token to an operand.
1353 unsigned Idx;
1354 if (!Operands.hasOperandNamed(OperandName, Idx))
1355 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1356 OperandName.str() + "'");
1357
1358 // If the instruction operand has multiple suboperands, but the parser
1359 // match class for the asm operand is still the default "ImmAsmOperand",
1360 // then handle each suboperand separately.
1361 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1362 Record *Rec = Operands[Idx].Rec;
1363 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1364 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1365 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1366 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1367 StringRef Token = Op->Token; // save this in case Op gets moved
1368 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1369 MatchableInfo::AsmOperand NewAsmOp(Token);
1370 NewAsmOp.SubOpIdx = SI;
1371 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1372 }
1373 // Replace Op with first suboperand.
1374 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1375 Op->SubOpIdx = 0;
1376 }
1377 }
1378
1379 // Set up the operand class.
1380 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1381
1382 // If the named operand is tied, canonicalize it to the untied operand.
1383 // For example, something like:
1384 // (outs GPR:$dst), (ins GPR:$src)
1385 // with an asmstring of
1386 // "inc $src"
1387 // we want to canonicalize to:
1388 // "inc $dst"
1389 // so that we know how to provide the $dst operand when filling in the result.
1390 int OITied = Operands[Idx].getTiedRegister();
1391 if (OITied != -1) {
1392 // The tied operand index is an MIOperand index, find the operand that
1393 // contains it.
1394 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1395 OperandName = Operands[Idx.first].Name;
1396 Op->SubOpIdx = Idx.second;
1397 }
1398
1399 Op->SrcOpName = OperandName;
1400 }
1401
1402 /// BuildAliasOperandReference - When parsing an operand reference out of the
1403 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1404 /// operand reference is by looking it up in the result pattern definition.
BuildAliasOperandReference(MatchableInfo * II,StringRef OperandName,MatchableInfo::AsmOperand & Op)1405 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1406 StringRef OperandName,
1407 MatchableInfo::AsmOperand &Op) {
1408 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1409
1410 // Set up the operand class.
1411 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1412 if (CGA.ResultOperands[i].isRecord() &&
1413 CGA.ResultOperands[i].getName() == OperandName) {
1414 // It's safe to go with the first one we find, because CodeGenInstAlias
1415 // validates that all operands with the same name have the same record.
1416 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1417 // Use the match class from the Alias definition, not the
1418 // destination instruction, as we may have an immediate that's
1419 // being munged by the match class.
1420 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1421 Op.SubOpIdx);
1422 Op.SrcOpName = OperandName;
1423 return;
1424 }
1425
1426 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1427 OperandName.str() + "'");
1428 }
1429
BuildInstructionResultOperands()1430 void MatchableInfo::BuildInstructionResultOperands() {
1431 const CodeGenInstruction *ResultInst = getResultInst();
1432
1433 // Loop over all operands of the result instruction, determining how to
1434 // populate them.
1435 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1436 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1437
1438 // If this is a tied operand, just copy from the previously handled operand.
1439 int TiedOp = OpInfo.getTiedRegister();
1440 if (TiedOp != -1) {
1441 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1442 continue;
1443 }
1444
1445 // Find out what operand from the asmparser this MCInst operand comes from.
1446 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1447 if (OpInfo.Name.empty() || SrcOperand == -1)
1448 throw TGError(TheDef->getLoc(), "Instruction '" +
1449 TheDef->getName() + "' has operand '" + OpInfo.Name +
1450 "' that doesn't appear in asm string!");
1451
1452 // Check if the one AsmOperand populates the entire operand.
1453 unsigned NumOperands = OpInfo.MINumOperands;
1454 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1455 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1456 continue;
1457 }
1458
1459 // Add a separate ResOperand for each suboperand.
1460 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1461 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1462 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1463 "unexpected AsmOperands for suboperands");
1464 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1465 }
1466 }
1467 }
1468
BuildAliasResultOperands()1469 void MatchableInfo::BuildAliasResultOperands() {
1470 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1471 const CodeGenInstruction *ResultInst = getResultInst();
1472
1473 // Loop over all operands of the result instruction, determining how to
1474 // populate them.
1475 unsigned AliasOpNo = 0;
1476 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1477 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1478 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1479
1480 // If this is a tied operand, just copy from the previously handled operand.
1481 int TiedOp = OpInfo->getTiedRegister();
1482 if (TiedOp != -1) {
1483 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1484 continue;
1485 }
1486
1487 // Handle all the suboperands for this operand.
1488 const std::string &OpName = OpInfo->Name;
1489 for ( ; AliasOpNo < LastOpNo &&
1490 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1491 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1492
1493 // Find out what operand from the asmparser that this MCInst operand
1494 // comes from.
1495 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1496 case CodeGenInstAlias::ResultOperand::K_Record: {
1497 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1498 int SrcOperand = FindAsmOperand(Name, SubIdx);
1499 if (SrcOperand == -1)
1500 throw TGError(TheDef->getLoc(), "Instruction '" +
1501 TheDef->getName() + "' has operand '" + OpName +
1502 "' that doesn't appear in asm string!");
1503 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1504 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1505 NumOperands));
1506 break;
1507 }
1508 case CodeGenInstAlias::ResultOperand::K_Imm: {
1509 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1510 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1511 break;
1512 }
1513 case CodeGenInstAlias::ResultOperand::K_Reg: {
1514 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1515 ResOperands.push_back(ResOperand::getRegOp(Reg));
1516 break;
1517 }
1518 }
1519 }
1520 }
1521 }
1522
EmitConvertToMCInst(CodeGenTarget & Target,StringRef ClassName,std::vector<MatchableInfo * > & Infos,raw_ostream & OS)1523 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1524 std::vector<MatchableInfo*> &Infos,
1525 raw_ostream &OS) {
1526 // Write the convert function to a separate stream, so we can drop it after
1527 // the enum.
1528 std::string ConvertFnBody;
1529 raw_string_ostream CvtOS(ConvertFnBody);
1530
1531 // Function we have already generated.
1532 std::set<std::string> GeneratedFns;
1533
1534 // Start the unified conversion function.
1535 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1536 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1537 << "unsigned Opcode,\n"
1538 << " const SmallVectorImpl<MCParsedAsmOperand*"
1539 << "> &Operands) {\n";
1540 CvtOS << " Inst.setOpcode(Opcode);\n";
1541 CvtOS << " switch (Kind) {\n";
1542 CvtOS << " default:\n";
1543
1544 // Start the enum, which we will generate inline.
1545
1546 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1547 OS << "enum ConversionKind {\n";
1548
1549 // TargetOperandClass - This is the target's operand class, like X86Operand.
1550 std::string TargetOperandClass = Target.getName() + "Operand";
1551
1552 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1553 ie = Infos.end(); it != ie; ++it) {
1554 MatchableInfo &II = **it;
1555
1556 // Check if we have a custom match function.
1557 std::string AsmMatchConverter =
1558 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1559 if (!AsmMatchConverter.empty()) {
1560 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1561 II.ConversionFnKind = Signature;
1562
1563 // Check if we have already generated this signature.
1564 if (!GeneratedFns.insert(Signature).second)
1565 continue;
1566
1567 // If not, emit it now. Add to the enum list.
1568 OS << " " << Signature << ",\n";
1569
1570 CvtOS << " case " << Signature << ":\n";
1571 CvtOS << " return " << AsmMatchConverter
1572 << "(Inst, Opcode, Operands);\n";
1573 continue;
1574 }
1575
1576 // Build the conversion function signature.
1577 std::string Signature = "Convert";
1578 std::string CaseBody;
1579 raw_string_ostream CaseOS(CaseBody);
1580
1581 // Compute the convert enum and the case body.
1582 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1583 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1584
1585 // Generate code to populate each result operand.
1586 switch (OpInfo.Kind) {
1587 case MatchableInfo::ResOperand::RenderAsmOperand: {
1588 // This comes from something we parsed.
1589 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1590
1591 // Registers are always converted the same, don't duplicate the
1592 // conversion function based on them.
1593 Signature += "__";
1594 if (Op.Class->isRegisterClass())
1595 Signature += "Reg";
1596 else
1597 Signature += Op.Class->ClassName;
1598 Signature += utostr(OpInfo.MINumOperands);
1599 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1600
1601 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1602 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1603 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1604 break;
1605 }
1606
1607 case MatchableInfo::ResOperand::TiedOperand: {
1608 // If this operand is tied to a previous one, just copy the MCInst
1609 // operand from the earlier one.We can only tie single MCOperand values.
1610 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1611 unsigned TiedOp = OpInfo.TiedOperandNum;
1612 assert(i > TiedOp && "Tied operand precedes its target!");
1613 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1614 Signature += "__Tie" + utostr(TiedOp);
1615 break;
1616 }
1617 case MatchableInfo::ResOperand::ImmOperand: {
1618 int64_t Val = OpInfo.ImmVal;
1619 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1620 Signature += "__imm" + itostr(Val);
1621 break;
1622 }
1623 case MatchableInfo::ResOperand::RegOperand: {
1624 if (OpInfo.Register == 0) {
1625 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1626 Signature += "__reg0";
1627 } else {
1628 std::string N = getQualifiedName(OpInfo.Register);
1629 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1630 Signature += "__reg" + OpInfo.Register->getName();
1631 }
1632 }
1633 }
1634 }
1635
1636 II.ConversionFnKind = Signature;
1637
1638 // Check if we have already generated this signature.
1639 if (!GeneratedFns.insert(Signature).second)
1640 continue;
1641
1642 // If not, emit it now. Add to the enum list.
1643 OS << " " << Signature << ",\n";
1644
1645 CvtOS << " case " << Signature << ":\n";
1646 CvtOS << CaseOS.str();
1647 CvtOS << " return true;\n";
1648 }
1649
1650 // Finish the convert function.
1651
1652 CvtOS << " }\n";
1653 CvtOS << " return false;\n";
1654 CvtOS << "}\n\n";
1655
1656 // Finish the enum, and drop the convert function after it.
1657
1658 OS << " NumConversionVariants\n";
1659 OS << "};\n\n";
1660
1661 OS << CvtOS.str();
1662 }
1663
1664 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
EmitMatchClassEnumeration(CodeGenTarget & Target,std::vector<ClassInfo * > & Infos,raw_ostream & OS)1665 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1666 std::vector<ClassInfo*> &Infos,
1667 raw_ostream &OS) {
1668 OS << "namespace {\n\n";
1669
1670 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1671 << "/// instruction matching.\n";
1672 OS << "enum MatchClassKind {\n";
1673 OS << " InvalidMatchClass = 0,\n";
1674 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1675 ie = Infos.end(); it != ie; ++it) {
1676 ClassInfo &CI = **it;
1677 OS << " " << CI.Name << ", // ";
1678 if (CI.Kind == ClassInfo::Token) {
1679 OS << "'" << CI.ValueName << "'\n";
1680 } else if (CI.isRegisterClass()) {
1681 if (!CI.ValueName.empty())
1682 OS << "register class '" << CI.ValueName << "'\n";
1683 else
1684 OS << "derived register class\n";
1685 } else {
1686 OS << "user defined class '" << CI.ValueName << "'\n";
1687 }
1688 }
1689 OS << " NumMatchClassKinds\n";
1690 OS << "};\n\n";
1691
1692 OS << "}\n\n";
1693 }
1694
1695 /// EmitValidateOperandClass - Emit the function to validate an operand class.
EmitValidateOperandClass(AsmMatcherInfo & Info,raw_ostream & OS)1696 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1697 raw_ostream &OS) {
1698 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1699 << "MatchClassKind Kind) {\n";
1700 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1701 << Info.Target.getName() << "Operand*)GOp;\n";
1702
1703 // The InvalidMatchClass is not to match any operand.
1704 OS << " if (Kind == InvalidMatchClass)\n";
1705 OS << " return false;\n\n";
1706
1707 // Check for Token operands first.
1708 OS << " if (Operand.isToken())\n";
1709 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1710 << "\n\n";
1711
1712 // Check for register operands, including sub-classes.
1713 OS << " if (Operand.isReg()) {\n";
1714 OS << " MatchClassKind OpKind;\n";
1715 OS << " switch (Operand.getReg()) {\n";
1716 OS << " default: OpKind = InvalidMatchClass; break;\n";
1717 for (std::map<Record*, ClassInfo*>::iterator
1718 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1719 it != ie; ++it)
1720 OS << " case " << Info.Target.getName() << "::"
1721 << it->first->getName() << ": OpKind = " << it->second->Name
1722 << "; break;\n";
1723 OS << " }\n";
1724 OS << " return isSubclass(OpKind, Kind);\n";
1725 OS << " }\n\n";
1726
1727 // Check the user classes. We don't care what order since we're only
1728 // actually matching against one of them.
1729 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1730 ie = Info.Classes.end(); it != ie; ++it) {
1731 ClassInfo &CI = **it;
1732
1733 if (!CI.isUserClass())
1734 continue;
1735
1736 OS << " // '" << CI.ClassName << "' class\n";
1737 OS << " if (Kind == " << CI.Name
1738 << " && Operand." << CI.PredicateMethod << "()) {\n";
1739 OS << " return true;\n";
1740 OS << " }\n\n";
1741 }
1742
1743 OS << " return false;\n";
1744 OS << "}\n\n";
1745 }
1746
1747 /// EmitIsSubclass - Emit the subclass predicate function.
EmitIsSubclass(CodeGenTarget & Target,std::vector<ClassInfo * > & Infos,raw_ostream & OS)1748 static void EmitIsSubclass(CodeGenTarget &Target,
1749 std::vector<ClassInfo*> &Infos,
1750 raw_ostream &OS) {
1751 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1752 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1753 OS << " if (A == B)\n";
1754 OS << " return true;\n\n";
1755
1756 OS << " switch (A) {\n";
1757 OS << " default:\n";
1758 OS << " return false;\n";
1759 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1760 ie = Infos.end(); it != ie; ++it) {
1761 ClassInfo &A = **it;
1762
1763 std::vector<StringRef> SuperClasses;
1764 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1765 ie = Infos.end(); it != ie; ++it) {
1766 ClassInfo &B = **it;
1767
1768 if (&A != &B && A.isSubsetOf(B))
1769 SuperClasses.push_back(B.Name);
1770 }
1771
1772 if (SuperClasses.empty())
1773 continue;
1774
1775 OS << "\n case " << A.Name << ":\n";
1776
1777 if (SuperClasses.size() == 1) {
1778 OS << " return B == " << SuperClasses.back() << ";\n";
1779 continue;
1780 }
1781
1782 OS << " switch (B) {\n";
1783 OS << " default: return false;\n";
1784 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1785 OS << " case " << SuperClasses[i] << ": return true;\n";
1786 OS << " }\n";
1787 }
1788 OS << " }\n";
1789 OS << "}\n\n";
1790 }
1791
1792 /// EmitMatchTokenString - Emit the function to match a token string to the
1793 /// appropriate match class value.
EmitMatchTokenString(CodeGenTarget & Target,std::vector<ClassInfo * > & Infos,raw_ostream & OS)1794 static void EmitMatchTokenString(CodeGenTarget &Target,
1795 std::vector<ClassInfo*> &Infos,
1796 raw_ostream &OS) {
1797 // Construct the match list.
1798 std::vector<StringMatcher::StringPair> Matches;
1799 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1800 ie = Infos.end(); it != ie; ++it) {
1801 ClassInfo &CI = **it;
1802
1803 if (CI.Kind == ClassInfo::Token)
1804 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1805 "return " + CI.Name + ";"));
1806 }
1807
1808 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1809
1810 StringMatcher("Name", Matches, OS).Emit();
1811
1812 OS << " return InvalidMatchClass;\n";
1813 OS << "}\n\n";
1814 }
1815
1816 /// EmitMatchRegisterName - Emit the function to match a string to the target
1817 /// specific register enum.
EmitMatchRegisterName(CodeGenTarget & Target,Record * AsmParser,raw_ostream & OS)1818 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1819 raw_ostream &OS) {
1820 // Construct the match list.
1821 std::vector<StringMatcher::StringPair> Matches;
1822 const std::vector<CodeGenRegister*> &Regs =
1823 Target.getRegBank().getRegisters();
1824 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1825 const CodeGenRegister *Reg = Regs[i];
1826 if (Reg->TheDef->getValueAsString("AsmName").empty())
1827 continue;
1828
1829 Matches.push_back(StringMatcher::StringPair(
1830 Reg->TheDef->getValueAsString("AsmName"),
1831 "return " + utostr(Reg->EnumValue) + ";"));
1832 }
1833
1834 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1835
1836 StringMatcher("Name", Matches, OS).Emit();
1837
1838 OS << " return 0;\n";
1839 OS << "}\n\n";
1840 }
1841
1842 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1843 /// definitions.
EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo & Info,raw_ostream & OS)1844 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1845 raw_ostream &OS) {
1846 OS << "// Flags for subtarget features that participate in "
1847 << "instruction matching.\n";
1848 OS << "enum SubtargetFeatureFlag {\n";
1849 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1850 it = Info.SubtargetFeatures.begin(),
1851 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1852 SubtargetFeatureInfo &SFI = *it->second;
1853 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1854 }
1855 OS << " Feature_None = 0\n";
1856 OS << "};\n\n";
1857 }
1858
1859 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1860 /// available features given a subtarget.
EmitComputeAvailableFeatures(AsmMatcherInfo & Info,raw_ostream & OS)1861 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1862 raw_ostream &OS) {
1863 std::string ClassName =
1864 Info.AsmParser->getValueAsString("AsmParserClassName");
1865
1866 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1867 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1868 OS << " unsigned Features = 0;\n";
1869 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1870 it = Info.SubtargetFeatures.begin(),
1871 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1872 SubtargetFeatureInfo &SFI = *it->second;
1873
1874 OS << " if (";
1875 std::string CondStorage =
1876 SFI.TheDef->getValueAsString("AssemblerCondString");
1877 StringRef Conds = CondStorage;
1878 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1879 bool First = true;
1880 do {
1881 if (!First)
1882 OS << " && ";
1883
1884 bool Neg = false;
1885 StringRef Cond = Comma.first;
1886 if (Cond[0] == '!') {
1887 Neg = true;
1888 Cond = Cond.substr(1);
1889 }
1890
1891 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1892 if (Neg)
1893 OS << " == 0";
1894 else
1895 OS << " != 0";
1896 OS << ")";
1897
1898 if (Comma.second.empty())
1899 break;
1900
1901 First = false;
1902 Comma = Comma.second.split(',');
1903 } while (true);
1904
1905 OS << ")\n";
1906 OS << " Features |= " << SFI.getEnumName() << ";\n";
1907 }
1908 OS << " return Features;\n";
1909 OS << "}\n\n";
1910 }
1911
GetAliasRequiredFeatures(Record * R,const AsmMatcherInfo & Info)1912 static std::string GetAliasRequiredFeatures(Record *R,
1913 const AsmMatcherInfo &Info) {
1914 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1915 std::string Result;
1916 unsigned NumFeatures = 0;
1917 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1918 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1919
1920 if (F == 0)
1921 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1922 "' is not marked as an AssemblerPredicate!");
1923
1924 if (NumFeatures)
1925 Result += '|';
1926
1927 Result += F->getEnumName();
1928 ++NumFeatures;
1929 }
1930
1931 if (NumFeatures > 1)
1932 Result = '(' + Result + ')';
1933 return Result;
1934 }
1935
1936 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1937 /// emit a function for them and return true, otherwise return false.
EmitMnemonicAliases(raw_ostream & OS,const AsmMatcherInfo & Info)1938 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1939 // Ignore aliases when match-prefix is set.
1940 if (!MatchPrefix.empty())
1941 return false;
1942
1943 std::vector<Record*> Aliases =
1944 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1945 if (Aliases.empty()) return false;
1946
1947 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1948 "unsigned Features) {\n";
1949
1950 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1951 // iteration order of the map is stable.
1952 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1953
1954 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1955 Record *R = Aliases[i];
1956 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1957 }
1958
1959 // Process each alias a "from" mnemonic at a time, building the code executed
1960 // by the string remapper.
1961 std::vector<StringMatcher::StringPair> Cases;
1962 for (std::map<std::string, std::vector<Record*> >::iterator
1963 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1964 I != E; ++I) {
1965 const std::vector<Record*> &ToVec = I->second;
1966
1967 // Loop through each alias and emit code that handles each case. If there
1968 // are two instructions without predicates, emit an error. If there is one,
1969 // emit it last.
1970 std::string MatchCode;
1971 int AliasWithNoPredicate = -1;
1972
1973 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1974 Record *R = ToVec[i];
1975 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1976
1977 // If this unconditionally matches, remember it for later and diagnose
1978 // duplicates.
1979 if (FeatureMask.empty()) {
1980 if (AliasWithNoPredicate != -1) {
1981 // We can't have two aliases from the same mnemonic with no predicate.
1982 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1983 "two MnemonicAliases with the same 'from' mnemonic!");
1984 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1985 }
1986
1987 AliasWithNoPredicate = i;
1988 continue;
1989 }
1990 if (R->getValueAsString("ToMnemonic") == I->first)
1991 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1992
1993 if (!MatchCode.empty())
1994 MatchCode += "else ";
1995 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1996 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1997 }
1998
1999 if (AliasWithNoPredicate != -1) {
2000 Record *R = ToVec[AliasWithNoPredicate];
2001 if (!MatchCode.empty())
2002 MatchCode += "else\n ";
2003 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2004 }
2005
2006 MatchCode += "return;";
2007
2008 Cases.push_back(std::make_pair(I->first, MatchCode));
2009 }
2010
2011 StringMatcher("Mnemonic", Cases, OS).Emit();
2012 OS << "}\n\n";
2013
2014 return true;
2015 }
2016
getMinimalTypeForRange(uint64_t Range)2017 static const char *getMinimalTypeForRange(uint64_t Range) {
2018 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2019 if (Range > 0xFFFF)
2020 return "uint32_t";
2021 if (Range > 0xFF)
2022 return "uint16_t";
2023 return "uint8_t";
2024 }
2025
EmitCustomOperandParsing(raw_ostream & OS,CodeGenTarget & Target,const AsmMatcherInfo & Info,StringRef ClassName)2026 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2027 const AsmMatcherInfo &Info, StringRef ClassName) {
2028 // Emit the static custom operand parsing table;
2029 OS << "namespace {\n";
2030 OS << " struct OperandMatchEntry {\n";
2031 OS << " static const char *const MnemonicTable;\n";
2032 OS << " uint32_t OperandMask;\n";
2033 OS << " uint32_t Mnemonic;\n";
2034 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2035 << " RequiredFeatures;\n";
2036 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2037 << " Class;\n\n";
2038 OS << " StringRef getMnemonic() const {\n";
2039 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2040 OS << " MnemonicTable[Mnemonic]);\n";
2041 OS << " }\n";
2042 OS << " };\n\n";
2043
2044 OS << " // Predicate for searching for an opcode.\n";
2045 OS << " struct LessOpcodeOperand {\n";
2046 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2047 OS << " return LHS.getMnemonic() < RHS;\n";
2048 OS << " }\n";
2049 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2050 OS << " return LHS < RHS.getMnemonic();\n";
2051 OS << " }\n";
2052 OS << " bool operator()(const OperandMatchEntry &LHS,";
2053 OS << " const OperandMatchEntry &RHS) {\n";
2054 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2055 OS << " }\n";
2056 OS << " };\n";
2057
2058 OS << "} // end anonymous namespace.\n\n";
2059
2060 StringToOffsetTable StringTable;
2061
2062 OS << "static const OperandMatchEntry OperandMatchTable["
2063 << Info.OperandMatchInfo.size() << "] = {\n";
2064
2065 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2066 for (std::vector<OperandMatchEntry>::const_iterator it =
2067 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2068 it != ie; ++it) {
2069 const OperandMatchEntry &OMI = *it;
2070 const MatchableInfo &II = *OMI.MI;
2071
2072 OS << " { " << OMI.OperandMask;
2073
2074 OS << " /* ";
2075 bool printComma = false;
2076 for (int i = 0, e = 31; i !=e; ++i)
2077 if (OMI.OperandMask & (1 << i)) {
2078 if (printComma)
2079 OS << ", ";
2080 OS << i;
2081 printComma = true;
2082 }
2083 OS << " */";
2084
2085 // Store a pascal-style length byte in the mnemonic.
2086 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2087 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2088 << " /* " << II.Mnemonic << " */, ";
2089
2090 // Write the required features mask.
2091 if (!II.RequiredFeatures.empty()) {
2092 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2093 if (i) OS << "|";
2094 OS << II.RequiredFeatures[i]->getEnumName();
2095 }
2096 } else
2097 OS << "0";
2098
2099 OS << ", " << OMI.CI->Name;
2100
2101 OS << " },\n";
2102 }
2103 OS << "};\n\n";
2104
2105 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
2106 StringTable.EmitString(OS);
2107 OS << ";\n\n";
2108
2109 // Emit the operand class switch to call the correct custom parser for
2110 // the found operand class.
2111 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2112 << Target.getName() << ClassName << "::\n"
2113 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2114 << " &Operands,\n unsigned MCK) {\n\n"
2115 << " switch(MCK) {\n";
2116
2117 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2118 ie = Info.Classes.end(); it != ie; ++it) {
2119 ClassInfo *CI = *it;
2120 if (CI->ParserMethod.empty())
2121 continue;
2122 OS << " case " << CI->Name << ":\n"
2123 << " return " << CI->ParserMethod << "(Operands);\n";
2124 }
2125
2126 OS << " default:\n";
2127 OS << " return MatchOperand_NoMatch;\n";
2128 OS << " }\n";
2129 OS << " return MatchOperand_NoMatch;\n";
2130 OS << "}\n\n";
2131
2132 // Emit the static custom operand parser. This code is very similar with
2133 // the other matcher. Also use MatchResultTy here just in case we go for
2134 // a better error handling.
2135 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2136 << Target.getName() << ClassName << "::\n"
2137 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2138 << " &Operands,\n StringRef Mnemonic) {\n";
2139
2140 // Emit code to get the available features.
2141 OS << " // Get the current feature set.\n";
2142 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2143
2144 OS << " // Get the next operand index.\n";
2145 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2146
2147 // Emit code to search the table.
2148 OS << " // Search the table.\n";
2149 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2150 OS << " MnemonicRange =\n";
2151 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2152 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2153 << " LessOpcodeOperand());\n\n";
2154
2155 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2156 OS << " return MatchOperand_NoMatch;\n\n";
2157
2158 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2159 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2160
2161 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2162 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2163
2164 // Emit check that the required features are available.
2165 OS << " // check if the available features match\n";
2166 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2167 << "!= it->RequiredFeatures) {\n";
2168 OS << " continue;\n";
2169 OS << " }\n\n";
2170
2171 // Emit check to ensure the operand number matches.
2172 OS << " // check if the operand in question has a custom parser.\n";
2173 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2174 OS << " continue;\n\n";
2175
2176 // Emit call to the custom parser method
2177 OS << " // call custom parse method to handle the operand\n";
2178 OS << " OperandMatchResultTy Result = ";
2179 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2180 OS << " if (Result != MatchOperand_NoMatch)\n";
2181 OS << " return Result;\n";
2182 OS << " }\n\n";
2183
2184 OS << " // Okay, we had no match.\n";
2185 OS << " return MatchOperand_NoMatch;\n";
2186 OS << "}\n\n";
2187 }
2188
run(raw_ostream & OS)2189 void AsmMatcherEmitter::run(raw_ostream &OS) {
2190 CodeGenTarget Target(Records);
2191 Record *AsmParser = Target.getAsmParser();
2192 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2193
2194 // Compute the information on the instructions to match.
2195 AsmMatcherInfo Info(AsmParser, Target, Records);
2196 Info.BuildInfo();
2197
2198 // Sort the instruction table using the partial order on classes. We use
2199 // stable_sort to ensure that ambiguous instructions are still
2200 // deterministically ordered.
2201 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2202 less_ptr<MatchableInfo>());
2203
2204 DEBUG_WITH_TYPE("instruction_info", {
2205 for (std::vector<MatchableInfo*>::iterator
2206 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2207 it != ie; ++it)
2208 (*it)->dump();
2209 });
2210
2211 // Check for ambiguous matchables.
2212 DEBUG_WITH_TYPE("ambiguous_instrs", {
2213 unsigned NumAmbiguous = 0;
2214 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2215 for (unsigned j = i + 1; j != e; ++j) {
2216 MatchableInfo &A = *Info.Matchables[i];
2217 MatchableInfo &B = *Info.Matchables[j];
2218
2219 if (A.CouldMatchAmbiguouslyWith(B)) {
2220 errs() << "warning: ambiguous matchables:\n";
2221 A.dump();
2222 errs() << "\nis incomparable with:\n";
2223 B.dump();
2224 errs() << "\n\n";
2225 ++NumAmbiguous;
2226 }
2227 }
2228 }
2229 if (NumAmbiguous)
2230 errs() << "warning: " << NumAmbiguous
2231 << " ambiguous matchables!\n";
2232 });
2233
2234 // Compute the information on the custom operand parsing.
2235 Info.BuildOperandMatchInfo();
2236
2237 // Write the output.
2238
2239 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2240
2241 // Information for the class declaration.
2242 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2243 OS << "#undef GET_ASSEMBLER_HEADER\n";
2244 OS << " // This should be included into the middle of the declaration of\n";
2245 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2246 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2247 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2248 << "unsigned Opcode,\n"
2249 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2250 << "&Operands);\n";
2251 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2252 OS << " unsigned MatchInstructionImpl(\n";
2253 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2254 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2255
2256 if (Info.OperandMatchInfo.size()) {
2257 OS << "\n enum OperandMatchResultTy {\n";
2258 OS << " MatchOperand_Success, // operand matched successfully\n";
2259 OS << " MatchOperand_NoMatch, // operand did not match\n";
2260 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2261 OS << " };\n";
2262 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2263 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2264 OS << " StringRef Mnemonic);\n";
2265
2266 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2267 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2268 OS << " unsigned MCK);\n\n";
2269 }
2270
2271 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2272
2273 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2274 OS << "#undef GET_REGISTER_MATCHER\n\n";
2275
2276 // Emit the subtarget feature enumeration.
2277 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2278
2279 // Emit the function to match a register name to number.
2280 EmitMatchRegisterName(Target, AsmParser, OS);
2281
2282 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2283
2284
2285 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2286 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2287
2288 // Generate the function that remaps for mnemonic aliases.
2289 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2290
2291 // Generate the unified function to convert operands into an MCInst.
2292 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2293
2294 // Emit the enumeration for classes which participate in matching.
2295 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2296
2297 // Emit the routine to match token strings to their match class.
2298 EmitMatchTokenString(Target, Info.Classes, OS);
2299
2300 // Emit the subclass predicate routine.
2301 EmitIsSubclass(Target, Info.Classes, OS);
2302
2303 // Emit the routine to validate an operand against a match class.
2304 EmitValidateOperandClass(Info, OS);
2305
2306 // Emit the available features compute function.
2307 EmitComputeAvailableFeatures(Info, OS);
2308
2309
2310 size_t MaxNumOperands = 0;
2311 for (std::vector<MatchableInfo*>::const_iterator it =
2312 Info.Matchables.begin(), ie = Info.Matchables.end();
2313 it != ie; ++it)
2314 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2315
2316 // Emit the static match table; unused classes get initalized to 0 which is
2317 // guaranteed to be InvalidMatchClass.
2318 //
2319 // FIXME: We can reduce the size of this table very easily. First, we change
2320 // it so that store the kinds in separate bit-fields for each index, which
2321 // only needs to be the max width used for classes at that index (we also need
2322 // to reject based on this during classification). If we then make sure to
2323 // order the match kinds appropriately (putting mnemonics last), then we
2324 // should only end up using a few bits for each class, especially the ones
2325 // following the mnemonic.
2326 OS << "namespace {\n";
2327 OS << " struct MatchEntry {\n";
2328 OS << " static const char *const MnemonicTable;\n";
2329 OS << " uint32_t Mnemonic;\n";
2330 OS << " uint16_t Opcode;\n";
2331 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2332 << " ConvertFn;\n";
2333 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2334 << " RequiredFeatures;\n";
2335 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2336 << " Classes[" << MaxNumOperands << "];\n";
2337 OS << " uint8_t AsmVariantID;\n\n";
2338 OS << " StringRef getMnemonic() const {\n";
2339 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2340 OS << " MnemonicTable[Mnemonic]);\n";
2341 OS << " }\n";
2342 OS << " };\n\n";
2343
2344 OS << " // Predicate for searching for an opcode.\n";
2345 OS << " struct LessOpcode {\n";
2346 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2347 OS << " return LHS.getMnemonic() < RHS;\n";
2348 OS << " }\n";
2349 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2350 OS << " return LHS < RHS.getMnemonic();\n";
2351 OS << " }\n";
2352 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2353 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2354 OS << " }\n";
2355 OS << " };\n";
2356
2357 OS << "} // end anonymous namespace.\n\n";
2358
2359 StringToOffsetTable StringTable;
2360
2361 OS << "static const MatchEntry MatchTable["
2362 << Info.Matchables.size() << "] = {\n";
2363
2364 for (std::vector<MatchableInfo*>::const_iterator it =
2365 Info.Matchables.begin(), ie = Info.Matchables.end();
2366 it != ie; ++it) {
2367 MatchableInfo &II = **it;
2368
2369 // Store a pascal-style length byte in the mnemonic.
2370 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2371 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2372 << " /* " << II.Mnemonic << " */, "
2373 << Target.getName() << "::"
2374 << II.getResultInst()->TheDef->getName() << ", "
2375 << II.ConversionFnKind << ", ";
2376
2377 // Write the required features mask.
2378 if (!II.RequiredFeatures.empty()) {
2379 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2380 if (i) OS << "|";
2381 OS << II.RequiredFeatures[i]->getEnumName();
2382 }
2383 } else
2384 OS << "0";
2385
2386 OS << ", { ";
2387 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2388 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2389
2390 if (i) OS << ", ";
2391 OS << Op.Class->Name;
2392 }
2393 OS << " }, " << II.AsmVariantID;
2394 OS << "},\n";
2395 }
2396
2397 OS << "};\n\n";
2398
2399 OS << "const char *const MatchEntry::MnemonicTable =\n";
2400 StringTable.EmitString(OS);
2401 OS << ";\n\n";
2402
2403 // A method to determine if a mnemonic is in the list.
2404 OS << "bool " << Target.getName() << ClassName << "::\n"
2405 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2406 OS << " // Search the table.\n";
2407 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2408 OS << " std::equal_range(MatchTable, MatchTable+"
2409 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2410 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2411 OS << "}\n\n";
2412
2413 // Finally, build the match function.
2414 OS << "unsigned "
2415 << Target.getName() << ClassName << "::\n"
2416 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2417 << " &Operands,\n";
2418 OS << " MCInst &Inst, unsigned &ErrorInfo,\n";
2419 OS << " unsigned VariantID) {\n";
2420
2421 // Emit code to get the available features.
2422 OS << " // Get the current feature set.\n";
2423 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2424
2425 OS << " // Get the instruction mnemonic, which is the first token.\n";
2426 OS << " StringRef Mnemonic = ((" << Target.getName()
2427 << "Operand*)Operands[0])->getToken();\n\n";
2428
2429 if (HasMnemonicAliases) {
2430 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2431 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2432 OS << " if (!VariantID)\n";
2433 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2434 }
2435
2436 // Emit code to compute the class list for this operand vector.
2437 OS << " // Eliminate obvious mismatches.\n";
2438 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2439 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2440 OS << " return Match_InvalidOperand;\n";
2441 OS << " }\n\n";
2442
2443 OS << " // Some state to try to produce better error messages.\n";
2444 OS << " bool HadMatchOtherThanFeatures = false;\n";
2445 OS << " bool HadMatchOtherThanPredicate = false;\n";
2446 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2447 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2448 OS << " // wrong for all instances of the instruction.\n";
2449 OS << " ErrorInfo = ~0U;\n";
2450
2451 // Emit code to search the table.
2452 OS << " // Search the table.\n";
2453 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2454 OS << " std::equal_range(MatchTable, MatchTable+"
2455 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2456
2457 OS << " // Return a more specific error code if no mnemonics match.\n";
2458 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2459 OS << " return Match_MnemonicFail;\n\n";
2460
2461 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2462 << "*ie = MnemonicRange.second;\n";
2463 OS << " it != ie; ++it) {\n";
2464
2465 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2466 OS << " assert(Mnemonic == it->getMnemonic());\n";
2467
2468 // Emit check that the subclasses match.
2469 OS << " if (VariantID != it->AsmVariantID) continue;\n";
2470 OS << " bool OperandsValid = true;\n";
2471 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2472 OS << " if (i + 1 >= Operands.size()) {\n";
2473 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2474 OS << " break;\n";
2475 OS << " }\n";
2476 OS << " if (validateOperandClass(Operands[i+1], "
2477 "(MatchClassKind)it->Classes[i]))\n";
2478 OS << " continue;\n";
2479 OS << " // If this operand is broken for all of the instances of this\n";
2480 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2481 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2482 OS << " ErrorInfo = i+1;\n";
2483 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2484 OS << " OperandsValid = false;\n";
2485 OS << " break;\n";
2486 OS << " }\n\n";
2487
2488 OS << " if (!OperandsValid) continue;\n";
2489
2490 // Emit check that the required features are available.
2491 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2492 << "!= it->RequiredFeatures) {\n";
2493 OS << " HadMatchOtherThanFeatures = true;\n";
2494 OS << " continue;\n";
2495 OS << " }\n";
2496 OS << "\n";
2497 OS << " // We have selected a definite instruction, convert the parsed\n"
2498 << " // operands into the appropriate MCInst.\n";
2499 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2500 << " it->Opcode, Operands))\n";
2501 OS << " return Match_ConversionFail;\n";
2502 OS << "\n";
2503
2504 // Verify the instruction with the target-specific match predicate function.
2505 OS << " // We have a potential match. Check the target predicate to\n"
2506 << " // handle any context sensitive constraints.\n"
2507 << " unsigned MatchResult;\n"
2508 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2509 << " Match_Success) {\n"
2510 << " Inst.clear();\n"
2511 << " RetCode = MatchResult;\n"
2512 << " HadMatchOtherThanPredicate = true;\n"
2513 << " continue;\n"
2514 << " }\n\n";
2515
2516 // Call the post-processing function, if used.
2517 std::string InsnCleanupFn =
2518 AsmParser->getValueAsString("AsmParserInstCleanup");
2519 if (!InsnCleanupFn.empty())
2520 OS << " " << InsnCleanupFn << "(Inst);\n";
2521
2522 OS << " return Match_Success;\n";
2523 OS << " }\n\n";
2524
2525 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2526 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2527 OS << " return RetCode;\n";
2528 OS << " return Match_MissingFeature;\n";
2529 OS << "}\n\n";
2530
2531 if (Info.OperandMatchInfo.size())
2532 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2533
2534 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2535 }
2536