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