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