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