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