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