Re-commit r152202 hopefully fixing the MSVC linker error.
[oota-llvm.git] / utils / TableGen / AsmMatcherEmitter.cpp
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.
182   bool isRegisterClass() const {
183     return Kind >= RegisterClass0 && Kind < UserClass0;
184   }
185
186   /// isUserClass() - Check if this is a user defined class.
187   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.
193   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;
231   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.
246   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
290     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
337     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
345     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
353     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
361     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
380   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
412   MatchableInfo(const CodeGenInstruction &CGI)
413     : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
414       AsmString(CGI.AsmString) {
415   }
416
417   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.
438   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.
448   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.
459   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).
482   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
533   SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
534
535   /// \brief The name of the enumerated constant identifying this feature.
536   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
546   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.
629   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
636   RecordKeeper &getRecords() const {
637     return Records;
638   }
639 };
640
641 }
642
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
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.
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
761 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::
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
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
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 *
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 *
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::
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
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
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.
1128 void AsmMatcherInfo::BuildOperandMatchInfo() {
1129
1130   /// Map containing a mask with all operands indicies 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
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 = AsmVariant->getValueAsString("CommentDelimiter");
1185     std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1186     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1187
1188     for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1189            E = Target.inst_end(); I != E; ++I) {
1190       const CodeGenInstruction &CGI = **I;
1191
1192       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1193       // filter the set of instructions we consider.
1194       if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1195         continue;
1196
1197       // Ignore "codegen only" instructions.
1198       if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1199         continue;
1200
1201       // Validate the operand list to ensure we can handle this instruction.
1202       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1203         const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1204         
1205         // Validate tied operands.
1206         if (OI.getTiedRegister() != -1) {
1207           // If we have a tied operand that consists of multiple MCOperands,
1208           // reject it.  We reject aliases and ignore instructions for now.
1209           if (OI.MINumOperands != 1) {
1210             // FIXME: Should reject these.  The ARM backend hits this with $lane
1211             // in a bunch of instructions. It is unclear what the right answer is.
1212             DEBUG({
1213                 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1214                        << "ignoring instruction with multi-operand tied operand '"
1215                        << OI.Name << "'\n";
1216               });
1217             continue;
1218           }
1219         }
1220       }
1221
1222       OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1223
1224       II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1225
1226       // Ignore instructions which shouldn't be matched and diagnose invalid
1227       // instruction definitions with an error.
1228       if (!II->Validate(CommentDelimiter, true))
1229         continue;
1230
1231       // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1232       //
1233       // FIXME: This is a total hack.
1234       if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1235           StringRef(II->TheDef->getName()).endswith("_Int"))
1236         continue;
1237
1238       Matchables.push_back(II.take());
1239     }
1240
1241     // Parse all of the InstAlias definitions and stick them in the list of
1242     // matchables.
1243     std::vector<Record*> AllInstAliases =
1244       Records.getAllDerivedDefinitions("InstAlias");
1245     for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1246       CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1247
1248       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1249       // filter the set of instruction aliases we consider, based on the target
1250       // instruction.
1251       if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1252                                                                       MatchPrefix))
1253         continue;
1254
1255       OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1256
1257       II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1258
1259       // Validate the alias definitions.
1260       II->Validate(CommentDelimiter, false);
1261
1262       Matchables.push_back(II.take());
1263     }
1264   }
1265
1266   // Build info for the register classes.
1267   BuildRegisterClasses(SingletonRegisters);
1268
1269   // Build info for the user defined assembly operand classes.
1270   BuildOperandClasses();
1271
1272   // Build the information about matchables, now that we have fully formed
1273   // classes.
1274   for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1275          ie = Matchables.end(); it != ie; ++it) {
1276     MatchableInfo *II = *it;
1277
1278     // Parse the tokens after the mnemonic.
1279     // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1280     // don't precompute the loop bound.
1281     for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1282       MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1283       StringRef Token = Op.Token;
1284
1285       // Check for singleton registers.
1286       if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1287         Op.Class = RegisterClasses[RegRecord];
1288         assert(Op.Class && Op.Class->Registers.size() == 1 &&
1289                "Unexpected class for singleton register");
1290         continue;
1291       }
1292
1293       // Check for simple tokens.
1294       if (Token[0] != '$') {
1295         Op.Class = getTokenClass(Token);
1296         continue;
1297       }
1298
1299       if (Token.size() > 1 && isdigit(Token[1])) {
1300         Op.Class = getTokenClass(Token);
1301         continue;
1302       }
1303
1304       // Otherwise this is an operand reference.
1305       StringRef OperandName;
1306       if (Token[1] == '{')
1307         OperandName = Token.substr(2, Token.size() - 3);
1308       else
1309         OperandName = Token.substr(1);
1310
1311       if (II->DefRec.is<const CodeGenInstruction*>())
1312         BuildInstructionOperandReference(II, OperandName, i);
1313       else
1314         BuildAliasOperandReference(II, OperandName, Op);
1315     }
1316
1317     if (II->DefRec.is<const CodeGenInstruction*>())
1318       II->BuildInstructionResultOperands();
1319     else
1320       II->BuildAliasResultOperands();
1321   }
1322
1323   // Process token alias definitions and set up the associated superclass
1324   // information.
1325   std::vector<Record*> AllTokenAliases =
1326     Records.getAllDerivedDefinitions("TokenAlias");
1327   for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1328     Record *Rec = AllTokenAliases[i];
1329     ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1330     ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1331     FromClass->SuperClasses.push_back(ToClass);
1332   }
1333
1334   // Reorder classes so that classes precede super classes.
1335   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1336 }
1337
1338 /// BuildInstructionOperandReference - The specified operand is a reference to a
1339 /// named operand such as $src.  Resolve the Class and OperandInfo pointers.
1340 void AsmMatcherInfo::
1341 BuildInstructionOperandReference(MatchableInfo *II,
1342                                  StringRef OperandName,
1343                                  unsigned AsmOpIdx) {
1344   const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1345   const CGIOperandList &Operands = CGI.Operands;
1346   MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1347
1348   // Map this token to an operand.
1349   unsigned Idx;
1350   if (!Operands.hasOperandNamed(OperandName, Idx))
1351     throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1352                   OperandName.str() + "'");
1353
1354   // If the instruction operand has multiple suboperands, but the parser
1355   // match class for the asm operand is still the default "ImmAsmOperand",
1356   // then handle each suboperand separately.
1357   if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1358     Record *Rec = Operands[Idx].Rec;
1359     assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1360     Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1361     if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1362       // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1363       StringRef Token = Op->Token; // save this in case Op gets moved
1364       for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1365         MatchableInfo::AsmOperand NewAsmOp(Token);
1366         NewAsmOp.SubOpIdx = SI;
1367         II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1368       }
1369       // Replace Op with first suboperand.
1370       Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1371       Op->SubOpIdx = 0;
1372     }
1373   }
1374
1375   // Set up the operand class.
1376   Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1377
1378   // If the named operand is tied, canonicalize it to the untied operand.
1379   // For example, something like:
1380   //   (outs GPR:$dst), (ins GPR:$src)
1381   // with an asmstring of
1382   //   "inc $src"
1383   // we want to canonicalize to:
1384   //   "inc $dst"
1385   // so that we know how to provide the $dst operand when filling in the result.
1386   int OITied = Operands[Idx].getTiedRegister();
1387   if (OITied != -1) {
1388     // The tied operand index is an MIOperand index, find the operand that
1389     // contains it.
1390     std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1391     OperandName = Operands[Idx.first].Name;
1392     Op->SubOpIdx = Idx.second;
1393   }
1394
1395   Op->SrcOpName = OperandName;
1396 }
1397
1398 /// BuildAliasOperandReference - When parsing an operand reference out of the
1399 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1400 /// operand reference is by looking it up in the result pattern definition.
1401 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1402                                                 StringRef OperandName,
1403                                                 MatchableInfo::AsmOperand &Op) {
1404   const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1405
1406   // Set up the operand class.
1407   for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1408     if (CGA.ResultOperands[i].isRecord() &&
1409         CGA.ResultOperands[i].getName() == OperandName) {
1410       // It's safe to go with the first one we find, because CodeGenInstAlias
1411       // validates that all operands with the same name have the same record.
1412       Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1413       // Use the match class from the Alias definition, not the
1414       // destination instruction, as we may have an immediate that's
1415       // being munged by the match class.
1416       Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1417                                  Op.SubOpIdx);
1418       Op.SrcOpName = OperandName;
1419       return;
1420     }
1421
1422   throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1423                 OperandName.str() + "'");
1424 }
1425
1426 void MatchableInfo::BuildInstructionResultOperands() {
1427   const CodeGenInstruction *ResultInst = getResultInst();
1428
1429   // Loop over all operands of the result instruction, determining how to
1430   // populate them.
1431   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1432     const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1433
1434     // If this is a tied operand, just copy from the previously handled operand.
1435     int TiedOp = OpInfo.getTiedRegister();
1436     if (TiedOp != -1) {
1437       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1438       continue;
1439     }
1440
1441     // Find out what operand from the asmparser this MCInst operand comes from.
1442     int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1443     if (OpInfo.Name.empty() || SrcOperand == -1)
1444       throw TGError(TheDef->getLoc(), "Instruction '" +
1445                     TheDef->getName() + "' has operand '" + OpInfo.Name +
1446                     "' that doesn't appear in asm string!");
1447
1448     // Check if the one AsmOperand populates the entire operand.
1449     unsigned NumOperands = OpInfo.MINumOperands;
1450     if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1451       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1452       continue;
1453     }
1454
1455     // Add a separate ResOperand for each suboperand.
1456     for (unsigned AI = 0; AI < NumOperands; ++AI) {
1457       assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1458              AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1459              "unexpected AsmOperands for suboperands");
1460       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1461     }
1462   }
1463 }
1464
1465 void MatchableInfo::BuildAliasResultOperands() {
1466   const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1467   const CodeGenInstruction *ResultInst = getResultInst();
1468
1469   // Loop over all operands of the result instruction, determining how to
1470   // populate them.
1471   unsigned AliasOpNo = 0;
1472   unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1473   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1474     const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1475
1476     // If this is a tied operand, just copy from the previously handled operand.
1477     int TiedOp = OpInfo->getTiedRegister();
1478     if (TiedOp != -1) {
1479       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1480       continue;
1481     }
1482
1483     // Handle all the suboperands for this operand.
1484     const std::string &OpName = OpInfo->Name;
1485     for ( ; AliasOpNo <  LastOpNo &&
1486             CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1487       int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1488
1489       // Find out what operand from the asmparser that this MCInst operand
1490       // comes from.
1491       switch (CGA.ResultOperands[AliasOpNo].Kind) {
1492       case CodeGenInstAlias::ResultOperand::K_Record: {
1493         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1494         int SrcOperand = FindAsmOperand(Name, SubIdx);
1495         if (SrcOperand == -1)
1496           throw TGError(TheDef->getLoc(), "Instruction '" +
1497                         TheDef->getName() + "' has operand '" + OpName +
1498                         "' that doesn't appear in asm string!");
1499         unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1500         ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1501                                                         NumOperands));
1502         break;
1503       }
1504       case CodeGenInstAlias::ResultOperand::K_Imm: {
1505         int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1506         ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1507         break;
1508       }
1509       case CodeGenInstAlias::ResultOperand::K_Reg: {
1510         Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1511         ResOperands.push_back(ResOperand::getRegOp(Reg));
1512         break;
1513       }
1514       }
1515     }
1516   }
1517 }
1518
1519 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1520                                 std::vector<MatchableInfo*> &Infos,
1521                                 raw_ostream &OS) {
1522   // Write the convert function to a separate stream, so we can drop it after
1523   // the enum.
1524   std::string ConvertFnBody;
1525   raw_string_ostream CvtOS(ConvertFnBody);
1526
1527   // Function we have already generated.
1528   std::set<std::string> GeneratedFns;
1529
1530   // Start the unified conversion function.
1531   CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1532   CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1533         << "unsigned Opcode,\n"
1534         << "                      const SmallVectorImpl<MCParsedAsmOperand*"
1535         << "> &Operands) {\n";
1536   CvtOS << "  Inst.setOpcode(Opcode);\n";
1537   CvtOS << "  switch (Kind) {\n";
1538   CvtOS << "  default:\n";
1539
1540   // Start the enum, which we will generate inline.
1541
1542   OS << "// Unified function for converting operands to MCInst instances.\n\n";
1543   OS << "enum ConversionKind {\n";
1544
1545   // TargetOperandClass - This is the target's operand class, like X86Operand.
1546   std::string TargetOperandClass = Target.getName() + "Operand";
1547
1548   for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1549          ie = Infos.end(); it != ie; ++it) {
1550     MatchableInfo &II = **it;
1551
1552     // Check if we have a custom match function.
1553     std::string AsmMatchConverter =
1554       II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1555     if (!AsmMatchConverter.empty()) {
1556       std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1557       II.ConversionFnKind = Signature;
1558
1559       // Check if we have already generated this signature.
1560       if (!GeneratedFns.insert(Signature).second)
1561         continue;
1562
1563       // If not, emit it now.  Add to the enum list.
1564       OS << "  " << Signature << ",\n";
1565
1566       CvtOS << "  case " << Signature << ":\n";
1567       CvtOS << "    return " << AsmMatchConverter
1568             << "(Inst, Opcode, Operands);\n";
1569       continue;
1570     }
1571
1572     // Build the conversion function signature.
1573     std::string Signature = "Convert";
1574     std::string CaseBody;
1575     raw_string_ostream CaseOS(CaseBody);
1576
1577     // Compute the convert enum and the case body.
1578     for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1579       const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1580
1581       // Generate code to populate each result operand.
1582       switch (OpInfo.Kind) {
1583       case MatchableInfo::ResOperand::RenderAsmOperand: {
1584         // This comes from something we parsed.
1585         MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1586
1587         // Registers are always converted the same, don't duplicate the
1588         // conversion function based on them.
1589         Signature += "__";
1590         if (Op.Class->isRegisterClass())
1591           Signature += "Reg";
1592         else
1593           Signature += Op.Class->ClassName;
1594         Signature += utostr(OpInfo.MINumOperands);
1595         Signature += "_" + itostr(OpInfo.AsmOperandNum);
1596
1597         CaseOS << "    ((" << TargetOperandClass << "*)Operands["
1598                << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1599                << "(Inst, " << OpInfo.MINumOperands << ");\n";
1600         break;
1601       }
1602
1603       case MatchableInfo::ResOperand::TiedOperand: {
1604         // If this operand is tied to a previous one, just copy the MCInst
1605         // operand from the earlier one.We can only tie single MCOperand values.
1606         //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1607         unsigned TiedOp = OpInfo.TiedOperandNum;
1608         assert(i > TiedOp && "Tied operand precedes its target!");
1609         CaseOS << "    Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1610         Signature += "__Tie" + utostr(TiedOp);
1611         break;
1612       }
1613       case MatchableInfo::ResOperand::ImmOperand: {
1614         int64_t Val = OpInfo.ImmVal;
1615         CaseOS << "    Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1616         Signature += "__imm" + itostr(Val);
1617         break;
1618       }
1619       case MatchableInfo::ResOperand::RegOperand: {
1620         if (OpInfo.Register == 0) {
1621           CaseOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1622           Signature += "__reg0";
1623         } else {
1624           std::string N = getQualifiedName(OpInfo.Register);
1625           CaseOS << "    Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1626           Signature += "__reg" + OpInfo.Register->getName();
1627         }
1628       }
1629       }
1630     }
1631
1632     II.ConversionFnKind = Signature;
1633
1634     // Check if we have already generated this signature.
1635     if (!GeneratedFns.insert(Signature).second)
1636       continue;
1637
1638     // If not, emit it now.  Add to the enum list.
1639     OS << "  " << Signature << ",\n";
1640
1641     CvtOS << "  case " << Signature << ":\n";
1642     CvtOS << CaseOS.str();
1643     CvtOS << "    return true;\n";
1644   }
1645
1646   // Finish the convert function.
1647
1648   CvtOS << "  }\n";
1649   CvtOS << "  return false;\n";
1650   CvtOS << "}\n\n";
1651
1652   // Finish the enum, and drop the convert function after it.
1653
1654   OS << "  NumConversionVariants\n";
1655   OS << "};\n\n";
1656
1657   OS << CvtOS.str();
1658 }
1659
1660 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1661 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1662                                       std::vector<ClassInfo*> &Infos,
1663                                       raw_ostream &OS) {
1664   OS << "namespace {\n\n";
1665
1666   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1667      << "/// instruction matching.\n";
1668   OS << "enum MatchClassKind {\n";
1669   OS << "  InvalidMatchClass = 0,\n";
1670   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1671          ie = Infos.end(); it != ie; ++it) {
1672     ClassInfo &CI = **it;
1673     OS << "  " << CI.Name << ", // ";
1674     if (CI.Kind == ClassInfo::Token) {
1675       OS << "'" << CI.ValueName << "'\n";
1676     } else if (CI.isRegisterClass()) {
1677       if (!CI.ValueName.empty())
1678         OS << "register class '" << CI.ValueName << "'\n";
1679       else
1680         OS << "derived register class\n";
1681     } else {
1682       OS << "user defined class '" << CI.ValueName << "'\n";
1683     }
1684   }
1685   OS << "  NumMatchClassKinds\n";
1686   OS << "};\n\n";
1687
1688   OS << "}\n\n";
1689 }
1690
1691 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1692 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1693                                      raw_ostream &OS) {
1694   OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1695      << "MatchClassKind Kind) {\n";
1696   OS << "  " << Info.Target.getName() << "Operand &Operand = *("
1697      << Info.Target.getName() << "Operand*)GOp;\n";
1698
1699   // The InvalidMatchClass is not to match any operand.
1700   OS << "  if (Kind == InvalidMatchClass)\n";
1701   OS << "    return false;\n\n";
1702
1703   // Check for Token operands first.
1704   OS << "  if (Operand.isToken())\n";
1705   OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1706      << "\n\n";
1707
1708   // Check for register operands, including sub-classes.
1709   OS << "  if (Operand.isReg()) {\n";
1710   OS << "    MatchClassKind OpKind;\n";
1711   OS << "    switch (Operand.getReg()) {\n";
1712   OS << "    default: OpKind = InvalidMatchClass; break;\n";
1713   for (std::map<Record*, ClassInfo*>::iterator
1714          it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1715        it != ie; ++it)
1716     OS << "    case " << Info.Target.getName() << "::"
1717        << it->first->getName() << ": OpKind = " << it->second->Name
1718        << "; break;\n";
1719   OS << "    }\n";
1720   OS << "    return isSubclass(OpKind, Kind);\n";
1721   OS << "  }\n\n";
1722
1723   // Check the user classes. We don't care what order since we're only
1724   // actually matching against one of them.
1725   for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1726          ie = Info.Classes.end(); it != ie; ++it) {
1727     ClassInfo &CI = **it;
1728
1729     if (!CI.isUserClass())
1730       continue;
1731
1732     OS << "  // '" << CI.ClassName << "' class\n";
1733     OS << "  if (Kind == " << CI.Name
1734        << " && Operand." << CI.PredicateMethod << "()) {\n";
1735     OS << "    return true;\n";
1736     OS << "  }\n\n";
1737   }
1738
1739   OS << "  return false;\n";
1740   OS << "}\n\n";
1741 }
1742
1743 /// EmitIsSubclass - Emit the subclass predicate function.
1744 static void EmitIsSubclass(CodeGenTarget &Target,
1745                            std::vector<ClassInfo*> &Infos,
1746                            raw_ostream &OS) {
1747   OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1748   OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1749   OS << "  if (A == B)\n";
1750   OS << "    return true;\n\n";
1751
1752   OS << "  switch (A) {\n";
1753   OS << "  default:\n";
1754   OS << "    return false;\n";
1755   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1756          ie = Infos.end(); it != ie; ++it) {
1757     ClassInfo &A = **it;
1758
1759     std::vector<StringRef> SuperClasses;
1760     for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1761          ie = Infos.end(); it != ie; ++it) {
1762       ClassInfo &B = **it;
1763
1764       if (&A != &B && A.isSubsetOf(B))
1765         SuperClasses.push_back(B.Name);
1766     }
1767
1768     if (SuperClasses.empty())
1769       continue;
1770
1771     OS << "\n  case " << A.Name << ":\n";
1772
1773     if (SuperClasses.size() == 1) {
1774       OS << "    return B == " << SuperClasses.back() << ";\n";
1775       continue;
1776     }
1777
1778     OS << "    switch (B) {\n";
1779     OS << "    default: return false;\n";
1780     for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1781       OS << "    case " << SuperClasses[i] << ": return true;\n";
1782     OS << "    }\n";
1783   }
1784   OS << "  }\n";
1785   OS << "}\n\n";
1786 }
1787
1788 /// EmitMatchTokenString - Emit the function to match a token string to the
1789 /// appropriate match class value.
1790 static void EmitMatchTokenString(CodeGenTarget &Target,
1791                                  std::vector<ClassInfo*> &Infos,
1792                                  raw_ostream &OS) {
1793   // Construct the match list.
1794   std::vector<StringMatcher::StringPair> Matches;
1795   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1796          ie = Infos.end(); it != ie; ++it) {
1797     ClassInfo &CI = **it;
1798
1799     if (CI.Kind == ClassInfo::Token)
1800       Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1801                                                   "return " + CI.Name + ";"));
1802   }
1803
1804   OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1805
1806   StringMatcher("Name", Matches, OS).Emit();
1807
1808   OS << "  return InvalidMatchClass;\n";
1809   OS << "}\n\n";
1810 }
1811
1812 /// EmitMatchRegisterName - Emit the function to match a string to the target
1813 /// specific register enum.
1814 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1815                                   raw_ostream &OS) {
1816   // Construct the match list.
1817   std::vector<StringMatcher::StringPair> Matches;
1818   const std::vector<CodeGenRegister*> &Regs =
1819     Target.getRegBank().getRegisters();
1820   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1821     const CodeGenRegister *Reg = Regs[i];
1822     if (Reg->TheDef->getValueAsString("AsmName").empty())
1823       continue;
1824
1825     Matches.push_back(StringMatcher::StringPair(
1826                                      Reg->TheDef->getValueAsString("AsmName"),
1827                                      "return " + utostr(Reg->EnumValue) + ";"));
1828   }
1829
1830   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1831
1832   StringMatcher("Name", Matches, OS).Emit();
1833
1834   OS << "  return 0;\n";
1835   OS << "}\n\n";
1836 }
1837
1838 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1839 /// definitions.
1840 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1841                                                 raw_ostream &OS) {
1842   OS << "// Flags for subtarget features that participate in "
1843      << "instruction matching.\n";
1844   OS << "enum SubtargetFeatureFlag {\n";
1845   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1846          it = Info.SubtargetFeatures.begin(),
1847          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1848     SubtargetFeatureInfo &SFI = *it->second;
1849     OS << "  " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1850   }
1851   OS << "  Feature_None = 0\n";
1852   OS << "};\n\n";
1853 }
1854
1855 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1856 /// available features given a subtarget.
1857 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1858                                          raw_ostream &OS) {
1859   std::string ClassName =
1860     Info.AsmParser->getValueAsString("AsmParserClassName");
1861
1862   OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1863      << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1864   OS << "  unsigned Features = 0;\n";
1865   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1866          it = Info.SubtargetFeatures.begin(),
1867          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1868     SubtargetFeatureInfo &SFI = *it->second;
1869
1870     OS << "  if (";
1871     std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1872     StringRef Conds = CondStorage;
1873     std::pair<StringRef,StringRef> Comma = Conds.split(',');
1874     bool First = true;
1875     do {
1876       if (!First)
1877         OS << " && ";
1878
1879       bool Neg = false;
1880       StringRef Cond = Comma.first;
1881       if (Cond[0] == '!') {
1882         Neg = true;
1883         Cond = Cond.substr(1);
1884       }
1885
1886       OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1887       if (Neg)
1888         OS << " == 0";
1889       else
1890         OS << " != 0";
1891       OS << ")";
1892
1893       if (Comma.second.empty())
1894         break;
1895
1896       First = false;
1897       Comma = Comma.second.split(',');
1898     } while (true);
1899
1900     OS << ")\n";
1901     OS << "    Features |= " << SFI.getEnumName() << ";\n";
1902   }
1903   OS << "  return Features;\n";
1904   OS << "}\n\n";
1905 }
1906
1907 static std::string GetAliasRequiredFeatures(Record *R,
1908                                             const AsmMatcherInfo &Info) {
1909   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1910   std::string Result;
1911   unsigned NumFeatures = 0;
1912   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1913     SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1914
1915     if (F == 0)
1916       throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1917                     "' is not marked as an AssemblerPredicate!");
1918
1919     if (NumFeatures)
1920       Result += '|';
1921
1922     Result += F->getEnumName();
1923     ++NumFeatures;
1924   }
1925
1926   if (NumFeatures > 1)
1927     Result = '(' + Result + ')';
1928   return Result;
1929 }
1930
1931 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1932 /// emit a function for them and return true, otherwise return false.
1933 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1934   // Ignore aliases when match-prefix is set.
1935   if (!MatchPrefix.empty())
1936     return false;
1937
1938   std::vector<Record*> Aliases =
1939     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1940   if (Aliases.empty()) return false;
1941
1942   OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1943         "unsigned Features) {\n";
1944
1945   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
1946   // iteration order of the map is stable.
1947   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1948
1949   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1950     Record *R = Aliases[i];
1951     AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1952   }
1953
1954   // Process each alias a "from" mnemonic at a time, building the code executed
1955   // by the string remapper.
1956   std::vector<StringMatcher::StringPair> Cases;
1957   for (std::map<std::string, std::vector<Record*> >::iterator
1958        I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1959        I != E; ++I) {
1960     const std::vector<Record*> &ToVec = I->second;
1961
1962     // Loop through each alias and emit code that handles each case.  If there
1963     // are two instructions without predicates, emit an error.  If there is one,
1964     // emit it last.
1965     std::string MatchCode;
1966     int AliasWithNoPredicate = -1;
1967
1968     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1969       Record *R = ToVec[i];
1970       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1971
1972       // If this unconditionally matches, remember it for later and diagnose
1973       // duplicates.
1974       if (FeatureMask.empty()) {
1975         if (AliasWithNoPredicate != -1) {
1976           // We can't have two aliases from the same mnemonic with no predicate.
1977           PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1978                      "two MnemonicAliases with the same 'from' mnemonic!");
1979           throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1980         }
1981
1982         AliasWithNoPredicate = i;
1983         continue;
1984       }
1985       if (R->getValueAsString("ToMnemonic") == I->first)
1986         throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1987
1988       if (!MatchCode.empty())
1989         MatchCode += "else ";
1990       MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1991       MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1992     }
1993
1994     if (AliasWithNoPredicate != -1) {
1995       Record *R = ToVec[AliasWithNoPredicate];
1996       if (!MatchCode.empty())
1997         MatchCode += "else\n  ";
1998       MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1999     }
2000
2001     MatchCode += "return;";
2002
2003     Cases.push_back(std::make_pair(I->first, MatchCode));
2004   }
2005
2006   StringMatcher("Mnemonic", Cases, OS).Emit();
2007   OS << "}\n\n";
2008
2009   return true;
2010 }
2011
2012 static const char *getMinimalTypeForRange(uint64_t Range) {
2013   assert(Range < 0xFFFFFFFFULL && "Enum too large");
2014   if (Range > 0xFFFF)
2015     return "uint32_t";
2016   if (Range > 0xFF)
2017     return "uint16_t";
2018   return "uint8_t";
2019 }
2020
2021 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2022                               const AsmMatcherInfo &Info, StringRef ClassName) {
2023   // Emit the static custom operand parsing table;
2024   OS << "namespace {\n";
2025   OS << "  struct OperandMatchEntry {\n";
2026   OS << "    static const char *const MnemonicTable;\n";
2027   OS << "    unsigned OperandMask;\n";
2028   OS << "    uint16_t Mnemonic;\n";
2029   OS << "    " << getMinimalTypeForRange(Info.Classes.size())
2030                << " Class;\n";
2031   OS << "    " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2032                << " RequiredFeatures;\n\n";
2033   OS << "    StringRef getMnemonic() const {\n";
2034   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
2035   OS << "                       MnemonicTable[Mnemonic]);\n";
2036   OS << "    }\n";
2037   OS << "  };\n\n";
2038
2039   OS << "  // Predicate for searching for an opcode.\n";
2040   OS << "  struct LessOpcodeOperand {\n";
2041   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2042   OS << "      return LHS.getMnemonic()  < RHS;\n";
2043   OS << "    }\n";
2044   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2045   OS << "      return LHS < RHS.getMnemonic();\n";
2046   OS << "    }\n";
2047   OS << "    bool operator()(const OperandMatchEntry &LHS,";
2048   OS << " const OperandMatchEntry &RHS) {\n";
2049   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
2050   OS << "    }\n";
2051   OS << "  };\n";
2052
2053   OS << "} // end anonymous namespace.\n\n";
2054
2055   StringToOffsetTable StringTable;
2056
2057   OS << "static const OperandMatchEntry OperandMatchTable["
2058      << Info.OperandMatchInfo.size() << "] = {\n";
2059
2060   OS << "  /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2061   for (std::vector<OperandMatchEntry>::const_iterator it =
2062        Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2063        it != ie; ++it) {
2064     const OperandMatchEntry &OMI = *it;
2065     const MatchableInfo &II = *OMI.MI;
2066
2067     OS << "  { " << OMI.OperandMask;
2068
2069     OS << " /* ";
2070     bool printComma = false;
2071     for (int i = 0, e = 31; i !=e; ++i)
2072       if (OMI.OperandMask & (1 << i)) {
2073         if (printComma)
2074           OS << ", ";
2075         OS << i;
2076         printComma = true;
2077       }
2078     OS << " */";
2079
2080     // Store a pascal-style length byte in the mnemonic.
2081     std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2082     unsigned Idx = StringTable.GetOrAddStringOffset(LenMnemonic, false);
2083     assert(Idx <= 0xffff && "String offset too large to fit in table");
2084     OS << ", " << Idx << " /* " << II.Mnemonic << " */";
2085
2086     OS << ", " << OMI.CI->Name
2087        << ", ";
2088
2089     // Write the required features mask.
2090     if (!II.RequiredFeatures.empty()) {
2091       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2092         if (i) OS << "|";
2093         OS << II.RequiredFeatures[i]->getEnumName();
2094       }
2095     } else
2096       OS << "0";
2097     OS << " },\n";
2098   }
2099   OS << "};\n\n";
2100
2101   OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
2102   StringTable.EmitString(OS);
2103   OS << ";\n\n";
2104
2105   // Emit the operand class switch to call the correct custom parser for
2106   // the found operand class.
2107   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2108      << Target.getName() << ClassName << "::\n"
2109      << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2110      << " &Operands,\n                      unsigned MCK) {\n\n"
2111      << "  switch(MCK) {\n";
2112
2113   for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2114        ie = Info.Classes.end(); it != ie; ++it) {
2115     ClassInfo *CI = *it;
2116     if (CI->ParserMethod.empty())
2117       continue;
2118     OS << "  case " << CI->Name << ":\n"
2119        << "    return " << CI->ParserMethod << "(Operands);\n";
2120   }
2121
2122   OS << "  default:\n";
2123   OS << "    return MatchOperand_NoMatch;\n";
2124   OS << "  }\n";
2125   OS << "  return MatchOperand_NoMatch;\n";
2126   OS << "}\n\n";
2127
2128   // Emit the static custom operand parser. This code is very similar with
2129   // the other matcher. Also use MatchResultTy here just in case we go for
2130   // a better error handling.
2131   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2132      << Target.getName() << ClassName << "::\n"
2133      << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2134      << " &Operands,\n                       StringRef Mnemonic) {\n";
2135
2136   // Emit code to get the available features.
2137   OS << "  // Get the current feature set.\n";
2138   OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2139
2140   OS << "  // Get the next operand index.\n";
2141   OS << "  unsigned NextOpNum = Operands.size()-1;\n";
2142
2143   // Emit code to search the table.
2144   OS << "  // Search the table.\n";
2145   OS << "  std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2146   OS << " MnemonicRange =\n";
2147   OS << "    std::equal_range(OperandMatchTable, OperandMatchTable+"
2148      << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2149      << "                     LessOpcodeOperand());\n\n";
2150
2151   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2152   OS << "    return MatchOperand_NoMatch;\n\n";
2153
2154   OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2155      << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
2156
2157   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2158   OS << "    assert(Mnemonic == it->getMnemonic());\n\n";
2159
2160   // Emit check that the required features are available.
2161   OS << "    // check if the available features match\n";
2162   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2163      << "!= it->RequiredFeatures) {\n";
2164   OS << "      continue;\n";
2165   OS << "    }\n\n";
2166
2167   // Emit check to ensure the operand number matches.
2168   OS << "    // check if the operand in question has a custom parser.\n";
2169   OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
2170   OS << "      continue;\n\n";
2171
2172   // Emit call to the custom parser method
2173   OS << "    // call custom parse method to handle the operand\n";
2174   OS << "    OperandMatchResultTy Result = ";
2175   OS << "tryCustomParseOperand(Operands, it->Class);\n";
2176   OS << "    if (Result != MatchOperand_NoMatch)\n";
2177   OS << "      return Result;\n";
2178   OS << "  }\n\n";
2179
2180   OS << "  // Okay, we had no match.\n";
2181   OS << "  return MatchOperand_NoMatch;\n";
2182   OS << "}\n\n";
2183 }
2184
2185 void AsmMatcherEmitter::run(raw_ostream &OS) {
2186   CodeGenTarget Target(Records);
2187   Record *AsmParser = Target.getAsmParser();
2188   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2189
2190   // Compute the information on the instructions to match.
2191   AsmMatcherInfo Info(AsmParser, Target, Records);
2192   Info.BuildInfo();
2193
2194   // Sort the instruction table using the partial order on classes. We use
2195   // stable_sort to ensure that ambiguous instructions are still
2196   // deterministically ordered.
2197   std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2198                    less_ptr<MatchableInfo>());
2199
2200   DEBUG_WITH_TYPE("instruction_info", {
2201       for (std::vector<MatchableInfo*>::iterator
2202              it = Info.Matchables.begin(), ie = Info.Matchables.end();
2203            it != ie; ++it)
2204         (*it)->dump();
2205     });
2206
2207   // Check for ambiguous matchables.
2208   DEBUG_WITH_TYPE("ambiguous_instrs", {
2209     unsigned NumAmbiguous = 0;
2210     for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2211       for (unsigned j = i + 1; j != e; ++j) {
2212         MatchableInfo &A = *Info.Matchables[i];
2213         MatchableInfo &B = *Info.Matchables[j];
2214
2215         if (A.CouldMatchAmbiguouslyWith(B)) {
2216           errs() << "warning: ambiguous matchables:\n";
2217           A.dump();
2218           errs() << "\nis incomparable with:\n";
2219           B.dump();
2220           errs() << "\n\n";
2221           ++NumAmbiguous;
2222         }
2223       }
2224     }
2225     if (NumAmbiguous)
2226       errs() << "warning: " << NumAmbiguous
2227              << " ambiguous matchables!\n";
2228   });
2229
2230   // Compute the information on the custom operand parsing.
2231   Info.BuildOperandMatchInfo();
2232
2233   // Write the output.
2234
2235   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2236
2237   // Information for the class declaration.
2238   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2239   OS << "#undef GET_ASSEMBLER_HEADER\n";
2240   OS << "  // This should be included into the middle of the declaration of\n";
2241   OS << "  // your subclasses implementation of MCTargetAsmParser.\n";
2242   OS << "  unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2243   OS << "  bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2244      << "unsigned Opcode,\n"
2245      << "                       const SmallVectorImpl<MCParsedAsmOperand*> "
2246      << "&Operands);\n";
2247   OS << "  bool MnemonicIsValid(StringRef Mnemonic);\n";
2248   OS << "  unsigned MatchInstructionImpl(\n";
2249   OS << "    const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2250   OS << "    MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2251
2252   if (Info.OperandMatchInfo.size()) {
2253     OS << "\n  enum OperandMatchResultTy {\n";
2254     OS << "    MatchOperand_Success,    // operand matched successfully\n";
2255     OS << "    MatchOperand_NoMatch,    // operand did not match\n";
2256     OS << "    MatchOperand_ParseFail   // operand matched but had errors\n";
2257     OS << "  };\n";
2258     OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
2259     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2260     OS << "    StringRef Mnemonic);\n";
2261
2262     OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
2263     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2264     OS << "    unsigned MCK);\n\n";
2265   }
2266
2267   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2268
2269   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2270   OS << "#undef GET_REGISTER_MATCHER\n\n";
2271
2272   // Emit the subtarget feature enumeration.
2273   EmitSubtargetFeatureFlagEnumeration(Info, OS);
2274
2275   // Emit the function to match a register name to number.
2276   EmitMatchRegisterName(Target, AsmParser, OS);
2277
2278   OS << "#endif // GET_REGISTER_MATCHER\n\n";
2279
2280
2281   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2282   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2283
2284   // Generate the function that remaps for mnemonic aliases.
2285   bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2286
2287   // Generate the unified function to convert operands into an MCInst.
2288   EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2289
2290   // Emit the enumeration for classes which participate in matching.
2291   EmitMatchClassEnumeration(Target, Info.Classes, OS);
2292
2293   // Emit the routine to match token strings to their match class.
2294   EmitMatchTokenString(Target, Info.Classes, OS);
2295
2296   // Emit the subclass predicate routine.
2297   EmitIsSubclass(Target, Info.Classes, OS);
2298
2299   // Emit the routine to validate an operand against a match class.
2300   EmitValidateOperandClass(Info, OS);
2301
2302   // Emit the available features compute function.
2303   EmitComputeAvailableFeatures(Info, OS);
2304
2305
2306   size_t MaxNumOperands = 0;
2307   for (std::vector<MatchableInfo*>::const_iterator it =
2308          Info.Matchables.begin(), ie = Info.Matchables.end();
2309        it != ie; ++it)
2310     MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2311
2312   // Emit the static match table; unused classes get initalized to 0 which is
2313   // guaranteed to be InvalidMatchClass.
2314   //
2315   // FIXME: We can reduce the size of this table very easily. First, we change
2316   // it so that store the kinds in separate bit-fields for each index, which
2317   // only needs to be the max width used for classes at that index (we also need
2318   // to reject based on this during classification). If we then make sure to
2319   // order the match kinds appropriately (putting mnemonics last), then we
2320   // should only end up using a few bits for each class, especially the ones
2321   // following the mnemonic.
2322   OS << "namespace {\n";
2323   OS << "  struct MatchEntry {\n";
2324   OS << "    static const char *const MnemonicTable;\n";
2325   OS << "    uint16_t Opcode;\n";
2326   OS << "    uint16_t Mnemonic;\n";
2327   OS << "    " << getMinimalTypeForRange(Info.Matchables.size())
2328                << " ConvertFn;\n";
2329   OS << "    " << getMinimalTypeForRange(Info.Classes.size())
2330                << " Classes[" << MaxNumOperands << "];\n";
2331   OS << "    " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2332                << " RequiredFeatures;\n";
2333   OS << "    uint8_t AsmVariantID;\n\n";
2334   OS << "    StringRef getMnemonic() const {\n";
2335   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
2336   OS << "                       MnemonicTable[Mnemonic]);\n";
2337   OS << "    }\n";
2338   OS << "  };\n\n";
2339
2340   OS << "  // Predicate for searching for an opcode.\n";
2341   OS << "  struct LessOpcode {\n";
2342   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2343   OS << "      return LHS.getMnemonic() < RHS;\n";
2344   OS << "    }\n";
2345   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2346   OS << "      return LHS < RHS.getMnemonic();\n";
2347   OS << "    }\n";
2348   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2349   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
2350   OS << "    }\n";
2351   OS << "  };\n";
2352
2353   OS << "} // end anonymous namespace.\n\n";
2354
2355   StringToOffsetTable StringTable;
2356
2357   OS << "static const MatchEntry MatchTable["
2358      << Info.Matchables.size() << "] = {\n";
2359
2360   for (std::vector<MatchableInfo*>::const_iterator it =
2361        Info.Matchables.begin(), ie = Info.Matchables.end();
2362        it != ie; ++it) {
2363     MatchableInfo &II = **it;
2364
2365     // Store a pascal-style length byte in the mnemonic.
2366     std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2367     unsigned Idx = StringTable.GetOrAddStringOffset(LenMnemonic, false);
2368     assert(Idx <= 0xffff && "String offset too large to fit in table");
2369     OS << "  { " << Target.getName() << "::"
2370        << II.getResultInst()->TheDef->getName() << ", "
2371        << Idx << " /* " << II.Mnemonic << " */"
2372        << ", " << II.ConversionFnKind << ", { ";
2373     for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2374       MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2375
2376       if (i) OS << ", ";
2377       OS << Op.Class->Name;
2378     }
2379     OS << " }, ";
2380
2381     // Write the required features mask.
2382     if (!II.RequiredFeatures.empty()) {
2383       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2384         if (i) OS << "|";
2385         OS << II.RequiredFeatures[i]->getEnumName();
2386       }
2387     } else
2388       OS << "0";
2389     OS << ", " << II.AsmVariantID;
2390     OS << "},\n";
2391   }
2392
2393   OS << "};\n\n";
2394
2395   OS << "const char *const MatchEntry::MnemonicTable =\n";
2396   StringTable.EmitString(OS);
2397   OS << ";\n\n";
2398
2399   // A method to determine if a mnemonic is in the list.
2400   OS << "bool " << Target.getName() << ClassName << "::\n"
2401      << "MnemonicIsValid(StringRef Mnemonic) {\n";
2402   OS << "  // Search the table.\n";
2403   OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2404   OS << "    std::equal_range(MatchTable, MatchTable+"
2405      << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2406   OS << "  return MnemonicRange.first != MnemonicRange.second;\n";
2407   OS << "}\n\n";
2408
2409   // Finally, build the match function.
2410   OS << "unsigned "
2411      << Target.getName() << ClassName << "::\n"
2412      << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2413      << " &Operands,\n";
2414   OS << "                     MCInst &Inst, unsigned &ErrorInfo,\n";
2415   OS << "                     unsigned VariantID) {\n";
2416
2417   // Emit code to get the available features.
2418   OS << "  // Get the current feature set.\n";
2419   OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2420
2421   OS << "  // Get the instruction mnemonic, which is the first token.\n";
2422   OS << "  StringRef Mnemonic = ((" << Target.getName()
2423      << "Operand*)Operands[0])->getToken();\n\n";
2424
2425   if (HasMnemonicAliases) {
2426     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
2427     OS << "  // FIXME : Add an entry in AsmParserVariant to check this.\n";
2428     OS << "  if (!VariantID)\n";
2429     OS << "    applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2430   }
2431
2432   // Emit code to compute the class list for this operand vector.
2433   OS << "  // Eliminate obvious mismatches.\n";
2434   OS << "  if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2435   OS << "    ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2436   OS << "    return Match_InvalidOperand;\n";
2437   OS << "  }\n\n";
2438
2439   OS << "  // Some state to try to produce better error messages.\n";
2440   OS << "  bool HadMatchOtherThanFeatures = false;\n";
2441   OS << "  bool HadMatchOtherThanPredicate = false;\n";
2442   OS << "  unsigned RetCode = Match_InvalidOperand;\n";
2443   OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
2444   OS << "  // wrong for all instances of the instruction.\n";
2445   OS << "  ErrorInfo = ~0U;\n";
2446
2447   // Emit code to search the table.
2448   OS << "  // Search the table.\n";
2449   OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2450   OS << "    std::equal_range(MatchTable, MatchTable+"
2451      << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2452
2453   OS << "  // Return a more specific error code if no mnemonics match.\n";
2454   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2455   OS << "    return Match_MnemonicFail;\n\n";
2456
2457   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
2458      << "*ie = MnemonicRange.second;\n";
2459   OS << "       it != ie; ++it) {\n";
2460
2461   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2462   OS << "    assert(Mnemonic == it->getMnemonic());\n";
2463
2464   // Emit check that the subclasses match.
2465   OS << "    if (VariantID != it->AsmVariantID) continue;\n";
2466   OS << "    bool OperandsValid = true;\n";
2467   OS << "    for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2468   OS << "      if (i + 1 >= Operands.size()) {\n";
2469   OS << "        OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2470   OS << "        break;\n";
2471   OS << "      }\n";
2472   OS << "      if (validateOperandClass(Operands[i+1], "
2473                                        "(MatchClassKind)it->Classes[i]))\n";
2474   OS << "        continue;\n";
2475   OS << "      // If this operand is broken for all of the instances of this\n";
2476   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
2477   OS << "      if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2478   OS << "        ErrorInfo = i+1;\n";
2479   OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
2480   OS << "      OperandsValid = false;\n";
2481   OS << "      break;\n";
2482   OS << "    }\n\n";
2483
2484   OS << "    if (!OperandsValid) continue;\n";
2485
2486   // Emit check that the required features are available.
2487   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2488      << "!= it->RequiredFeatures) {\n";
2489   OS << "      HadMatchOtherThanFeatures = true;\n";
2490   OS << "      continue;\n";
2491   OS << "    }\n";
2492   OS << "\n";
2493   OS << "    // We have selected a definite instruction, convert the parsed\n"
2494      << "    // operands into the appropriate MCInst.\n";
2495   OS << "    if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2496      << "                         it->Opcode, Operands))\n";
2497   OS << "      return Match_ConversionFail;\n";
2498   OS << "\n";
2499
2500   // Verify the instruction with the target-specific match predicate function.
2501   OS << "    // We have a potential match. Check the target predicate to\n"
2502      << "    // handle any context sensitive constraints.\n"
2503      << "    unsigned MatchResult;\n"
2504      << "    if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2505      << " Match_Success) {\n"
2506      << "      Inst.clear();\n"
2507      << "      RetCode = MatchResult;\n"
2508      << "      HadMatchOtherThanPredicate = true;\n"
2509      << "      continue;\n"
2510      << "    }\n\n";
2511
2512   // Call the post-processing function, if used.
2513   std::string InsnCleanupFn =
2514     AsmParser->getValueAsString("AsmParserInstCleanup");
2515   if (!InsnCleanupFn.empty())
2516     OS << "    " << InsnCleanupFn << "(Inst);\n";
2517
2518   OS << "    return Match_Success;\n";
2519   OS << "  }\n\n";
2520
2521   OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
2522   OS << "  if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2523   OS << " return RetCode;\n";
2524   OS << "  return Match_MissingFeature;\n";
2525   OS << "}\n\n";
2526
2527   if (Info.OperandMatchInfo.size())
2528     EmitCustomOperandParsing(OS, Target, Info, ClassName);
2529
2530   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2531 }