Home | History | Annotate | Download | only in TableGen
      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 values 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 "CodeGenTarget.h"
    100 #include "llvm/ADT/PointerUnion.h"
    101 #include "llvm/ADT/STLExtras.h"
    102 #include "llvm/ADT/SmallPtrSet.h"
    103 #include "llvm/ADT/SmallVector.h"
    104 #include "llvm/ADT/StringExtras.h"
    105 #include "llvm/Support/CommandLine.h"
    106 #include "llvm/Support/Debug.h"
    107 #include "llvm/Support/ErrorHandling.h"
    108 #include "llvm/TableGen/Error.h"
    109 #include "llvm/TableGen/Record.h"
    110 #include "llvm/TableGen/StringMatcher.h"
    111 #include "llvm/TableGen/StringToOffsetTable.h"
    112 #include "llvm/TableGen/TableGenBackend.h"
    113 #include <cassert>
    114 #include <cctype>
    115 #include <forward_list>
    116 #include <map>
    117 #include <set>
    118 
    119 using namespace llvm;
    120 
    121 #define DEBUG_TYPE "asm-matcher-emitter"
    122 
    123 static cl::opt<std::string>
    124 MatchPrefix("match-prefix", cl::init(""),
    125             cl::desc("Only match instructions with the given prefix"));
    126 
    127 namespace {
    128 class AsmMatcherInfo;
    129 struct SubtargetFeatureInfo;
    130 
    131 // Register sets are used as keys in some second-order sets TableGen creates
    132 // when generating its data structures. This means that the order of two
    133 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
    134 // can even affect compiler output (at least seen in diagnostics produced when
    135 // all matches fail). So we use a type that sorts them consistently.
    136 typedef std::set<Record*, LessRecordByID> RegisterSet;
    137 
    138 class AsmMatcherEmitter {
    139   RecordKeeper &Records;
    140 public:
    141   AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
    142 
    143   void run(raw_ostream &o);
    144 };
    145 
    146 /// ClassInfo - Helper class for storing the information about a particular
    147 /// class of operands which can be matched.
    148 struct ClassInfo {
    149   enum ClassInfoKind {
    150     /// Invalid kind, for use as a sentinel value.
    151     Invalid = 0,
    152 
    153     /// The class for a particular token.
    154     Token,
    155 
    156     /// The (first) register class, subsequent register classes are
    157     /// RegisterClass0+1, and so on.
    158     RegisterClass0,
    159 
    160     /// The (first) user defined class, subsequent user defined classes are
    161     /// UserClass0+1, and so on.
    162     UserClass0 = 1<<16
    163   };
    164 
    165   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
    166   /// N) for the Nth user defined class.
    167   unsigned Kind;
    168 
    169   /// SuperClasses - The super classes of this class. Note that for simplicities
    170   /// sake user operands only record their immediate super class, while register
    171   /// operands include all superclasses.
    172   std::vector<ClassInfo*> SuperClasses;
    173 
    174   /// Name - The full class name, suitable for use in an enum.
    175   std::string Name;
    176 
    177   /// ClassName - The unadorned generic name for this class (e.g., Token).
    178   std::string ClassName;
    179 
    180   /// ValueName - The name of the value this class represents; for a token this
    181   /// is the literal token string, for an operand it is the TableGen class (or
    182   /// empty if this is a derived class).
    183   std::string ValueName;
    184 
    185   /// PredicateMethod - The name of the operand method to test whether the
    186   /// operand matches this class; this is not valid for Token or register kinds.
    187   std::string PredicateMethod;
    188 
    189   /// RenderMethod - The name of the operand method to add this operand to an
    190   /// MCInst; this is not valid for Token or register kinds.
    191   std::string RenderMethod;
    192 
    193   /// ParserMethod - The name of the operand method to do a target specific
    194   /// parsing on the operand.
    195   std::string ParserMethod;
    196 
    197   /// For register classes: the records for all the registers in this class.
    198   RegisterSet Registers;
    199 
    200   /// For custom match classes: the diagnostic kind for when the predicate fails.
    201   std::string DiagnosticType;
    202 
    203   /// Is this operand optional and not always required.
    204   bool IsOptional;
    205 
    206   /// DefaultMethod - The name of the method that returns the default operand
    207   /// for optional operand
    208   std::string DefaultMethod;
    209 
    210 public:
    211   /// isRegisterClass() - Check if this is a register class.
    212   bool isRegisterClass() const {
    213     return Kind >= RegisterClass0 && Kind < UserClass0;
    214   }
    215 
    216   /// isUserClass() - Check if this is a user defined class.
    217   bool isUserClass() const {
    218     return Kind >= UserClass0;
    219   }
    220 
    221   /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
    222   /// are related if they are in the same class hierarchy.
    223   bool isRelatedTo(const ClassInfo &RHS) const {
    224     // Tokens are only related to tokens.
    225     if (Kind == Token || RHS.Kind == Token)
    226       return Kind == Token && RHS.Kind == Token;
    227 
    228     // Registers classes are only related to registers classes, and only if
    229     // their intersection is non-empty.
    230     if (isRegisterClass() || RHS.isRegisterClass()) {
    231       if (!isRegisterClass() || !RHS.isRegisterClass())
    232         return false;
    233 
    234       RegisterSet Tmp;
    235       std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
    236       std::set_intersection(Registers.begin(), Registers.end(),
    237                             RHS.Registers.begin(), RHS.Registers.end(),
    238                             II, LessRecordByID());
    239 
    240       return !Tmp.empty();
    241     }
    242 
    243     // Otherwise we have two users operands; they are related if they are in the
    244     // same class hierarchy.
    245     //
    246     // FIXME: This is an oversimplification, they should only be related if they
    247     // intersect, however we don't have that information.
    248     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
    249     const ClassInfo *Root = this;
    250     while (!Root->SuperClasses.empty())
    251       Root = Root->SuperClasses.front();
    252 
    253     const ClassInfo *RHSRoot = &RHS;
    254     while (!RHSRoot->SuperClasses.empty())
    255       RHSRoot = RHSRoot->SuperClasses.front();
    256 
    257     return Root == RHSRoot;
    258   }
    259 
    260   /// isSubsetOf - Test whether this class is a subset of \p RHS.
    261   bool isSubsetOf(const ClassInfo &RHS) const {
    262     // This is a subset of RHS if it is the same class...
    263     if (this == &RHS)
    264       return true;
    265 
    266     // ... or if any of its super classes are a subset of RHS.
    267     for (const ClassInfo *CI : SuperClasses)
    268       if (CI->isSubsetOf(RHS))
    269         return true;
    270 
    271     return false;
    272   }
    273 
    274   int getTreeDepth() const {
    275     int Depth = 0;
    276     const ClassInfo *Root = this;
    277     while (!Root->SuperClasses.empty()) {
    278       Depth++;
    279       Root = Root->SuperClasses.front();
    280     }
    281     return Depth;
    282   }
    283 
    284   const ClassInfo *findRoot() const {
    285     const ClassInfo *Root = this;
    286     while (!Root->SuperClasses.empty())
    287       Root = Root->SuperClasses.front();
    288     return Root;
    289   }
    290 
    291   /// Compare two classes. This does not produce a total ordering, but does
    292   /// guarantee that subclasses are sorted before their parents, and that the
    293   /// ordering is transitive.
    294   bool operator<(const ClassInfo &RHS) const {
    295     if (this == &RHS)
    296       return false;
    297 
    298     // First, enforce the ordering between the three different types of class.
    299     // Tokens sort before registers, which sort before user classes.
    300     if (Kind == Token) {
    301       if (RHS.Kind != Token)
    302         return true;
    303       assert(RHS.Kind == Token);
    304     } else if (isRegisterClass()) {
    305       if (RHS.Kind == Token)
    306         return false;
    307       else if (RHS.isUserClass())
    308         return true;
    309       assert(RHS.isRegisterClass());
    310     } else if (isUserClass()) {
    311       if (!RHS.isUserClass())
    312         return false;
    313       assert(RHS.isUserClass());
    314     } else {
    315       llvm_unreachable("Unknown ClassInfoKind");
    316     }
    317 
    318     if (Kind == Token || isUserClass()) {
    319       // Related tokens and user classes get sorted by depth in the inheritence
    320       // tree (so that subclasses are before their parents).
    321       if (isRelatedTo(RHS)) {
    322         if (getTreeDepth() > RHS.getTreeDepth())
    323           return true;
    324         if (getTreeDepth() < RHS.getTreeDepth())
    325           return false;
    326       } else {
    327         // Unrelated tokens and user classes are ordered by the name of their
    328         // root nodes, so that there is a consistent ordering between
    329         // unconnected trees.
    330         return findRoot()->ValueName < RHS.findRoot()->ValueName;
    331       }
    332     } else if (isRegisterClass()) {
    333       // For register sets, sort by number of registers. This guarantees that
    334       // a set will always sort before all of it's strict supersets.
    335       if (Registers.size() != RHS.Registers.size())
    336         return Registers.size() < RHS.Registers.size();
    337     } else {
    338       llvm_unreachable("Unknown ClassInfoKind");
    339     }
    340 
    341     // FIXME: We should be able to just return false here, as we only need a
    342     // partial order (we use stable sorts, so this is deterministic) and the
    343     // name of a class shouldn't be significant. However, some of the backends
    344     // accidentally rely on this behaviour, so it will have to stay like this
    345     // until they are fixed.
    346     return ValueName < RHS.ValueName;
    347   }
    348 };
    349 
    350 class AsmVariantInfo {
    351 public:
    352   std::string RegisterPrefix;
    353   std::string TokenizingCharacters;
    354   std::string SeparatorCharacters;
    355   std::string BreakCharacters;
    356   int AsmVariantNo;
    357 };
    358 
    359 /// MatchableInfo - Helper class for storing the necessary information for an
    360 /// instruction or alias which is capable of being matched.
    361 struct MatchableInfo {
    362   struct AsmOperand {
    363     /// Token - This is the token that the operand came from.
    364     StringRef Token;
    365 
    366     /// The unique class instance this operand should match.
    367     ClassInfo *Class;
    368 
    369     /// The operand name this is, if anything.
    370     StringRef SrcOpName;
    371 
    372     /// The suboperand index within SrcOpName, or -1 for the entire operand.
    373     int SubOpIdx;
    374 
    375     /// Whether the token is "isolated", i.e., it is preceded and followed
    376     /// by separators.
    377     bool IsIsolatedToken;
    378 
    379     /// Register record if this token is singleton register.
    380     Record *SingletonReg;
    381 
    382     explicit AsmOperand(bool IsIsolatedToken, StringRef T)
    383         : Token(T), Class(nullptr), SubOpIdx(-1),
    384           IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
    385   };
    386 
    387   /// ResOperand - This represents a single operand in the result instruction
    388   /// generated by the match.  In cases (like addressing modes) where a single
    389   /// assembler operand expands to multiple MCOperands, this represents the
    390   /// single assembler operand, not the MCOperand.
    391   struct ResOperand {
    392     enum {
    393       /// RenderAsmOperand - This represents an operand result that is
    394       /// generated by calling the render method on the assembly operand.  The
    395       /// corresponding AsmOperand is specified by AsmOperandNum.
    396       RenderAsmOperand,
    397 
    398       /// TiedOperand - This represents a result operand that is a duplicate of
    399       /// a previous result operand.
    400       TiedOperand,
    401 
    402       /// ImmOperand - This represents an immediate value that is dumped into
    403       /// the operand.
    404       ImmOperand,
    405 
    406       /// RegOperand - This represents a fixed register that is dumped in.
    407       RegOperand
    408     } Kind;
    409 
    410     union {
    411       /// This is the operand # in the AsmOperands list that this should be
    412       /// copied from.
    413       unsigned AsmOperandNum;
    414 
    415       /// TiedOperandNum - This is the (earlier) result operand that should be
    416       /// copied from.
    417       unsigned TiedOperandNum;
    418 
    419       /// ImmVal - This is the immediate value added to the instruction.
    420       int64_t ImmVal;
    421 
    422       /// Register - This is the register record.
    423       Record *Register;
    424     };
    425 
    426     /// MINumOperands - The number of MCInst operands populated by this
    427     /// operand.
    428     unsigned MINumOperands;
    429 
    430     static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
    431       ResOperand X;
    432       X.Kind = RenderAsmOperand;
    433       X.AsmOperandNum = AsmOpNum;
    434       X.MINumOperands = NumOperands;
    435       return X;
    436     }
    437 
    438     static ResOperand getTiedOp(unsigned TiedOperandNum) {
    439       ResOperand X;
    440       X.Kind = TiedOperand;
    441       X.TiedOperandNum = TiedOperandNum;
    442       X.MINumOperands = 1;
    443       return X;
    444     }
    445 
    446     static ResOperand getImmOp(int64_t Val) {
    447       ResOperand X;
    448       X.Kind = ImmOperand;
    449       X.ImmVal = Val;
    450       X.MINumOperands = 1;
    451       return X;
    452     }
    453 
    454     static ResOperand getRegOp(Record *Reg) {
    455       ResOperand X;
    456       X.Kind = RegOperand;
    457       X.Register = Reg;
    458       X.MINumOperands = 1;
    459       return X;
    460     }
    461   };
    462 
    463   /// AsmVariantID - Target's assembly syntax variant no.
    464   int AsmVariantID;
    465 
    466   /// AsmString - The assembly string for this instruction (with variants
    467   /// removed), e.g. "movsx $src, $dst".
    468   std::string AsmString;
    469 
    470   /// TheDef - This is the definition of the instruction or InstAlias that this
    471   /// matchable came from.
    472   Record *const TheDef;
    473 
    474   /// DefRec - This is the definition that it came from.
    475   PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
    476 
    477   const CodeGenInstruction *getResultInst() const {
    478     if (DefRec.is<const CodeGenInstruction*>())
    479       return DefRec.get<const CodeGenInstruction*>();
    480     return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
    481   }
    482 
    483   /// ResOperands - This is the operand list that should be built for the result
    484   /// MCInst.
    485   SmallVector<ResOperand, 8> ResOperands;
    486 
    487   /// Mnemonic - This is the first token of the matched instruction, its
    488   /// mnemonic.
    489   StringRef Mnemonic;
    490 
    491   /// AsmOperands - The textual operands that this instruction matches,
    492   /// annotated with a class and where in the OperandList they were defined.
    493   /// This directly corresponds to the tokenized AsmString after the mnemonic is
    494   /// removed.
    495   SmallVector<AsmOperand, 8> AsmOperands;
    496 
    497   /// Predicates - The required subtarget features to match this instruction.
    498   SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
    499 
    500   /// ConversionFnKind - The enum value which is passed to the generated
    501   /// convertToMCInst to convert parsed operands into an MCInst for this
    502   /// function.
    503   std::string ConversionFnKind;
    504 
    505   /// If this instruction is deprecated in some form.
    506   bool HasDeprecation;
    507 
    508   /// If this is an alias, this is use to determine whether or not to using
    509   /// the conversion function defined by the instruction's AsmMatchConverter
    510   /// or to use the function generated by the alias.
    511   bool UseInstAsmMatchConverter;
    512 
    513   MatchableInfo(const CodeGenInstruction &CGI)
    514     : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
    515       UseInstAsmMatchConverter(true) {
    516   }
    517 
    518   MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
    519     : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
    520       DefRec(Alias.release()),
    521       UseInstAsmMatchConverter(
    522         TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
    523   }
    524 
    525   // Could remove this and the dtor if PointerUnion supported unique_ptr
    526   // elements with a dynamic failure/assertion (like the one below) in the case
    527   // where it was copied while being in an owning state.
    528   MatchableInfo(const MatchableInfo &RHS)
    529       : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
    530         TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
    531         Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
    532         RequiredFeatures(RHS.RequiredFeatures),
    533         ConversionFnKind(RHS.ConversionFnKind),
    534         HasDeprecation(RHS.HasDeprecation),
    535         UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
    536     assert(!DefRec.is<const CodeGenInstAlias *>());
    537   }
    538 
    539   ~MatchableInfo() {
    540     delete DefRec.dyn_cast<const CodeGenInstAlias*>();
    541   }
    542 
    543   // Two-operand aliases clone from the main matchable, but mark the second
    544   // operand as a tied operand of the first for purposes of the assembler.
    545   void formTwoOperandAlias(StringRef Constraint);
    546 
    547   void initialize(const AsmMatcherInfo &Info,
    548                   SmallPtrSetImpl<Record*> &SingletonRegisters,
    549                   AsmVariantInfo const &Variant,
    550                   bool HasMnemonicFirst);
    551 
    552   /// validate - Return true if this matchable is a valid thing to match against
    553   /// and perform a bunch of validity checking.
    554   bool validate(StringRef CommentDelimiter, bool Hack) const;
    555 
    556   /// findAsmOperand - Find the AsmOperand with the specified name and
    557   /// suboperand index.
    558   int findAsmOperand(StringRef N, int SubOpIdx) const {
    559     auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(),
    560                           [&](const AsmOperand &Op) {
    561                             return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
    562                           });
    563     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
    564   }
    565 
    566   /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
    567   /// This does not check the suboperand index.
    568   int findAsmOperandNamed(StringRef N) const {
    569     auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(),
    570                           [&](const AsmOperand &Op) {
    571                             return Op.SrcOpName == N;
    572                           });
    573     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
    574   }
    575 
    576   void buildInstructionResultOperands();
    577   void buildAliasResultOperands();
    578 
    579   /// operator< - Compare two matchables.
    580   bool operator<(const MatchableInfo &RHS) const {
    581     // The primary comparator is the instruction mnemonic.
    582     if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
    583       return Cmp == -1;
    584 
    585     if (AsmOperands.size() != RHS.AsmOperands.size())
    586       return AsmOperands.size() < RHS.AsmOperands.size();
    587 
    588     // Compare lexicographically by operand. The matcher validates that other
    589     // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
    590     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
    591       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
    592         return true;
    593       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
    594         return false;
    595     }
    596 
    597     // Give matches that require more features higher precedence. This is useful
    598     // because we cannot define AssemblerPredicates with the negation of
    599     // processor features. For example, ARM v6 "nop" may be either a HINT or
    600     // MOV. With v6, we want to match HINT. The assembler has no way to
    601     // predicate MOV under "NoV6", but HINT will always match first because it
    602     // requires V6 while MOV does not.
    603     if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
    604       return RequiredFeatures.size() > RHS.RequiredFeatures.size();
    605 
    606     return false;
    607   }
    608 
    609   /// couldMatchAmbiguouslyWith - Check whether this matchable could
    610   /// ambiguously match the same set of operands as \p RHS (without being a
    611   /// strictly superior match).
    612   bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
    613     // The primary comparator is the instruction mnemonic.
    614     if (Mnemonic != RHS.Mnemonic)
    615       return false;
    616 
    617     // The number of operands is unambiguous.
    618     if (AsmOperands.size() != RHS.AsmOperands.size())
    619       return false;
    620 
    621     // Otherwise, make sure the ordering of the two instructions is unambiguous
    622     // by checking that either (a) a token or operand kind discriminates them,
    623     // or (b) the ordering among equivalent kinds is consistent.
    624 
    625     // Tokens and operand kinds are unambiguous (assuming a correct target
    626     // specific parser).
    627     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
    628       if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
    629           AsmOperands[i].Class->Kind == ClassInfo::Token)
    630         if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
    631             *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
    632           return false;
    633 
    634     // Otherwise, this operand could commute if all operands are equivalent, or
    635     // there is a pair of operands that compare less than and a pair that
    636     // compare greater than.
    637     bool HasLT = false, HasGT = false;
    638     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
    639       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
    640         HasLT = true;
    641       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
    642         HasGT = true;
    643     }
    644 
    645     return HasLT == HasGT;
    646   }
    647 
    648   void dump() const;
    649 
    650 private:
    651   void tokenizeAsmString(AsmMatcherInfo const &Info,
    652                          AsmVariantInfo const &Variant);
    653   void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
    654 };
    655 
    656 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
    657 /// feature which participates in instruction matching.
    658 struct SubtargetFeatureInfo {
    659   /// \brief The predicate record for this feature.
    660   Record *TheDef;
    661 
    662   /// \brief An unique index assigned to represent this feature.
    663   uint64_t Index;
    664 
    665   SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {}
    666 
    667   /// \brief The name of the enumerated constant identifying this feature.
    668   std::string getEnumName() const {
    669     return "Feature_" + TheDef->getName();
    670   }
    671 
    672   void dump() const {
    673     errs() << getEnumName() << " " << Index << "\n";
    674     TheDef->dump();
    675   }
    676 };
    677 
    678 struct OperandMatchEntry {
    679   unsigned OperandMask;
    680   const MatchableInfo* MI;
    681   ClassInfo *CI;
    682 
    683   static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
    684                                   unsigned opMask) {
    685     OperandMatchEntry X;
    686     X.OperandMask = opMask;
    687     X.CI = ci;
    688     X.MI = mi;
    689     return X;
    690   }
    691 };
    692 
    693 class AsmMatcherInfo {
    694 public:
    695   /// Tracked Records
    696   RecordKeeper &Records;
    697 
    698   /// The tablegen AsmParser record.
    699   Record *AsmParser;
    700 
    701   /// Target - The target information.
    702   CodeGenTarget &Target;
    703 
    704   /// The classes which are needed for matching.
    705   std::forward_list<ClassInfo> Classes;
    706 
    707   /// The information on the matchables to match.
    708   std::vector<std::unique_ptr<MatchableInfo>> Matchables;
    709 
    710   /// Info for custom matching operands by user defined methods.
    711   std::vector<OperandMatchEntry> OperandMatchInfo;
    712 
    713   /// Map of Register records to their class information.
    714   typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
    715   RegisterClassesTy RegisterClasses;
    716 
    717   /// Map of Predicate records to their subtarget information.
    718   std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
    719 
    720   /// Map of AsmOperandClass records to their class information.
    721   std::map<Record*, ClassInfo*> AsmOperandClasses;
    722 
    723 private:
    724   /// Map of token to class information which has already been constructed.
    725   std::map<std::string, ClassInfo*> TokenClasses;
    726 
    727   /// Map of RegisterClass records to their class information.
    728   std::map<Record*, ClassInfo*> RegisterClassClasses;
    729 
    730 private:
    731   /// getTokenClass - Lookup or create the class for the given token.
    732   ClassInfo *getTokenClass(StringRef Token);
    733 
    734   /// getOperandClass - Lookup or create the class for the given operand.
    735   ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
    736                              int SubOpIdx);
    737   ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
    738 
    739   /// buildRegisterClasses - Build the ClassInfo* instances for register
    740   /// classes.
    741   void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
    742 
    743   /// buildOperandClasses - Build the ClassInfo* instances for user defined
    744   /// operand classes.
    745   void buildOperandClasses();
    746 
    747   void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
    748                                         unsigned AsmOpIdx);
    749   void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
    750                                   MatchableInfo::AsmOperand &Op);
    751 
    752 public:
    753   AsmMatcherInfo(Record *AsmParser,
    754                  CodeGenTarget &Target,
    755                  RecordKeeper &Records);
    756 
    757   /// buildInfo - Construct the various tables used during matching.
    758   void buildInfo();
    759 
    760   /// buildOperandMatchInfo - Build the necessary information to handle user
    761   /// defined operand parsing methods.
    762   void buildOperandMatchInfo();
    763 
    764   /// getSubtargetFeature - Lookup or create the subtarget feature info for the
    765   /// given operand.
    766   const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
    767     assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
    768     const auto &I = SubtargetFeatures.find(Def);
    769     return I == SubtargetFeatures.end() ? nullptr : &I->second;
    770   }
    771 
    772   RecordKeeper &getRecords() const {
    773     return Records;
    774   }
    775 
    776   bool hasOptionalOperands() const {
    777     return std::find_if(Classes.begin(), Classes.end(),
    778                         [](const ClassInfo& Class){ return Class.IsOptional; })
    779               != Classes.end();
    780   }
    781 };
    782 
    783 } // end anonymous namespace
    784 
    785 void MatchableInfo::dump() const {
    786   errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
    787 
    788   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
    789     const AsmOperand &Op = AsmOperands[i];
    790     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
    791     errs() << '\"' << Op.Token << "\"\n";
    792   }
    793 }
    794 
    795 static std::pair<StringRef, StringRef>
    796 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
    797   // Split via the '='.
    798   std::pair<StringRef, StringRef> Ops = S.split('=');
    799   if (Ops.second == "")
    800     PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
    801   // Trim whitespace and the leading '$' on the operand names.
    802   size_t start = Ops.first.find_first_of('$');
    803   if (start == std::string::npos)
    804     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
    805   Ops.first = Ops.first.slice(start + 1, std::string::npos);
    806   size_t end = Ops.first.find_last_of(" \t");
    807   Ops.first = Ops.first.slice(0, end);
    808   // Now the second operand.
    809   start = Ops.second.find_first_of('$');
    810   if (start == std::string::npos)
    811     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
    812   Ops.second = Ops.second.slice(start + 1, std::string::npos);
    813   end = Ops.second.find_last_of(" \t");
    814   Ops.first = Ops.first.slice(0, end);
    815   return Ops;
    816 }
    817 
    818 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
    819   // Figure out which operands are aliased and mark them as tied.
    820   std::pair<StringRef, StringRef> Ops =
    821     parseTwoOperandConstraint(Constraint, TheDef->getLoc());
    822 
    823   // Find the AsmOperands that refer to the operands we're aliasing.
    824   int SrcAsmOperand = findAsmOperandNamed(Ops.first);
    825   int DstAsmOperand = findAsmOperandNamed(Ops.second);
    826   if (SrcAsmOperand == -1)
    827     PrintFatalError(TheDef->getLoc(),
    828                     "unknown source two-operand alias operand '" + Ops.first +
    829                     "'.");
    830   if (DstAsmOperand == -1)
    831     PrintFatalError(TheDef->getLoc(),
    832                     "unknown destination two-operand alias operand '" +
    833                     Ops.second + "'.");
    834 
    835   // Find the ResOperand that refers to the operand we're aliasing away
    836   // and update it to refer to the combined operand instead.
    837   for (ResOperand &Op : ResOperands) {
    838     if (Op.Kind == ResOperand::RenderAsmOperand &&
    839         Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
    840       Op.AsmOperandNum = DstAsmOperand;
    841       break;
    842     }
    843   }
    844   // Remove the AsmOperand for the alias operand.
    845   AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
    846   // Adjust the ResOperand references to any AsmOperands that followed
    847   // the one we just deleted.
    848   for (ResOperand &Op : ResOperands) {
    849     switch(Op.Kind) {
    850     default:
    851       // Nothing to do for operands that don't reference AsmOperands.
    852       break;
    853     case ResOperand::RenderAsmOperand:
    854       if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
    855         --Op.AsmOperandNum;
    856       break;
    857     case ResOperand::TiedOperand:
    858       if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
    859         --Op.TiedOperandNum;
    860       break;
    861     }
    862   }
    863 }
    864 
    865 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
    866 /// if present, from specified token.
    867 static void
    868 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
    869                                       const AsmMatcherInfo &Info,
    870                                       StringRef RegisterPrefix) {
    871   StringRef Tok = Op.Token;
    872 
    873   // If this token is not an isolated token, i.e., it isn't separated from
    874   // other tokens (e.g. with whitespace), don't interpret it as a register name.
    875   if (!Op.IsIsolatedToken)
    876     return;
    877 
    878   if (RegisterPrefix.empty()) {
    879     std::string LoweredTok = Tok.lower();
    880     if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
    881       Op.SingletonReg = Reg->TheDef;
    882     return;
    883   }
    884 
    885   if (!Tok.startswith(RegisterPrefix))
    886     return;
    887 
    888   StringRef RegName = Tok.substr(RegisterPrefix.size());
    889   if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
    890     Op.SingletonReg = Reg->TheDef;
    891 
    892   // If there is no register prefix (i.e. "%" in "%eax"), then this may
    893   // be some random non-register token, just ignore it.
    894 }
    895 
    896 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
    897                                SmallPtrSetImpl<Record*> &SingletonRegisters,
    898                                AsmVariantInfo const &Variant,
    899                                bool HasMnemonicFirst) {
    900   AsmVariantID = Variant.AsmVariantNo;
    901   AsmString =
    902     CodeGenInstruction::FlattenAsmStringVariants(AsmString,
    903                                                  Variant.AsmVariantNo);
    904 
    905   tokenizeAsmString(Info, Variant);
    906 
    907   // The first token of the instruction is the mnemonic, which must be a
    908   // simple string, not a $foo variable or a singleton register.
    909   if (AsmOperands.empty())
    910     PrintFatalError(TheDef->getLoc(),
    911                   "Instruction '" + TheDef->getName() + "' has no tokens");
    912 
    913   assert(!AsmOperands[0].Token.empty());
    914   if (HasMnemonicFirst) {
    915     Mnemonic = AsmOperands[0].Token;
    916     if (Mnemonic[0] == '$')
    917       PrintFatalError(TheDef->getLoc(),
    918                       "Invalid instruction mnemonic '" + Mnemonic + "'!");
    919 
    920     // Remove the first operand, it is tracked in the mnemonic field.
    921     AsmOperands.erase(AsmOperands.begin());
    922   } else if (AsmOperands[0].Token[0] != '$')
    923     Mnemonic = AsmOperands[0].Token;
    924 
    925   // Compute the require features.
    926   for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
    927     if (const SubtargetFeatureInfo *Feature =
    928             Info.getSubtargetFeature(Predicate))
    929       RequiredFeatures.push_back(Feature);
    930 
    931   // Collect singleton registers, if used.
    932   for (MatchableInfo::AsmOperand &Op : AsmOperands) {
    933     extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
    934     if (Record *Reg = Op.SingletonReg)
    935       SingletonRegisters.insert(Reg);
    936   }
    937 
    938   const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
    939   if (!DepMask)
    940     DepMask = TheDef->getValue("ComplexDeprecationPredicate");
    941 
    942   HasDeprecation =
    943       DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
    944 }
    945 
    946 /// Append an AsmOperand for the given substring of AsmString.
    947 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
    948   AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
    949 }
    950 
    951 /// tokenizeAsmString - Tokenize a simplified assembly string.
    952 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
    953                                       AsmVariantInfo const &Variant) {
    954   StringRef String = AsmString;
    955   size_t Prev = 0;
    956   bool InTok = false;
    957   bool IsIsolatedToken = true;
    958   for (size_t i = 0, e = String.size(); i != e; ++i) {
    959     char Char = String[i];
    960     if (Variant.BreakCharacters.find(Char) != std::string::npos) {
    961       if (InTok) {
    962         addAsmOperand(String.slice(Prev, i), false);
    963         Prev = i;
    964         IsIsolatedToken = false;
    965       }
    966       InTok = true;
    967       continue;
    968     }
    969     if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
    970       if (InTok) {
    971         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
    972         InTok = false;
    973         IsIsolatedToken = false;
    974       }
    975       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
    976       Prev = i + 1;
    977       IsIsolatedToken = true;
    978       continue;
    979     }
    980     if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
    981       if (InTok) {
    982         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
    983         InTok = false;
    984       }
    985       Prev = i + 1;
    986       IsIsolatedToken = true;
    987       continue;
    988     }
    989 
    990     switch (Char) {
    991     case '\\':
    992       if (InTok) {
    993         addAsmOperand(String.slice(Prev, i), false);
    994         InTok = false;
    995         IsIsolatedToken = false;
    996       }
    997       ++i;
    998       assert(i != String.size() && "Invalid quoted character");
    999       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
   1000       Prev = i + 1;
   1001       IsIsolatedToken = false;
   1002       break;
   1003 
   1004     case '$': {
   1005       if (InTok) {
   1006         addAsmOperand(String.slice(Prev, i), false);
   1007         InTok = false;
   1008         IsIsolatedToken = false;
   1009       }
   1010 
   1011       // If this isn't "${", start new identifier looking like "$xxx"
   1012       if (i + 1 == String.size() || String[i + 1] != '{') {
   1013         Prev = i;
   1014         break;
   1015       }
   1016 
   1017       size_t EndPos = String.find('}', i);
   1018       assert(EndPos != StringRef::npos &&
   1019              "Missing brace in operand reference!");
   1020       addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
   1021       Prev = EndPos + 1;
   1022       i = EndPos;
   1023       IsIsolatedToken = false;
   1024       break;
   1025     }
   1026 
   1027     default:
   1028       InTok = true;
   1029       break;
   1030     }
   1031   }
   1032   if (InTok && Prev != String.size())
   1033     addAsmOperand(String.substr(Prev), IsIsolatedToken);
   1034 }
   1035 
   1036 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
   1037   // Reject matchables with no .s string.
   1038   if (AsmString.empty())
   1039     PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
   1040 
   1041   // Reject any matchables with a newline in them, they should be marked
   1042   // isCodeGenOnly if they are pseudo instructions.
   1043   if (AsmString.find('\n') != std::string::npos)
   1044     PrintFatalError(TheDef->getLoc(),
   1045                   "multiline instruction is not valid for the asmparser, "
   1046                   "mark it isCodeGenOnly");
   1047 
   1048   // Remove comments from the asm string.  We know that the asmstring only
   1049   // has one line.
   1050   if (!CommentDelimiter.empty() &&
   1051       StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
   1052     PrintFatalError(TheDef->getLoc(),
   1053                   "asmstring for instruction has comment character in it, "
   1054                   "mark it isCodeGenOnly");
   1055 
   1056   // Reject matchables with operand modifiers, these aren't something we can
   1057   // handle, the target should be refactored to use operands instead of
   1058   // modifiers.
   1059   //
   1060   // Also, check for instructions which reference the operand multiple times;
   1061   // this implies a constraint we would not honor.
   1062   std::set<std::string> OperandNames;
   1063   for (const AsmOperand &Op : AsmOperands) {
   1064     StringRef Tok = Op.Token;
   1065     if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
   1066       PrintFatalError(TheDef->getLoc(),
   1067                       "matchable with operand modifier '" + Tok +
   1068                       "' not supported by asm matcher.  Mark isCodeGenOnly!");
   1069 
   1070     // Verify that any operand is only mentioned once.
   1071     // We reject aliases and ignore instructions for now.
   1072     if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
   1073       if (!Hack)
   1074         PrintFatalError(TheDef->getLoc(),
   1075                         "ERROR: matchable with tied operand '" + Tok +
   1076                         "' can never be matched!");
   1077       // FIXME: Should reject these.  The ARM backend hits this with $lane in a
   1078       // bunch of instructions.  It is unclear what the right answer is.
   1079       DEBUG({
   1080         errs() << "warning: '" << TheDef->getName() << "': "
   1081                << "ignoring instruction with tied operand '"
   1082                << Tok << "'\n";
   1083       });
   1084       return false;
   1085     }
   1086   }
   1087 
   1088   return true;
   1089 }
   1090 
   1091 static std::string getEnumNameForToken(StringRef Str) {
   1092   std::string Res;
   1093 
   1094   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
   1095     switch (*it) {
   1096     case '*': Res += "_STAR_"; break;
   1097     case '%': Res += "_PCT_"; break;
   1098     case ':': Res += "_COLON_"; break;
   1099     case '!': Res += "_EXCLAIM_"; break;
   1100     case '.': Res += "_DOT_"; break;
   1101     case '<': Res += "_LT_"; break;
   1102     case '>': Res += "_GT_"; break;
   1103     case '-': Res += "_MINUS_"; break;
   1104     default:
   1105       if ((*it >= 'A' && *it <= 'Z') ||
   1106           (*it >= 'a' && *it <= 'z') ||
   1107           (*it >= '0' && *it <= '9'))
   1108         Res += *it;
   1109       else
   1110         Res += "_" + utostr((unsigned) *it) + "_";
   1111     }
   1112   }
   1113 
   1114   return Res;
   1115 }
   1116 
   1117 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
   1118   ClassInfo *&Entry = TokenClasses[Token];
   1119 
   1120   if (!Entry) {
   1121     Classes.emplace_front();
   1122     Entry = &Classes.front();
   1123     Entry->Kind = ClassInfo::Token;
   1124     Entry->ClassName = "Token";
   1125     Entry->Name = "MCK_" + getEnumNameForToken(Token);
   1126     Entry->ValueName = Token;
   1127     Entry->PredicateMethod = "<invalid>";
   1128     Entry->RenderMethod = "<invalid>";
   1129     Entry->ParserMethod = "";
   1130     Entry->DiagnosticType = "";
   1131     Entry->IsOptional = false;
   1132     Entry->DefaultMethod = "<invalid>";
   1133   }
   1134 
   1135   return Entry;
   1136 }
   1137 
   1138 ClassInfo *
   1139 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
   1140                                 int SubOpIdx) {
   1141   Record *Rec = OI.Rec;
   1142   if (SubOpIdx != -1)
   1143     Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
   1144   return getOperandClass(Rec, SubOpIdx);
   1145 }
   1146 
   1147 ClassInfo *
   1148 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
   1149   if (Rec->isSubClassOf("RegisterOperand")) {
   1150     // RegisterOperand may have an associated ParserMatchClass. If it does,
   1151     // use it, else just fall back to the underlying register class.
   1152     const RecordVal *R = Rec->getValue("ParserMatchClass");
   1153     if (!R || !R->getValue())
   1154       PrintFatalError("Record `" + Rec->getName() +
   1155         "' does not have a ParserMatchClass!\n");
   1156 
   1157     if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
   1158       Record *MatchClass = DI->getDef();
   1159       if (ClassInfo *CI = AsmOperandClasses[MatchClass])
   1160         return CI;
   1161     }
   1162 
   1163     // No custom match class. Just use the register class.
   1164     Record *ClassRec = Rec->getValueAsDef("RegClass");
   1165     if (!ClassRec)
   1166       PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
   1167                     "' has no associated register class!\n");
   1168     if (ClassInfo *CI = RegisterClassClasses[ClassRec])
   1169       return CI;
   1170     PrintFatalError(Rec->getLoc(), "register class has no class info!");
   1171   }
   1172 
   1173   if (Rec->isSubClassOf("RegisterClass")) {
   1174     if (ClassInfo *CI = RegisterClassClasses[Rec])
   1175       return CI;
   1176     PrintFatalError(Rec->getLoc(), "register class has no class info!");
   1177   }
   1178 
   1179   if (!Rec->isSubClassOf("Operand"))
   1180     PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
   1181                   "' does not derive from class Operand!\n");
   1182   Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
   1183   if (ClassInfo *CI = AsmOperandClasses[MatchClass])
   1184     return CI;
   1185 
   1186   PrintFatalError(Rec->getLoc(), "operand has no match class!");
   1187 }
   1188 
   1189 struct LessRegisterSet {
   1190   bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
   1191     // std::set<T> defines its own compariso "operator<", but it
   1192     // performs a lexicographical comparison by T's innate comparison
   1193     // for some reason. We don't want non-deterministic pointer
   1194     // comparisons so use this instead.
   1195     return std::lexicographical_compare(LHS.begin(), LHS.end(),
   1196                                         RHS.begin(), RHS.end(),
   1197                                         LessRecordByID());
   1198   }
   1199 };
   1200 
   1201 void AsmMatcherInfo::
   1202 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
   1203   const auto &Registers = Target.getRegBank().getRegisters();
   1204   auto &RegClassList = Target.getRegBank().getRegClasses();
   1205 
   1206   typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
   1207 
   1208   // The register sets used for matching.
   1209   RegisterSetSet RegisterSets;
   1210 
   1211   // Gather the defined sets.
   1212   for (const CodeGenRegisterClass &RC : RegClassList)
   1213     RegisterSets.insert(
   1214         RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
   1215 
   1216   // Add any required singleton sets.
   1217   for (Record *Rec : SingletonRegisters) {
   1218     RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
   1219   }
   1220 
   1221   // Introduce derived sets where necessary (when a register does not determine
   1222   // a unique register set class), and build the mapping of registers to the set
   1223   // they should classify to.
   1224   std::map<Record*, RegisterSet> RegisterMap;
   1225   for (const CodeGenRegister &CGR : Registers) {
   1226     // Compute the intersection of all sets containing this register.
   1227     RegisterSet ContainingSet;
   1228 
   1229     for (const RegisterSet &RS : RegisterSets) {
   1230       if (!RS.count(CGR.TheDef))
   1231         continue;
   1232 
   1233       if (ContainingSet.empty()) {
   1234         ContainingSet = RS;
   1235         continue;
   1236       }
   1237 
   1238       RegisterSet Tmp;
   1239       std::swap(Tmp, ContainingSet);
   1240       std::insert_iterator<RegisterSet> II(ContainingSet,
   1241                                            ContainingSet.begin());
   1242       std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
   1243                             LessRecordByID());
   1244     }
   1245 
   1246     if (!ContainingSet.empty()) {
   1247       RegisterSets.insert(ContainingSet);
   1248       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
   1249     }
   1250   }
   1251 
   1252   // Construct the register classes.
   1253   std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
   1254   unsigned Index = 0;
   1255   for (const RegisterSet &RS : RegisterSets) {
   1256     Classes.emplace_front();
   1257     ClassInfo *CI = &Classes.front();
   1258     CI->Kind = ClassInfo::RegisterClass0 + Index;
   1259     CI->ClassName = "Reg" + utostr(Index);
   1260     CI->Name = "MCK_Reg" + utostr(Index);
   1261     CI->ValueName = "";
   1262     CI->PredicateMethod = ""; // unused
   1263     CI->RenderMethod = "addRegOperands";
   1264     CI->Registers = RS;
   1265     // FIXME: diagnostic type.
   1266     CI->DiagnosticType = "";
   1267     CI->IsOptional = false;
   1268     CI->DefaultMethod = ""; // unused
   1269     RegisterSetClasses.insert(std::make_pair(RS, CI));
   1270     ++Index;
   1271   }
   1272 
   1273   // Find the superclasses; we could compute only the subgroup lattice edges,
   1274   // but there isn't really a point.
   1275   for (const RegisterSet &RS : RegisterSets) {
   1276     ClassInfo *CI = RegisterSetClasses[RS];
   1277     for (const RegisterSet &RS2 : RegisterSets)
   1278       if (RS != RS2 &&
   1279           std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
   1280                         LessRecordByID()))
   1281         CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
   1282   }
   1283 
   1284   // Name the register classes which correspond to a user defined RegisterClass.
   1285   for (const CodeGenRegisterClass &RC : RegClassList) {
   1286     // Def will be NULL for non-user defined register classes.
   1287     Record *Def = RC.getDef();
   1288     if (!Def)
   1289       continue;
   1290     ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
   1291                                                    RC.getOrder().end())];
   1292     if (CI->ValueName.empty()) {
   1293       CI->ClassName = RC.getName();
   1294       CI->Name = "MCK_" + RC.getName();
   1295       CI->ValueName = RC.getName();
   1296     } else
   1297       CI->ValueName = CI->ValueName + "," + RC.getName();
   1298 
   1299     RegisterClassClasses.insert(std::make_pair(Def, CI));
   1300   }
   1301 
   1302   // Populate the map for individual registers.
   1303   for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
   1304          ie = RegisterMap.end(); it != ie; ++it)
   1305     RegisterClasses[it->first] = RegisterSetClasses[it->second];
   1306 
   1307   // Name the register classes which correspond to singleton registers.
   1308   for (Record *Rec : SingletonRegisters) {
   1309     ClassInfo *CI = RegisterClasses[Rec];
   1310     assert(CI && "Missing singleton register class info!");
   1311 
   1312     if (CI->ValueName.empty()) {
   1313       CI->ClassName = Rec->getName();
   1314       CI->Name = "MCK_" + Rec->getName();
   1315       CI->ValueName = Rec->getName();
   1316     } else
   1317       CI->ValueName = CI->ValueName + "," + Rec->getName();
   1318   }
   1319 }
   1320 
   1321 void AsmMatcherInfo::buildOperandClasses() {
   1322   std::vector<Record*> AsmOperands =
   1323     Records.getAllDerivedDefinitions("AsmOperandClass");
   1324 
   1325   // Pre-populate AsmOperandClasses map.
   1326   for (Record *Rec : AsmOperands) {
   1327     Classes.emplace_front();
   1328     AsmOperandClasses[Rec] = &Classes.front();
   1329   }
   1330 
   1331   unsigned Index = 0;
   1332   for (Record *Rec : AsmOperands) {
   1333     ClassInfo *CI = AsmOperandClasses[Rec];
   1334     CI->Kind = ClassInfo::UserClass0 + Index;
   1335 
   1336     ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
   1337     for (Init *I : Supers->getValues()) {
   1338       DefInit *DI = dyn_cast<DefInit>(I);
   1339       if (!DI) {
   1340         PrintError(Rec->getLoc(), "Invalid super class reference!");
   1341         continue;
   1342       }
   1343 
   1344       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
   1345       if (!SC)
   1346         PrintError(Rec->getLoc(), "Invalid super class reference!");
   1347       else
   1348         CI->SuperClasses.push_back(SC);
   1349     }
   1350     CI->ClassName = Rec->getValueAsString("Name");
   1351     CI->Name = "MCK_" + CI->ClassName;
   1352     CI->ValueName = Rec->getName();
   1353 
   1354     // Get or construct the predicate method name.
   1355     Init *PMName = Rec->getValueInit("PredicateMethod");
   1356     if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
   1357       CI->PredicateMethod = SI->getValue();
   1358     } else {
   1359       assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
   1360       CI->PredicateMethod = "is" + CI->ClassName;
   1361     }
   1362 
   1363     // Get or construct the render method name.
   1364     Init *RMName = Rec->getValueInit("RenderMethod");
   1365     if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
   1366       CI->RenderMethod = SI->getValue();
   1367     } else {
   1368       assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
   1369       CI->RenderMethod = "add" + CI->ClassName + "Operands";
   1370     }
   1371 
   1372     // Get the parse method name or leave it as empty.
   1373     Init *PRMName = Rec->getValueInit("ParserMethod");
   1374     if (StringInit *SI = dyn_cast<StringInit>(PRMName))
   1375       CI->ParserMethod = SI->getValue();
   1376 
   1377     // Get the diagnostic type or leave it as empty.
   1378     // Get the parse method name or leave it as empty.
   1379     Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
   1380     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
   1381       CI->DiagnosticType = SI->getValue();
   1382 
   1383     Init *IsOptional = Rec->getValueInit("IsOptional");
   1384     if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
   1385       CI->IsOptional = BI->getValue();
   1386 
   1387     // Get or construct the default method name.
   1388     Init *DMName = Rec->getValueInit("DefaultMethod");
   1389     if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
   1390       CI->DefaultMethod = SI->getValue();
   1391     } else {
   1392       assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
   1393       CI->DefaultMethod = "default" + CI->ClassName + "Operands";
   1394     }
   1395 
   1396     ++Index;
   1397   }
   1398 }
   1399 
   1400 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
   1401                                CodeGenTarget &target,
   1402                                RecordKeeper &records)
   1403   : Records(records), AsmParser(asmParser), Target(target) {
   1404 }
   1405 
   1406 /// buildOperandMatchInfo - Build the necessary information to handle user
   1407 /// defined operand parsing methods.
   1408 void AsmMatcherInfo::buildOperandMatchInfo() {
   1409 
   1410   /// Map containing a mask with all operands indices that can be found for
   1411   /// that class inside a instruction.
   1412   typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
   1413   OpClassMaskTy OpClassMask;
   1414 
   1415   for (const auto &MI : Matchables) {
   1416     OpClassMask.clear();
   1417 
   1418     // Keep track of all operands of this instructions which belong to the
   1419     // same class.
   1420     for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
   1421       const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
   1422       if (Op.Class->ParserMethod.empty())
   1423         continue;
   1424       unsigned &OperandMask = OpClassMask[Op.Class];
   1425       OperandMask |= (1 << i);
   1426     }
   1427 
   1428     // Generate operand match info for each mnemonic/operand class pair.
   1429     for (const auto &OCM : OpClassMask) {
   1430       unsigned OpMask = OCM.second;
   1431       ClassInfo *CI = OCM.first;
   1432       OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
   1433                                                            OpMask));
   1434     }
   1435   }
   1436 }
   1437 
   1438 void AsmMatcherInfo::buildInfo() {
   1439   // Build information about all of the AssemblerPredicates.
   1440   std::vector<Record*> AllPredicates =
   1441     Records.getAllDerivedDefinitions("Predicate");
   1442   for (Record *Pred : AllPredicates) {
   1443     // Ignore predicates that are not intended for the assembler.
   1444     if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
   1445       continue;
   1446 
   1447     if (Pred->getName().empty())
   1448       PrintFatalError(Pred->getLoc(), "Predicate has no name!");
   1449 
   1450     SubtargetFeatures.insert(std::make_pair(
   1451         Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size())));
   1452     DEBUG(SubtargetFeatures.find(Pred)->second.dump());
   1453     assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
   1454   }
   1455 
   1456   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
   1457 
   1458   // Parse the instructions; we need to do this first so that we can gather the
   1459   // singleton register classes.
   1460   SmallPtrSet<Record*, 16> SingletonRegisters;
   1461   unsigned VariantCount = Target.getAsmParserVariantCount();
   1462   for (unsigned VC = 0; VC != VariantCount; ++VC) {
   1463     Record *AsmVariant = Target.getAsmParserVariant(VC);
   1464     std::string CommentDelimiter =
   1465       AsmVariant->getValueAsString("CommentDelimiter");
   1466     AsmVariantInfo Variant;
   1467     Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
   1468     Variant.TokenizingCharacters =
   1469         AsmVariant->getValueAsString("TokenizingCharacters");
   1470     Variant.SeparatorCharacters =
   1471         AsmVariant->getValueAsString("SeparatorCharacters");
   1472     Variant.BreakCharacters =
   1473         AsmVariant->getValueAsString("BreakCharacters");
   1474     Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
   1475 
   1476     for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
   1477 
   1478       // If the tblgen -match-prefix option is specified (for tblgen hackers),
   1479       // filter the set of instructions we consider.
   1480       if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
   1481         continue;
   1482 
   1483       // Ignore "codegen only" instructions.
   1484       if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
   1485         continue;
   1486 
   1487       auto II = llvm::make_unique<MatchableInfo>(*CGI);
   1488 
   1489       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
   1490 
   1491       // Ignore instructions which shouldn't be matched and diagnose invalid
   1492       // instruction definitions with an error.
   1493       if (!II->validate(CommentDelimiter, true))
   1494         continue;
   1495 
   1496       Matchables.push_back(std::move(II));
   1497     }
   1498 
   1499     // Parse all of the InstAlias definitions and stick them in the list of
   1500     // matchables.
   1501     std::vector<Record*> AllInstAliases =
   1502       Records.getAllDerivedDefinitions("InstAlias");
   1503     for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
   1504       auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
   1505                                                        Variant.AsmVariantNo,
   1506                                                        Target);
   1507 
   1508       // If the tblgen -match-prefix option is specified (for tblgen hackers),
   1509       // filter the set of instruction aliases we consider, based on the target
   1510       // instruction.
   1511       if (!StringRef(Alias->ResultInst->TheDef->getName())
   1512             .startswith( MatchPrefix))
   1513         continue;
   1514 
   1515       auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
   1516 
   1517       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
   1518 
   1519       // Validate the alias definitions.
   1520       II->validate(CommentDelimiter, false);
   1521 
   1522       Matchables.push_back(std::move(II));
   1523     }
   1524   }
   1525 
   1526   // Build info for the register classes.
   1527   buildRegisterClasses(SingletonRegisters);
   1528 
   1529   // Build info for the user defined assembly operand classes.
   1530   buildOperandClasses();
   1531 
   1532   // Build the information about matchables, now that we have fully formed
   1533   // classes.
   1534   std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
   1535   for (auto &II : Matchables) {
   1536     // Parse the tokens after the mnemonic.
   1537     // Note: buildInstructionOperandReference may insert new AsmOperands, so
   1538     // don't precompute the loop bound.
   1539     for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
   1540       MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
   1541       StringRef Token = Op.Token;
   1542 
   1543       // Check for singleton registers.
   1544       if (Record *RegRecord = Op.SingletonReg) {
   1545         Op.Class = RegisterClasses[RegRecord];
   1546         assert(Op.Class && Op.Class->Registers.size() == 1 &&
   1547                "Unexpected class for singleton register");
   1548         continue;
   1549       }
   1550 
   1551       // Check for simple tokens.
   1552       if (Token[0] != '$') {
   1553         Op.Class = getTokenClass(Token);
   1554         continue;
   1555       }
   1556 
   1557       if (Token.size() > 1 && isdigit(Token[1])) {
   1558         Op.Class = getTokenClass(Token);
   1559         continue;
   1560       }
   1561 
   1562       // Otherwise this is an operand reference.
   1563       StringRef OperandName;
   1564       if (Token[1] == '{')
   1565         OperandName = Token.substr(2, Token.size() - 3);
   1566       else
   1567         OperandName = Token.substr(1);
   1568 
   1569       if (II->DefRec.is<const CodeGenInstruction*>())
   1570         buildInstructionOperandReference(II.get(), OperandName, i);
   1571       else
   1572         buildAliasOperandReference(II.get(), OperandName, Op);
   1573     }
   1574 
   1575     if (II->DefRec.is<const CodeGenInstruction*>()) {
   1576       II->buildInstructionResultOperands();
   1577       // If the instruction has a two-operand alias, build up the
   1578       // matchable here. We'll add them in bulk at the end to avoid
   1579       // confusing this loop.
   1580       std::string Constraint =
   1581         II->TheDef->getValueAsString("TwoOperandAliasConstraint");
   1582       if (Constraint != "") {
   1583         // Start by making a copy of the original matchable.
   1584         auto AliasII = llvm::make_unique<MatchableInfo>(*II);
   1585 
   1586         // Adjust it to be a two-operand alias.
   1587         AliasII->formTwoOperandAlias(Constraint);
   1588 
   1589         // Add the alias to the matchables list.
   1590         NewMatchables.push_back(std::move(AliasII));
   1591       }
   1592     } else
   1593       II->buildAliasResultOperands();
   1594   }
   1595   if (!NewMatchables.empty())
   1596     Matchables.insert(Matchables.end(),
   1597                       std::make_move_iterator(NewMatchables.begin()),
   1598                       std::make_move_iterator(NewMatchables.end()));
   1599 
   1600   // Process token alias definitions and set up the associated superclass
   1601   // information.
   1602   std::vector<Record*> AllTokenAliases =
   1603     Records.getAllDerivedDefinitions("TokenAlias");
   1604   for (Record *Rec : AllTokenAliases) {
   1605     ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
   1606     ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
   1607     if (FromClass == ToClass)
   1608       PrintFatalError(Rec->getLoc(),
   1609                     "error: Destination value identical to source value.");
   1610     FromClass->SuperClasses.push_back(ToClass);
   1611   }
   1612 
   1613   // Reorder classes so that classes precede super classes.
   1614   Classes.sort();
   1615 
   1616 #ifndef NDEBUG
   1617   // Verify that the table is now sorted
   1618   for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
   1619     for (auto J = I; J != E; ++J) {
   1620       assert(!(*J < *I));
   1621       assert(I == J || !J->isSubsetOf(*I));
   1622     }
   1623   }
   1624 #endif // NDEBUG
   1625 }
   1626 
   1627 /// buildInstructionOperandReference - The specified operand is a reference to a
   1628 /// named operand such as $src.  Resolve the Class and OperandInfo pointers.
   1629 void AsmMatcherInfo::
   1630 buildInstructionOperandReference(MatchableInfo *II,
   1631                                  StringRef OperandName,
   1632                                  unsigned AsmOpIdx) {
   1633   const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
   1634   const CGIOperandList &Operands = CGI.Operands;
   1635   MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
   1636 
   1637   // Map this token to an operand.
   1638   unsigned Idx;
   1639   if (!Operands.hasOperandNamed(OperandName, Idx))
   1640     PrintFatalError(II->TheDef->getLoc(),
   1641                     "error: unable to find operand: '" + OperandName + "'");
   1642 
   1643   // If the instruction operand has multiple suboperands, but the parser
   1644   // match class for the asm operand is still the default "ImmAsmOperand",
   1645   // then handle each suboperand separately.
   1646   if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
   1647     Record *Rec = Operands[Idx].Rec;
   1648     assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
   1649     Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
   1650     if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
   1651       // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
   1652       StringRef Token = Op->Token; // save this in case Op gets moved
   1653       for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
   1654         MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
   1655         NewAsmOp.SubOpIdx = SI;
   1656         II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
   1657       }
   1658       // Replace Op with first suboperand.
   1659       Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
   1660       Op->SubOpIdx = 0;
   1661     }
   1662   }
   1663 
   1664   // Set up the operand class.
   1665   Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
   1666 
   1667   // If the named operand is tied, canonicalize it to the untied operand.
   1668   // For example, something like:
   1669   //   (outs GPR:$dst), (ins GPR:$src)
   1670   // with an asmstring of
   1671   //   "inc $src"
   1672   // we want to canonicalize to:
   1673   //   "inc $dst"
   1674   // so that we know how to provide the $dst operand when filling in the result.
   1675   int OITied = -1;
   1676   if (Operands[Idx].MINumOperands == 1)
   1677     OITied = Operands[Idx].getTiedRegister();
   1678   if (OITied != -1) {
   1679     // The tied operand index is an MIOperand index, find the operand that
   1680     // contains it.
   1681     std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
   1682     OperandName = Operands[Idx.first].Name;
   1683     Op->SubOpIdx = Idx.second;
   1684   }
   1685 
   1686   Op->SrcOpName = OperandName;
   1687 }
   1688 
   1689 /// buildAliasOperandReference - When parsing an operand reference out of the
   1690 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
   1691 /// operand reference is by looking it up in the result pattern definition.
   1692 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
   1693                                                 StringRef OperandName,
   1694                                                 MatchableInfo::AsmOperand &Op) {
   1695   const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
   1696 
   1697   // Set up the operand class.
   1698   for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
   1699     if (CGA.ResultOperands[i].isRecord() &&
   1700         CGA.ResultOperands[i].getName() == OperandName) {
   1701       // It's safe to go with the first one we find, because CodeGenInstAlias
   1702       // validates that all operands with the same name have the same record.
   1703       Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
   1704       // Use the match class from the Alias definition, not the
   1705       // destination instruction, as we may have an immediate that's
   1706       // being munged by the match class.
   1707       Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
   1708                                  Op.SubOpIdx);
   1709       Op.SrcOpName = OperandName;
   1710       return;
   1711     }
   1712 
   1713   PrintFatalError(II->TheDef->getLoc(),
   1714                   "error: unable to find operand: '" + OperandName + "'");
   1715 }
   1716 
   1717 void MatchableInfo::buildInstructionResultOperands() {
   1718   const CodeGenInstruction *ResultInst = getResultInst();
   1719 
   1720   // Loop over all operands of the result instruction, determining how to
   1721   // populate them.
   1722   for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
   1723     // If this is a tied operand, just copy from the previously handled operand.
   1724     int TiedOp = -1;
   1725     if (OpInfo.MINumOperands == 1)
   1726       TiedOp = OpInfo.getTiedRegister();
   1727     if (TiedOp != -1) {
   1728       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
   1729       continue;
   1730     }
   1731 
   1732     // Find out what operand from the asmparser this MCInst operand comes from.
   1733     int SrcOperand = findAsmOperandNamed(OpInfo.Name);
   1734     if (OpInfo.Name.empty() || SrcOperand == -1) {
   1735       // This may happen for operands that are tied to a suboperand of a
   1736       // complex operand.  Simply use a dummy value here; nobody should
   1737       // use this operand slot.
   1738       // FIXME: The long term goal is for the MCOperand list to not contain
   1739       // tied operands at all.
   1740       ResOperands.push_back(ResOperand::getImmOp(0));
   1741       continue;
   1742     }
   1743 
   1744     // Check if the one AsmOperand populates the entire operand.
   1745     unsigned NumOperands = OpInfo.MINumOperands;
   1746     if (AsmOperands[SrcOperand].SubOpIdx == -1) {
   1747       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
   1748       continue;
   1749     }
   1750 
   1751     // Add a separate ResOperand for each suboperand.
   1752     for (unsigned AI = 0; AI < NumOperands; ++AI) {
   1753       assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
   1754              AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
   1755              "unexpected AsmOperands for suboperands");
   1756       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
   1757     }
   1758   }
   1759 }
   1760 
   1761 void MatchableInfo::buildAliasResultOperands() {
   1762   const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
   1763   const CodeGenInstruction *ResultInst = getResultInst();
   1764 
   1765   // Loop over all operands of the result instruction, determining how to
   1766   // populate them.
   1767   unsigned AliasOpNo = 0;
   1768   unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
   1769   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
   1770     const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
   1771 
   1772     // If this is a tied operand, just copy from the previously handled operand.
   1773     int TiedOp = -1;
   1774     if (OpInfo->MINumOperands == 1)
   1775       TiedOp = OpInfo->getTiedRegister();
   1776     if (TiedOp != -1) {
   1777       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
   1778       continue;
   1779     }
   1780 
   1781     // Handle all the suboperands for this operand.
   1782     const std::string &OpName = OpInfo->Name;
   1783     for ( ; AliasOpNo <  LastOpNo &&
   1784             CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
   1785       int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
   1786 
   1787       // Find out what operand from the asmparser that this MCInst operand
   1788       // comes from.
   1789       switch (CGA.ResultOperands[AliasOpNo].Kind) {
   1790       case CodeGenInstAlias::ResultOperand::K_Record: {
   1791         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
   1792         int SrcOperand = findAsmOperand(Name, SubIdx);
   1793         if (SrcOperand == -1)
   1794           PrintFatalError(TheDef->getLoc(), "Instruction '" +
   1795                         TheDef->getName() + "' has operand '" + OpName +
   1796                         "' that doesn't appear in asm string!");
   1797         unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
   1798         ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
   1799                                                         NumOperands));
   1800         break;
   1801       }
   1802       case CodeGenInstAlias::ResultOperand::K_Imm: {
   1803         int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
   1804         ResOperands.push_back(ResOperand::getImmOp(ImmVal));
   1805         break;
   1806       }
   1807       case CodeGenInstAlias::ResultOperand::K_Reg: {
   1808         Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
   1809         ResOperands.push_back(ResOperand::getRegOp(Reg));
   1810         break;
   1811       }
   1812       }
   1813     }
   1814   }
   1815 }
   1816 
   1817 static unsigned getConverterOperandID(const std::string &Name,
   1818                                       SmallSetVector<std::string, 16> &Table,
   1819                                       bool &IsNew) {
   1820   IsNew = Table.insert(Name);
   1821 
   1822   unsigned ID = IsNew ? Table.size() - 1 :
   1823     std::find(Table.begin(), Table.end(), Name) - Table.begin();
   1824 
   1825   assert(ID < Table.size());
   1826 
   1827   return ID;
   1828 }
   1829 
   1830 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
   1831                              std::vector<std::unique_ptr<MatchableInfo>> &Infos,
   1832                              bool HasMnemonicFirst, bool HasOptionalOperands,
   1833                              raw_ostream &OS) {
   1834   SmallSetVector<std::string, 16> OperandConversionKinds;
   1835   SmallSetVector<std::string, 16> InstructionConversionKinds;
   1836   std::vector<std::vector<uint8_t> > ConversionTable;
   1837   size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
   1838 
   1839   // TargetOperandClass - This is the target's operand class, like X86Operand.
   1840   std::string TargetOperandClass = Target.getName() + "Operand";
   1841 
   1842   // Write the convert function to a separate stream, so we can drop it after
   1843   // the enum. We'll build up the conversion handlers for the individual
   1844   // operand types opportunistically as we encounter them.
   1845   std::string ConvertFnBody;
   1846   raw_string_ostream CvtOS(ConvertFnBody);
   1847   // Start the unified conversion function.
   1848   if (HasOptionalOperands) {
   1849     CvtOS << "void " << Target.getName() << ClassName << "::\n"
   1850           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
   1851           << "unsigned Opcode,\n"
   1852           << "                const OperandVector &Operands,\n"
   1853           << "                const SmallBitVector &OptionalOperandsMask) {\n";
   1854   } else {
   1855     CvtOS << "void " << Target.getName() << ClassName << "::\n"
   1856           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
   1857           << "unsigned Opcode,\n"
   1858           << "                const OperandVector &Operands) {\n";
   1859   }
   1860   CvtOS << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
   1861   CvtOS << "  const uint8_t *Converter = ConversionTable[Kind];\n";
   1862   if (HasOptionalOperands) {
   1863     CvtOS << "  unsigned NumDefaults = 0;\n";
   1864   }
   1865   CvtOS << "  unsigned OpIdx;\n";
   1866   CvtOS << "  Inst.setOpcode(Opcode);\n";
   1867   CvtOS << "  for (const uint8_t *p = Converter; *p; p+= 2) {\n";
   1868   if (HasOptionalOperands) {
   1869     CvtOS << "    OpIdx = *(p + 1) - NumDefaults;\n";
   1870   } else {
   1871     CvtOS << "    OpIdx = *(p + 1);\n";
   1872   }
   1873   CvtOS << "    switch (*p) {\n";
   1874   CvtOS << "    default: llvm_unreachable(\"invalid conversion entry!\");\n";
   1875   CvtOS << "    case CVT_Reg:\n";
   1876   CvtOS << "      static_cast<" << TargetOperandClass
   1877         << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
   1878   CvtOS << "      break;\n";
   1879   CvtOS << "    case CVT_Tied:\n";
   1880   CvtOS << "      Inst.addOperand(Inst.getOperand(OpIdx));\n";
   1881   CvtOS << "      break;\n";
   1882 
   1883   std::string OperandFnBody;
   1884   raw_string_ostream OpOS(OperandFnBody);
   1885   // Start the operand number lookup function.
   1886   OpOS << "void " << Target.getName() << ClassName << "::\n"
   1887        << "convertToMapAndConstraints(unsigned Kind,\n";
   1888   OpOS.indent(27);
   1889   OpOS << "const OperandVector &Operands) {\n"
   1890        << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
   1891        << "  unsigned NumMCOperands = 0;\n"
   1892        << "  const uint8_t *Converter = ConversionTable[Kind];\n"
   1893        << "  for (const uint8_t *p = Converter; *p; p+= 2) {\n"
   1894        << "    switch (*p) {\n"
   1895        << "    default: llvm_unreachable(\"invalid conversion entry!\");\n"
   1896        << "    case CVT_Reg:\n"
   1897        << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
   1898        << "      Operands[*(p + 1)]->setConstraint(\"r\");\n"
   1899        << "      ++NumMCOperands;\n"
   1900        << "      break;\n"
   1901        << "    case CVT_Tied:\n"
   1902        << "      ++NumMCOperands;\n"
   1903        << "      break;\n";
   1904 
   1905   // Pre-populate the operand conversion kinds with the standard always
   1906   // available entries.
   1907   OperandConversionKinds.insert("CVT_Done");
   1908   OperandConversionKinds.insert("CVT_Reg");
   1909   OperandConversionKinds.insert("CVT_Tied");
   1910   enum { CVT_Done, CVT_Reg, CVT_Tied };
   1911 
   1912   for (auto &II : Infos) {
   1913     // Check if we have a custom match function.
   1914     std::string AsmMatchConverter =
   1915       II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
   1916     if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
   1917       std::string Signature = "ConvertCustom_" + AsmMatchConverter;
   1918       II->ConversionFnKind = Signature;
   1919 
   1920       // Check if we have already generated this signature.
   1921       if (!InstructionConversionKinds.insert(Signature))
   1922         continue;
   1923 
   1924       // Remember this converter for the kind enum.
   1925       unsigned KindID = OperandConversionKinds.size();
   1926       OperandConversionKinds.insert("CVT_" +
   1927                                     getEnumNameForToken(AsmMatchConverter));
   1928 
   1929       // Add the converter row for this instruction.
   1930       ConversionTable.emplace_back();
   1931       ConversionTable.back().push_back(KindID);
   1932       ConversionTable.back().push_back(CVT_Done);
   1933 
   1934       // Add the handler to the conversion driver function.
   1935       CvtOS << "    case CVT_"
   1936             << getEnumNameForToken(AsmMatchConverter) << ":\n"
   1937             << "      " << AsmMatchConverter << "(Inst, Operands);\n"
   1938             << "      break;\n";
   1939 
   1940       // FIXME: Handle the operand number lookup for custom match functions.
   1941       continue;
   1942     }
   1943 
   1944     // Build the conversion function signature.
   1945     std::string Signature = "Convert";
   1946 
   1947     std::vector<uint8_t> ConversionRow;
   1948 
   1949     // Compute the convert enum and the case body.
   1950     MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
   1951 
   1952     for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
   1953       const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
   1954 
   1955       // Generate code to populate each result operand.
   1956       switch (OpInfo.Kind) {
   1957       case MatchableInfo::ResOperand::RenderAsmOperand: {
   1958         // This comes from something we parsed.
   1959         const MatchableInfo::AsmOperand &Op =
   1960           II->AsmOperands[OpInfo.AsmOperandNum];
   1961 
   1962         // Registers are always converted the same, don't duplicate the
   1963         // conversion function based on them.
   1964         Signature += "__";
   1965         std::string Class;
   1966         Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
   1967         Signature += Class;
   1968         Signature += utostr(OpInfo.MINumOperands);
   1969         Signature += "_" + itostr(OpInfo.AsmOperandNum);
   1970 
   1971         // Add the conversion kind, if necessary, and get the associated ID
   1972         // the index of its entry in the vector).
   1973         std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
   1974                                      Op.Class->RenderMethod);
   1975         if (Op.Class->IsOptional) {
   1976           // For optional operands we must also care about DefaultMethod
   1977           assert(HasOptionalOperands);
   1978           Name += "_" + Op.Class->DefaultMethod;
   1979         }
   1980         Name = getEnumNameForToken(Name);
   1981 
   1982         bool IsNewConverter = false;
   1983         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
   1984                                             IsNewConverter);
   1985 
   1986         // Add the operand entry to the instruction kind conversion row.
   1987         ConversionRow.push_back(ID);
   1988         ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
   1989 
   1990         if (!IsNewConverter)
   1991           break;
   1992 
   1993         // This is a new operand kind. Add a handler for it to the
   1994         // converter driver.
   1995         CvtOS << "    case " << Name << ":\n";
   1996         if (Op.Class->IsOptional) {
   1997           // If optional operand is not present in actual instruction then we
   1998           // should call its DefaultMethod before RenderMethod
   1999           assert(HasOptionalOperands);
   2000           CvtOS << "      if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
   2001                 << "        " << Op.Class->DefaultMethod << "()"
   2002                 << "->" << Op.Class->RenderMethod << "(Inst, "
   2003                 << OpInfo.MINumOperands << ");\n"
   2004                 << "        ++NumDefaults;\n"
   2005                 << "      } else {\n"
   2006                 << "        static_cast<" << TargetOperandClass
   2007                 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
   2008                 << "(Inst, " << OpInfo.MINumOperands << ");\n"
   2009                 << "      }\n";
   2010         } else {
   2011           CvtOS << "      static_cast<" << TargetOperandClass
   2012                 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
   2013                 << "(Inst, " << OpInfo.MINumOperands << ");\n";
   2014         }
   2015         CvtOS << "      break;\n";
   2016 
   2017         // Add a handler for the operand number lookup.
   2018         OpOS << "    case " << Name << ":\n"
   2019              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
   2020 
   2021         if (Op.Class->isRegisterClass())
   2022           OpOS << "      Operands[*(p + 1)]->setConstraint(\"r\");\n";
   2023         else
   2024           OpOS << "      Operands[*(p + 1)]->setConstraint(\"m\");\n";
   2025         OpOS << "      NumMCOperands += " << OpInfo.MINumOperands << ";\n"
   2026              << "      break;\n";
   2027         break;
   2028       }
   2029       case MatchableInfo::ResOperand::TiedOperand: {
   2030         // If this operand is tied to a previous one, just copy the MCInst
   2031         // operand from the earlier one.We can only tie single MCOperand values.
   2032         assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
   2033         unsigned TiedOp = OpInfo.TiedOperandNum;
   2034         assert(i > TiedOp && "Tied operand precedes its target!");
   2035         Signature += "__Tie" + utostr(TiedOp);
   2036         ConversionRow.push_back(CVT_Tied);
   2037         ConversionRow.push_back(TiedOp);
   2038         break;
   2039       }
   2040       case MatchableInfo::ResOperand::ImmOperand: {
   2041         int64_t Val = OpInfo.ImmVal;
   2042         std::string Ty = "imm_" + itostr(Val);
   2043         Ty = getEnumNameForToken(Ty);
   2044         Signature += "__" + Ty;
   2045 
   2046         std::string Name = "CVT_" + Ty;
   2047         bool IsNewConverter = false;
   2048         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
   2049                                             IsNewConverter);
   2050         // Add the operand entry to the instruction kind conversion row.
   2051         ConversionRow.push_back(ID);
   2052         ConversionRow.push_back(0);
   2053 
   2054         if (!IsNewConverter)
   2055           break;
   2056 
   2057         CvtOS << "    case " << Name << ":\n"
   2058               << "      Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
   2059               << "      break;\n";
   2060 
   2061         OpOS << "    case " << Name << ":\n"
   2062              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
   2063              << "      Operands[*(p + 1)]->setConstraint(\"\");\n"
   2064              << "      ++NumMCOperands;\n"
   2065              << "      break;\n";
   2066         break;
   2067       }
   2068       case MatchableInfo::ResOperand::RegOperand: {
   2069         std::string Reg, Name;
   2070         if (!OpInfo.Register) {
   2071           Name = "reg0";
   2072           Reg = "0";
   2073         } else {
   2074           Reg = getQualifiedName(OpInfo.Register);
   2075           Name = "reg" + OpInfo.Register->getName();
   2076         }
   2077         Signature += "__" + Name;
   2078         Name = "CVT_" + Name;
   2079         bool IsNewConverter = false;
   2080         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
   2081                                             IsNewConverter);
   2082         // Add the operand entry to the instruction kind conversion row.
   2083         ConversionRow.push_back(ID);
   2084         ConversionRow.push_back(0);
   2085 
   2086         if (!IsNewConverter)
   2087           break;
   2088         CvtOS << "    case " << Name << ":\n"
   2089               << "      Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
   2090               << "      break;\n";
   2091 
   2092         OpOS << "    case " << Name << ":\n"
   2093              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
   2094              << "      Operands[*(p + 1)]->setConstraint(\"m\");\n"
   2095              << "      ++NumMCOperands;\n"
   2096              << "      break;\n";
   2097       }
   2098       }
   2099     }
   2100 
   2101     // If there were no operands, add to the signature to that effect
   2102     if (Signature == "Convert")
   2103       Signature += "_NoOperands";
   2104 
   2105     II->ConversionFnKind = Signature;
   2106 
   2107     // Save the signature. If we already have it, don't add a new row
   2108     // to the table.
   2109     if (!InstructionConversionKinds.insert(Signature))
   2110       continue;
   2111 
   2112     // Add the row to the table.
   2113     ConversionTable.push_back(std::move(ConversionRow));
   2114   }
   2115 
   2116   // Finish up the converter driver function.
   2117   CvtOS << "    }\n  }\n}\n\n";
   2118 
   2119   // Finish up the operand number lookup function.
   2120   OpOS << "    }\n  }\n}\n\n";
   2121 
   2122   OS << "namespace {\n";
   2123 
   2124   // Output the operand conversion kind enum.
   2125   OS << "enum OperatorConversionKind {\n";
   2126   for (const std::string &Converter : OperandConversionKinds)
   2127     OS << "  " << Converter << ",\n";
   2128   OS << "  CVT_NUM_CONVERTERS\n";
   2129   OS << "};\n\n";
   2130 
   2131   // Output the instruction conversion kind enum.
   2132   OS << "enum InstructionConversionKind {\n";
   2133   for (const std::string &Signature : InstructionConversionKinds)
   2134     OS << "  " << Signature << ",\n";
   2135   OS << "  CVT_NUM_SIGNATURES\n";
   2136   OS << "};\n\n";
   2137 
   2138   OS << "} // end anonymous namespace\n\n";
   2139 
   2140   // Output the conversion table.
   2141   OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
   2142      << MaxRowLength << "] = {\n";
   2143 
   2144   for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
   2145     assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
   2146     OS << "  // " << InstructionConversionKinds[Row] << "\n";
   2147     OS << "  { ";
   2148     for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
   2149       OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
   2150          << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
   2151     OS << "CVT_Done },\n";
   2152   }
   2153 
   2154   OS << "};\n\n";
   2155 
   2156   // Spit out the conversion driver function.
   2157   OS << CvtOS.str();
   2158 
   2159   // Spit out the operand number lookup function.
   2160   OS << OpOS.str();
   2161 }
   2162 
   2163 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
   2164 static void emitMatchClassEnumeration(CodeGenTarget &Target,
   2165                                       std::forward_list<ClassInfo> &Infos,
   2166                                       raw_ostream &OS) {
   2167   OS << "namespace {\n\n";
   2168 
   2169   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
   2170      << "/// instruction matching.\n";
   2171   OS << "enum MatchClassKind {\n";
   2172   OS << "  InvalidMatchClass = 0,\n";
   2173   OS << "  OptionalMatchClass = 1,\n";
   2174   for (const auto &CI : Infos) {
   2175     OS << "  " << CI.Name << ", // ";
   2176     if (CI.Kind == ClassInfo::Token) {
   2177       OS << "'" << CI.ValueName << "'\n";
   2178     } else if (CI.isRegisterClass()) {
   2179       if (!CI.ValueName.empty())
   2180         OS << "register class '" << CI.ValueName << "'\n";
   2181       else
   2182         OS << "derived register class\n";
   2183     } else {
   2184       OS << "user defined class '" << CI.ValueName << "'\n";
   2185     }
   2186   }
   2187   OS << "  NumMatchClassKinds\n";
   2188   OS << "};\n\n";
   2189 
   2190   OS << "}\n\n";
   2191 }
   2192 
   2193 /// emitValidateOperandClass - Emit the function to validate an operand class.
   2194 static void emitValidateOperandClass(AsmMatcherInfo &Info,
   2195                                      raw_ostream &OS) {
   2196   OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
   2197      << "MatchClassKind Kind) {\n";
   2198   OS << "  " << Info.Target.getName() << "Operand &Operand = ("
   2199      << Info.Target.getName() << "Operand&)GOp;\n";
   2200 
   2201   // The InvalidMatchClass is not to match any operand.
   2202   OS << "  if (Kind == InvalidMatchClass)\n";
   2203   OS << "    return MCTargetAsmParser::Match_InvalidOperand;\n\n";
   2204 
   2205   // Check for Token operands first.
   2206   // FIXME: Use a more specific diagnostic type.
   2207   OS << "  if (Operand.isToken())\n";
   2208   OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
   2209      << "             MCTargetAsmParser::Match_Success :\n"
   2210      << "             MCTargetAsmParser::Match_InvalidOperand;\n\n";
   2211 
   2212   // Check the user classes. We don't care what order since we're only
   2213   // actually matching against one of them.
   2214   OS << "  switch (Kind) {\n"
   2215         "  default: break;\n";
   2216   for (const auto &CI : Info.Classes) {
   2217     if (!CI.isUserClass())
   2218       continue;
   2219 
   2220     OS << "  // '" << CI.ClassName << "' class\n";
   2221     OS << "  case " << CI.Name << ":\n";
   2222     OS << "    if (Operand." << CI.PredicateMethod << "())\n";
   2223     OS << "      return MCTargetAsmParser::Match_Success;\n";
   2224     if (!CI.DiagnosticType.empty())
   2225       OS << "    return " << Info.Target.getName() << "AsmParser::Match_"
   2226          << CI.DiagnosticType << ";\n";
   2227     else
   2228       OS << "    break;\n";
   2229   }
   2230   OS << "  } // end switch (Kind)\n\n";
   2231 
   2232   // Check for register operands, including sub-classes.
   2233   OS << "  if (Operand.isReg()) {\n";
   2234   OS << "    MatchClassKind OpKind;\n";
   2235   OS << "    switch (Operand.getReg()) {\n";
   2236   OS << "    default: OpKind = InvalidMatchClass; break;\n";
   2237   for (const auto &RC : Info.RegisterClasses)
   2238     OS << "    case " << Info.Target.getName() << "::"
   2239        << RC.first->getName() << ": OpKind = " << RC.second->Name
   2240        << "; break;\n";
   2241   OS << "    }\n";
   2242   OS << "    return isSubclass(OpKind, Kind) ? "
   2243      << "MCTargetAsmParser::Match_Success :\n                             "
   2244      << "         MCTargetAsmParser::Match_InvalidOperand;\n  }\n\n";
   2245 
   2246   // Generic fallthrough match failure case for operands that don't have
   2247   // specialized diagnostic types.
   2248   OS << "  return MCTargetAsmParser::Match_InvalidOperand;\n";
   2249   OS << "}\n\n";
   2250 }
   2251 
   2252 /// emitIsSubclass - Emit the subclass predicate function.
   2253 static void emitIsSubclass(CodeGenTarget &Target,
   2254                            std::forward_list<ClassInfo> &Infos,
   2255                            raw_ostream &OS) {
   2256   OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
   2257   OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
   2258   OS << "  if (A == B)\n";
   2259   OS << "    return true;\n\n";
   2260 
   2261   bool EmittedSwitch = false;
   2262   for (const auto &A : Infos) {
   2263     std::vector<StringRef> SuperClasses;
   2264     if (A.IsOptional)
   2265       SuperClasses.push_back("OptionalMatchClass");
   2266     for (const auto &B : Infos) {
   2267       if (&A != &B && A.isSubsetOf(B))
   2268         SuperClasses.push_back(B.Name);
   2269     }
   2270 
   2271     if (SuperClasses.empty())
   2272       continue;
   2273 
   2274     // If this is the first SuperClass, emit the switch header.
   2275     if (!EmittedSwitch) {
   2276       OS << "  switch (A) {\n";
   2277       OS << "  default:\n";
   2278       OS << "    return false;\n";
   2279       EmittedSwitch = true;
   2280     }
   2281 
   2282     OS << "\n  case " << A.Name << ":\n";
   2283 
   2284     if (SuperClasses.size() == 1) {
   2285       OS << "    return B == " << SuperClasses.back() << ";\n";
   2286       continue;
   2287     }
   2288 
   2289     if (!SuperClasses.empty()) {
   2290       OS << "    switch (B) {\n";
   2291       OS << "    default: return false;\n";
   2292       for (StringRef SC : SuperClasses)
   2293         OS << "    case " << SC << ": return true;\n";
   2294       OS << "    }\n";
   2295     } else {
   2296       // No case statement to emit
   2297       OS << "    return false;\n";
   2298     }
   2299   }
   2300 
   2301   // If there were case statements emitted into the string stream write the
   2302   // default.
   2303   if (EmittedSwitch)
   2304     OS << "  }\n";
   2305   else
   2306     OS << "  return false;\n";
   2307 
   2308   OS << "}\n\n";
   2309 }
   2310 
   2311 /// emitMatchTokenString - Emit the function to match a token string to the
   2312 /// appropriate match class value.
   2313 static void emitMatchTokenString(CodeGenTarget &Target,
   2314                                  std::forward_list<ClassInfo> &Infos,
   2315                                  raw_ostream &OS) {
   2316   // Construct the match list.
   2317   std::vector<StringMatcher::StringPair> Matches;
   2318   for (const auto &CI : Infos) {
   2319     if (CI.Kind == ClassInfo::Token)
   2320       Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
   2321   }
   2322 
   2323   OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
   2324 
   2325   StringMatcher("Name", Matches, OS).Emit();
   2326 
   2327   OS << "  return InvalidMatchClass;\n";
   2328   OS << "}\n\n";
   2329 }
   2330 
   2331 /// emitMatchRegisterName - Emit the function to match a string to the target
   2332 /// specific register enum.
   2333 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
   2334                                   raw_ostream &OS) {
   2335   // Construct the match list.
   2336   std::vector<StringMatcher::StringPair> Matches;
   2337   const auto &Regs = Target.getRegBank().getRegisters();
   2338   for (const CodeGenRegister &Reg : Regs) {
   2339     if (Reg.TheDef->getValueAsString("AsmName").empty())
   2340       continue;
   2341 
   2342     Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
   2343                          "return " + utostr(Reg.EnumValue) + ";");
   2344   }
   2345 
   2346   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
   2347 
   2348   StringMatcher("Name", Matches, OS).Emit();
   2349 
   2350   OS << "  return 0;\n";
   2351   OS << "}\n\n";
   2352 }
   2353 
   2354 /// Emit the function to match a string to the target
   2355 /// specific register enum.
   2356 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
   2357                                      raw_ostream &OS) {
   2358   // Construct the match list.
   2359   std::vector<StringMatcher::StringPair> Matches;
   2360   const auto &Regs = Target.getRegBank().getRegisters();
   2361   for (const CodeGenRegister &Reg : Regs) {
   2362 
   2363     auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
   2364 
   2365     for (auto AltName : AltNames) {
   2366       AltName = StringRef(AltName).trim();
   2367 
   2368       // don't handle empty alternative names
   2369       if (AltName.empty())
   2370         continue;
   2371 
   2372       Matches.emplace_back(AltName,
   2373                            "return " + utostr(Reg.EnumValue) + ";");
   2374     }
   2375   }
   2376 
   2377   OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
   2378 
   2379   StringMatcher("Name", Matches, OS).Emit();
   2380 
   2381   OS << "  return 0;\n";
   2382   OS << "}\n\n";
   2383 }
   2384 
   2385 static const char *getMinimalTypeForRange(uint64_t Range) {
   2386   assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large");
   2387   if (Range > 0xFFFFFFFFULL)
   2388     return "uint64_t";
   2389   if (Range > 0xFFFF)
   2390     return "uint32_t";
   2391   if (Range > 0xFF)
   2392     return "uint16_t";
   2393   return "uint8_t";
   2394 }
   2395 
   2396 static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) {
   2397   uint64_t MaxIndex = Info.SubtargetFeatures.size();
   2398   if (MaxIndex > 0)
   2399     MaxIndex--;
   2400   return getMinimalTypeForRange(1ULL << MaxIndex);
   2401 }
   2402 
   2403 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
   2404 /// definitions.
   2405 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
   2406                                                 raw_ostream &OS) {
   2407   OS << "// Flags for subtarget features that participate in "
   2408      << "instruction matching.\n";
   2409   OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info)
   2410      << " {\n";
   2411   for (const auto &SF : Info.SubtargetFeatures) {
   2412     const SubtargetFeatureInfo &SFI = SF.second;
   2413     OS << "  " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n";
   2414   }
   2415   OS << "  Feature_None = 0\n";
   2416   OS << "};\n\n";
   2417 }
   2418 
   2419 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
   2420 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
   2421   // Get the set of diagnostic types from all of the operand classes.
   2422   std::set<StringRef> Types;
   2423   for (const auto &OpClassEntry : Info.AsmOperandClasses) {
   2424     if (!OpClassEntry.second->DiagnosticType.empty())
   2425       Types.insert(OpClassEntry.second->DiagnosticType);
   2426   }
   2427 
   2428   if (Types.empty()) return;
   2429 
   2430   // Now emit the enum entries.
   2431   for (StringRef Type : Types)
   2432     OS << "  Match_" << Type << ",\n";
   2433   OS << "  END_OPERAND_DIAGNOSTIC_TYPES\n";
   2434 }
   2435 
   2436 /// emitGetSubtargetFeatureName - Emit the helper function to get the
   2437 /// user-level name for a subtarget feature.
   2438 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
   2439   OS << "// User-level names for subtarget features that participate in\n"
   2440      << "// instruction matching.\n"
   2441      << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
   2442   if (!Info.SubtargetFeatures.empty()) {
   2443     OS << "  switch(Val) {\n";
   2444     for (const auto &SF : Info.SubtargetFeatures) {
   2445       const SubtargetFeatureInfo &SFI = SF.second;
   2446       // FIXME: Totally just a placeholder name to get the algorithm working.
   2447       OS << "  case " << SFI.getEnumName() << ": return \""
   2448          << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
   2449     }
   2450     OS << "  default: return \"(unknown)\";\n";
   2451     OS << "  }\n";
   2452   } else {
   2453     // Nothing to emit, so skip the switch
   2454     OS << "  return \"(unknown)\";\n";
   2455   }
   2456   OS << "}\n\n";
   2457 }
   2458 
   2459 /// emitComputeAvailableFeatures - Emit the function to compute the list of
   2460 /// available features given a subtarget.
   2461 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
   2462                                          raw_ostream &OS) {
   2463   std::string ClassName =
   2464     Info.AsmParser->getValueAsString("AsmParserClassName");
   2465 
   2466   OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n"
   2467      << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n";
   2468   OS << "  uint64_t Features = 0;\n";
   2469   for (const auto &SF : Info.SubtargetFeatures) {
   2470     const SubtargetFeatureInfo &SFI = SF.second;
   2471 
   2472     OS << "  if (";
   2473     std::string CondStorage =
   2474       SFI.TheDef->getValueAsString("AssemblerCondString");
   2475     StringRef Conds = CondStorage;
   2476     std::pair<StringRef,StringRef> Comma = Conds.split(',');
   2477     bool First = true;
   2478     do {
   2479       if (!First)
   2480         OS << " && ";
   2481 
   2482       bool Neg = false;
   2483       StringRef Cond = Comma.first;
   2484       if (Cond[0] == '!') {
   2485         Neg = true;
   2486         Cond = Cond.substr(1);
   2487       }
   2488 
   2489       OS << "(";
   2490       if (Neg)
   2491         OS << "!";
   2492       OS << "FB[" << Info.Target.getName() << "::" << Cond << "])";
   2493 
   2494       if (Comma.second.empty())
   2495         break;
   2496 
   2497       First = false;
   2498       Comma = Comma.second.split(',');
   2499     } while (true);
   2500 
   2501     OS << ")\n";
   2502     OS << "    Features |= " << SFI.getEnumName() << ";\n";
   2503   }
   2504   OS << "  return Features;\n";
   2505   OS << "}\n\n";
   2506 }
   2507 
   2508 static std::string GetAliasRequiredFeatures(Record *R,
   2509                                             const AsmMatcherInfo &Info) {
   2510   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
   2511   std::string Result;
   2512   unsigned NumFeatures = 0;
   2513   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
   2514     const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
   2515 
   2516     if (!F)
   2517       PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
   2518                     "' is not marked as an AssemblerPredicate!");
   2519 
   2520     if (NumFeatures)
   2521       Result += '|';
   2522 
   2523     Result += F->getEnumName();
   2524     ++NumFeatures;
   2525   }
   2526 
   2527   if (NumFeatures > 1)
   2528     Result = '(' + Result + ')';
   2529   return Result;
   2530 }
   2531 
   2532 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
   2533                                      std::vector<Record*> &Aliases,
   2534                                      unsigned Indent = 0,
   2535                                   StringRef AsmParserVariantName = StringRef()){
   2536   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
   2537   // iteration order of the map is stable.
   2538   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
   2539 
   2540   for (Record *R : Aliases) {
   2541     // FIXME: Allow AssemblerVariantName to be a comma separated list.
   2542     std::string AsmVariantName = R->getValueAsString("AsmVariantName");
   2543     if (AsmVariantName != AsmParserVariantName)
   2544       continue;
   2545     AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
   2546   }
   2547   if (AliasesFromMnemonic.empty())
   2548     return;
   2549 
   2550   // Process each alias a "from" mnemonic at a time, building the code executed
   2551   // by the string remapper.
   2552   std::vector<StringMatcher::StringPair> Cases;
   2553   for (const auto &AliasEntry : AliasesFromMnemonic) {
   2554     const std::vector<Record*> &ToVec = AliasEntry.second;
   2555 
   2556     // Loop through each alias and emit code that handles each case.  If there
   2557     // are two instructions without predicates, emit an error.  If there is one,
   2558     // emit it last.
   2559     std::string MatchCode;
   2560     int AliasWithNoPredicate = -1;
   2561 
   2562     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
   2563       Record *R = ToVec[i];
   2564       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
   2565 
   2566       // If this unconditionally matches, remember it for later and diagnose
   2567       // duplicates.
   2568       if (FeatureMask.empty()) {
   2569         if (AliasWithNoPredicate != -1) {
   2570           // We can't have two aliases from the same mnemonic with no predicate.
   2571           PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
   2572                      "two MnemonicAliases with the same 'from' mnemonic!");
   2573           PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
   2574         }
   2575 
   2576         AliasWithNoPredicate = i;
   2577         continue;
   2578       }
   2579       if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
   2580         PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
   2581 
   2582       if (!MatchCode.empty())
   2583         MatchCode += "else ";
   2584       MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
   2585       MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
   2586     }
   2587 
   2588     if (AliasWithNoPredicate != -1) {
   2589       Record *R = ToVec[AliasWithNoPredicate];
   2590       if (!MatchCode.empty())
   2591         MatchCode += "else\n  ";
   2592       MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
   2593     }
   2594 
   2595     MatchCode += "return;";
   2596 
   2597     Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
   2598   }
   2599   StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
   2600 }
   2601 
   2602 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
   2603 /// emit a function for them and return true, otherwise return false.
   2604 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
   2605                                 CodeGenTarget &Target) {
   2606   // Ignore aliases when match-prefix is set.
   2607   if (!MatchPrefix.empty())
   2608     return false;
   2609 
   2610   std::vector<Record*> Aliases =
   2611     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
   2612   if (Aliases.empty()) return false;
   2613 
   2614   OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
   2615     "uint64_t Features, unsigned VariantID) {\n";
   2616   OS << "  switch (VariantID) {\n";
   2617   unsigned VariantCount = Target.getAsmParserVariantCount();
   2618   for (unsigned VC = 0; VC != VariantCount; ++VC) {
   2619     Record *AsmVariant = Target.getAsmParserVariant(VC);
   2620     int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
   2621     std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
   2622     OS << "    case " << AsmParserVariantNo << ":\n";
   2623     emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
   2624                              AsmParserVariantName);
   2625     OS << "    break;\n";
   2626   }
   2627   OS << "  }\n";
   2628 
   2629   // Emit aliases that apply to all variants.
   2630   emitMnemonicAliasVariant(OS, Info, Aliases);
   2631 
   2632   OS << "}\n\n";
   2633 
   2634   return true;
   2635 }
   2636 
   2637 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
   2638                               const AsmMatcherInfo &Info, StringRef ClassName,
   2639                               StringToOffsetTable &StringTable,
   2640                               unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
   2641   unsigned MaxMask = 0;
   2642   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
   2643     MaxMask |= OMI.OperandMask;
   2644   }
   2645 
   2646   // Emit the static custom operand parsing table;
   2647   OS << "namespace {\n";
   2648   OS << "  struct OperandMatchEntry {\n";
   2649   OS << "    " << getMinimalRequiredFeaturesType(Info)
   2650                << " RequiredFeatures;\n";
   2651   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
   2652                << " Mnemonic;\n";
   2653   OS << "    " << getMinimalTypeForRange(std::distance(
   2654                       Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
   2655   OS << "    " << getMinimalTypeForRange(MaxMask)
   2656                << " OperandMask;\n\n";
   2657   OS << "    StringRef getMnemonic() const {\n";
   2658   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
   2659   OS << "                       MnemonicTable[Mnemonic]);\n";
   2660   OS << "    }\n";
   2661   OS << "  };\n\n";
   2662 
   2663   OS << "  // Predicate for searching for an opcode.\n";
   2664   OS << "  struct LessOpcodeOperand {\n";
   2665   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
   2666   OS << "      return LHS.getMnemonic()  < RHS;\n";
   2667   OS << "    }\n";
   2668   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
   2669   OS << "      return LHS < RHS.getMnemonic();\n";
   2670   OS << "    }\n";
   2671   OS << "    bool operator()(const OperandMatchEntry &LHS,";
   2672   OS << " const OperandMatchEntry &RHS) {\n";
   2673   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
   2674   OS << "    }\n";
   2675   OS << "  };\n";
   2676 
   2677   OS << "} // end anonymous namespace.\n\n";
   2678 
   2679   OS << "static const OperandMatchEntry OperandMatchTable["
   2680      << Info.OperandMatchInfo.size() << "] = {\n";
   2681 
   2682   OS << "  /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
   2683   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
   2684     const MatchableInfo &II = *OMI.MI;
   2685 
   2686     OS << "  { ";
   2687 
   2688     // Write the required features mask.
   2689     if (!II.RequiredFeatures.empty()) {
   2690       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
   2691         if (i) OS << "|";
   2692         OS << II.RequiredFeatures[i]->getEnumName();
   2693       }
   2694     } else
   2695       OS << "0";
   2696 
   2697     // Store a pascal-style length byte in the mnemonic.
   2698     std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
   2699     OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
   2700        << " /* " << II.Mnemonic << " */, ";
   2701 
   2702     OS << OMI.CI->Name;
   2703 
   2704     OS << ", " << OMI.OperandMask;
   2705     OS << " /* ";
   2706     bool printComma = false;
   2707     for (int i = 0, e = 31; i !=e; ++i)
   2708       if (OMI.OperandMask & (1 << i)) {
   2709         if (printComma)
   2710           OS << ", ";
   2711         OS << i;
   2712         printComma = true;
   2713       }
   2714     OS << " */";
   2715 
   2716     OS << " },\n";
   2717   }
   2718   OS << "};\n\n";
   2719 
   2720   // Emit the operand class switch to call the correct custom parser for
   2721   // the found operand class.
   2722   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
   2723      << Target.getName() << ClassName << "::\n"
   2724      << "tryCustomParseOperand(OperandVector"
   2725      << " &Operands,\n                      unsigned MCK) {\n\n"
   2726      << "  switch(MCK) {\n";
   2727 
   2728   for (const auto &CI : Info.Classes) {
   2729     if (CI.ParserMethod.empty())
   2730       continue;
   2731     OS << "  case " << CI.Name << ":\n"
   2732        << "    return " << CI.ParserMethod << "(Operands);\n";
   2733   }
   2734 
   2735   OS << "  default:\n";
   2736   OS << "    return MatchOperand_NoMatch;\n";
   2737   OS << "  }\n";
   2738   OS << "  return MatchOperand_NoMatch;\n";
   2739   OS << "}\n\n";
   2740 
   2741   // Emit the static custom operand parser. This code is very similar with
   2742   // the other matcher. Also use MatchResultTy here just in case we go for
   2743   // a better error handling.
   2744   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
   2745      << Target.getName() << ClassName << "::\n"
   2746      << "MatchOperandParserImpl(OperandVector"
   2747      << " &Operands,\n                       StringRef Mnemonic) {\n";
   2748 
   2749   // Emit code to get the available features.
   2750   OS << "  // Get the current feature set.\n";
   2751   OS << "  uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
   2752 
   2753   OS << "  // Get the next operand index.\n";
   2754   OS << "  unsigned NextOpNum = Operands.size()"
   2755      << (HasMnemonicFirst ? " - 1" : "") << ";\n";
   2756 
   2757   // Emit code to search the table.
   2758   OS << "  // Search the table.\n";
   2759   if (HasMnemonicFirst) {
   2760     OS << "  auto MnemonicRange =\n";
   2761     OS << "    std::equal_range(std::begin(OperandMatchTable), "
   2762           "std::end(OperandMatchTable),\n";
   2763     OS << "                     Mnemonic, LessOpcodeOperand());\n\n";
   2764   } else {
   2765     OS << "  auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
   2766           " std::end(OperandMatchTable));\n";
   2767     OS << "  if (!Mnemonic.empty())\n";
   2768     OS << "    MnemonicRange =\n";
   2769     OS << "      std::equal_range(std::begin(OperandMatchTable), "
   2770           "std::end(OperandMatchTable),\n";
   2771     OS << "                       Mnemonic, LessOpcodeOperand());\n\n";
   2772   }
   2773 
   2774   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
   2775   OS << "    return MatchOperand_NoMatch;\n\n";
   2776 
   2777   OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
   2778      << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
   2779 
   2780   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
   2781   OS << "    assert(Mnemonic == it->getMnemonic());\n\n";
   2782 
   2783   // Emit check that the required features are available.
   2784   OS << "    // check if the available features match\n";
   2785   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
   2786      << "!= it->RequiredFeatures) {\n";
   2787   OS << "      continue;\n";
   2788   OS << "    }\n\n";
   2789 
   2790   // Emit check to ensure the operand number matches.
   2791   OS << "    // check if the operand in question has a custom parser.\n";
   2792   OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
   2793   OS << "      continue;\n\n";
   2794 
   2795   // Emit call to the custom parser method
   2796   OS << "    // call custom parse method to handle the operand\n";
   2797   OS << "    OperandMatchResultTy Result = ";
   2798   OS << "tryCustomParseOperand(Operands, it->Class);\n";
   2799   OS << "    if (Result != MatchOperand_NoMatch)\n";
   2800   OS << "      return Result;\n";
   2801   OS << "  }\n\n";
   2802 
   2803   OS << "  // Okay, we had no match.\n";
   2804   OS << "  return MatchOperand_NoMatch;\n";
   2805   OS << "}\n\n";
   2806 }
   2807 
   2808 void AsmMatcherEmitter::run(raw_ostream &OS) {
   2809   CodeGenTarget Target(Records);
   2810   Record *AsmParser = Target.getAsmParser();
   2811   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
   2812 
   2813   // Compute the information on the instructions to match.
   2814   AsmMatcherInfo Info(AsmParser, Target, Records);
   2815   Info.buildInfo();
   2816 
   2817   // Sort the instruction table using the partial order on classes. We use
   2818   // stable_sort to ensure that ambiguous instructions are still
   2819   // deterministically ordered.
   2820   std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
   2821                    [](const std::unique_ptr<MatchableInfo> &a,
   2822                       const std::unique_ptr<MatchableInfo> &b){
   2823                      return *a < *b;});
   2824 
   2825 #ifndef NDEBUG
   2826   // Verify that the table is now sorted
   2827   for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
   2828        ++I) {
   2829     for (auto J = I; J != E; ++J) {
   2830       assert(!(**J < **I));
   2831     }
   2832   }
   2833 #endif // NDEBUG
   2834 
   2835   DEBUG_WITH_TYPE("instruction_info", {
   2836       for (const auto &MI : Info.Matchables)
   2837         MI->dump();
   2838     });
   2839 
   2840   // Check for ambiguous matchables.
   2841   DEBUG_WITH_TYPE("ambiguous_instrs", {
   2842     unsigned NumAmbiguous = 0;
   2843     for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
   2844          ++I) {
   2845       for (auto J = std::next(I); J != E; ++J) {
   2846         const MatchableInfo &A = **I;
   2847         const MatchableInfo &B = **J;
   2848 
   2849         if (A.couldMatchAmbiguouslyWith(B)) {
   2850           errs() << "warning: ambiguous matchables:\n";
   2851           A.dump();
   2852           errs() << "\nis incomparable with:\n";
   2853           B.dump();
   2854           errs() << "\n\n";
   2855           ++NumAmbiguous;
   2856         }
   2857       }
   2858     }
   2859     if (NumAmbiguous)
   2860       errs() << "warning: " << NumAmbiguous
   2861              << " ambiguous matchables!\n";
   2862   });
   2863 
   2864   // Compute the information on the custom operand parsing.
   2865   Info.buildOperandMatchInfo();
   2866 
   2867   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
   2868   bool HasOptionalOperands = Info.hasOptionalOperands();
   2869 
   2870   // Write the output.
   2871 
   2872   // Information for the class declaration.
   2873   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
   2874   OS << "#undef GET_ASSEMBLER_HEADER\n";
   2875   OS << "  // This should be included into the middle of the declaration of\n";
   2876   OS << "  // your subclasses implementation of MCTargetAsmParser.\n";
   2877   OS << "  uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
   2878   if (HasOptionalOperands) {
   2879     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
   2880        << "unsigned Opcode,\n"
   2881        << "                       const OperandVector &Operands,\n"
   2882        << "                       const SmallBitVector &OptionalOperandsMask);\n";
   2883   } else {
   2884     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
   2885        << "unsigned Opcode,\n"
   2886        << "                       const OperandVector &Operands);\n";
   2887   }
   2888   OS << "  void convertToMapAndConstraints(unsigned Kind,\n                ";
   2889   OS << "           const OperandVector &Operands) override;\n";
   2890   if (HasMnemonicFirst)
   2891     OS << "  bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n";
   2892   OS << "  unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
   2893      << "                                MCInst &Inst,\n"
   2894      << "                                uint64_t &ErrorInfo,"
   2895      << " bool matchingInlineAsm,\n"
   2896      << "                                unsigned VariantID = 0);\n";
   2897 
   2898   if (!Info.OperandMatchInfo.empty()) {
   2899     OS << "\n  enum OperandMatchResultTy {\n";
   2900     OS << "    MatchOperand_Success,    // operand matched successfully\n";
   2901     OS << "    MatchOperand_NoMatch,    // operand did not match\n";
   2902     OS << "    MatchOperand_ParseFail   // operand matched but had errors\n";
   2903     OS << "  };\n";
   2904     OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
   2905     OS << "    OperandVector &Operands,\n";
   2906     OS << "    StringRef Mnemonic);\n";
   2907 
   2908     OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
   2909     OS << "    OperandVector &Operands,\n";
   2910     OS << "    unsigned MCK);\n\n";
   2911   }
   2912 
   2913   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
   2914 
   2915   // Emit the operand match diagnostic enum names.
   2916   OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
   2917   OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
   2918   emitOperandDiagnosticTypes(Info, OS);
   2919   OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
   2920 
   2921   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
   2922   OS << "#undef GET_REGISTER_MATCHER\n\n";
   2923 
   2924   // Emit the subtarget feature enumeration.
   2925   emitSubtargetFeatureFlagEnumeration(Info, OS);
   2926 
   2927   // Emit the function to match a register name to number.
   2928   // This should be omitted for Mips target
   2929   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
   2930     emitMatchRegisterName(Target, AsmParser, OS);
   2931 
   2932   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
   2933     emitMatchRegisterAltName(Target, AsmParser, OS);
   2934 
   2935   OS << "#endif // GET_REGISTER_MATCHER\n\n";
   2936 
   2937   OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
   2938   OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
   2939 
   2940   // Generate the helper function to get the names for subtarget features.
   2941   emitGetSubtargetFeatureName(Info, OS);
   2942 
   2943   OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
   2944 
   2945   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
   2946   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
   2947 
   2948   // Generate the function that remaps for mnemonic aliases.
   2949   bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
   2950 
   2951   // Generate the convertToMCInst function to convert operands into an MCInst.
   2952   // Also, generate the convertToMapAndConstraints function for MS-style inline
   2953   // assembly.  The latter doesn't actually generate a MCInst.
   2954   emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
   2955                    HasOptionalOperands, OS);
   2956 
   2957   // Emit the enumeration for classes which participate in matching.
   2958   emitMatchClassEnumeration(Target, Info.Classes, OS);
   2959 
   2960   // Emit the routine to match token strings to their match class.
   2961   emitMatchTokenString(Target, Info.Classes, OS);
   2962 
   2963   // Emit the subclass predicate routine.
   2964   emitIsSubclass(Target, Info.Classes, OS);
   2965 
   2966   // Emit the routine to validate an operand against a match class.
   2967   emitValidateOperandClass(Info, OS);
   2968 
   2969   // Emit the available features compute function.
   2970   emitComputeAvailableFeatures(Info, OS);
   2971 
   2972   StringToOffsetTable StringTable;
   2973 
   2974   size_t MaxNumOperands = 0;
   2975   unsigned MaxMnemonicIndex = 0;
   2976   bool HasDeprecation = false;
   2977   for (const auto &MI : Info.Matchables) {
   2978     MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
   2979     HasDeprecation |= MI->HasDeprecation;
   2980 
   2981     // Store a pascal-style length byte in the mnemonic.
   2982     std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
   2983     MaxMnemonicIndex = std::max(MaxMnemonicIndex,
   2984                         StringTable.GetOrAddStringOffset(LenMnemonic, false));
   2985   }
   2986 
   2987   OS << "static const char *const MnemonicTable =\n";
   2988   StringTable.EmitString(OS);
   2989   OS << ";\n\n";
   2990 
   2991   // Emit the static match table; unused classes get initalized to 0 which is
   2992   // guaranteed to be InvalidMatchClass.
   2993   //
   2994   // FIXME: We can reduce the size of this table very easily. First, we change
   2995   // it so that store the kinds in separate bit-fields for each index, which
   2996   // only needs to be the max width used for classes at that index (we also need
   2997   // to reject based on this during classification). If we then make sure to
   2998   // order the match kinds appropriately (putting mnemonics last), then we
   2999   // should only end up using a few bits for each class, especially the ones
   3000   // following the mnemonic.
   3001   OS << "namespace {\n";
   3002   OS << "  struct MatchEntry {\n";
   3003   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
   3004                << " Mnemonic;\n";
   3005   OS << "    uint16_t Opcode;\n";
   3006   OS << "    " << getMinimalTypeForRange(Info.Matchables.size())
   3007                << " ConvertFn;\n";
   3008   OS << "    " << getMinimalRequiredFeaturesType(Info)
   3009                << " RequiredFeatures;\n";
   3010   OS << "    " << getMinimalTypeForRange(
   3011                       std::distance(Info.Classes.begin(), Info.Classes.end()))
   3012      << " Classes[" << MaxNumOperands << "];\n";
   3013   OS << "    StringRef getMnemonic() const {\n";
   3014   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
   3015   OS << "                       MnemonicTable[Mnemonic]);\n";
   3016   OS << "    }\n";
   3017   OS << "  };\n\n";
   3018 
   3019   OS << "  // Predicate for searching for an opcode.\n";
   3020   OS << "  struct LessOpcode {\n";
   3021   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
   3022   OS << "      return LHS.getMnemonic() < RHS;\n";
   3023   OS << "    }\n";
   3024   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
   3025   OS << "      return LHS < RHS.getMnemonic();\n";
   3026   OS << "    }\n";
   3027   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
   3028   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
   3029   OS << "    }\n";
   3030   OS << "  };\n";
   3031 
   3032   OS << "} // end anonymous namespace.\n\n";
   3033 
   3034   unsigned VariantCount = Target.getAsmParserVariantCount();
   3035   for (unsigned VC = 0; VC != VariantCount; ++VC) {
   3036     Record *AsmVariant = Target.getAsmParserVariant(VC);
   3037     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
   3038 
   3039     OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
   3040 
   3041     for (const auto &MI : Info.Matchables) {
   3042       if (MI->AsmVariantID != AsmVariantNo)
   3043         continue;
   3044 
   3045       // Store a pascal-style length byte in the mnemonic.
   3046       std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
   3047       OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
   3048          << " /* " << MI->Mnemonic << " */, "
   3049          << Target.getName() << "::"
   3050          << MI->getResultInst()->TheDef->getName() << ", "
   3051          << MI->ConversionFnKind << ", ";
   3052 
   3053       // Write the required features mask.
   3054       if (!MI->RequiredFeatures.empty()) {
   3055         for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
   3056           if (i) OS << "|";
   3057           OS << MI->RequiredFeatures[i]->getEnumName();
   3058         }
   3059       } else
   3060         OS << "0";
   3061 
   3062       OS << ", { ";
   3063       for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
   3064         const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
   3065 
   3066         if (i) OS << ", ";
   3067         OS << Op.Class->Name;
   3068       }
   3069       OS << " }, },\n";
   3070     }
   3071 
   3072     OS << "};\n\n";
   3073   }
   3074 
   3075   // A method to determine if a mnemonic is in the list.
   3076   if (HasMnemonicFirst) {
   3077     OS << "bool " << Target.getName() << ClassName << "::\n"
   3078        << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
   3079     OS << "  // Find the appropriate table for this asm variant.\n";
   3080     OS << "  const MatchEntry *Start, *End;\n";
   3081     OS << "  switch (VariantID) {\n";
   3082     OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
   3083     for (unsigned VC = 0; VC != VariantCount; ++VC) {
   3084       Record *AsmVariant = Target.getAsmParserVariant(VC);
   3085       int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
   3086       OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
   3087          << "); End = std::end(MatchTable" << VC << "); break;\n";
   3088     }
   3089     OS << "  }\n";
   3090     OS << "  // Search the table.\n";
   3091     OS << "  auto MnemonicRange = ";
   3092     OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
   3093     OS << "  return MnemonicRange.first != MnemonicRange.second;\n";
   3094     OS << "}\n\n";
   3095   }
   3096 
   3097   // Finally, build the match function.
   3098   OS << "unsigned " << Target.getName() << ClassName << "::\n"
   3099      << "MatchInstructionImpl(const OperandVector &Operands,\n";
   3100   OS << "                     MCInst &Inst, uint64_t &ErrorInfo,\n"
   3101      << "                     bool matchingInlineAsm, unsigned VariantID) {\n";
   3102 
   3103   OS << "  // Eliminate obvious mismatches.\n";
   3104   OS << "  if (Operands.size() > "
   3105      << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
   3106   OS << "    ErrorInfo = "
   3107      << (MaxNumOperands + HasMnemonicFirst) << ";\n";
   3108   OS << "    return Match_InvalidOperand;\n";
   3109   OS << "  }\n\n";
   3110 
   3111   // Emit code to get the available features.
   3112   OS << "  // Get the current feature set.\n";
   3113   OS << "  uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
   3114 
   3115   OS << "  // Get the instruction mnemonic, which is the first token.\n";
   3116   if (HasMnemonicFirst) {
   3117     OS << "  StringRef Mnemonic = ((" << Target.getName()
   3118        << "Operand&)*Operands[0]).getToken();\n\n";
   3119   } else {
   3120     OS << "  StringRef Mnemonic;\n";
   3121     OS << "  if (Operands[0]->isToken())\n";
   3122     OS << "    Mnemonic = ((" << Target.getName()
   3123        << "Operand&)*Operands[0]).getToken();\n\n";
   3124   }
   3125 
   3126   if (HasMnemonicAliases) {
   3127     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
   3128     OS << "  applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
   3129   }
   3130 
   3131   // Emit code to compute the class list for this operand vector.
   3132   OS << "  // Some state to try to produce better error messages.\n";
   3133   OS << "  bool HadMatchOtherThanFeatures = false;\n";
   3134   OS << "  bool HadMatchOtherThanPredicate = false;\n";
   3135   OS << "  unsigned RetCode = Match_InvalidOperand;\n";
   3136   OS << "  uint64_t MissingFeatures = ~0ULL;\n";
   3137   if (HasOptionalOperands) {
   3138     OS << "  SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
   3139   }
   3140   OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
   3141   OS << "  // wrong for all instances of the instruction.\n";
   3142   OS << "  ErrorInfo = ~0ULL;\n";
   3143 
   3144   // Emit code to search the table.
   3145   OS << "  // Find the appropriate table for this asm variant.\n";
   3146   OS << "  const MatchEntry *Start, *End;\n";
   3147   OS << "  switch (VariantID) {\n";
   3148   OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
   3149   for (unsigned VC = 0; VC != VariantCount; ++VC) {
   3150     Record *AsmVariant = Target.getAsmParserVariant(VC);
   3151     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
   3152     OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
   3153        << "); End = std::end(MatchTable" << VC << "); break;\n";
   3154   }
   3155   OS << "  }\n";
   3156 
   3157   OS << "  // Search the table.\n";
   3158   if (HasMnemonicFirst) {
   3159     OS << "  auto MnemonicRange = "
   3160           "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
   3161   } else {
   3162     OS << "  auto MnemonicRange = std::make_pair(Start, End);\n";
   3163     OS << "  unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
   3164     OS << "  if (!Mnemonic.empty())\n";
   3165     OS << "    MnemonicRange = "
   3166           "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
   3167   }
   3168 
   3169   OS << "  // Return a more specific error code if no mnemonics match.\n";
   3170   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
   3171   OS << "    return Match_MnemonicFail;\n\n";
   3172 
   3173   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
   3174      << "*ie = MnemonicRange.second;\n";
   3175   OS << "       it != ie; ++it) {\n";
   3176 
   3177   if (HasMnemonicFirst) {
   3178     OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
   3179     OS << "    assert(Mnemonic == it->getMnemonic());\n";
   3180   }
   3181 
   3182   // Emit check that the subclasses match.
   3183   OS << "    bool OperandsValid = true;\n";
   3184   if (HasOptionalOperands) {
   3185     OS << "    OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
   3186   }
   3187   OS << "    for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
   3188      << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
   3189      << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
   3190   OS << "      auto Formal = "
   3191      << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
   3192   OS << "      if (ActualIdx >= Operands.size()) {\n";
   3193   OS << "        OperandsValid = (Formal == " <<"InvalidMatchClass) || "
   3194                                  "isSubclass(Formal, OptionalMatchClass);\n";
   3195   OS << "        if (!OperandsValid) ErrorInfo = ActualIdx;\n";
   3196   if (HasOptionalOperands) {
   3197     OS << "        OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
   3198        << ");\n";
   3199   }
   3200   OS << "        break;\n";
   3201   OS << "      }\n";
   3202   OS << "      MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
   3203   OS << "      unsigned Diag = validateOperandClass(Actual, Formal);\n";
   3204   OS << "      if (Diag == Match_Success) {\n";
   3205   OS << "        ++ActualIdx;\n";
   3206   OS << "        continue;\n";
   3207   OS << "      }\n";
   3208   OS << "      // If the generic handler indicates an invalid operand\n";
   3209   OS << "      // failure, check for a special case.\n";
   3210   OS << "      if (Diag == Match_InvalidOperand) {\n";
   3211   OS << "        Diag = validateTargetOperandClass(Actual, Formal);\n";
   3212   OS << "        if (Diag == Match_Success) {\n";
   3213   OS << "          ++ActualIdx;\n";
   3214   OS << "          continue;\n";
   3215   OS << "        }\n";
   3216   OS << "      }\n";
   3217   OS << "      // If current formal operand wasn't matched and it is optional\n"
   3218      << "      // then try to match next formal operand\n";
   3219   OS << "      if (Diag == Match_InvalidOperand "
   3220      << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
   3221   if (HasOptionalOperands) {
   3222     OS << "        OptionalOperandsMask.set(FormalIdx);\n";
   3223   }
   3224   OS << "        continue;\n";
   3225   OS << "      }\n";
   3226   OS << "      // If this operand is broken for all of the instances of this\n";
   3227   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
   3228   OS << "      // If we already had a match that only failed due to a\n";
   3229   OS << "      // target predicate, that diagnostic is preferred.\n";
   3230   OS << "      if (!HadMatchOtherThanPredicate &&\n";
   3231   OS << "          (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
   3232   OS << "        ErrorInfo = ActualIdx;\n";
   3233   OS << "        // InvalidOperand is the default. Prefer specificity.\n";
   3234   OS << "        if (Diag != Match_InvalidOperand)\n";
   3235   OS << "          RetCode = Diag;\n";
   3236   OS << "      }\n";
   3237   OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
   3238   OS << "      OperandsValid = false;\n";
   3239   OS << "      break;\n";
   3240   OS << "    }\n\n";
   3241 
   3242   OS << "    if (!OperandsValid) continue;\n";
   3243 
   3244   // Emit check that the required features are available.
   3245   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
   3246      << "!= it->RequiredFeatures) {\n";
   3247   OS << "      HadMatchOtherThanFeatures = true;\n";
   3248   OS << "      uint64_t NewMissingFeatures = it->RequiredFeatures & "
   3249         "~AvailableFeatures;\n";
   3250   OS << "      if (countPopulation(NewMissingFeatures) <=\n"
   3251         "          countPopulation(MissingFeatures))\n";
   3252   OS << "        MissingFeatures = NewMissingFeatures;\n";
   3253   OS << "      continue;\n";
   3254   OS << "    }\n";
   3255   OS << "\n";
   3256   OS << "    Inst.clear();\n\n";
   3257   OS << "    if (matchingInlineAsm) {\n";
   3258   OS << "      Inst.setOpcode(it->Opcode);\n";
   3259   OS << "      convertToMapAndConstraints(it->ConvertFn, Operands);\n";
   3260   OS << "      return Match_Success;\n";
   3261   OS << "    }\n\n";
   3262   OS << "    // We have selected a definite instruction, convert the parsed\n"
   3263      << "    // operands into the appropriate MCInst.\n";
   3264   if (HasOptionalOperands) {
   3265     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
   3266        << "                    OptionalOperandsMask);\n";
   3267   } else {
   3268     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
   3269   }
   3270   OS << "\n";
   3271 
   3272   // Verify the instruction with the target-specific match predicate function.
   3273   OS << "    // We have a potential match. Check the target predicate to\n"
   3274      << "    // handle any context sensitive constraints.\n"
   3275      << "    unsigned MatchResult;\n"
   3276      << "    if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
   3277      << " Match_Success) {\n"
   3278      << "      Inst.clear();\n"
   3279      << "      RetCode = MatchResult;\n"
   3280      << "      HadMatchOtherThanPredicate = true;\n"
   3281      << "      continue;\n"
   3282      << "    }\n\n";
   3283 
   3284   // Call the post-processing function, if used.
   3285   std::string InsnCleanupFn =
   3286     AsmParser->getValueAsString("AsmParserInstCleanup");
   3287   if (!InsnCleanupFn.empty())
   3288     OS << "    " << InsnCleanupFn << "(Inst);\n";
   3289 
   3290   if (HasDeprecation) {
   3291     OS << "    std::string Info;\n";
   3292     OS << "    if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
   3293     OS << "      SMLoc Loc = ((" << Target.getName()
   3294        << "Operand&)*Operands[0]).getStartLoc();\n";
   3295     OS << "      getParser().Warning(Loc, Info, None);\n";
   3296     OS << "    }\n";
   3297   }
   3298 
   3299   OS << "    return Match_Success;\n";
   3300   OS << "  }\n\n";
   3301 
   3302   OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
   3303   OS << "  if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
   3304   OS << "    return RetCode;\n\n";
   3305   OS << "  // Missing feature matches return which features were missing\n";
   3306   OS << "  ErrorInfo = MissingFeatures;\n";
   3307   OS << "  return Match_MissingFeature;\n";
   3308   OS << "}\n\n";
   3309 
   3310   if (!Info.OperandMatchInfo.empty())
   3311     emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
   3312                              MaxMnemonicIndex, HasMnemonicFirst);
   3313 
   3314   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
   3315 }
   3316 
   3317 namespace llvm {
   3318 
   3319 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
   3320   emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
   3321   AsmMatcherEmitter(RK).run(OS);
   3322 }
   3323 
   3324 } // end namespace llvm
   3325