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