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