xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/AsmMatcherEmitter.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend emits a target specifier matcher for converting parsed
10 // assembly operands in the MCInst structures. It also emits a matcher for
11 // custom operand parsing.
12 //
13 // Converting assembly operands into MCInst structures
14 // ---------------------------------------------------
15 //
16 // The input to the target specific matcher is a list of literal tokens and
17 // operands. The target specific parser should generally eliminate any syntax
18 // which is not relevant for matching; for example, comma tokens should have
19 // already been consumed and eliminated by the parser. Most instructions will
20 // end up with a single literal token (the instruction name) and some number of
21 // operands.
22 //
23 // Some example inputs, for X86:
24 //   'addl' (immediate ...) (register ...)
25 //   'add' (immediate ...) (memory ...)
26 //   'call' '*' %epc
27 //
28 // The assembly matcher is responsible for converting this input into a precise
29 // machine instruction (i.e., an instruction with a well defined encoding). This
30 // mapping has several properties which complicate matching:
31 //
32 //  - It may be ambiguous; many architectures can legally encode particular
33 //    variants of an instruction in different ways (for example, using a smaller
34 //    encoding for small immediates). Such ambiguities should never be
35 //    arbitrarily resolved by the assembler, the assembler is always responsible
36 //    for choosing the "best" available instruction.
37 //
38 //  - It may depend on the subtarget or the assembler context. Instructions
39 //    which are invalid for the current mode, but otherwise unambiguous (e.g.,
40 //    an SSE instruction in a file being assembled for i486) should be accepted
41 //    and rejected by the assembler front end. However, if the proper encoding
42 //    for an instruction is dependent on the assembler context then the matcher
43 //    is responsible for selecting the correct machine instruction for the
44 //    current mode.
45 //
46 // The core matching algorithm attempts to exploit the regularity in most
47 // instruction sets to quickly determine the set of possibly matching
48 // instructions, and the simplify the generated code. Additionally, this helps
49 // to ensure that the ambiguities are intentionally resolved by the user.
50 //
51 // The matching is divided into two distinct phases:
52 //
53 //   1. Classification: Each operand is mapped to the unique set which (a)
54 //      contains it, and (b) is the largest such subset for which a single
55 //      instruction could match all members.
56 //
57 //      For register classes, we can generate these subgroups automatically. For
58 //      arbitrary operands, we expect the user to define the classes and their
59 //      relations to one another (for example, 8-bit signed immediates as a
60 //      subset of 32-bit immediates).
61 //
62 //      By partitioning the operands in this way, we guarantee that for any
63 //      tuple of classes, any single instruction must match either all or none
64 //      of the sets of operands which could classify to that tuple.
65 //
66 //      In addition, the subset relation amongst classes induces a partial order
67 //      on such tuples, which we use to resolve ambiguities.
68 //
69 //   2. The input can now be treated as a tuple of classes (static tokens are
70 //      simple singleton sets). Each such tuple should generally map to a single
71 //      instruction (we currently ignore cases where this isn't true, whee!!!),
72 //      which we can emit a simple matcher for.
73 //
74 // Custom Operand Parsing
75 // ----------------------
76 //
77 //  Some targets need a custom way to parse operands, some specific instructions
78 //  can contain arguments that can represent processor flags and other kinds of
79 //  identifiers that need to be mapped to specific values in the final encoded
80 //  instructions. The target specific custom operand parsing works in the
81 //  following way:
82 //
83 //   1. A operand match table is built, each entry contains a mnemonic, an
84 //      operand class, a mask for all operand positions for that same
85 //      class/mnemonic and target features to be checked while trying to match.
86 //
87 //   2. The operand matcher will try every possible entry with the same
88 //      mnemonic and will check if the target feature for this mnemonic also
89 //      matches. After that, if the operand to be matched has its index
90 //      present in the mask, a successful match occurs. Otherwise, fallback
91 //      to the regular operand parsing.
92 //
93 //   3. For a match success, each operand class that has a 'ParserMethod'
94 //      becomes part of a switch from where the custom method is called.
95 //
96 //===----------------------------------------------------------------------===//
97 
98 #include "CodeGenTarget.h"
99 #include "SubtargetFeatureInfo.h"
100 #include "Types.h"
101 #include "llvm/ADT/CachedHashString.h"
102 #include "llvm/ADT/PointerUnion.h"
103 #include "llvm/ADT/STLExtras.h"
104 #include "llvm/ADT/SmallPtrSet.h"
105 #include "llvm/ADT/SmallVector.h"
106 #include "llvm/ADT/StringExtras.h"
107 #include "llvm/Config/llvm-config.h"
108 #include "llvm/Support/CommandLine.h"
109 #include "llvm/Support/Debug.h"
110 #include "llvm/Support/ErrorHandling.h"
111 #include "llvm/TableGen/Error.h"
112 #include "llvm/TableGen/Record.h"
113 #include "llvm/TableGen/StringMatcher.h"
114 #include "llvm/TableGen/StringToOffsetTable.h"
115 #include "llvm/TableGen/TableGenBackend.h"
116 #include <cassert>
117 #include <cctype>
118 #include <forward_list>
119 #include <map>
120 #include <set>
121 
122 using namespace llvm;
123 
124 #define DEBUG_TYPE "asm-matcher-emitter"
125 
126 cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
127 
128 static cl::opt<std::string>
129     MatchPrefix("match-prefix", cl::init(""),
130                 cl::desc("Only match instructions with the given prefix"),
131                 cl::cat(AsmMatcherEmitterCat));
132 
133 namespace {
134 class AsmMatcherInfo;
135 
136 // Register sets are used as keys in some second-order sets TableGen creates
137 // when generating its data structures. This means that the order of two
138 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
139 // can even affect compiler output (at least seen in diagnostics produced when
140 // all matches fail). So we use a type that sorts them consistently.
141 typedef std::set<Record*, LessRecordByID> RegisterSet;
142 
143 class AsmMatcherEmitter {
144   RecordKeeper &Records;
145 public:
146   AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
147 
148   void run(raw_ostream &o);
149 };
150 
151 /// ClassInfo - Helper class for storing the information about a particular
152 /// class of operands which can be matched.
153 struct ClassInfo {
154   enum ClassInfoKind {
155     /// Invalid kind, for use as a sentinel value.
156     Invalid = 0,
157 
158     /// The class for a particular token.
159     Token,
160 
161     /// The (first) register class, subsequent register classes are
162     /// RegisterClass0+1, and so on.
163     RegisterClass0,
164 
165     /// The (first) user defined class, subsequent user defined classes are
166     /// UserClass0+1, and so on.
167     UserClass0 = 1<<16
168   };
169 
170   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
171   /// N) for the Nth user defined class.
172   unsigned Kind;
173 
174   /// SuperClasses - The super classes of this class. Note that for simplicities
175   /// sake user operands only record their immediate super class, while register
176   /// operands include all superclasses.
177   std::vector<ClassInfo*> SuperClasses;
178 
179   /// Name - The full class name, suitable for use in an enum.
180   std::string Name;
181 
182   /// ClassName - The unadorned generic name for this class (e.g., Token).
183   std::string ClassName;
184 
185   /// ValueName - The name of the value this class represents; for a token this
186   /// is the literal token string, for an operand it is the TableGen class (or
187   /// empty if this is a derived class).
188   std::string ValueName;
189 
190   /// PredicateMethod - The name of the operand method to test whether the
191   /// operand matches this class; this is not valid for Token or register kinds.
192   std::string PredicateMethod;
193 
194   /// RenderMethod - The name of the operand method to add this operand to an
195   /// MCInst; this is not valid for Token or register kinds.
196   std::string RenderMethod;
197 
198   /// ParserMethod - The name of the operand method to do a target specific
199   /// parsing on the operand.
200   std::string ParserMethod;
201 
202   /// For register classes: the records for all the registers in this class.
203   RegisterSet Registers;
204 
205   /// For custom match classes: the diagnostic kind for when the predicate fails.
206   std::string DiagnosticType;
207 
208   /// For custom match classes: the diagnostic string for when the predicate fails.
209   std::string DiagnosticString;
210 
211   /// Is this operand optional and not always required.
212   bool IsOptional;
213 
214   /// DefaultMethod - The name of the method that returns the default operand
215   /// for optional operand
216   std::string DefaultMethod;
217 
218 public:
219   /// isRegisterClass() - Check if this is a register class.
220   bool isRegisterClass() const {
221     return Kind >= RegisterClass0 && Kind < UserClass0;
222   }
223 
224   /// isUserClass() - Check if this is a user defined class.
225   bool isUserClass() const {
226     return Kind >= UserClass0;
227   }
228 
229   /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
230   /// are related if they are in the same class hierarchy.
231   bool isRelatedTo(const ClassInfo &RHS) const {
232     // Tokens are only related to tokens.
233     if (Kind == Token || RHS.Kind == Token)
234       return Kind == Token && RHS.Kind == Token;
235 
236     // Registers classes are only related to registers classes, and only if
237     // their intersection is non-empty.
238     if (isRegisterClass() || RHS.isRegisterClass()) {
239       if (!isRegisterClass() || !RHS.isRegisterClass())
240         return false;
241 
242       RegisterSet Tmp;
243       std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
244       std::set_intersection(Registers.begin(), Registers.end(),
245                             RHS.Registers.begin(), RHS.Registers.end(),
246                             II, LessRecordByID());
247 
248       return !Tmp.empty();
249     }
250 
251     // Otherwise we have two users operands; they are related if they are in the
252     // same class hierarchy.
253     //
254     // FIXME: This is an oversimplification, they should only be related if they
255     // intersect, however we don't have that information.
256     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
257     const ClassInfo *Root = this;
258     while (!Root->SuperClasses.empty())
259       Root = Root->SuperClasses.front();
260 
261     const ClassInfo *RHSRoot = &RHS;
262     while (!RHSRoot->SuperClasses.empty())
263       RHSRoot = RHSRoot->SuperClasses.front();
264 
265     return Root == RHSRoot;
266   }
267 
268   /// isSubsetOf - Test whether this class is a subset of \p RHS.
269   bool isSubsetOf(const ClassInfo &RHS) const {
270     // This is a subset of RHS if it is the same class...
271     if (this == &RHS)
272       return true;
273 
274     // ... or if any of its super classes are a subset of RHS.
275     SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
276                                                 SuperClasses.end());
277     SmallPtrSet<const ClassInfo *, 16> Visited;
278     while (!Worklist.empty()) {
279       auto *CI = Worklist.pop_back_val();
280       if (CI == &RHS)
281         return true;
282       for (auto *Super : CI->SuperClasses)
283         if (Visited.insert(Super).second)
284           Worklist.push_back(Super);
285     }
286 
287     return false;
288   }
289 
290   int getTreeDepth() const {
291     int Depth = 0;
292     const ClassInfo *Root = this;
293     while (!Root->SuperClasses.empty()) {
294       Depth++;
295       Root = Root->SuperClasses.front();
296     }
297     return Depth;
298   }
299 
300   const ClassInfo *findRoot() const {
301     const ClassInfo *Root = this;
302     while (!Root->SuperClasses.empty())
303       Root = Root->SuperClasses.front();
304     return Root;
305   }
306 
307   /// Compare two classes. This does not produce a total ordering, but does
308   /// guarantee that subclasses are sorted before their parents, and that the
309   /// ordering is transitive.
310   bool operator<(const ClassInfo &RHS) const {
311     if (this == &RHS)
312       return false;
313 
314     // First, enforce the ordering between the three different types of class.
315     // Tokens sort before registers, which sort before user classes.
316     if (Kind == Token) {
317       if (RHS.Kind != Token)
318         return true;
319       assert(RHS.Kind == Token);
320     } else if (isRegisterClass()) {
321       if (RHS.Kind == Token)
322         return false;
323       else if (RHS.isUserClass())
324         return true;
325       assert(RHS.isRegisterClass());
326     } else if (isUserClass()) {
327       if (!RHS.isUserClass())
328         return false;
329       assert(RHS.isUserClass());
330     } else {
331       llvm_unreachable("Unknown ClassInfoKind");
332     }
333 
334     if (Kind == Token || isUserClass()) {
335       // Related tokens and user classes get sorted by depth in the inheritence
336       // tree (so that subclasses are before their parents).
337       if (isRelatedTo(RHS)) {
338         if (getTreeDepth() > RHS.getTreeDepth())
339           return true;
340         if (getTreeDepth() < RHS.getTreeDepth())
341           return false;
342       } else {
343         // Unrelated tokens and user classes are ordered by the name of their
344         // root nodes, so that there is a consistent ordering between
345         // unconnected trees.
346         return findRoot()->ValueName < RHS.findRoot()->ValueName;
347       }
348     } else if (isRegisterClass()) {
349       // For register sets, sort by number of registers. This guarantees that
350       // a set will always sort before all of it's strict supersets.
351       if (Registers.size() != RHS.Registers.size())
352         return Registers.size() < RHS.Registers.size();
353     } else {
354       llvm_unreachable("Unknown ClassInfoKind");
355     }
356 
357     // FIXME: We should be able to just return false here, as we only need a
358     // partial order (we use stable sorts, so this is deterministic) and the
359     // name of a class shouldn't be significant. However, some of the backends
360     // accidentally rely on this behaviour, so it will have to stay like this
361     // until they are fixed.
362     return ValueName < RHS.ValueName;
363   }
364 };
365 
366 class AsmVariantInfo {
367 public:
368   StringRef RegisterPrefix;
369   StringRef TokenizingCharacters;
370   StringRef SeparatorCharacters;
371   StringRef BreakCharacters;
372   StringRef Name;
373   int AsmVariantNo;
374 };
375 
376 /// MatchableInfo - Helper class for storing the necessary information for an
377 /// instruction or alias which is capable of being matched.
378 struct MatchableInfo {
379   struct AsmOperand {
380     /// Token - This is the token that the operand came from.
381     StringRef Token;
382 
383     /// The unique class instance this operand should match.
384     ClassInfo *Class;
385 
386     /// The operand name this is, if anything.
387     StringRef SrcOpName;
388 
389     /// The operand name this is, before renaming for tied operands.
390     StringRef OrigSrcOpName;
391 
392     /// The suboperand index within SrcOpName, or -1 for the entire operand.
393     int SubOpIdx;
394 
395     /// Whether the token is "isolated", i.e., it is preceded and followed
396     /// by separators.
397     bool IsIsolatedToken;
398 
399     /// Register record if this token is singleton register.
400     Record *SingletonReg;
401 
402     explicit AsmOperand(bool IsIsolatedToken, StringRef T)
403         : Token(T), Class(nullptr), SubOpIdx(-1),
404           IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
405   };
406 
407   /// ResOperand - This represents a single operand in the result instruction
408   /// generated by the match.  In cases (like addressing modes) where a single
409   /// assembler operand expands to multiple MCOperands, this represents the
410   /// single assembler operand, not the MCOperand.
411   struct ResOperand {
412     enum {
413       /// RenderAsmOperand - This represents an operand result that is
414       /// generated by calling the render method on the assembly operand.  The
415       /// corresponding AsmOperand is specified by AsmOperandNum.
416       RenderAsmOperand,
417 
418       /// TiedOperand - This represents a result operand that is a duplicate of
419       /// a previous result operand.
420       TiedOperand,
421 
422       /// ImmOperand - This represents an immediate value that is dumped into
423       /// the operand.
424       ImmOperand,
425 
426       /// RegOperand - This represents a fixed register that is dumped in.
427       RegOperand
428     } Kind;
429 
430     /// Tuple containing the index of the (earlier) result operand that should
431     /// be copied from, as well as the indices of the corresponding (parsed)
432     /// operands in the asm string.
433     struct TiedOperandsTuple {
434       unsigned ResOpnd;
435       unsigned SrcOpnd1Idx;
436       unsigned SrcOpnd2Idx;
437     };
438 
439     union {
440       /// This is the operand # in the AsmOperands list that this should be
441       /// copied from.
442       unsigned AsmOperandNum;
443 
444       /// Description of tied operands.
445       TiedOperandsTuple TiedOperands;
446 
447       /// ImmVal - This is the immediate value added to the instruction.
448       int64_t ImmVal;
449 
450       /// Register - This is the register record.
451       Record *Register;
452     };
453 
454     /// MINumOperands - The number of MCInst operands populated by this
455     /// operand.
456     unsigned MINumOperands;
457 
458     static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
459       ResOperand X;
460       X.Kind = RenderAsmOperand;
461       X.AsmOperandNum = AsmOpNum;
462       X.MINumOperands = NumOperands;
463       return X;
464     }
465 
466     static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
467                                 unsigned SrcOperand2) {
468       ResOperand X;
469       X.Kind = TiedOperand;
470       X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
471       X.MINumOperands = 1;
472       return X;
473     }
474 
475     static ResOperand getImmOp(int64_t Val) {
476       ResOperand X;
477       X.Kind = ImmOperand;
478       X.ImmVal = Val;
479       X.MINumOperands = 1;
480       return X;
481     }
482 
483     static ResOperand getRegOp(Record *Reg) {
484       ResOperand X;
485       X.Kind = RegOperand;
486       X.Register = Reg;
487       X.MINumOperands = 1;
488       return X;
489     }
490   };
491 
492   /// AsmVariantID - Target's assembly syntax variant no.
493   int AsmVariantID;
494 
495   /// AsmString - The assembly string for this instruction (with variants
496   /// removed), e.g. "movsx $src, $dst".
497   std::string AsmString;
498 
499   /// TheDef - This is the definition of the instruction or InstAlias that this
500   /// matchable came from.
501   Record *const TheDef;
502 
503   /// DefRec - This is the definition that it came from.
504   PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
505 
506   const CodeGenInstruction *getResultInst() const {
507     if (DefRec.is<const CodeGenInstruction*>())
508       return DefRec.get<const CodeGenInstruction*>();
509     return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
510   }
511 
512   /// ResOperands - This is the operand list that should be built for the result
513   /// MCInst.
514   SmallVector<ResOperand, 8> ResOperands;
515 
516   /// Mnemonic - This is the first token of the matched instruction, its
517   /// mnemonic.
518   StringRef Mnemonic;
519 
520   /// AsmOperands - The textual operands that this instruction matches,
521   /// annotated with a class and where in the OperandList they were defined.
522   /// This directly corresponds to the tokenized AsmString after the mnemonic is
523   /// removed.
524   SmallVector<AsmOperand, 8> AsmOperands;
525 
526   /// Predicates - The required subtarget features to match this instruction.
527   SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
528 
529   /// ConversionFnKind - The enum value which is passed to the generated
530   /// convertToMCInst to convert parsed operands into an MCInst for this
531   /// function.
532   std::string ConversionFnKind;
533 
534   /// If this instruction is deprecated in some form.
535   bool HasDeprecation;
536 
537   /// If this is an alias, this is use to determine whether or not to using
538   /// the conversion function defined by the instruction's AsmMatchConverter
539   /// or to use the function generated by the alias.
540   bool UseInstAsmMatchConverter;
541 
542   MatchableInfo(const CodeGenInstruction &CGI)
543     : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
544       UseInstAsmMatchConverter(true) {
545   }
546 
547   MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
548     : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
549       DefRec(Alias.release()),
550       UseInstAsmMatchConverter(
551         TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
552   }
553 
554   // Could remove this and the dtor if PointerUnion supported unique_ptr
555   // elements with a dynamic failure/assertion (like the one below) in the case
556   // where it was copied while being in an owning state.
557   MatchableInfo(const MatchableInfo &RHS)
558       : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
559         TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
560         Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
561         RequiredFeatures(RHS.RequiredFeatures),
562         ConversionFnKind(RHS.ConversionFnKind),
563         HasDeprecation(RHS.HasDeprecation),
564         UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
565     assert(!DefRec.is<const CodeGenInstAlias *>());
566   }
567 
568   ~MatchableInfo() {
569     delete DefRec.dyn_cast<const CodeGenInstAlias*>();
570   }
571 
572   // Two-operand aliases clone from the main matchable, but mark the second
573   // operand as a tied operand of the first for purposes of the assembler.
574   void formTwoOperandAlias(StringRef Constraint);
575 
576   void initialize(const AsmMatcherInfo &Info,
577                   SmallPtrSetImpl<Record*> &SingletonRegisters,
578                   AsmVariantInfo const &Variant,
579                   bool HasMnemonicFirst);
580 
581   /// validate - Return true if this matchable is a valid thing to match against
582   /// and perform a bunch of validity checking.
583   bool validate(StringRef CommentDelimiter, bool IsAlias) const;
584 
585   /// findAsmOperand - Find the AsmOperand with the specified name and
586   /// suboperand index.
587   int findAsmOperand(StringRef N, int SubOpIdx) const {
588     auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
589       return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
590     });
591     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
592   }
593 
594   /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
595   /// This does not check the suboperand index.
596   int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
597     auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
598                      [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
599     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
600   }
601 
602   int findAsmOperandOriginallyNamed(StringRef N) const {
603     auto I =
604         find_if(AsmOperands,
605                 [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
606     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
607   }
608 
609   void buildInstructionResultOperands();
610   void buildAliasResultOperands(bool AliasConstraintsAreChecked);
611 
612   /// operator< - Compare two matchables.
613   bool operator<(const MatchableInfo &RHS) const {
614     // The primary comparator is the instruction mnemonic.
615     if (int Cmp = Mnemonic.compare_insensitive(RHS.Mnemonic))
616       return Cmp == -1;
617 
618     if (AsmOperands.size() != RHS.AsmOperands.size())
619       return AsmOperands.size() < RHS.AsmOperands.size();
620 
621     // Compare lexicographically by operand. The matcher validates that other
622     // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
623     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
624       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
625         return true;
626       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
627         return false;
628     }
629 
630     // Give matches that require more features higher precedence. This is useful
631     // because we cannot define AssemblerPredicates with the negation of
632     // processor features. For example, ARM v6 "nop" may be either a HINT or
633     // MOV. With v6, we want to match HINT. The assembler has no way to
634     // predicate MOV under "NoV6", but HINT will always match first because it
635     // requires V6 while MOV does not.
636     if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
637       return RequiredFeatures.size() > RHS.RequiredFeatures.size();
638 
639     // For X86 AVX/AVX512 instructions, we prefer vex encoding because the
640     // vex encoding size is smaller. Since X86InstrSSE.td is included ahead
641     // of X86InstrAVX512.td, the AVX instruction ID is less than AVX512 ID.
642     // We use the ID to sort AVX instruction before AVX512 instruction in
643     // matching table.
644     if (TheDef->isSubClassOf("Instruction") &&
645         TheDef->getValueAsBit("HasPositionOrder"))
646       return TheDef->getID() < RHS.TheDef->getID();
647 
648     return false;
649   }
650 
651   /// couldMatchAmbiguouslyWith - Check whether this matchable could
652   /// ambiguously match the same set of operands as \p RHS (without being a
653   /// strictly superior match).
654   bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
655     // The primary comparator is the instruction mnemonic.
656     if (Mnemonic != RHS.Mnemonic)
657       return false;
658 
659     // Different variants can't conflict.
660     if (AsmVariantID != RHS.AsmVariantID)
661       return false;
662 
663     // The number of operands is unambiguous.
664     if (AsmOperands.size() != RHS.AsmOperands.size())
665       return false;
666 
667     // Otherwise, make sure the ordering of the two instructions is unambiguous
668     // by checking that either (a) a token or operand kind discriminates them,
669     // or (b) the ordering among equivalent kinds is consistent.
670 
671     // Tokens and operand kinds are unambiguous (assuming a correct target
672     // specific parser).
673     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
674       if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
675           AsmOperands[i].Class->Kind == ClassInfo::Token)
676         if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
677             *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
678           return false;
679 
680     // Otherwise, this operand could commute if all operands are equivalent, or
681     // there is a pair of operands that compare less than and a pair that
682     // compare greater than.
683     bool HasLT = false, HasGT = false;
684     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
685       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
686         HasLT = true;
687       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
688         HasGT = true;
689     }
690 
691     return HasLT == HasGT;
692   }
693 
694   void dump() const;
695 
696 private:
697   void tokenizeAsmString(AsmMatcherInfo const &Info,
698                          AsmVariantInfo const &Variant);
699   void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
700 };
701 
702 struct OperandMatchEntry {
703   unsigned OperandMask;
704   const MatchableInfo* MI;
705   ClassInfo *CI;
706 
707   static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
708                                   unsigned opMask) {
709     OperandMatchEntry X;
710     X.OperandMask = opMask;
711     X.CI = ci;
712     X.MI = mi;
713     return X;
714   }
715 };
716 
717 class AsmMatcherInfo {
718 public:
719   /// Tracked Records
720   RecordKeeper &Records;
721 
722   /// The tablegen AsmParser record.
723   Record *AsmParser;
724 
725   /// Target - The target information.
726   CodeGenTarget &Target;
727 
728   /// The classes which are needed for matching.
729   std::forward_list<ClassInfo> Classes;
730 
731   /// The information on the matchables to match.
732   std::vector<std::unique_ptr<MatchableInfo>> Matchables;
733 
734   /// Info for custom matching operands by user defined methods.
735   std::vector<OperandMatchEntry> OperandMatchInfo;
736 
737   /// Map of Register records to their class information.
738   typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
739   RegisterClassesTy RegisterClasses;
740 
741   /// Map of Predicate records to their subtarget information.
742   std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
743 
744   /// Map of AsmOperandClass records to their class information.
745   std::map<Record*, ClassInfo*> AsmOperandClasses;
746 
747   /// Map of RegisterClass records to their class information.
748   std::map<Record*, ClassInfo*> RegisterClassClasses;
749 
750 private:
751   /// Map of token to class information which has already been constructed.
752   std::map<std::string, ClassInfo*> TokenClasses;
753 
754 private:
755   /// getTokenClass - Lookup or create the class for the given token.
756   ClassInfo *getTokenClass(StringRef Token);
757 
758   /// getOperandClass - Lookup or create the class for the given operand.
759   ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
760                              int SubOpIdx);
761   ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
762 
763   /// buildRegisterClasses - Build the ClassInfo* instances for register
764   /// classes.
765   void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
766 
767   /// buildOperandClasses - Build the ClassInfo* instances for user defined
768   /// operand classes.
769   void buildOperandClasses();
770 
771   void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
772                                         unsigned AsmOpIdx);
773   void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
774                                   MatchableInfo::AsmOperand &Op);
775 
776 public:
777   AsmMatcherInfo(Record *AsmParser,
778                  CodeGenTarget &Target,
779                  RecordKeeper &Records);
780 
781   /// Construct the various tables used during matching.
782   void buildInfo();
783 
784   /// buildOperandMatchInfo - Build the necessary information to handle user
785   /// defined operand parsing methods.
786   void buildOperandMatchInfo();
787 
788   /// getSubtargetFeature - Lookup or create the subtarget feature info for the
789   /// given operand.
790   const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
791     assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
792     const auto &I = SubtargetFeatures.find(Def);
793     return I == SubtargetFeatures.end() ? nullptr : &I->second;
794   }
795 
796   RecordKeeper &getRecords() const {
797     return Records;
798   }
799 
800   bool hasOptionalOperands() const {
801     return any_of(Classes,
802                   [](const ClassInfo &Class) { return Class.IsOptional; });
803   }
804 };
805 
806 } // end anonymous namespace
807 
808 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
809 LLVM_DUMP_METHOD void MatchableInfo::dump() const {
810   errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
811 
812   errs() << "  variant: " << AsmVariantID << "\n";
813 
814   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
815     const AsmOperand &Op = AsmOperands[i];
816     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
817     errs() << '\"' << Op.Token << "\"\n";
818   }
819 }
820 #endif
821 
822 static std::pair<StringRef, StringRef>
823 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
824   // Split via the '='.
825   std::pair<StringRef, StringRef> Ops = S.split('=');
826   if (Ops.second == "")
827     PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
828   // Trim whitespace and the leading '$' on the operand names.
829   size_t start = Ops.first.find_first_of('$');
830   if (start == std::string::npos)
831     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
832   Ops.first = Ops.first.slice(start + 1, std::string::npos);
833   size_t end = Ops.first.find_last_of(" \t");
834   Ops.first = Ops.first.slice(0, end);
835   // Now the second operand.
836   start = Ops.second.find_first_of('$');
837   if (start == std::string::npos)
838     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
839   Ops.second = Ops.second.slice(start + 1, std::string::npos);
840   end = Ops.second.find_last_of(" \t");
841   Ops.first = Ops.first.slice(0, end);
842   return Ops;
843 }
844 
845 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
846   // Figure out which operands are aliased and mark them as tied.
847   std::pair<StringRef, StringRef> Ops =
848     parseTwoOperandConstraint(Constraint, TheDef->getLoc());
849 
850   // Find the AsmOperands that refer to the operands we're aliasing.
851   int SrcAsmOperand = findAsmOperandNamed(Ops.first);
852   int DstAsmOperand = findAsmOperandNamed(Ops.second);
853   if (SrcAsmOperand == -1)
854     PrintFatalError(TheDef->getLoc(),
855                     "unknown source two-operand alias operand '" + Ops.first +
856                     "'.");
857   if (DstAsmOperand == -1)
858     PrintFatalError(TheDef->getLoc(),
859                     "unknown destination two-operand alias operand '" +
860                     Ops.second + "'.");
861 
862   // Find the ResOperand that refers to the operand we're aliasing away
863   // and update it to refer to the combined operand instead.
864   for (ResOperand &Op : ResOperands) {
865     if (Op.Kind == ResOperand::RenderAsmOperand &&
866         Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
867       Op.AsmOperandNum = DstAsmOperand;
868       break;
869     }
870   }
871   // Remove the AsmOperand for the alias operand.
872   AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
873   // Adjust the ResOperand references to any AsmOperands that followed
874   // the one we just deleted.
875   for (ResOperand &Op : ResOperands) {
876     switch(Op.Kind) {
877     default:
878       // Nothing to do for operands that don't reference AsmOperands.
879       break;
880     case ResOperand::RenderAsmOperand:
881       if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
882         --Op.AsmOperandNum;
883       break;
884     }
885   }
886 }
887 
888 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
889 /// if present, from specified token.
890 static void
891 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
892                                       const AsmMatcherInfo &Info,
893                                       StringRef RegisterPrefix) {
894   StringRef Tok = Op.Token;
895 
896   // If this token is not an isolated token, i.e., it isn't separated from
897   // other tokens (e.g. with whitespace), don't interpret it as a register name.
898   if (!Op.IsIsolatedToken)
899     return;
900 
901   if (RegisterPrefix.empty()) {
902     std::string LoweredTok = Tok.lower();
903     if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
904       Op.SingletonReg = Reg->TheDef;
905     return;
906   }
907 
908   if (!Tok.startswith(RegisterPrefix))
909     return;
910 
911   StringRef RegName = Tok.substr(RegisterPrefix.size());
912   if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
913     Op.SingletonReg = Reg->TheDef;
914 
915   // If there is no register prefix (i.e. "%" in "%eax"), then this may
916   // be some random non-register token, just ignore it.
917 }
918 
919 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
920                                SmallPtrSetImpl<Record*> &SingletonRegisters,
921                                AsmVariantInfo const &Variant,
922                                bool HasMnemonicFirst) {
923   AsmVariantID = Variant.AsmVariantNo;
924   AsmString =
925     CodeGenInstruction::FlattenAsmStringVariants(AsmString,
926                                                  Variant.AsmVariantNo);
927 
928   tokenizeAsmString(Info, Variant);
929 
930   // The first token of the instruction is the mnemonic, which must be a
931   // simple string, not a $foo variable or a singleton register.
932   if (AsmOperands.empty())
933     PrintFatalError(TheDef->getLoc(),
934                   "Instruction '" + TheDef->getName() + "' has no tokens");
935 
936   assert(!AsmOperands[0].Token.empty());
937   if (HasMnemonicFirst) {
938     Mnemonic = AsmOperands[0].Token;
939     if (Mnemonic[0] == '$')
940       PrintFatalError(TheDef->getLoc(),
941                       "Invalid instruction mnemonic '" + Mnemonic + "'!");
942 
943     // Remove the first operand, it is tracked in the mnemonic field.
944     AsmOperands.erase(AsmOperands.begin());
945   } else if (AsmOperands[0].Token[0] != '$')
946     Mnemonic = AsmOperands[0].Token;
947 
948   // Compute the require features.
949   for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
950     if (const SubtargetFeatureInfo *Feature =
951             Info.getSubtargetFeature(Predicate))
952       RequiredFeatures.push_back(Feature);
953 
954   // Collect singleton registers, if used.
955   for (MatchableInfo::AsmOperand &Op : AsmOperands) {
956     extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
957     if (Record *Reg = Op.SingletonReg)
958       SingletonRegisters.insert(Reg);
959   }
960 
961   const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
962   if (!DepMask)
963     DepMask = TheDef->getValue("ComplexDeprecationPredicate");
964 
965   HasDeprecation =
966       DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
967 }
968 
969 /// Append an AsmOperand for the given substring of AsmString.
970 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
971   AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
972 }
973 
974 /// tokenizeAsmString - Tokenize a simplified assembly string.
975 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
976                                       AsmVariantInfo const &Variant) {
977   StringRef String = AsmString;
978   size_t Prev = 0;
979   bool InTok = false;
980   bool IsIsolatedToken = true;
981   for (size_t i = 0, e = String.size(); i != e; ++i) {
982     char Char = String[i];
983     if (Variant.BreakCharacters.find(Char) != std::string::npos) {
984       if (InTok) {
985         addAsmOperand(String.slice(Prev, i), false);
986         Prev = i;
987         IsIsolatedToken = false;
988       }
989       InTok = true;
990       continue;
991     }
992     if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
993       if (InTok) {
994         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
995         InTok = false;
996         IsIsolatedToken = false;
997       }
998       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
999       Prev = i + 1;
1000       IsIsolatedToken = true;
1001       continue;
1002     }
1003     if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
1004       if (InTok) {
1005         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1006         InTok = false;
1007       }
1008       Prev = i + 1;
1009       IsIsolatedToken = true;
1010       continue;
1011     }
1012 
1013     switch (Char) {
1014     case '\\':
1015       if (InTok) {
1016         addAsmOperand(String.slice(Prev, i), false);
1017         InTok = false;
1018         IsIsolatedToken = false;
1019       }
1020       ++i;
1021       assert(i != String.size() && "Invalid quoted character");
1022       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1023       Prev = i + 1;
1024       IsIsolatedToken = false;
1025       break;
1026 
1027     case '$': {
1028       if (InTok) {
1029         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1030         InTok = false;
1031         IsIsolatedToken = false;
1032       }
1033 
1034       // If this isn't "${", start new identifier looking like "$xxx"
1035       if (i + 1 == String.size() || String[i + 1] != '{') {
1036         Prev = i;
1037         break;
1038       }
1039 
1040       size_t EndPos = String.find('}', i);
1041       assert(EndPos != StringRef::npos &&
1042              "Missing brace in operand reference!");
1043       addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
1044       Prev = EndPos + 1;
1045       i = EndPos;
1046       IsIsolatedToken = false;
1047       break;
1048     }
1049 
1050     default:
1051       InTok = true;
1052       break;
1053     }
1054   }
1055   if (InTok && Prev != String.size())
1056     addAsmOperand(String.substr(Prev), IsIsolatedToken);
1057 }
1058 
1059 bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
1060   // Reject matchables with no .s string.
1061   if (AsmString.empty())
1062     PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
1063 
1064   // Reject any matchables with a newline in them, they should be marked
1065   // isCodeGenOnly if they are pseudo instructions.
1066   if (AsmString.find('\n') != std::string::npos)
1067     PrintFatalError(TheDef->getLoc(),
1068                   "multiline instruction is not valid for the asmparser, "
1069                   "mark it isCodeGenOnly");
1070 
1071   // Remove comments from the asm string.  We know that the asmstring only
1072   // has one line.
1073   if (!CommentDelimiter.empty() &&
1074       StringRef(AsmString).contains(CommentDelimiter))
1075     PrintFatalError(TheDef->getLoc(),
1076                   "asmstring for instruction has comment character in it, "
1077                   "mark it isCodeGenOnly");
1078 
1079   // Reject matchables with operand modifiers, these aren't something we can
1080   // handle, the target should be refactored to use operands instead of
1081   // modifiers.
1082   //
1083   // Also, check for instructions which reference the operand multiple times,
1084   // if they don't define a custom AsmMatcher: this implies a constraint that
1085   // the built-in matching code would not honor.
1086   std::set<std::string> OperandNames;
1087   for (const AsmOperand &Op : AsmOperands) {
1088     StringRef Tok = Op.Token;
1089     if (Tok[0] == '$' && Tok.contains(':'))
1090       PrintFatalError(TheDef->getLoc(),
1091                       "matchable with operand modifier '" + Tok +
1092                       "' not supported by asm matcher.  Mark isCodeGenOnly!");
1093     // Verify that any operand is only mentioned once.
1094     // We reject aliases and ignore instructions for now.
1095     if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
1096         Tok[0] == '$' && !OperandNames.insert(std::string(Tok)).second) {
1097       LLVM_DEBUG({
1098         errs() << "warning: '" << TheDef->getName() << "': "
1099                << "ignoring instruction with tied operand '"
1100                << Tok << "'\n";
1101       });
1102       return false;
1103     }
1104   }
1105 
1106   return true;
1107 }
1108 
1109 static std::string getEnumNameForToken(StringRef Str) {
1110   std::string Res;
1111 
1112   for (char C : Str) {
1113     switch (C) {
1114     case '*': Res += "_STAR_"; break;
1115     case '%': Res += "_PCT_"; break;
1116     case ':': Res += "_COLON_"; break;
1117     case '!': Res += "_EXCLAIM_"; break;
1118     case '.': Res += "_DOT_"; break;
1119     case '<': Res += "_LT_"; break;
1120     case '>': Res += "_GT_"; break;
1121     case '-': Res += "_MINUS_"; break;
1122     case '#': Res += "_HASH_"; break;
1123     default:
1124       if (isAlnum(C))
1125         Res += C;
1126       else
1127         Res += "_" + utostr((unsigned)C) + "_";
1128     }
1129   }
1130 
1131   return Res;
1132 }
1133 
1134 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
1135   ClassInfo *&Entry = TokenClasses[std::string(Token)];
1136 
1137   if (!Entry) {
1138     Classes.emplace_front();
1139     Entry = &Classes.front();
1140     Entry->Kind = ClassInfo::Token;
1141     Entry->ClassName = "Token";
1142     Entry->Name = "MCK_" + getEnumNameForToken(Token);
1143     Entry->ValueName = std::string(Token);
1144     Entry->PredicateMethod = "<invalid>";
1145     Entry->RenderMethod = "<invalid>";
1146     Entry->ParserMethod = "";
1147     Entry->DiagnosticType = "";
1148     Entry->IsOptional = false;
1149     Entry->DefaultMethod = "<invalid>";
1150   }
1151 
1152   return Entry;
1153 }
1154 
1155 ClassInfo *
1156 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1157                                 int SubOpIdx) {
1158   Record *Rec = OI.Rec;
1159   if (SubOpIdx != -1)
1160     Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1161   return getOperandClass(Rec, SubOpIdx);
1162 }
1163 
1164 ClassInfo *
1165 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1166   if (Rec->isSubClassOf("RegisterOperand")) {
1167     // RegisterOperand may have an associated ParserMatchClass. If it does,
1168     // use it, else just fall back to the underlying register class.
1169     const RecordVal *R = Rec->getValue("ParserMatchClass");
1170     if (!R || !R->getValue())
1171       PrintFatalError(Rec->getLoc(),
1172                       "Record `" + Rec->getName() +
1173                           "' does not have a ParserMatchClass!\n");
1174 
1175     if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1176       Record *MatchClass = DI->getDef();
1177       if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1178         return CI;
1179     }
1180 
1181     // No custom match class. Just use the register class.
1182     Record *ClassRec = Rec->getValueAsDef("RegClass");
1183     if (!ClassRec)
1184       PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1185                     "' has no associated register class!\n");
1186     if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1187       return CI;
1188     PrintFatalError(Rec->getLoc(), "register class has no class info!");
1189   }
1190 
1191   if (Rec->isSubClassOf("RegisterClass")) {
1192     if (ClassInfo *CI = RegisterClassClasses[Rec])
1193       return CI;
1194     PrintFatalError(Rec->getLoc(), "register class has no class info!");
1195   }
1196 
1197   if (!Rec->isSubClassOf("Operand"))
1198     PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1199                   "' does not derive from class Operand!\n");
1200   Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1201   if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1202     return CI;
1203 
1204   PrintFatalError(Rec->getLoc(), "operand has no match class!");
1205 }
1206 
1207 struct LessRegisterSet {
1208   bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1209     // std::set<T> defines its own compariso "operator<", but it
1210     // performs a lexicographical comparison by T's innate comparison
1211     // for some reason. We don't want non-deterministic pointer
1212     // comparisons so use this instead.
1213     return std::lexicographical_compare(LHS.begin(), LHS.end(),
1214                                         RHS.begin(), RHS.end(),
1215                                         LessRecordByID());
1216   }
1217 };
1218 
1219 void AsmMatcherInfo::
1220 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
1221   const auto &Registers = Target.getRegBank().getRegisters();
1222   auto &RegClassList = Target.getRegBank().getRegClasses();
1223 
1224   typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1225 
1226   // The register sets used for matching.
1227   RegisterSetSet RegisterSets;
1228 
1229   // Gather the defined sets.
1230   for (const CodeGenRegisterClass &RC : RegClassList)
1231     RegisterSets.insert(
1232         RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
1233 
1234   // Add any required singleton sets.
1235   for (Record *Rec : SingletonRegisters) {
1236     RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1237   }
1238 
1239   // Introduce derived sets where necessary (when a register does not determine
1240   // a unique register set class), and build the mapping of registers to the set
1241   // they should classify to.
1242   std::map<Record*, RegisterSet> RegisterMap;
1243   for (const CodeGenRegister &CGR : Registers) {
1244     // Compute the intersection of all sets containing this register.
1245     RegisterSet ContainingSet;
1246 
1247     for (const RegisterSet &RS : RegisterSets) {
1248       if (!RS.count(CGR.TheDef))
1249         continue;
1250 
1251       if (ContainingSet.empty()) {
1252         ContainingSet = RS;
1253         continue;
1254       }
1255 
1256       RegisterSet Tmp;
1257       std::swap(Tmp, ContainingSet);
1258       std::insert_iterator<RegisterSet> II(ContainingSet,
1259                                            ContainingSet.begin());
1260       std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
1261                             LessRecordByID());
1262     }
1263 
1264     if (!ContainingSet.empty()) {
1265       RegisterSets.insert(ContainingSet);
1266       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1267     }
1268   }
1269 
1270   // Construct the register classes.
1271   std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1272   unsigned Index = 0;
1273   for (const RegisterSet &RS : RegisterSets) {
1274     Classes.emplace_front();
1275     ClassInfo *CI = &Classes.front();
1276     CI->Kind = ClassInfo::RegisterClass0 + Index;
1277     CI->ClassName = "Reg" + utostr(Index);
1278     CI->Name = "MCK_Reg" + utostr(Index);
1279     CI->ValueName = "";
1280     CI->PredicateMethod = ""; // unused
1281     CI->RenderMethod = "addRegOperands";
1282     CI->Registers = RS;
1283     // FIXME: diagnostic type.
1284     CI->DiagnosticType = "";
1285     CI->IsOptional = false;
1286     CI->DefaultMethod = ""; // unused
1287     RegisterSetClasses.insert(std::make_pair(RS, CI));
1288     ++Index;
1289   }
1290 
1291   // Find the superclasses; we could compute only the subgroup lattice edges,
1292   // but there isn't really a point.
1293   for (const RegisterSet &RS : RegisterSets) {
1294     ClassInfo *CI = RegisterSetClasses[RS];
1295     for (const RegisterSet &RS2 : RegisterSets)
1296       if (RS != RS2 &&
1297           std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
1298                         LessRecordByID()))
1299         CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
1300   }
1301 
1302   // Name the register classes which correspond to a user defined RegisterClass.
1303   for (const CodeGenRegisterClass &RC : RegClassList) {
1304     // Def will be NULL for non-user defined register classes.
1305     Record *Def = RC.getDef();
1306     if (!Def)
1307       continue;
1308     ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1309                                                    RC.getOrder().end())];
1310     if (CI->ValueName.empty()) {
1311       CI->ClassName = RC.getName();
1312       CI->Name = "MCK_" + RC.getName();
1313       CI->ValueName = RC.getName();
1314     } else
1315       CI->ValueName = CI->ValueName + "," + RC.getName();
1316 
1317     Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1318     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1319       CI->DiagnosticType = std::string(SI->getValue());
1320 
1321     Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1322     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1323       CI->DiagnosticString = std::string(SI->getValue());
1324 
1325     // If we have a diagnostic string but the diagnostic type is not specified
1326     // explicitly, create an anonymous diagnostic type.
1327     if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1328       CI->DiagnosticType = RC.getName();
1329 
1330     RegisterClassClasses.insert(std::make_pair(Def, CI));
1331   }
1332 
1333   // Populate the map for individual registers.
1334   for (auto &It : RegisterMap)
1335     RegisterClasses[It.first] = RegisterSetClasses[It.second];
1336 
1337   // Name the register classes which correspond to singleton registers.
1338   for (Record *Rec : SingletonRegisters) {
1339     ClassInfo *CI = RegisterClasses[Rec];
1340     assert(CI && "Missing singleton register class info!");
1341 
1342     if (CI->ValueName.empty()) {
1343       CI->ClassName = std::string(Rec->getName());
1344       CI->Name = "MCK_" + Rec->getName().str();
1345       CI->ValueName = std::string(Rec->getName());
1346     } else
1347       CI->ValueName = CI->ValueName + "," + Rec->getName().str();
1348   }
1349 }
1350 
1351 void AsmMatcherInfo::buildOperandClasses() {
1352   std::vector<Record*> AsmOperands =
1353     Records.getAllDerivedDefinitions("AsmOperandClass");
1354 
1355   // Pre-populate AsmOperandClasses map.
1356   for (Record *Rec : AsmOperands) {
1357     Classes.emplace_front();
1358     AsmOperandClasses[Rec] = &Classes.front();
1359   }
1360 
1361   unsigned Index = 0;
1362   for (Record *Rec : AsmOperands) {
1363     ClassInfo *CI = AsmOperandClasses[Rec];
1364     CI->Kind = ClassInfo::UserClass0 + Index;
1365 
1366     ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
1367     for (Init *I : Supers->getValues()) {
1368       DefInit *DI = dyn_cast<DefInit>(I);
1369       if (!DI) {
1370         PrintError(Rec->getLoc(), "Invalid super class reference!");
1371         continue;
1372       }
1373 
1374       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1375       if (!SC)
1376         PrintError(Rec->getLoc(), "Invalid super class reference!");
1377       else
1378         CI->SuperClasses.push_back(SC);
1379     }
1380     CI->ClassName = std::string(Rec->getValueAsString("Name"));
1381     CI->Name = "MCK_" + CI->ClassName;
1382     CI->ValueName = std::string(Rec->getName());
1383 
1384     // Get or construct the predicate method name.
1385     Init *PMName = Rec->getValueInit("PredicateMethod");
1386     if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1387       CI->PredicateMethod = std::string(SI->getValue());
1388     } else {
1389       assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1390       CI->PredicateMethod = "is" + CI->ClassName;
1391     }
1392 
1393     // Get or construct the render method name.
1394     Init *RMName = Rec->getValueInit("RenderMethod");
1395     if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1396       CI->RenderMethod = std::string(SI->getValue());
1397     } else {
1398       assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1399       CI->RenderMethod = "add" + CI->ClassName + "Operands";
1400     }
1401 
1402     // Get the parse method name or leave it as empty.
1403     Init *PRMName = Rec->getValueInit("ParserMethod");
1404     if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1405       CI->ParserMethod = std::string(SI->getValue());
1406 
1407     // Get the diagnostic type and string or leave them as empty.
1408     Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
1409     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1410       CI->DiagnosticType = std::string(SI->getValue());
1411     Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1412     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1413       CI->DiagnosticString = std::string(SI->getValue());
1414     // If we have a DiagnosticString, we need a DiagnosticType for use within
1415     // the matcher.
1416     if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1417       CI->DiagnosticType = CI->ClassName;
1418 
1419     Init *IsOptional = Rec->getValueInit("IsOptional");
1420     if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1421       CI->IsOptional = BI->getValue();
1422 
1423     // Get or construct the default method name.
1424     Init *DMName = Rec->getValueInit("DefaultMethod");
1425     if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1426       CI->DefaultMethod = std::string(SI->getValue());
1427     } else {
1428       assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1429       CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1430     }
1431 
1432     ++Index;
1433   }
1434 }
1435 
1436 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1437                                CodeGenTarget &target,
1438                                RecordKeeper &records)
1439   : Records(records), AsmParser(asmParser), Target(target) {
1440 }
1441 
1442 /// buildOperandMatchInfo - Build the necessary information to handle user
1443 /// defined operand parsing methods.
1444 void AsmMatcherInfo::buildOperandMatchInfo() {
1445 
1446   /// Map containing a mask with all operands indices that can be found for
1447   /// that class inside a instruction.
1448   typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
1449   OpClassMaskTy OpClassMask;
1450 
1451   for (const auto &MI : Matchables) {
1452     OpClassMask.clear();
1453 
1454     // Keep track of all operands of this instructions which belong to the
1455     // same class.
1456     for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1457       const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
1458       if (Op.Class->ParserMethod.empty())
1459         continue;
1460       unsigned &OperandMask = OpClassMask[Op.Class];
1461       OperandMask |= (1 << i);
1462     }
1463 
1464     // Generate operand match info for each mnemonic/operand class pair.
1465     for (const auto &OCM : OpClassMask) {
1466       unsigned OpMask = OCM.second;
1467       ClassInfo *CI = OCM.first;
1468       OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1469                                                            OpMask));
1470     }
1471   }
1472 }
1473 
1474 void AsmMatcherInfo::buildInfo() {
1475   // Build information about all of the AssemblerPredicates.
1476   const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1477       &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1478   SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1479                            SubtargetFeaturePairs.end());
1480 #ifndef NDEBUG
1481   for (const auto &Pair : SubtargetFeatures)
1482     LLVM_DEBUG(Pair.second.dump());
1483 #endif // NDEBUG
1484 
1485   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1486   bool ReportMultipleNearMisses =
1487       AsmParser->getValueAsBit("ReportMultipleNearMisses");
1488 
1489   // Parse the instructions; we need to do this first so that we can gather the
1490   // singleton register classes.
1491   SmallPtrSet<Record*, 16> SingletonRegisters;
1492   unsigned VariantCount = Target.getAsmParserVariantCount();
1493   for (unsigned VC = 0; VC != VariantCount; ++VC) {
1494     Record *AsmVariant = Target.getAsmParserVariant(VC);
1495     StringRef CommentDelimiter =
1496         AsmVariant->getValueAsString("CommentDelimiter");
1497     AsmVariantInfo Variant;
1498     Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1499     Variant.TokenizingCharacters =
1500         AsmVariant->getValueAsString("TokenizingCharacters");
1501     Variant.SeparatorCharacters =
1502         AsmVariant->getValueAsString("SeparatorCharacters");
1503     Variant.BreakCharacters =
1504         AsmVariant->getValueAsString("BreakCharacters");
1505     Variant.Name = AsmVariant->getValueAsString("Name");
1506     Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1507 
1508     for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
1509 
1510       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1511       // filter the set of instructions we consider.
1512       if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
1513         continue;
1514 
1515       // Ignore "codegen only" instructions.
1516       if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
1517         continue;
1518 
1519       // Ignore instructions for different instructions
1520       StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
1521       if (!V.empty() && V != Variant.Name)
1522         continue;
1523 
1524       auto II = std::make_unique<MatchableInfo>(*CGI);
1525 
1526       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1527 
1528       // Ignore instructions which shouldn't be matched and diagnose invalid
1529       // instruction definitions with an error.
1530       if (!II->validate(CommentDelimiter, false))
1531         continue;
1532 
1533       Matchables.push_back(std::move(II));
1534     }
1535 
1536     // Parse all of the InstAlias definitions and stick them in the list of
1537     // matchables.
1538     std::vector<Record*> AllInstAliases =
1539       Records.getAllDerivedDefinitions("InstAlias");
1540     for (Record *InstAlias : AllInstAliases) {
1541       auto Alias = std::make_unique<CodeGenInstAlias>(InstAlias, Target);
1542 
1543       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1544       // filter the set of instruction aliases we consider, based on the target
1545       // instruction.
1546       if (!StringRef(Alias->ResultInst->TheDef->getName())
1547             .startswith( MatchPrefix))
1548         continue;
1549 
1550       StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
1551       if (!V.empty() && V != Variant.Name)
1552         continue;
1553 
1554       auto II = std::make_unique<MatchableInfo>(std::move(Alias));
1555 
1556       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1557 
1558       // Validate the alias definitions.
1559       II->validate(CommentDelimiter, true);
1560 
1561       Matchables.push_back(std::move(II));
1562     }
1563   }
1564 
1565   // Build info for the register classes.
1566   buildRegisterClasses(SingletonRegisters);
1567 
1568   // Build info for the user defined assembly operand classes.
1569   buildOperandClasses();
1570 
1571   // Build the information about matchables, now that we have fully formed
1572   // classes.
1573   std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
1574   for (auto &II : Matchables) {
1575     // Parse the tokens after the mnemonic.
1576     // Note: buildInstructionOperandReference may insert new AsmOperands, so
1577     // don't precompute the loop bound.
1578     for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1579       MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1580       StringRef Token = Op.Token;
1581 
1582       // Check for singleton registers.
1583       if (Record *RegRecord = Op.SingletonReg) {
1584         Op.Class = RegisterClasses[RegRecord];
1585         assert(Op.Class && Op.Class->Registers.size() == 1 &&
1586                "Unexpected class for singleton register");
1587         continue;
1588       }
1589 
1590       // Check for simple tokens.
1591       if (Token[0] != '$') {
1592         Op.Class = getTokenClass(Token);
1593         continue;
1594       }
1595 
1596       if (Token.size() > 1 && isdigit(Token[1])) {
1597         Op.Class = getTokenClass(Token);
1598         continue;
1599       }
1600 
1601       // Otherwise this is an operand reference.
1602       StringRef OperandName;
1603       if (Token[1] == '{')
1604         OperandName = Token.substr(2, Token.size() - 3);
1605       else
1606         OperandName = Token.substr(1);
1607 
1608       if (II->DefRec.is<const CodeGenInstruction*>())
1609         buildInstructionOperandReference(II.get(), OperandName, i);
1610       else
1611         buildAliasOperandReference(II.get(), OperandName, Op);
1612     }
1613 
1614     if (II->DefRec.is<const CodeGenInstruction*>()) {
1615       II->buildInstructionResultOperands();
1616       // If the instruction has a two-operand alias, build up the
1617       // matchable here. We'll add them in bulk at the end to avoid
1618       // confusing this loop.
1619       StringRef Constraint =
1620           II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1621       if (Constraint != "") {
1622         // Start by making a copy of the original matchable.
1623         auto AliasII = std::make_unique<MatchableInfo>(*II);
1624 
1625         // Adjust it to be a two-operand alias.
1626         AliasII->formTwoOperandAlias(Constraint);
1627 
1628         // Add the alias to the matchables list.
1629         NewMatchables.push_back(std::move(AliasII));
1630       }
1631     } else
1632       // FIXME: The tied operands checking is not yet integrated with the
1633       // framework for reporting multiple near misses. To prevent invalid
1634       // formats from being matched with an alias if a tied-operands check
1635       // would otherwise have disallowed it, we just disallow such constructs
1636       // in TableGen completely.
1637       II->buildAliasResultOperands(!ReportMultipleNearMisses);
1638   }
1639   if (!NewMatchables.empty())
1640     Matchables.insert(Matchables.end(),
1641                       std::make_move_iterator(NewMatchables.begin()),
1642                       std::make_move_iterator(NewMatchables.end()));
1643 
1644   // Process token alias definitions and set up the associated superclass
1645   // information.
1646   std::vector<Record*> AllTokenAliases =
1647     Records.getAllDerivedDefinitions("TokenAlias");
1648   for (Record *Rec : AllTokenAliases) {
1649     ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1650     ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1651     if (FromClass == ToClass)
1652       PrintFatalError(Rec->getLoc(),
1653                     "error: Destination value identical to source value.");
1654     FromClass->SuperClasses.push_back(ToClass);
1655   }
1656 
1657   // Reorder classes so that classes precede super classes.
1658   Classes.sort();
1659 
1660 #ifdef EXPENSIVE_CHECKS
1661   // Verify that the table is sorted and operator < works transitively.
1662   for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1663     for (auto J = I; J != E; ++J) {
1664       assert(!(*J < *I));
1665       assert(I == J || !J->isSubsetOf(*I));
1666     }
1667   }
1668 #endif
1669 }
1670 
1671 /// buildInstructionOperandReference - The specified operand is a reference to a
1672 /// named operand such as $src.  Resolve the Class and OperandInfo pointers.
1673 void AsmMatcherInfo::
1674 buildInstructionOperandReference(MatchableInfo *II,
1675                                  StringRef OperandName,
1676                                  unsigned AsmOpIdx) {
1677   const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1678   const CGIOperandList &Operands = CGI.Operands;
1679   MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1680 
1681   // Map this token to an operand.
1682   unsigned Idx;
1683   if (!Operands.hasOperandNamed(OperandName, Idx))
1684     PrintFatalError(II->TheDef->getLoc(),
1685                     "error: unable to find operand: '" + OperandName + "'");
1686 
1687   // If the instruction operand has multiple suboperands, but the parser
1688   // match class for the asm operand is still the default "ImmAsmOperand",
1689   // then handle each suboperand separately.
1690   if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1691     Record *Rec = Operands[Idx].Rec;
1692     assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1693     Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1694     if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1695       // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1696       StringRef Token = Op->Token; // save this in case Op gets moved
1697       for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1698         MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
1699         NewAsmOp.SubOpIdx = SI;
1700         II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1701       }
1702       // Replace Op with first suboperand.
1703       Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1704       Op->SubOpIdx = 0;
1705     }
1706   }
1707 
1708   // Set up the operand class.
1709   Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1710   Op->OrigSrcOpName = OperandName;
1711 
1712   // If the named operand is tied, canonicalize it to the untied operand.
1713   // For example, something like:
1714   //   (outs GPR:$dst), (ins GPR:$src)
1715   // with an asmstring of
1716   //   "inc $src"
1717   // we want to canonicalize to:
1718   //   "inc $dst"
1719   // so that we know how to provide the $dst operand when filling in the result.
1720   int OITied = -1;
1721   if (Operands[Idx].MINumOperands == 1)
1722     OITied = Operands[Idx].getTiedRegister();
1723   if (OITied != -1) {
1724     // The tied operand index is an MIOperand index, find the operand that
1725     // contains it.
1726     std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1727     OperandName = Operands[Idx.first].Name;
1728     Op->SubOpIdx = Idx.second;
1729   }
1730 
1731   Op->SrcOpName = OperandName;
1732 }
1733 
1734 /// buildAliasOperandReference - When parsing an operand reference out of the
1735 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1736 /// operand reference is by looking it up in the result pattern definition.
1737 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1738                                                 StringRef OperandName,
1739                                                 MatchableInfo::AsmOperand &Op) {
1740   const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1741 
1742   // Set up the operand class.
1743   for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1744     if (CGA.ResultOperands[i].isRecord() &&
1745         CGA.ResultOperands[i].getName() == OperandName) {
1746       // It's safe to go with the first one we find, because CodeGenInstAlias
1747       // validates that all operands with the same name have the same record.
1748       Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1749       // Use the match class from the Alias definition, not the
1750       // destination instruction, as we may have an immediate that's
1751       // being munged by the match class.
1752       Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1753                                  Op.SubOpIdx);
1754       Op.SrcOpName = OperandName;
1755       Op.OrigSrcOpName = OperandName;
1756       return;
1757     }
1758 
1759   PrintFatalError(II->TheDef->getLoc(),
1760                   "error: unable to find operand: '" + OperandName + "'");
1761 }
1762 
1763 void MatchableInfo::buildInstructionResultOperands() {
1764   const CodeGenInstruction *ResultInst = getResultInst();
1765 
1766   // Loop over all operands of the result instruction, determining how to
1767   // populate them.
1768   for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
1769     // If this is a tied operand, just copy from the previously handled operand.
1770     int TiedOp = -1;
1771     if (OpInfo.MINumOperands == 1)
1772       TiedOp = OpInfo.getTiedRegister();
1773     if (TiedOp != -1) {
1774       int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1775       if (TiedSrcOperand != -1 &&
1776           ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1777         ResOperands.push_back(ResOperand::getTiedOp(
1778             TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1779       else
1780         ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
1781       continue;
1782     }
1783 
1784     int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1785     if (OpInfo.Name.empty() || SrcOperand == -1) {
1786       // This may happen for operands that are tied to a suboperand of a
1787       // complex operand.  Simply use a dummy value here; nobody should
1788       // use this operand slot.
1789       // FIXME: The long term goal is for the MCOperand list to not contain
1790       // tied operands at all.
1791       ResOperands.push_back(ResOperand::getImmOp(0));
1792       continue;
1793     }
1794 
1795     // Check if the one AsmOperand populates the entire operand.
1796     unsigned NumOperands = OpInfo.MINumOperands;
1797     if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1798       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1799       continue;
1800     }
1801 
1802     // Add a separate ResOperand for each suboperand.
1803     for (unsigned AI = 0; AI < NumOperands; ++AI) {
1804       assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1805              AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1806              "unexpected AsmOperands for suboperands");
1807       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1808     }
1809   }
1810 }
1811 
1812 void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
1813   const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1814   const CodeGenInstruction *ResultInst = getResultInst();
1815 
1816   // Map of:  $reg -> #lastref
1817   //   where $reg is the name of the operand in the asm string
1818   //   where #lastref is the last processed index where $reg was referenced in
1819   //   the asm string.
1820   SmallDenseMap<StringRef, int> OperandRefs;
1821 
1822   // Loop over all operands of the result instruction, determining how to
1823   // populate them.
1824   unsigned AliasOpNo = 0;
1825   unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1826   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1827     const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1828 
1829     // If this is a tied operand, just copy from the previously handled operand.
1830     int TiedOp = -1;
1831     if (OpInfo->MINumOperands == 1)
1832       TiedOp = OpInfo->getTiedRegister();
1833     if (TiedOp != -1) {
1834       unsigned SrcOp1 = 0;
1835       unsigned SrcOp2 = 0;
1836 
1837       // If an operand has been specified twice in the asm string,
1838       // add the two source operand's indices to the TiedOp so that
1839       // at runtime the 'tied' constraint is checked.
1840       if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1841         SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1842 
1843         // Find the next operand (similarly named operand) in the string.
1844         StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1845         auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1846         SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1847 
1848         // Not updating the record in OperandRefs will cause TableGen
1849         // to fail with an error at the end of this function.
1850         if (AliasConstraintsAreChecked)
1851           Insert.first->second = SrcOp2;
1852 
1853         // In case it only has one reference in the asm string,
1854         // it doesn't need to be checked for tied constraints.
1855         SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1856       }
1857 
1858       // If the alias operand is of a different operand class, we only want
1859       // to benefit from the tied-operands check and just match the operand
1860       // as a normal, but not copy the original (TiedOp) to the result
1861       // instruction. We do this by passing -1 as the tied operand to copy.
1862       if (ResultInst->Operands[i].Rec->getName() !=
1863           ResultInst->Operands[TiedOp].Rec->getName()) {
1864         SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1865         int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1866         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1867         SrcOp2 = findAsmOperand(Name, SubIdx);
1868         ResOperands.push_back(
1869             ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1870       } else {
1871         ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1872         continue;
1873       }
1874     }
1875 
1876     // Handle all the suboperands for this operand.
1877     const std::string &OpName = OpInfo->Name;
1878     for ( ; AliasOpNo <  LastOpNo &&
1879             CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1880       int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1881 
1882       // Find out what operand from the asmparser that this MCInst operand
1883       // comes from.
1884       switch (CGA.ResultOperands[AliasOpNo].Kind) {
1885       case CodeGenInstAlias::ResultOperand::K_Record: {
1886         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1887         int SrcOperand = findAsmOperand(Name, SubIdx);
1888         if (SrcOperand == -1)
1889           PrintFatalError(TheDef->getLoc(), "Instruction '" +
1890                         TheDef->getName() + "' has operand '" + OpName +
1891                         "' that doesn't appear in asm string!");
1892 
1893         // Add it to the operand references. If it is added a second time, the
1894         // record won't be updated and it will fail later on.
1895         OperandRefs.try_emplace(Name, SrcOperand);
1896 
1897         unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1898         ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1899                                                         NumOperands));
1900         break;
1901       }
1902       case CodeGenInstAlias::ResultOperand::K_Imm: {
1903         int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1904         ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1905         break;
1906       }
1907       case CodeGenInstAlias::ResultOperand::K_Reg: {
1908         Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1909         ResOperands.push_back(ResOperand::getRegOp(Reg));
1910         break;
1911       }
1912       }
1913     }
1914   }
1915 
1916   // Check that operands are not repeated more times than is supported.
1917   for (auto &T : OperandRefs) {
1918     if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1919       PrintFatalError(TheDef->getLoc(),
1920                       "Operand '" + T.first + "' can never be matched");
1921   }
1922 }
1923 
1924 static unsigned
1925 getConverterOperandID(const std::string &Name,
1926                       SmallSetVector<CachedHashString, 16> &Table,
1927                       bool &IsNew) {
1928   IsNew = Table.insert(CachedHashString(Name));
1929 
1930   unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
1931 
1932   assert(ID < Table.size());
1933 
1934   return ID;
1935 }
1936 
1937 static unsigned
1938 emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1939                  std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1940                  bool HasMnemonicFirst, bool HasOptionalOperands,
1941                  raw_ostream &OS) {
1942   SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1943   SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
1944   std::vector<std::vector<uint8_t> > ConversionTable;
1945   size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1946 
1947   // TargetOperandClass - This is the target's operand class, like X86Operand.
1948   std::string TargetOperandClass = Target.getName().str() + "Operand";
1949 
1950   // Write the convert function to a separate stream, so we can drop it after
1951   // the enum. We'll build up the conversion handlers for the individual
1952   // operand types opportunistically as we encounter them.
1953   std::string ConvertFnBody;
1954   raw_string_ostream CvtOS(ConvertFnBody);
1955   // Start the unified conversion function.
1956   if (HasOptionalOperands) {
1957     CvtOS << "void " << Target.getName() << ClassName << "::\n"
1958           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1959           << "unsigned Opcode,\n"
1960           << "                const OperandVector &Operands,\n"
1961           << "                const SmallBitVector &OptionalOperandsMask) {\n";
1962   } else {
1963     CvtOS << "void " << Target.getName() << ClassName << "::\n"
1964           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1965           << "unsigned Opcode,\n"
1966           << "                const OperandVector &Operands) {\n";
1967   }
1968   CvtOS << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1969   CvtOS << "  const uint8_t *Converter = ConversionTable[Kind];\n";
1970   if (HasOptionalOperands) {
1971     size_t MaxNumOperands = 0;
1972     for (const auto &MI : Infos) {
1973       MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1974     }
1975     CvtOS << "  unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1976           << "] = { 0 };\n";
1977     CvtOS << "  assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1978           << ");\n";
1979     CvtOS << "  for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1980           << "; ++i) {\n";
1981     CvtOS << "    DefaultsOffset[i + 1] = NumDefaults;\n";
1982     CvtOS << "    NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1983     CvtOS << "  }\n";
1984   }
1985   CvtOS << "  unsigned OpIdx;\n";
1986   CvtOS << "  Inst.setOpcode(Opcode);\n";
1987   CvtOS << "  for (const uint8_t *p = Converter; *p; p += 2) {\n";
1988   if (HasOptionalOperands) {
1989     CvtOS << "    OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
1990   } else {
1991     CvtOS << "    OpIdx = *(p + 1);\n";
1992   }
1993   CvtOS << "    switch (*p) {\n";
1994   CvtOS << "    default: llvm_unreachable(\"invalid conversion entry!\");\n";
1995   CvtOS << "    case CVT_Reg:\n";
1996   CvtOS << "      static_cast<" << TargetOperandClass
1997         << " &>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1998   CvtOS << "      break;\n";
1999   CvtOS << "    case CVT_Tied: {\n";
2000   CvtOS << "      assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
2001   CvtOS << "                              std::begin(TiedAsmOperandTable)) &&\n";
2002   CvtOS << "             \"Tied operand not found\");\n";
2003   CvtOS << "      unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
2004   CvtOS << "      if (TiedResOpnd != (uint8_t)-1)\n";
2005   CvtOS << "        Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
2006   CvtOS << "      break;\n";
2007   CvtOS << "    }\n";
2008 
2009   std::string OperandFnBody;
2010   raw_string_ostream OpOS(OperandFnBody);
2011   // Start the operand number lookup function.
2012   OpOS << "void " << Target.getName() << ClassName << "::\n"
2013        << "convertToMapAndConstraints(unsigned Kind,\n";
2014   OpOS.indent(27);
2015   OpOS << "const OperandVector &Operands) {\n"
2016        << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
2017        << "  unsigned NumMCOperands = 0;\n"
2018        << "  const uint8_t *Converter = ConversionTable[Kind];\n"
2019        << "  for (const uint8_t *p = Converter; *p; p += 2) {\n"
2020        << "    switch (*p) {\n"
2021        << "    default: llvm_unreachable(\"invalid conversion entry!\");\n"
2022        << "    case CVT_Reg:\n"
2023        << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2024        << "      Operands[*(p + 1)]->setConstraint(\"r\");\n"
2025        << "      ++NumMCOperands;\n"
2026        << "      break;\n"
2027        << "    case CVT_Tied:\n"
2028        << "      ++NumMCOperands;\n"
2029        << "      break;\n";
2030 
2031   // Pre-populate the operand conversion kinds with the standard always
2032   // available entries.
2033   OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2034   OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2035   OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
2036   enum { CVT_Done, CVT_Reg, CVT_Tied };
2037 
2038   // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2039   std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
2040   TiedOperandsEnumMap;
2041 
2042   for (auto &II : Infos) {
2043     // Check if we have a custom match function.
2044     StringRef AsmMatchConverter =
2045         II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
2046     if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
2047       std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
2048       II->ConversionFnKind = Signature;
2049 
2050       // Check if we have already generated this signature.
2051       if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2052         continue;
2053 
2054       // Remember this converter for the kind enum.
2055       unsigned KindID = OperandConversionKinds.size();
2056       OperandConversionKinds.insert(
2057           CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
2058 
2059       // Add the converter row for this instruction.
2060       ConversionTable.emplace_back();
2061       ConversionTable.back().push_back(KindID);
2062       ConversionTable.back().push_back(CVT_Done);
2063 
2064       // Add the handler to the conversion driver function.
2065       CvtOS << "    case CVT_"
2066             << getEnumNameForToken(AsmMatchConverter) << ":\n"
2067             << "      " << AsmMatchConverter << "(Inst, Operands);\n"
2068             << "      break;\n";
2069 
2070       // FIXME: Handle the operand number lookup for custom match functions.
2071       continue;
2072     }
2073 
2074     // Build the conversion function signature.
2075     std::string Signature = "Convert";
2076 
2077     std::vector<uint8_t> ConversionRow;
2078 
2079     // Compute the convert enum and the case body.
2080     MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
2081 
2082     for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2083       const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
2084 
2085       // Generate code to populate each result operand.
2086       switch (OpInfo.Kind) {
2087       case MatchableInfo::ResOperand::RenderAsmOperand: {
2088         // This comes from something we parsed.
2089         const MatchableInfo::AsmOperand &Op =
2090           II->AsmOperands[OpInfo.AsmOperandNum];
2091 
2092         // Registers are always converted the same, don't duplicate the
2093         // conversion function based on them.
2094         Signature += "__";
2095         std::string Class;
2096         Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2097         Signature += Class;
2098         Signature += utostr(OpInfo.MINumOperands);
2099         Signature += "_" + itostr(OpInfo.AsmOperandNum);
2100 
2101         // Add the conversion kind, if necessary, and get the associated ID
2102         // the index of its entry in the vector).
2103         std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
2104                                      Op.Class->RenderMethod);
2105         if (Op.Class->IsOptional) {
2106           // For optional operands we must also care about DefaultMethod
2107           assert(HasOptionalOperands);
2108           Name += "_" + Op.Class->DefaultMethod;
2109         }
2110         Name = getEnumNameForToken(Name);
2111 
2112         bool IsNewConverter = false;
2113         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2114                                             IsNewConverter);
2115 
2116         // Add the operand entry to the instruction kind conversion row.
2117         ConversionRow.push_back(ID);
2118         ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
2119 
2120         if (!IsNewConverter)
2121           break;
2122 
2123         // This is a new operand kind. Add a handler for it to the
2124         // converter driver.
2125         CvtOS << "    case " << Name << ":\n";
2126         if (Op.Class->IsOptional) {
2127           // If optional operand is not present in actual instruction then we
2128           // should call its DefaultMethod before RenderMethod
2129           assert(HasOptionalOperands);
2130           CvtOS << "      if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2131                 << "        " << Op.Class->DefaultMethod << "()"
2132                 << "->" << Op.Class->RenderMethod << "(Inst, "
2133                 << OpInfo.MINumOperands << ");\n"
2134                 << "      } else {\n"
2135                 << "        static_cast<" << TargetOperandClass
2136                 << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2137                 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2138                 << "      }\n";
2139         } else {
2140           CvtOS << "      static_cast<" << TargetOperandClass
2141                 << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2142                 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2143         }
2144         CvtOS << "      break;\n";
2145 
2146         // Add a handler for the operand number lookup.
2147         OpOS << "    case " << Name << ":\n"
2148              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2149 
2150         if (Op.Class->isRegisterClass())
2151           OpOS << "      Operands[*(p + 1)]->setConstraint(\"r\");\n";
2152         else
2153           OpOS << "      Operands[*(p + 1)]->setConstraint(\"m\");\n";
2154         OpOS << "      NumMCOperands += " << OpInfo.MINumOperands << ";\n"
2155              << "      break;\n";
2156         break;
2157       }
2158       case MatchableInfo::ResOperand::TiedOperand: {
2159         // If this operand is tied to a previous one, just copy the MCInst
2160         // operand from the earlier one.We can only tie single MCOperand values.
2161         assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
2162         uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
2163         uint8_t SrcOp1 =
2164             OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2165         uint8_t SrcOp2 =
2166             OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
2167         assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
2168                "Tied operand precedes its target!");
2169         auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2170                              utostr(SrcOp1) + '_' + utostr(SrcOp2);
2171         Signature += "__" + TiedTupleName;
2172         ConversionRow.push_back(CVT_Tied);
2173         ConversionRow.push_back(TiedOp);
2174         ConversionRow.push_back(SrcOp1);
2175         ConversionRow.push_back(SrcOp2);
2176 
2177         // Also create an 'enum' for this combination of tied operands.
2178         auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
2179         TiedOperandsEnumMap.emplace(Key, TiedTupleName);
2180         break;
2181       }
2182       case MatchableInfo::ResOperand::ImmOperand: {
2183         int64_t Val = OpInfo.ImmVal;
2184         std::string Ty = "imm_" + itostr(Val);
2185         Ty = getEnumNameForToken(Ty);
2186         Signature += "__" + Ty;
2187 
2188         std::string Name = "CVT_" + Ty;
2189         bool IsNewConverter = false;
2190         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2191                                             IsNewConverter);
2192         // Add the operand entry to the instruction kind conversion row.
2193         ConversionRow.push_back(ID);
2194         ConversionRow.push_back(0);
2195 
2196         if (!IsNewConverter)
2197           break;
2198 
2199         CvtOS << "    case " << Name << ":\n"
2200               << "      Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
2201               << "      break;\n";
2202 
2203         OpOS << "    case " << Name << ":\n"
2204              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2205              << "      Operands[*(p + 1)]->setConstraint(\"\");\n"
2206              << "      ++NumMCOperands;\n"
2207              << "      break;\n";
2208         break;
2209       }
2210       case MatchableInfo::ResOperand::RegOperand: {
2211         std::string Reg, Name;
2212         if (!OpInfo.Register) {
2213           Name = "reg0";
2214           Reg = "0";
2215         } else {
2216           Reg = getQualifiedName(OpInfo.Register);
2217           Name = "reg" + OpInfo.Register->getName().str();
2218         }
2219         Signature += "__" + Name;
2220         Name = "CVT_" + Name;
2221         bool IsNewConverter = false;
2222         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2223                                             IsNewConverter);
2224         // Add the operand entry to the instruction kind conversion row.
2225         ConversionRow.push_back(ID);
2226         ConversionRow.push_back(0);
2227 
2228         if (!IsNewConverter)
2229           break;
2230         CvtOS << "    case " << Name << ":\n"
2231               << "      Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
2232               << "      break;\n";
2233 
2234         OpOS << "    case " << Name << ":\n"
2235              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2236              << "      Operands[*(p + 1)]->setConstraint(\"m\");\n"
2237              << "      ++NumMCOperands;\n"
2238              << "      break;\n";
2239       }
2240       }
2241     }
2242 
2243     // If there were no operands, add to the signature to that effect
2244     if (Signature == "Convert")
2245       Signature += "_NoOperands";
2246 
2247     II->ConversionFnKind = Signature;
2248 
2249     // Save the signature. If we already have it, don't add a new row
2250     // to the table.
2251     if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2252       continue;
2253 
2254     // Add the row to the table.
2255     ConversionTable.push_back(std::move(ConversionRow));
2256   }
2257 
2258   // Finish up the converter driver function.
2259   CvtOS << "    }\n  }\n}\n\n";
2260 
2261   // Finish up the operand number lookup function.
2262   OpOS << "    }\n  }\n}\n\n";
2263 
2264   // Output a static table for tied operands.
2265   if (TiedOperandsEnumMap.size()) {
2266     // The number of tied operand combinations will be small in practice,
2267     // but just add the assert to be sure.
2268     assert(TiedOperandsEnumMap.size() <= 254 &&
2269            "Too many tied-operand combinations to reference with "
2270            "an 8bit offset from the conversion table, where index "
2271            "'255' is reserved as operand not to be copied.");
2272 
2273     OS << "enum {\n";
2274     for (auto &KV : TiedOperandsEnumMap) {
2275       OS << "  " << KV.second << ",\n";
2276     }
2277     OS << "};\n\n";
2278 
2279     OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
2280     for (auto &KV : TiedOperandsEnumMap) {
2281       OS << "  /* " << KV.second << " */ { "
2282          << utostr(std::get<0>(KV.first)) << ", "
2283          << utostr(std::get<1>(KV.first)) << ", "
2284          << utostr(std::get<2>(KV.first)) << " },\n";
2285     }
2286     OS << "};\n\n";
2287   } else
2288     OS << "static const uint8_t TiedAsmOperandTable[][3] = "
2289           "{ /* empty  */ {0, 0, 0} };\n\n";
2290 
2291   OS << "namespace {\n";
2292 
2293   // Output the operand conversion kind enum.
2294   OS << "enum OperatorConversionKind {\n";
2295   for (const auto &Converter : OperandConversionKinds)
2296     OS << "  " << Converter << ",\n";
2297   OS << "  CVT_NUM_CONVERTERS\n";
2298   OS << "};\n\n";
2299 
2300   // Output the instruction conversion kind enum.
2301   OS << "enum InstructionConversionKind {\n";
2302   for (const auto &Signature : InstructionConversionKinds)
2303     OS << "  " << Signature << ",\n";
2304   OS << "  CVT_NUM_SIGNATURES\n";
2305   OS << "};\n\n";
2306 
2307   OS << "} // end anonymous namespace\n\n";
2308 
2309   // Output the conversion table.
2310   OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2311      << MaxRowLength << "] = {\n";
2312 
2313   for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2314     assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2315     OS << "  // " << InstructionConversionKinds[Row] << "\n";
2316     OS << "  { ";
2317     for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2318       OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2319       if (OperandConversionKinds[ConversionTable[Row][i]] !=
2320           CachedHashString("CVT_Tied")) {
2321         OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2322         continue;
2323       }
2324 
2325       // For a tied operand, emit a reference to the TiedAsmOperandTable
2326       // that contains the operand to copy, and the parsed operands to
2327       // check for their tied constraints.
2328       auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
2329                                  (uint8_t)ConversionTable[Row][i + 2],
2330                                  (uint8_t)ConversionTable[Row][i + 3]);
2331       auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2332       assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2333              "No record for tied operand pair");
2334       OS << TiedOpndEnum->second << ", ";
2335       i += 2;
2336     }
2337     OS << "CVT_Done },\n";
2338   }
2339 
2340   OS << "};\n\n";
2341 
2342   // Spit out the conversion driver function.
2343   OS << CvtOS.str();
2344 
2345   // Spit out the operand number lookup function.
2346   OS << OpOS.str();
2347 
2348   return ConversionTable.size();
2349 }
2350 
2351 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2352 static void emitMatchClassEnumeration(CodeGenTarget &Target,
2353                                       std::forward_list<ClassInfo> &Infos,
2354                                       raw_ostream &OS) {
2355   OS << "namespace {\n\n";
2356 
2357   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2358      << "/// instruction matching.\n";
2359   OS << "enum MatchClassKind {\n";
2360   OS << "  InvalidMatchClass = 0,\n";
2361   OS << "  OptionalMatchClass = 1,\n";
2362   ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2363   StringRef LastName = "OptionalMatchClass";
2364   for (const auto &CI : Infos) {
2365     if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2366       OS << "  MCK_LAST_TOKEN = " << LastName << ",\n";
2367     } else if (LastKind < ClassInfo::UserClass0 &&
2368                CI.Kind >= ClassInfo::UserClass0) {
2369       OS << "  MCK_LAST_REGISTER = " << LastName << ",\n";
2370     }
2371     LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2372     LastName = CI.Name;
2373 
2374     OS << "  " << CI.Name << ", // ";
2375     if (CI.Kind == ClassInfo::Token) {
2376       OS << "'" << CI.ValueName << "'\n";
2377     } else if (CI.isRegisterClass()) {
2378       if (!CI.ValueName.empty())
2379         OS << "register class '" << CI.ValueName << "'\n";
2380       else
2381         OS << "derived register class\n";
2382     } else {
2383       OS << "user defined class '" << CI.ValueName << "'\n";
2384     }
2385   }
2386   OS << "  NumMatchClassKinds\n";
2387   OS << "};\n\n";
2388 
2389   OS << "} // end anonymous namespace\n\n";
2390 }
2391 
2392 /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2393 /// used when an assembly operand does not match the expected operand class.
2394 static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2395   // If the target does not use DiagnosticString for any operands, don't emit
2396   // an unused function.
2397   if (llvm::all_of(Info.Classes, [](const ClassInfo &CI) {
2398         return CI.DiagnosticString.empty();
2399       }))
2400     return;
2401 
2402   OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2403      << "AsmParser::" << Info.Target.getName()
2404      << "MatchResultTy MatchResult) {\n";
2405   OS << "  switch (MatchResult) {\n";
2406 
2407   for (const auto &CI: Info.Classes) {
2408     if (!CI.DiagnosticString.empty()) {
2409       assert(!CI.DiagnosticType.empty() &&
2410              "DiagnosticString set without DiagnosticType");
2411       OS << "  case " << Info.Target.getName()
2412          << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2413       OS << "    return \"" << CI.DiagnosticString << "\";\n";
2414     }
2415   }
2416 
2417   OS << "  default:\n";
2418   OS << "    return nullptr;\n";
2419 
2420   OS << "  }\n";
2421   OS << "}\n\n";
2422 }
2423 
2424 static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2425   OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2426         "RegisterClass) {\n";
2427   if (none_of(Info.Classes, [](const ClassInfo &CI) {
2428         return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2429       })) {
2430     OS << "  return MCTargetAsmParser::Match_InvalidOperand;\n";
2431   } else {
2432     OS << "  switch (RegisterClass) {\n";
2433     for (const auto &CI: Info.Classes) {
2434       if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2435         OS << "  case " << CI.Name << ":\n";
2436         OS << "    return " << Info.Target.getName() << "AsmParser::Match_"
2437            << CI.DiagnosticType << ";\n";
2438       }
2439     }
2440 
2441     OS << "  default:\n";
2442     OS << "    return MCTargetAsmParser::Match_InvalidOperand;\n";
2443 
2444     OS << "  }\n";
2445   }
2446   OS << "}\n\n";
2447 }
2448 
2449 /// emitValidateOperandClass - Emit the function to validate an operand class.
2450 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2451                                      raw_ostream &OS) {
2452   OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2453      << "MatchClassKind Kind) {\n";
2454   OS << "  " << Info.Target.getName() << "Operand &Operand = ("
2455      << Info.Target.getName() << "Operand &)GOp;\n";
2456 
2457   // The InvalidMatchClass is not to match any operand.
2458   OS << "  if (Kind == InvalidMatchClass)\n";
2459   OS << "    return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2460 
2461   // Check for Token operands first.
2462   // FIXME: Use a more specific diagnostic type.
2463   OS << "  if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
2464   OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2465      << "             MCTargetAsmParser::Match_Success :\n"
2466      << "             MCTargetAsmParser::Match_InvalidOperand;\n\n";
2467 
2468   // Check the user classes. We don't care what order since we're only
2469   // actually matching against one of them.
2470   OS << "  switch (Kind) {\n"
2471         "  default: break;\n";
2472   for (const auto &CI : Info.Classes) {
2473     if (!CI.isUserClass())
2474       continue;
2475 
2476     OS << "  // '" << CI.ClassName << "' class\n";
2477     OS << "  case " << CI.Name << ": {\n";
2478     OS << "    DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2479        << "());\n";
2480     OS << "    if (DP.isMatch())\n";
2481     OS << "      return MCTargetAsmParser::Match_Success;\n";
2482     if (!CI.DiagnosticType.empty()) {
2483       OS << "    if (DP.isNearMatch())\n";
2484       OS << "      return " << Info.Target.getName() << "AsmParser::Match_"
2485          << CI.DiagnosticType << ";\n";
2486       OS << "    break;\n";
2487     }
2488     else
2489       OS << "    break;\n";
2490     OS << "    }\n";
2491   }
2492   OS << "  } // end switch (Kind)\n\n";
2493 
2494   // Check for register operands, including sub-classes.
2495   OS << "  if (Operand.isReg()) {\n";
2496   OS << "    MatchClassKind OpKind;\n";
2497   OS << "    switch (Operand.getReg()) {\n";
2498   OS << "    default: OpKind = InvalidMatchClass; break;\n";
2499   for (const auto &RC : Info.RegisterClasses)
2500     OS << "    case " << RC.first->getValueAsString("Namespace") << "::"
2501        << RC.first->getName() << ": OpKind = " << RC.second->Name
2502        << "; break;\n";
2503   OS << "    }\n";
2504   OS << "    return isSubclass(OpKind, Kind) ? "
2505      << "(unsigned)MCTargetAsmParser::Match_Success :\n                     "
2506      << "                 getDiagKindFromRegisterClass(Kind);\n  }\n\n";
2507 
2508   // Expected operand is a register, but actual is not.
2509   OS << "  if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2510   OS << "    return getDiagKindFromRegisterClass(Kind);\n\n";
2511 
2512   // Generic fallthrough match failure case for operands that don't have
2513   // specialized diagnostic types.
2514   OS << "  return MCTargetAsmParser::Match_InvalidOperand;\n";
2515   OS << "}\n\n";
2516 }
2517 
2518 /// emitIsSubclass - Emit the subclass predicate function.
2519 static void emitIsSubclass(CodeGenTarget &Target,
2520                            std::forward_list<ClassInfo> &Infos,
2521                            raw_ostream &OS) {
2522   OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2523   OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2524   OS << "  if (A == B)\n";
2525   OS << "    return true;\n\n";
2526 
2527   bool EmittedSwitch = false;
2528   for (const auto &A : Infos) {
2529     std::vector<StringRef> SuperClasses;
2530     if (A.IsOptional)
2531       SuperClasses.push_back("OptionalMatchClass");
2532     for (const auto &B : Infos) {
2533       if (&A != &B && A.isSubsetOf(B))
2534         SuperClasses.push_back(B.Name);
2535     }
2536 
2537     if (SuperClasses.empty())
2538       continue;
2539 
2540     // If this is the first SuperClass, emit the switch header.
2541     if (!EmittedSwitch) {
2542       OS << "  switch (A) {\n";
2543       OS << "  default:\n";
2544       OS << "    return false;\n";
2545       EmittedSwitch = true;
2546     }
2547 
2548     OS << "\n  case " << A.Name << ":\n";
2549 
2550     if (SuperClasses.size() == 1) {
2551       OS << "    return B == " << SuperClasses.back() << ";\n";
2552       continue;
2553     }
2554 
2555     if (!SuperClasses.empty()) {
2556       OS << "    switch (B) {\n";
2557       OS << "    default: return false;\n";
2558       for (StringRef SC : SuperClasses)
2559         OS << "    case " << SC << ": return true;\n";
2560       OS << "    }\n";
2561     } else {
2562       // No case statement to emit
2563       OS << "    return false;\n";
2564     }
2565   }
2566 
2567   // If there were case statements emitted into the string stream write the
2568   // default.
2569   if (EmittedSwitch)
2570     OS << "  }\n";
2571   else
2572     OS << "  return false;\n";
2573 
2574   OS << "}\n\n";
2575 }
2576 
2577 /// emitMatchTokenString - Emit the function to match a token string to the
2578 /// appropriate match class value.
2579 static void emitMatchTokenString(CodeGenTarget &Target,
2580                                  std::forward_list<ClassInfo> &Infos,
2581                                  raw_ostream &OS) {
2582   // Construct the match list.
2583   std::vector<StringMatcher::StringPair> Matches;
2584   for (const auto &CI : Infos) {
2585     if (CI.Kind == ClassInfo::Token)
2586       Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
2587   }
2588 
2589   OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2590 
2591   StringMatcher("Name", Matches, OS).Emit();
2592 
2593   OS << "  return InvalidMatchClass;\n";
2594   OS << "}\n\n";
2595 }
2596 
2597 /// emitMatchRegisterName - Emit the function to match a string to the target
2598 /// specific register enum.
2599 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2600                                   raw_ostream &OS) {
2601   // Construct the match list.
2602   std::vector<StringMatcher::StringPair> Matches;
2603   const auto &Regs = Target.getRegBank().getRegisters();
2604   for (const CodeGenRegister &Reg : Regs) {
2605     if (Reg.TheDef->getValueAsString("AsmName").empty())
2606       continue;
2607 
2608     Matches.emplace_back(std::string(Reg.TheDef->getValueAsString("AsmName")),
2609                          "return " + utostr(Reg.EnumValue) + ";");
2610   }
2611 
2612   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2613 
2614   bool IgnoreDuplicates =
2615       AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2616   StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2617 
2618   OS << "  return 0;\n";
2619   OS << "}\n\n";
2620 }
2621 
2622 /// Emit the function to match a string to the target
2623 /// specific register enum.
2624 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2625                                      raw_ostream &OS) {
2626   // Construct the match list.
2627   std::vector<StringMatcher::StringPair> Matches;
2628   const auto &Regs = Target.getRegBank().getRegisters();
2629   for (const CodeGenRegister &Reg : Regs) {
2630 
2631     auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2632 
2633     for (auto AltName : AltNames) {
2634       AltName = StringRef(AltName).trim();
2635 
2636       // don't handle empty alternative names
2637       if (AltName.empty())
2638         continue;
2639 
2640       Matches.emplace_back(std::string(AltName),
2641                            "return " + utostr(Reg.EnumValue) + ";");
2642     }
2643   }
2644 
2645   OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2646 
2647   bool IgnoreDuplicates =
2648       AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2649   StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2650 
2651   OS << "  return 0;\n";
2652   OS << "}\n\n";
2653 }
2654 
2655 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2656 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2657   // Get the set of diagnostic types from all of the operand classes.
2658   std::set<StringRef> Types;
2659   for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2660     if (!OpClassEntry.second->DiagnosticType.empty())
2661       Types.insert(OpClassEntry.second->DiagnosticType);
2662   }
2663   for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2664     if (!OpClassEntry.second->DiagnosticType.empty())
2665       Types.insert(OpClassEntry.second->DiagnosticType);
2666   }
2667 
2668   if (Types.empty()) return;
2669 
2670   // Now emit the enum entries.
2671   for (StringRef Type : Types)
2672     OS << "  Match_" << Type << ",\n";
2673   OS << "  END_OPERAND_DIAGNOSTIC_TYPES\n";
2674 }
2675 
2676 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2677 /// user-level name for a subtarget feature.
2678 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2679   OS << "// User-level names for subtarget features that participate in\n"
2680      << "// instruction matching.\n"
2681      << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2682   if (!Info.SubtargetFeatures.empty()) {
2683     OS << "  switch(Val) {\n";
2684     for (const auto &SF : Info.SubtargetFeatures) {
2685       const SubtargetFeatureInfo &SFI = SF.second;
2686       // FIXME: Totally just a placeholder name to get the algorithm working.
2687       OS << "  case " << SFI.getEnumBitName() << ": return \""
2688          << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2689     }
2690     OS << "  default: return \"(unknown)\";\n";
2691     OS << "  }\n";
2692   } else {
2693     // Nothing to emit, so skip the switch
2694     OS << "  return \"(unknown)\";\n";
2695   }
2696   OS << "}\n\n";
2697 }
2698 
2699 static std::string GetAliasRequiredFeatures(Record *R,
2700                                             const AsmMatcherInfo &Info) {
2701   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2702   std::string Result;
2703 
2704   if (ReqFeatures.empty())
2705     return Result;
2706 
2707   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2708     const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2709 
2710     if (!F)
2711       PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2712                     "' is not marked as an AssemblerPredicate!");
2713 
2714     if (i)
2715       Result += " && ";
2716 
2717     Result += "Features.test(" + F->getEnumBitName() + ')';
2718   }
2719 
2720   return Result;
2721 }
2722 
2723 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2724                                      std::vector<Record*> &Aliases,
2725                                      unsigned Indent = 0,
2726                                   StringRef AsmParserVariantName = StringRef()){
2727   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
2728   // iteration order of the map is stable.
2729   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2730 
2731   for (Record *R : Aliases) {
2732     // FIXME: Allow AssemblerVariantName to be a comma separated list.
2733     StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
2734     if (AsmVariantName != AsmParserVariantName)
2735       continue;
2736     AliasesFromMnemonic[R->getValueAsString("FromMnemonic").lower()]
2737         .push_back(R);
2738   }
2739   if (AliasesFromMnemonic.empty())
2740     return;
2741 
2742   // Process each alias a "from" mnemonic at a time, building the code executed
2743   // by the string remapper.
2744   std::vector<StringMatcher::StringPair> Cases;
2745   for (const auto &AliasEntry : AliasesFromMnemonic) {
2746     const std::vector<Record*> &ToVec = AliasEntry.second;
2747 
2748     // Loop through each alias and emit code that handles each case.  If there
2749     // are two instructions without predicates, emit an error.  If there is one,
2750     // emit it last.
2751     std::string MatchCode;
2752     int AliasWithNoPredicate = -1;
2753 
2754     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2755       Record *R = ToVec[i];
2756       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2757 
2758       // If this unconditionally matches, remember it for later and diagnose
2759       // duplicates.
2760       if (FeatureMask.empty()) {
2761         if (AliasWithNoPredicate != -1 &&
2762             R->getValueAsString("ToMnemonic") !=
2763                 ToVec[AliasWithNoPredicate]->getValueAsString("ToMnemonic")) {
2764           // We can't have two different aliases from the same mnemonic with no
2765           // predicate.
2766           PrintError(
2767               ToVec[AliasWithNoPredicate]->getLoc(),
2768               "two different MnemonicAliases with the same 'from' mnemonic!");
2769           PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2770         }
2771 
2772         AliasWithNoPredicate = i;
2773         continue;
2774       }
2775       if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
2776         PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2777 
2778       if (!MatchCode.empty())
2779         MatchCode += "else ";
2780       MatchCode += "if (" + FeatureMask + ")\n";
2781       MatchCode += "  Mnemonic = \"";
2782       MatchCode += R->getValueAsString("ToMnemonic").lower();
2783       MatchCode += "\";\n";
2784     }
2785 
2786     if (AliasWithNoPredicate != -1) {
2787       Record *R = ToVec[AliasWithNoPredicate];
2788       if (!MatchCode.empty())
2789         MatchCode += "else\n  ";
2790       MatchCode += "Mnemonic = \"";
2791       MatchCode += R->getValueAsString("ToMnemonic").lower();
2792       MatchCode += "\";\n";
2793     }
2794 
2795     MatchCode += "return;";
2796 
2797     Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
2798   }
2799   StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2800 }
2801 
2802 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2803 /// emit a function for them and return true, otherwise return false.
2804 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2805                                 CodeGenTarget &Target) {
2806   // Ignore aliases when match-prefix is set.
2807   if (!MatchPrefix.empty())
2808     return false;
2809 
2810   std::vector<Record*> Aliases =
2811     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2812   if (Aliases.empty()) return false;
2813 
2814   OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2815     "const FeatureBitset &Features, unsigned VariantID) {\n";
2816   OS << "  switch (VariantID) {\n";
2817   unsigned VariantCount = Target.getAsmParserVariantCount();
2818   for (unsigned VC = 0; VC != VariantCount; ++VC) {
2819     Record *AsmVariant = Target.getAsmParserVariant(VC);
2820     int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2821     StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
2822     OS << "  case " << AsmParserVariantNo << ":\n";
2823     emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2824                              AsmParserVariantName);
2825     OS << "    break;\n";
2826   }
2827   OS << "  }\n";
2828 
2829   // Emit aliases that apply to all variants.
2830   emitMnemonicAliasVariant(OS, Info, Aliases);
2831 
2832   OS << "}\n\n";
2833 
2834   return true;
2835 }
2836 
2837 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2838                               const AsmMatcherInfo &Info, StringRef ClassName,
2839                               StringToOffsetTable &StringTable,
2840                               unsigned MaxMnemonicIndex,
2841                               unsigned MaxFeaturesIndex,
2842                               bool HasMnemonicFirst) {
2843   unsigned MaxMask = 0;
2844   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2845     MaxMask |= OMI.OperandMask;
2846   }
2847 
2848   // Emit the static custom operand parsing table;
2849   OS << "namespace {\n";
2850   OS << "  struct OperandMatchEntry {\n";
2851   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
2852                << " Mnemonic;\n";
2853   OS << "    " << getMinimalTypeForRange(MaxMask)
2854                << " OperandMask;\n";
2855   OS << "    " << getMinimalTypeForRange(std::distance(
2856                       Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
2857   OS << "    " << getMinimalTypeForRange(MaxFeaturesIndex)
2858                << " RequiredFeaturesIdx;\n\n";
2859   OS << "    StringRef getMnemonic() const {\n";
2860   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
2861   OS << "                       MnemonicTable[Mnemonic]);\n";
2862   OS << "    }\n";
2863   OS << "  };\n\n";
2864 
2865   OS << "  // Predicate for searching for an opcode.\n";
2866   OS << "  struct LessOpcodeOperand {\n";
2867   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2868   OS << "      return LHS.getMnemonic()  < RHS;\n";
2869   OS << "    }\n";
2870   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2871   OS << "      return LHS < RHS.getMnemonic();\n";
2872   OS << "    }\n";
2873   OS << "    bool operator()(const OperandMatchEntry &LHS,";
2874   OS << " const OperandMatchEntry &RHS) {\n";
2875   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
2876   OS << "    }\n";
2877   OS << "  };\n";
2878 
2879   OS << "} // end anonymous namespace\n\n";
2880 
2881   OS << "static const OperandMatchEntry OperandMatchTable["
2882      << Info.OperandMatchInfo.size() << "] = {\n";
2883 
2884   OS << "  /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
2885   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2886     const MatchableInfo &II = *OMI.MI;
2887 
2888     OS << "  { ";
2889 
2890     // Store a pascal-style length byte in the mnemonic.
2891     std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
2892     OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2893        << " /* " << II.Mnemonic << " */, ";
2894 
2895     OS << OMI.OperandMask;
2896     OS << " /* ";
2897     ListSeparator LS;
2898     for (int i = 0, e = 31; i !=e; ++i)
2899       if (OMI.OperandMask & (1 << i))
2900         OS << LS << i;
2901     OS << " */, ";
2902 
2903     OS << OMI.CI->Name;
2904 
2905     // Write the required features mask.
2906     OS << ", AMFBS";
2907     if (II.RequiredFeatures.empty())
2908       OS << "_None";
2909     else
2910       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
2911         OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
2912 
2913     OS << " },\n";
2914   }
2915   OS << "};\n\n";
2916 
2917   // Emit the operand class switch to call the correct custom parser for
2918   // the found operand class.
2919   OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2920      << "tryCustomParseOperand(OperandVector"
2921      << " &Operands,\n                      unsigned MCK) {\n\n"
2922      << "  switch(MCK) {\n";
2923 
2924   for (const auto &CI : Info.Classes) {
2925     if (CI.ParserMethod.empty())
2926       continue;
2927     OS << "  case " << CI.Name << ":\n"
2928        << "    return " << CI.ParserMethod << "(Operands);\n";
2929   }
2930 
2931   OS << "  default:\n";
2932   OS << "    return MatchOperand_NoMatch;\n";
2933   OS << "  }\n";
2934   OS << "  return MatchOperand_NoMatch;\n";
2935   OS << "}\n\n";
2936 
2937   // Emit the static custom operand parser. This code is very similar with
2938   // the other matcher. Also use MatchResultTy here just in case we go for
2939   // a better error handling.
2940   OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2941      << "MatchOperandParserImpl(OperandVector"
2942      << " &Operands,\n                       StringRef Mnemonic,\n"
2943      << "                       bool ParseForAllFeatures) {\n";
2944 
2945   // Emit code to get the available features.
2946   OS << "  // Get the current feature set.\n";
2947   OS << "  const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
2948 
2949   OS << "  // Get the next operand index.\n";
2950   OS << "  unsigned NextOpNum = Operands.size()"
2951      << (HasMnemonicFirst ? " - 1" : "") << ";\n";
2952 
2953   // Emit code to search the table.
2954   OS << "  // Search the table.\n";
2955   if (HasMnemonicFirst) {
2956     OS << "  auto MnemonicRange =\n";
2957     OS << "    std::equal_range(std::begin(OperandMatchTable), "
2958           "std::end(OperandMatchTable),\n";
2959     OS << "                     Mnemonic, LessOpcodeOperand());\n\n";
2960   } else {
2961     OS << "  auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2962           " std::end(OperandMatchTable));\n";
2963     OS << "  if (!Mnemonic.empty())\n";
2964     OS << "    MnemonicRange =\n";
2965     OS << "      std::equal_range(std::begin(OperandMatchTable), "
2966           "std::end(OperandMatchTable),\n";
2967     OS << "                       Mnemonic, LessOpcodeOperand());\n\n";
2968   }
2969 
2970   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2971   OS << "    return MatchOperand_NoMatch;\n\n";
2972 
2973   OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2974      << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
2975 
2976   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2977   OS << "    assert(Mnemonic == it->getMnemonic());\n\n";
2978 
2979   // Emit check that the required features are available.
2980   OS << "    // check if the available features match\n";
2981   OS << "    const FeatureBitset &RequiredFeatures = "
2982         "FeatureBitsets[it->RequiredFeaturesIdx];\n";
2983   OS << "    if (!ParseForAllFeatures && (AvailableFeatures & "
2984         "RequiredFeatures) != RequiredFeatures)\n";
2985   OS << "      continue;\n\n";
2986 
2987   // Emit check to ensure the operand number matches.
2988   OS << "    // check if the operand in question has a custom parser.\n";
2989   OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
2990   OS << "      continue;\n\n";
2991 
2992   // Emit call to the custom parser method
2993   OS << "    // call custom parse method to handle the operand\n";
2994   OS << "    OperandMatchResultTy Result = ";
2995   OS << "tryCustomParseOperand(Operands, it->Class);\n";
2996   OS << "    if (Result != MatchOperand_NoMatch)\n";
2997   OS << "      return Result;\n";
2998   OS << "  }\n\n";
2999 
3000   OS << "  // Okay, we had no match.\n";
3001   OS << "  return MatchOperand_NoMatch;\n";
3002   OS << "}\n\n";
3003 }
3004 
3005 static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
3006                                           AsmMatcherInfo &Info,
3007                                           raw_ostream &OS) {
3008   std::string AsmParserName =
3009       std::string(Info.AsmParser->getValueAsString("AsmParserClassName"));
3010   OS << "static bool ";
3011   OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3012      << AsmParserName << "&AsmParser,\n";
3013   OS << "                               unsigned Kind,\n";
3014   OS << "                               const OperandVector &Operands,\n";
3015   OS << "                               uint64_t &ErrorInfo) {\n";
3016   OS << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3017   OS << "  const uint8_t *Converter = ConversionTable[Kind];\n";
3018   OS << "  for (const uint8_t *p = Converter; *p; p += 2) {\n";
3019   OS << "    switch (*p) {\n";
3020   OS << "    case CVT_Tied: {\n";
3021   OS << "      unsigned OpIdx = *(p + 1);\n";
3022   OS << "      assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3023   OS << "                              std::begin(TiedAsmOperandTable)) &&\n";
3024   OS << "             \"Tied operand not found\");\n";
3025   OS << "      unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3026   OS << "      unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3027   OS << "      if (OpndNum1 != OpndNum2) {\n";
3028   OS << "        auto &SrcOp1 = Operands[OpndNum1];\n";
3029   OS << "        auto &SrcOp2 = Operands[OpndNum2];\n";
3030   OS << "        if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3031   OS << "          if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3032   OS << "            ErrorInfo = OpndNum2;\n";
3033   OS << "            return false;\n";
3034   OS << "          }\n";
3035   OS << "        }\n";
3036   OS << "      }\n";
3037   OS << "      break;\n";
3038   OS << "    }\n";
3039   OS << "    default:\n";
3040   OS << "      break;\n";
3041   OS << "    }\n";
3042   OS << "  }\n";
3043   OS << "  return true;\n";
3044   OS << "}\n\n";
3045 }
3046 
3047 static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3048                                      unsigned VariantCount) {
3049   OS << "static std::string " << Target.getName()
3050      << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3051      << " unsigned VariantID) {\n";
3052   if (!VariantCount)
3053     OS <<  "  return \"\";";
3054   else {
3055     OS << "  const unsigned MaxEditDist = 2;\n";
3056     OS << "  std::vector<StringRef> Candidates;\n";
3057     OS << "  StringRef Prev = \"\";\n\n";
3058 
3059     OS << "  // Find the appropriate table for this asm variant.\n";
3060     OS << "  const MatchEntry *Start, *End;\n";
3061     OS << "  switch (VariantID) {\n";
3062     OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
3063     for (unsigned VC = 0; VC != VariantCount; ++VC) {
3064       Record *AsmVariant = Target.getAsmParserVariant(VC);
3065       int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3066       OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3067          << "); End = std::end(MatchTable" << VC << "); break;\n";
3068     }
3069     OS << "  }\n\n";
3070     OS << "  for (auto I = Start; I < End; I++) {\n";
3071     OS << "    // Ignore unsupported instructions.\n";
3072     OS << "    const FeatureBitset &RequiredFeatures = "
3073           "FeatureBitsets[I->RequiredFeaturesIdx];\n";
3074     OS << "    if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
3075     OS << "      continue;\n";
3076     OS << "\n";
3077     OS << "    StringRef T = I->getMnemonic();\n";
3078     OS << "    // Avoid recomputing the edit distance for the same string.\n";
3079     OS << "    if (T.equals(Prev))\n";
3080     OS << "      continue;\n";
3081     OS << "\n";
3082     OS << "    Prev = T;\n";
3083     OS << "    unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3084     OS << "    if (Dist <= MaxEditDist)\n";
3085     OS << "      Candidates.push_back(T);\n";
3086     OS << "  }\n";
3087     OS << "\n";
3088     OS << "  if (Candidates.empty())\n";
3089     OS << "    return \"\";\n";
3090     OS << "\n";
3091     OS << "  std::string Res = \", did you mean: \";\n";
3092     OS << "  unsigned i = 0;\n";
3093     OS << "  for (; i < Candidates.size() - 1; i++)\n";
3094     OS << "    Res += Candidates[i].str() + \", \";\n";
3095     OS << "  return Res + Candidates[i].str() + \"?\";\n";
3096   }
3097   OS << "}\n";
3098   OS << "\n";
3099 }
3100 
3101 static void emitMnemonicChecker(raw_ostream &OS,
3102                                 CodeGenTarget &Target,
3103                                 unsigned VariantCount,
3104                                 bool HasMnemonicFirst,
3105                                 bool HasMnemonicAliases) {
3106   OS << "static bool " << Target.getName()
3107      << "CheckMnemonic(StringRef Mnemonic,\n";
3108   OS << "                                "
3109      << "const FeatureBitset &AvailableFeatures,\n";
3110   OS << "                                "
3111      << "unsigned VariantID) {\n";
3112 
3113   if (!VariantCount) {
3114     OS <<  "  return false;\n";
3115   } else {
3116     if (HasMnemonicAliases) {
3117       OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
3118       OS << "  applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);";
3119       OS << "\n\n";
3120     }
3121     OS << "  // Find the appropriate table for this asm variant.\n";
3122     OS << "  const MatchEntry *Start, *End;\n";
3123     OS << "  switch (VariantID) {\n";
3124     OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
3125     for (unsigned VC = 0; VC != VariantCount; ++VC) {
3126       Record *AsmVariant = Target.getAsmParserVariant(VC);
3127       int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3128       OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3129          << "); End = std::end(MatchTable" << VC << "); break;\n";
3130     }
3131     OS << "  }\n\n";
3132 
3133     OS << "  // Search the table.\n";
3134     if (HasMnemonicFirst) {
3135       OS << "  auto MnemonicRange = "
3136             "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3137     } else {
3138       OS << "  auto MnemonicRange = std::make_pair(Start, End);\n";
3139       OS << "  unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3140       OS << "  if (!Mnemonic.empty())\n";
3141       OS << "    MnemonicRange = "
3142          << "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3143     }
3144 
3145     OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
3146     OS << "    return false;\n\n";
3147 
3148     OS << "  for (const MatchEntry *it = MnemonicRange.first, "
3149        << "*ie = MnemonicRange.second;\n";
3150     OS << "       it != ie; ++it) {\n";
3151     OS << "    const FeatureBitset &RequiredFeatures =\n";
3152     OS << "      FeatureBitsets[it->RequiredFeaturesIdx];\n";
3153     OS << "    if ((AvailableFeatures & RequiredFeatures) == ";
3154     OS << "RequiredFeatures)\n";
3155     OS << "      return true;\n";
3156     OS << "  }\n";
3157     OS << "  return false;\n";
3158   }
3159   OS << "}\n";
3160   OS << "\n";
3161 }
3162 
3163 // Emit a function mapping match classes to strings, for debugging.
3164 static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3165                                     raw_ostream &OS) {
3166   OS << "#ifndef NDEBUG\n";
3167   OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3168   OS << "  switch (Kind) {\n";
3169 
3170   OS << "  case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3171   OS << "  case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3172   for (const auto &CI : Infos) {
3173     OS << "  case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3174   }
3175   OS << "  case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3176 
3177   OS << "  }\n";
3178   OS << "  llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3179   OS << "}\n\n";
3180   OS << "#endif // NDEBUG\n";
3181 }
3182 
3183 static std::string
3184 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
3185   std::string Name = "AMFBS";
3186   for (const auto &Feature : FeatureBitset)
3187     Name += ("_" + Feature->getName()).str();
3188   return Name;
3189 }
3190 
3191 void AsmMatcherEmitter::run(raw_ostream &OS) {
3192   CodeGenTarget Target(Records);
3193   Record *AsmParser = Target.getAsmParser();
3194   StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
3195 
3196   // Compute the information on the instructions to match.
3197   AsmMatcherInfo Info(AsmParser, Target, Records);
3198   Info.buildInfo();
3199 
3200   // Sort the instruction table using the partial order on classes. We use
3201   // stable_sort to ensure that ambiguous instructions are still
3202   // deterministically ordered.
3203   llvm::stable_sort(
3204       Info.Matchables,
3205       [](const std::unique_ptr<MatchableInfo> &a,
3206          const std::unique_ptr<MatchableInfo> &b) { return *a < *b; });
3207 
3208 #ifdef EXPENSIVE_CHECKS
3209   // Verify that the table is sorted and operator < works transitively.
3210   for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3211        ++I) {
3212     for (auto J = I; J != E; ++J) {
3213       assert(!(**J < **I));
3214     }
3215   }
3216 #endif
3217 
3218   DEBUG_WITH_TYPE("instruction_info", {
3219       for (const auto &MI : Info.Matchables)
3220         MI->dump();
3221     });
3222 
3223   // Check for ambiguous matchables.
3224   DEBUG_WITH_TYPE("ambiguous_instrs", {
3225     unsigned NumAmbiguous = 0;
3226     for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3227          ++I) {
3228       for (auto J = std::next(I); J != E; ++J) {
3229         const MatchableInfo &A = **I;
3230         const MatchableInfo &B = **J;
3231 
3232         if (A.couldMatchAmbiguouslyWith(B)) {
3233           errs() << "warning: ambiguous matchables:\n";
3234           A.dump();
3235           errs() << "\nis incomparable with:\n";
3236           B.dump();
3237           errs() << "\n\n";
3238           ++NumAmbiguous;
3239         }
3240       }
3241     }
3242     if (NumAmbiguous)
3243       errs() << "warning: " << NumAmbiguous
3244              << " ambiguous matchables!\n";
3245   });
3246 
3247   // Compute the information on the custom operand parsing.
3248   Info.buildOperandMatchInfo();
3249 
3250   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
3251   bool HasOptionalOperands = Info.hasOptionalOperands();
3252   bool ReportMultipleNearMisses =
3253       AsmParser->getValueAsBit("ReportMultipleNearMisses");
3254 
3255   // Write the output.
3256 
3257   // Information for the class declaration.
3258   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3259   OS << "#undef GET_ASSEMBLER_HEADER\n";
3260   OS << "  // This should be included into the middle of the declaration of\n";
3261   OS << "  // your subclasses implementation of MCTargetAsmParser.\n";
3262   OS << "  FeatureBitset ComputeAvailableFeatures(const FeatureBitset &FB) const;\n";
3263   if (HasOptionalOperands) {
3264     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
3265        << "unsigned Opcode,\n"
3266        << "                       const OperandVector &Operands,\n"
3267        << "                       const SmallBitVector &OptionalOperandsMask);\n";
3268   } else {
3269     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
3270        << "unsigned Opcode,\n"
3271        << "                       const OperandVector &Operands);\n";
3272   }
3273   OS << "  void convertToMapAndConstraints(unsigned Kind,\n                ";
3274   OS << "           const OperandVector &Operands) override;\n";
3275   OS << "  unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3276      << "                                MCInst &Inst,\n";
3277   if (ReportMultipleNearMisses)
3278     OS << "                                SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3279   else
3280     OS << "                                uint64_t &ErrorInfo,\n"
3281        << "                                FeatureBitset &MissingFeatures,\n";
3282   OS << "                                bool matchingInlineAsm,\n"
3283      << "                                unsigned VariantID = 0);\n";
3284   if (!ReportMultipleNearMisses)
3285     OS << "  unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3286        << "                                MCInst &Inst,\n"
3287        << "                                uint64_t &ErrorInfo,\n"
3288        << "                                bool matchingInlineAsm,\n"
3289        << "                                unsigned VariantID = 0) {\n"
3290        << "    FeatureBitset MissingFeatures;\n"
3291        << "    return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
3292        << "                                matchingInlineAsm, VariantID);\n"
3293        << "  }\n\n";
3294 
3295 
3296   if (!Info.OperandMatchInfo.empty()) {
3297     OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
3298     OS << "    OperandVector &Operands,\n";
3299     OS << "    StringRef Mnemonic,\n";
3300     OS << "    bool ParseForAllFeatures = false);\n";
3301 
3302     OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
3303     OS << "    OperandVector &Operands,\n";
3304     OS << "    unsigned MCK);\n\n";
3305   }
3306 
3307   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3308 
3309   // Emit the operand match diagnostic enum names.
3310   OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3311   OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3312   emitOperandDiagnosticTypes(Info, OS);
3313   OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3314 
3315   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3316   OS << "#undef GET_REGISTER_MATCHER\n\n";
3317 
3318   // Emit the subtarget feature enumeration.
3319   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
3320       Info.SubtargetFeatures, OS);
3321 
3322   // Emit the function to match a register name to number.
3323   // This should be omitted for Mips target
3324   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3325     emitMatchRegisterName(Target, AsmParser, OS);
3326 
3327   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3328     emitMatchRegisterAltName(Target, AsmParser, OS);
3329 
3330   OS << "#endif // GET_REGISTER_MATCHER\n\n";
3331 
3332   OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3333   OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
3334 
3335   // Generate the helper function to get the names for subtarget features.
3336   emitGetSubtargetFeatureName(Info, OS);
3337 
3338   OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3339 
3340   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3341   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3342 
3343   // Generate the function that remaps for mnemonic aliases.
3344   bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
3345 
3346   // Generate the convertToMCInst function to convert operands into an MCInst.
3347   // Also, generate the convertToMapAndConstraints function for MS-style inline
3348   // assembly.  The latter doesn't actually generate a MCInst.
3349   unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
3350                                             HasMnemonicFirst,
3351                                             HasOptionalOperands, OS);
3352 
3353   // Emit the enumeration for classes which participate in matching.
3354   emitMatchClassEnumeration(Target, Info.Classes, OS);
3355 
3356   // Emit a function to get the user-visible string to describe an operand
3357   // match failure in diagnostics.
3358   emitOperandMatchErrorDiagStrings(Info, OS);
3359 
3360   // Emit a function to map register classes to operand match failure codes.
3361   emitRegisterMatchErrorFunc(Info, OS);
3362 
3363   // Emit the routine to match token strings to their match class.
3364   emitMatchTokenString(Target, Info.Classes, OS);
3365 
3366   // Emit the subclass predicate routine.
3367   emitIsSubclass(Target, Info.Classes, OS);
3368 
3369   // Emit the routine to validate an operand against a match class.
3370   emitValidateOperandClass(Info, OS);
3371 
3372   emitMatchClassKindNames(Info.Classes, OS);
3373 
3374   // Emit the available features compute function.
3375   SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
3376       Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3377       Info.SubtargetFeatures, OS);
3378 
3379   if (!ReportMultipleNearMisses)
3380     emitAsmTiedOperandConstraints(Target, Info, OS);
3381 
3382   StringToOffsetTable StringTable;
3383 
3384   size_t MaxNumOperands = 0;
3385   unsigned MaxMnemonicIndex = 0;
3386   bool HasDeprecation = false;
3387   for (const auto &MI : Info.Matchables) {
3388     MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3389     HasDeprecation |= MI->HasDeprecation;
3390 
3391     // Store a pascal-style length byte in the mnemonic.
3392     std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3393     MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3394                         StringTable.GetOrAddStringOffset(LenMnemonic, false));
3395   }
3396 
3397   OS << "static const char *const MnemonicTable =\n";
3398   StringTable.EmitString(OS);
3399   OS << ";\n\n";
3400 
3401   std::vector<std::vector<Record *>> FeatureBitsets;
3402   for (const auto &MI : Info.Matchables) {
3403     if (MI->RequiredFeatures.empty())
3404       continue;
3405     FeatureBitsets.emplace_back();
3406     for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
3407       FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
3408   }
3409 
3410   llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
3411                                  const std::vector<Record *> &B) {
3412     if (A.size() < B.size())
3413       return true;
3414     if (A.size() > B.size())
3415       return false;
3416     for (auto Pair : zip(A, B)) {
3417       if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3418         return true;
3419       if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3420         return false;
3421     }
3422     return false;
3423   });
3424   FeatureBitsets.erase(
3425       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3426       FeatureBitsets.end());
3427   OS << "// Feature bitsets.\n"
3428      << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
3429      << "  AMFBS_None,\n";
3430   for (const auto &FeatureBitset : FeatureBitsets) {
3431     if (FeatureBitset.empty())
3432       continue;
3433     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3434   }
3435   OS << "};\n\n"
3436      << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
3437      << "  {}, // AMFBS_None\n";
3438   for (const auto &FeatureBitset : FeatureBitsets) {
3439     if (FeatureBitset.empty())
3440       continue;
3441     OS << "  {";
3442     for (const auto &Feature : FeatureBitset) {
3443       const auto &I = Info.SubtargetFeatures.find(Feature);
3444       assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
3445       OS << I->second.getEnumBitName() << ", ";
3446     }
3447     OS << "},\n";
3448   }
3449   OS << "};\n\n";
3450 
3451   // Emit the static match table; unused classes get initialized to 0 which is
3452   // guaranteed to be InvalidMatchClass.
3453   //
3454   // FIXME: We can reduce the size of this table very easily. First, we change
3455   // it so that store the kinds in separate bit-fields for each index, which
3456   // only needs to be the max width used for classes at that index (we also need
3457   // to reject based on this during classification). If we then make sure to
3458   // order the match kinds appropriately (putting mnemonics last), then we
3459   // should only end up using a few bits for each class, especially the ones
3460   // following the mnemonic.
3461   OS << "namespace {\n";
3462   OS << "  struct MatchEntry {\n";
3463   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
3464                << " Mnemonic;\n";
3465   OS << "    uint16_t Opcode;\n";
3466   OS << "    " << getMinimalTypeForRange(NumConverters)
3467                << " ConvertFn;\n";
3468   OS << "    " << getMinimalTypeForRange(FeatureBitsets.size())
3469                << " RequiredFeaturesIdx;\n";
3470   OS << "    " << getMinimalTypeForRange(
3471                       std::distance(Info.Classes.begin(), Info.Classes.end()))
3472      << " Classes[" << MaxNumOperands << "];\n";
3473   OS << "    StringRef getMnemonic() const {\n";
3474   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
3475   OS << "                       MnemonicTable[Mnemonic]);\n";
3476   OS << "    }\n";
3477   OS << "  };\n\n";
3478 
3479   OS << "  // Predicate for searching for an opcode.\n";
3480   OS << "  struct LessOpcode {\n";
3481   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3482   OS << "      return LHS.getMnemonic() < RHS;\n";
3483   OS << "    }\n";
3484   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3485   OS << "      return LHS < RHS.getMnemonic();\n";
3486   OS << "    }\n";
3487   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3488   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
3489   OS << "    }\n";
3490   OS << "  };\n";
3491 
3492   OS << "} // end anonymous namespace\n\n";
3493 
3494   unsigned VariantCount = Target.getAsmParserVariantCount();
3495   for (unsigned VC = 0; VC != VariantCount; ++VC) {
3496     Record *AsmVariant = Target.getAsmParserVariant(VC);
3497     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3498 
3499     OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
3500 
3501     for (const auto &MI : Info.Matchables) {
3502       if (MI->AsmVariantID != AsmVariantNo)
3503         continue;
3504 
3505       // Store a pascal-style length byte in the mnemonic.
3506       std::string LenMnemonic =
3507           char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3508       OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
3509          << " /* " << MI->Mnemonic << " */, "
3510          << Target.getInstNamespace() << "::"
3511          << MI->getResultInst()->TheDef->getName() << ", "
3512          << MI->ConversionFnKind << ", ";
3513 
3514       // Write the required features mask.
3515       OS << "AMFBS";
3516       if (MI->RequiredFeatures.empty())
3517         OS << "_None";
3518       else
3519         for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
3520           OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
3521 
3522       OS << ", { ";
3523       ListSeparator LS;
3524       for (const MatchableInfo::AsmOperand &Op : MI->AsmOperands)
3525         OS << LS << Op.Class->Name;
3526       OS << " }, },\n";
3527     }
3528 
3529     OS << "};\n\n";
3530   }
3531 
3532   OS << "#include \"llvm/Support/Debug.h\"\n";
3533   OS << "#include \"llvm/Support/Format.h\"\n\n";
3534 
3535   // Finally, build the match function.
3536   OS << "unsigned " << Target.getName() << ClassName << "::\n"
3537      << "MatchInstructionImpl(const OperandVector &Operands,\n";
3538   OS << "                     MCInst &Inst,\n";
3539   if (ReportMultipleNearMisses)
3540     OS << "                     SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3541   else
3542     OS << "                     uint64_t &ErrorInfo,\n"
3543        << "                     FeatureBitset &MissingFeatures,\n";
3544   OS << "                     bool matchingInlineAsm, unsigned VariantID) {\n";
3545 
3546   if (!ReportMultipleNearMisses) {
3547     OS << "  // Eliminate obvious mismatches.\n";
3548     OS << "  if (Operands.size() > "
3549        << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3550     OS << "    ErrorInfo = "
3551        << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3552     OS << "    return Match_InvalidOperand;\n";
3553     OS << "  }\n\n";
3554   }
3555 
3556   // Emit code to get the available features.
3557   OS << "  // Get the current feature set.\n";
3558   OS << "  const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
3559 
3560   OS << "  // Get the instruction mnemonic, which is the first token.\n";
3561   if (HasMnemonicFirst) {
3562     OS << "  StringRef Mnemonic = ((" << Target.getName()
3563        << "Operand &)*Operands[0]).getToken();\n\n";
3564   } else {
3565     OS << "  StringRef Mnemonic;\n";
3566     OS << "  if (Operands[0]->isToken())\n";
3567     OS << "    Mnemonic = ((" << Target.getName()
3568        << "Operand &)*Operands[0]).getToken();\n\n";
3569   }
3570 
3571   if (HasMnemonicAliases) {
3572     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
3573     OS << "  applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3574   }
3575 
3576   // Emit code to compute the class list for this operand vector.
3577   if (!ReportMultipleNearMisses) {
3578     OS << "  // Some state to try to produce better error messages.\n";
3579     OS << "  bool HadMatchOtherThanFeatures = false;\n";
3580     OS << "  bool HadMatchOtherThanPredicate = false;\n";
3581     OS << "  unsigned RetCode = Match_InvalidOperand;\n";
3582     OS << "  MissingFeatures.set();\n";
3583     OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
3584     OS << "  // wrong for all instances of the instruction.\n";
3585     OS << "  ErrorInfo = ~0ULL;\n";
3586   }
3587 
3588   if (HasOptionalOperands) {
3589     OS << "  SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3590   }
3591 
3592   // Emit code to search the table.
3593   OS << "  // Find the appropriate table for this asm variant.\n";
3594   OS << "  const MatchEntry *Start, *End;\n";
3595   OS << "  switch (VariantID) {\n";
3596   OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
3597   for (unsigned VC = 0; VC != VariantCount; ++VC) {
3598     Record *AsmVariant = Target.getAsmParserVariant(VC);
3599     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3600     OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3601        << "); End = std::end(MatchTable" << VC << "); break;\n";
3602   }
3603   OS << "  }\n";
3604 
3605   OS << "  // Search the table.\n";
3606   if (HasMnemonicFirst) {
3607     OS << "  auto MnemonicRange = "
3608           "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3609   } else {
3610     OS << "  auto MnemonicRange = std::make_pair(Start, End);\n";
3611     OS << "  unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3612     OS << "  if (!Mnemonic.empty())\n";
3613     OS << "    MnemonicRange = "
3614           "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3615   }
3616 
3617   OS << "  DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3618      << "  std::distance(MnemonicRange.first, MnemonicRange.second) <<\n"
3619      << "  \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3620 
3621   OS << "  // Return a more specific error code if no mnemonics match.\n";
3622   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
3623   OS << "    return Match_MnemonicFail;\n\n";
3624 
3625   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
3626      << "*ie = MnemonicRange.second;\n";
3627   OS << "       it != ie; ++it) {\n";
3628   OS << "    const FeatureBitset &RequiredFeatures = "
3629         "FeatureBitsets[it->RequiredFeaturesIdx];\n";
3630   OS << "    bool HasRequiredFeatures =\n";
3631   OS << "      (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
3632   OS << "    DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3633   OS << "                                          << MII.getName(it->Opcode) << \"\\n\");\n";
3634 
3635   if (ReportMultipleNearMisses) {
3636     OS << "    // Some state to record ways in which this instruction did not match.\n";
3637     OS << "    NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3638     OS << "    NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3639     OS << "    NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3640     OS << "    NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
3641     OS << "    bool MultipleInvalidOperands = false;\n";
3642   }
3643 
3644   if (HasMnemonicFirst) {
3645     OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
3646     OS << "    assert(Mnemonic == it->getMnemonic());\n";
3647   }
3648 
3649   // Emit check that the subclasses match.
3650   if (!ReportMultipleNearMisses)
3651     OS << "    bool OperandsValid = true;\n";
3652   if (HasOptionalOperands) {
3653     OS << "    OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3654   }
3655   OS << "    for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3656      << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3657      << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3658   OS << "      auto Formal = "
3659      << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3660   OS << "      DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3661   OS << "                      dbgs() << \"  Matching formal operand class \" << getMatchClassName(Formal)\n";
3662   OS << "                             << \" against actual operand at index \" << ActualIdx);\n";
3663   OS << "      if (ActualIdx < Operands.size())\n";
3664   OS << "        DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3665   OS << "                        Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3666   OS << "      else\n";
3667   OS << "        DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
3668   OS << "      if (ActualIdx >= Operands.size()) {\n";
3669   OS << "        DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
3670   if (ReportMultipleNearMisses) {
3671     OS << "        bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3672                                    "isSubclass(Formal, OptionalMatchClass);\n";
3673     OS << "        if (!ThisOperandValid) {\n";
3674     OS << "          if (!OperandNearMiss) {\n";
3675     OS << "            // Record info about match failure for later use.\n";
3676     OS << "            DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
3677     OS << "            OperandNearMiss =\n";
3678     OS << "                NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
3679     OS << "          } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
3680     OS << "            // If more than one operand is invalid, give up on this match entry.\n";
3681     OS << "            DEBUG_WITH_TYPE(\n";
3682     OS << "                \"asm-matcher\",\n";
3683     OS << "                dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
3684     OS << "            MultipleInvalidOperands = true;\n";
3685     OS << "            break;\n";
3686     OS << "          }\n";
3687     OS << "        } else {\n";
3688     OS << "          DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
3689     OS << "          break;\n";
3690     OS << "        }\n";
3691     OS << "        continue;\n";
3692   } else {
3693     OS << "        OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3694     OS << "        if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3695     if (HasOptionalOperands) {
3696       OS << "        OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3697          << ");\n";
3698     }
3699     OS << "        break;\n";
3700   }
3701   OS << "      }\n";
3702   OS << "      MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3703   OS << "      unsigned Diag = validateOperandClass(Actual, Formal);\n";
3704   OS << "      if (Diag == Match_Success) {\n";
3705   OS << "        DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3706   OS << "                        dbgs() << \"match success using generic matcher\\n\");\n";
3707   OS << "        ++ActualIdx;\n";
3708   OS << "        continue;\n";
3709   OS << "      }\n";
3710   OS << "      // If the generic handler indicates an invalid operand\n";
3711   OS << "      // failure, check for a special case.\n";
3712   OS << "      if (Diag != Match_Success) {\n";
3713   OS << "        unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3714   OS << "        if (TargetDiag == Match_Success) {\n";
3715   OS << "          DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3716   OS << "                          dbgs() << \"match success using target matcher\\n\");\n";
3717   OS << "          ++ActualIdx;\n";
3718   OS << "          continue;\n";
3719   OS << "        }\n";
3720   OS << "        // If the target matcher returned a specific error code use\n";
3721   OS << "        // that, else use the one from the generic matcher.\n";
3722   OS << "        if (TargetDiag != Match_InvalidOperand && "
3723         "HasRequiredFeatures)\n";
3724   OS << "          Diag = TargetDiag;\n";
3725   OS << "      }\n";
3726   OS << "      // If current formal operand wasn't matched and it is optional\n"
3727      << "      // then try to match next formal operand\n";
3728   OS << "      if (Diag == Match_InvalidOperand "
3729      << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3730   if (HasOptionalOperands) {
3731     OS << "        OptionalOperandsMask.set(FormalIdx);\n";
3732   }
3733     OS << "        DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
3734   OS << "        continue;\n";
3735   OS << "      }\n";
3736 
3737   if (ReportMultipleNearMisses) {
3738     OS << "      if (!OperandNearMiss) {\n";
3739     OS << "        // If this is the first invalid operand we have seen, record some\n";
3740     OS << "        // information about it.\n";
3741     OS << "        DEBUG_WITH_TYPE(\n";
3742     OS << "            \"asm-matcher\",\n";
3743     OS << "            dbgs()\n";
3744     OS << "                << \"operand match failed, recording near-miss with diag code \"\n";
3745     OS << "                << Diag << \"\\n\");\n";
3746     OS << "        OperandNearMiss =\n";
3747     OS << "            NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3748     OS << "        ++ActualIdx;\n";
3749     OS << "      } else {\n";
3750     OS << "        // If more than one operand is invalid, give up on this match entry.\n";
3751     OS << "        DEBUG_WITH_TYPE(\n";
3752     OS << "            \"asm-matcher\",\n";
3753     OS << "            dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
3754     OS << "        MultipleInvalidOperands = true;\n";
3755     OS << "        break;\n";
3756     OS << "      }\n";
3757     OS << "    }\n\n";
3758   } else {
3759     OS << "      // If this operand is broken for all of the instances of this\n";
3760     OS << "      // mnemonic, keep track of it so we can report loc info.\n";
3761     OS << "      // If we already had a match that only failed due to a\n";
3762     OS << "      // target predicate, that diagnostic is preferred.\n";
3763     OS << "      if (!HadMatchOtherThanPredicate &&\n";
3764     OS << "          (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3765     OS << "        if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3766           "!= Match_InvalidOperand))\n";
3767     OS << "          RetCode = Diag;\n";
3768     OS << "        ErrorInfo = ActualIdx;\n";
3769     OS << "      }\n";
3770     OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
3771     OS << "      OperandsValid = false;\n";
3772     OS << "      break;\n";
3773     OS << "    }\n\n";
3774   }
3775 
3776   if (ReportMultipleNearMisses)
3777     OS << "    if (MultipleInvalidOperands) {\n";
3778   else
3779     OS << "    if (!OperandsValid) {\n";
3780   OS << "      DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3781   OS << "                                               \"operand mismatches, ignoring \"\n";
3782   OS << "                                               \"this opcode\\n\");\n";
3783   OS << "      continue;\n";
3784   OS << "    }\n";
3785 
3786   // Emit check that the required features are available.
3787   OS << "    if (!HasRequiredFeatures) {\n";
3788   if (!ReportMultipleNearMisses)
3789     OS << "      HadMatchOtherThanFeatures = true;\n";
3790   OS << "      FeatureBitset NewMissingFeatures = RequiredFeatures & "
3791         "~AvailableFeatures;\n";
3792   OS << "      DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
3793   OS << "                      for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
3794   OS << "                        if (NewMissingFeatures[I])\n";
3795   OS << "                          dbgs() << ' ' << I;\n";
3796   OS << "                      dbgs() << \"\\n\");\n";
3797   if (ReportMultipleNearMisses) {
3798     OS << "      FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3799   } else {
3800     OS << "      if (NewMissingFeatures.count() <=\n"
3801           "          MissingFeatures.count())\n";
3802     OS << "        MissingFeatures = NewMissingFeatures;\n";
3803     OS << "      continue;\n";
3804   }
3805   OS << "    }\n";
3806   OS << "\n";
3807   OS << "    Inst.clear();\n\n";
3808   OS << "    Inst.setOpcode(it->Opcode);\n";
3809   // Verify the instruction with the target-specific match predicate function.
3810   OS << "    // We have a potential match but have not rendered the operands.\n"
3811      << "    // Check the target predicate to handle any context sensitive\n"
3812         "    // constraints.\n"
3813      << "    // For example, Ties that are referenced multiple times must be\n"
3814         "    // checked here to ensure the input is the same for each match\n"
3815         "    // constraints. If we leave it any later the ties will have been\n"
3816         "    // canonicalized\n"
3817      << "    unsigned MatchResult;\n"
3818      << "    if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3819         "Operands)) != Match_Success) {\n"
3820      << "      Inst.clear();\n";
3821   OS << "      DEBUG_WITH_TYPE(\n";
3822   OS << "          \"asm-matcher\",\n";
3823   OS << "          dbgs() << \"Early target match predicate failed with diag code \"\n";
3824   OS << "                 << MatchResult << \"\\n\");\n";
3825   if (ReportMultipleNearMisses) {
3826     OS << "      EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3827   } else {
3828     OS << "      RetCode = MatchResult;\n"
3829        << "      HadMatchOtherThanPredicate = true;\n"
3830        << "      continue;\n";
3831   }
3832   OS << "    }\n\n";
3833 
3834   if (ReportMultipleNearMisses) {
3835     OS << "    // If we did not successfully match the operands, then we can't convert to\n";
3836     OS << "    // an MCInst, so bail out on this instruction variant now.\n";
3837     OS << "    if (OperandNearMiss) {\n";
3838     OS << "      // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3839     OS << "      if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
3840     OS << "        DEBUG_WITH_TYPE(\n";
3841     OS << "            \"asm-matcher\",\n";
3842     OS << "            dbgs()\n";
3843     OS << "                << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
3844     OS << "        NearMisses->push_back(OperandNearMiss);\n";
3845     OS << "      } else {\n";
3846     OS << "        DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3847     OS << "                                                 \"types of mismatch, so not \"\n";
3848     OS << "                                                 \"reporting near-miss\\n\");\n";
3849     OS << "      }\n";
3850     OS << "      continue;\n";
3851     OS << "    }\n\n";
3852   }
3853 
3854   OS << "    if (matchingInlineAsm) {\n";
3855   OS << "      convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3856   if (!ReportMultipleNearMisses) {
3857     OS << "      if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3858           "Operands, ErrorInfo))\n";
3859     OS << "        return Match_InvalidTiedOperand;\n";
3860     OS << "\n";
3861   }
3862   OS << "      return Match_Success;\n";
3863   OS << "    }\n\n";
3864   OS << "    // We have selected a definite instruction, convert the parsed\n"
3865      << "    // operands into the appropriate MCInst.\n";
3866   if (HasOptionalOperands) {
3867     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3868        << "                    OptionalOperandsMask);\n";
3869   } else {
3870     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3871   }
3872   OS << "\n";
3873 
3874   // Verify the instruction with the target-specific match predicate function.
3875   OS << "    // We have a potential match. Check the target predicate to\n"
3876      << "    // handle any context sensitive constraints.\n"
3877      << "    if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3878      << " Match_Success) {\n"
3879      << "      DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3880      << "                      dbgs() << \"Target match predicate failed with diag code \"\n"
3881      << "                             << MatchResult << \"\\n\");\n"
3882      << "      Inst.clear();\n";
3883   if (ReportMultipleNearMisses) {
3884     OS << "      LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3885   } else {
3886     OS << "      RetCode = MatchResult;\n"
3887        << "      HadMatchOtherThanPredicate = true;\n"
3888        << "      continue;\n";
3889   }
3890   OS << "    }\n\n";
3891 
3892   if (ReportMultipleNearMisses) {
3893     OS << "    int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3894     OS << "                         (int)(bool)FeaturesNearMiss +\n";
3895     OS << "                         (int)(bool)EarlyPredicateNearMiss +\n";
3896     OS << "                         (int)(bool)LatePredicateNearMiss);\n";
3897     OS << "    if (NumNearMisses == 1) {\n";
3898     OS << "      // We had exactly one type of near-miss, so add that to the list.\n";
3899     OS << "      assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
3900     OS << "      DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3901     OS << "                                            \"mismatch, so reporting a \"\n";
3902     OS << "                                            \"near-miss\\n\");\n";
3903     OS << "      if (NearMisses && FeaturesNearMiss)\n";
3904     OS << "        NearMisses->push_back(FeaturesNearMiss);\n";
3905     OS << "      else if (NearMisses && EarlyPredicateNearMiss)\n";
3906     OS << "        NearMisses->push_back(EarlyPredicateNearMiss);\n";
3907     OS << "      else if (NearMisses && LatePredicateNearMiss)\n";
3908     OS << "        NearMisses->push_back(LatePredicateNearMiss);\n";
3909     OS << "\n";
3910     OS << "      continue;\n";
3911     OS << "    } else if (NumNearMisses > 1) {\n";
3912     OS << "      // This instruction missed in more than one way, so ignore it.\n";
3913     OS << "      DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3914     OS << "                                               \"types of mismatch, so not \"\n";
3915     OS << "                                               \"reporting near-miss\\n\");\n";
3916     OS << "      continue;\n";
3917     OS << "    }\n";
3918   }
3919 
3920   // Call the post-processing function, if used.
3921   StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
3922   if (!InsnCleanupFn.empty())
3923     OS << "    " << InsnCleanupFn << "(Inst);\n";
3924 
3925   if (HasDeprecation) {
3926     OS << "    std::string Info;\n";
3927     OS << "    if (!getParser().getTargetParser().getTargetOptions().MCNoDeprecatedWarn &&\n";
3928     OS << "        MII.getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
3929     OS << "      SMLoc Loc = ((" << Target.getName()
3930        << "Operand &)*Operands[0]).getStartLoc();\n";
3931     OS << "      getParser().Warning(Loc, Info, None);\n";
3932     OS << "    }\n";
3933   }
3934 
3935   if (!ReportMultipleNearMisses) {
3936     OS << "    if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3937           "Operands, ErrorInfo))\n";
3938     OS << "      return Match_InvalidTiedOperand;\n";
3939     OS << "\n";
3940   }
3941 
3942   OS << "    DEBUG_WITH_TYPE(\n";
3943   OS << "        \"asm-matcher\",\n";
3944   OS << "        dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
3945   OS << "    return Match_Success;\n";
3946   OS << "  }\n\n";
3947 
3948   if (ReportMultipleNearMisses) {
3949     OS << "  // No instruction variants matched exactly.\n";
3950     OS << "  return Match_NearMisses;\n";
3951   } else {
3952     OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
3953     OS << "  if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3954     OS << "    return RetCode;\n\n";
3955     OS << "  ErrorInfo = 0;\n";
3956     OS << "  return Match_MissingFeature;\n";
3957   }
3958   OS << "}\n\n";
3959 
3960   if (!Info.OperandMatchInfo.empty())
3961     emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3962                              MaxMnemonicIndex, FeatureBitsets.size(),
3963                              HasMnemonicFirst);
3964 
3965   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3966 
3967   OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3968   OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3969 
3970   emitMnemonicSpellChecker(OS, Target, VariantCount);
3971 
3972   OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
3973 
3974   OS << "\n#ifdef GET_MNEMONIC_CHECKER\n";
3975   OS << "#undef GET_MNEMONIC_CHECKER\n\n";
3976 
3977   emitMnemonicChecker(OS, Target, VariantCount,
3978                       HasMnemonicFirst, HasMnemonicAliases);
3979 
3980   OS << "#endif // GET_MNEMONIC_CHECKER\n\n";
3981 }
3982 
3983 namespace llvm {
3984 
3985 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3986   emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3987   AsmMatcherEmitter(RK).run(OS);
3988 }
3989 
3990 } // end namespace llvm
3991