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