llvm-mc/AsmParser: Check for matches with super classes when matching
[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 //      FIXME: What do we do if a crazy case shows up where this is the wrong
67 //      resolution?
68 //
69 //   2. The input can now be treated as a tuple of classes (static tokens are
70 //      simple singleton sets). Each such tuple should generally map to a single
71 //      instruction (we currently ignore cases where this isn't true, whee!!!),
72 //      which we can emit a simple matcher for.
73 //
74 //===----------------------------------------------------------------------===//
75
76 #include "AsmMatcherEmitter.h"
77 #include "CodeGenTarget.h"
78 #include "Record.h"
79 #include "llvm/ADT/OwningPtr.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 <list>
86 #include <map>
87 #include <set>
88 using namespace llvm;
89
90 namespace {
91 static cl::opt<std::string>
92 MatchPrefix("match-prefix", cl::init(""),
93             cl::desc("Only match instructions with the given prefix"));
94 }
95
96 /// FlattenVariants - Flatten an .td file assembly string by selecting the
97 /// variant at index \arg N.
98 static std::string FlattenVariants(const std::string &AsmString,
99                                    unsigned N) {
100   StringRef Cur = AsmString;
101   std::string Res = "";
102   
103   for (;;) {
104     // Find the start of the next variant string.
105     size_t VariantsStart = 0;
106     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
107       if (Cur[VariantsStart] == '{' && 
108           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
109                                   Cur[VariantsStart-1] != '\\')))
110         break;
111
112     // Add the prefix to the result.
113     Res += Cur.slice(0, VariantsStart);
114     if (VariantsStart == Cur.size())
115       break;
116
117     ++VariantsStart; // Skip the '{'.
118
119     // Scan to the end of the variants string.
120     size_t VariantsEnd = VariantsStart;
121     unsigned NestedBraces = 1;
122     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
123       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
124         if (--NestedBraces == 0)
125           break;
126       } else if (Cur[VariantsEnd] == '{')
127         ++NestedBraces;
128     }
129
130     // Select the Nth variant (or empty).
131     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
132     for (unsigned i = 0; i != N; ++i)
133       Selection = Selection.split('|').second;
134     Res += Selection.split('|').first;
135
136     assert(VariantsEnd != Cur.size() && 
137            "Unterminated variants in assembly string!");
138     Cur = Cur.substr(VariantsEnd + 1);
139   } 
140
141   return Res;
142 }
143
144 /// TokenizeAsmString - Tokenize a simplified assembly string.
145 static void TokenizeAsmString(const StringRef &AsmString, 
146                               SmallVectorImpl<StringRef> &Tokens) {
147   unsigned Prev = 0;
148   bool InTok = true;
149   for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
150     switch (AsmString[i]) {
151     case '[':
152     case ']':
153     case '*':
154     case '!':
155     case ' ':
156     case '\t':
157     case ',':
158       if (InTok) {
159         Tokens.push_back(AsmString.slice(Prev, i));
160         InTok = false;
161       }
162       if (!isspace(AsmString[i]) && AsmString[i] != ',')
163         Tokens.push_back(AsmString.substr(i, 1));
164       Prev = i + 1;
165       break;
166       
167     case '\\':
168       if (InTok) {
169         Tokens.push_back(AsmString.slice(Prev, i));
170         InTok = false;
171       }
172       ++i;
173       assert(i != AsmString.size() && "Invalid quoted character");
174       Tokens.push_back(AsmString.substr(i, 1));
175       Prev = i + 1;
176       break;
177
178     case '$': {
179       // If this isn't "${", treat like a normal token.
180       if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
181         if (InTok) {
182           Tokens.push_back(AsmString.slice(Prev, i));
183           InTok = false;
184         }
185         Prev = i;
186         break;
187       }
188
189       if (InTok) {
190         Tokens.push_back(AsmString.slice(Prev, i));
191         InTok = false;
192       }
193
194       StringRef::iterator End =
195         std::find(AsmString.begin() + i, AsmString.end(), '}');
196       assert(End != AsmString.end() && "Missing brace in operand reference!");
197       size_t EndPos = End - AsmString.begin();
198       Tokens.push_back(AsmString.slice(i, EndPos+1));
199       Prev = EndPos + 1;
200       i = EndPos;
201       break;
202     }
203
204     default:
205       InTok = true;
206     }
207   }
208   if (InTok && Prev != AsmString.size())
209     Tokens.push_back(AsmString.substr(Prev));
210 }
211
212 static bool IsAssemblerInstruction(const StringRef &Name,
213                                    const CodeGenInstruction &CGI, 
214                                    const SmallVectorImpl<StringRef> &Tokens) {
215   // Ignore psuedo ops.
216   //
217   // FIXME: This is a hack.
218   if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
219     if (Form->getValue()->getAsString() == "Pseudo")
220       return false;
221   
222   // Ignore "PHI" node.
223   //
224   // FIXME: This is also a hack.
225   if (Name == "PHI")
226     return false;
227
228   // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
229   //
230   // FIXME: This is a total hack.
231   if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
232     return false;
233
234   // Ignore instructions with no .s string.
235   //
236   // FIXME: What are these?
237   if (CGI.AsmString.empty())
238     return false;
239
240   // FIXME: Hack; ignore any instructions with a newline in them.
241   if (std::find(CGI.AsmString.begin(), 
242                 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
243     return false;
244   
245   // Ignore instructions with attributes, these are always fake instructions for
246   // simplifying codegen.
247   //
248   // FIXME: Is this true?
249   //
250   // Also, we ignore instructions which reference the operand multiple times;
251   // this implies a constraint we would not currently honor. These are
252   // currently always fake instructions for simplifying codegen.
253   //
254   // FIXME: Encode this assumption in the .td, so we can error out here.
255   std::set<std::string> OperandNames;
256   for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
257     if (Tokens[i][0] == '$' && 
258         std::find(Tokens[i].begin(), 
259                   Tokens[i].end(), ':') != Tokens[i].end()) {
260       DEBUG({
261           errs() << "warning: '" << Name << "': "
262                  << "ignoring instruction; operand with attribute '" 
263                  << Tokens[i] << "', \n";
264         });
265       return false;
266     }
267
268     if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
269       DEBUG({
270           errs() << "warning: '" << Name << "': "
271                  << "ignoring instruction; tied operand '" 
272                  << Tokens[i] << "'\n";
273         });
274       return false;
275     }
276   }
277
278   return true;
279 }
280
281 namespace {
282
283 /// ClassInfo - Helper class for storing the information about a particular
284 /// class of operands which can be matched.
285 struct ClassInfo {
286   enum ClassInfoKind {
287     Invalid = 0, ///< Invalid kind, for use as a sentinel value.
288     Token,       ///< The class for a particular token.
289     Register,    ///< A register class.
290     UserClass0   ///< The (first) user defined class, subsequent user defined
291                  /// classes are UserClass0+1, and so on.
292   };
293
294   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
295   /// N) for the Nth user defined class.
296   unsigned Kind;
297
298   /// SuperClassKind - The super class kind for user classes.
299   unsigned SuperClassKind;
300
301   /// SuperClass - The super class, or 0.
302   ClassInfo *SuperClass;
303
304   /// Name - The full class name, suitable for use in an enum.
305   std::string Name;
306
307   /// ClassName - The unadorned generic name for this class (e.g., Token).
308   std::string ClassName;
309
310   /// ValueName - The name of the value this class represents; for a token this
311   /// is the literal token string, for an operand it is the TableGen class (or
312   /// empty if this is a derived class).
313   std::string ValueName;
314
315   /// PredicateMethod - The name of the operand method to test whether the
316   /// operand matches this class; this is not valid for Token kinds.
317   std::string PredicateMethod;
318
319   /// RenderMethod - The name of the operand method to add this operand to an
320   /// MCInst; this is not valid for Token kinds.
321   std::string RenderMethod;
322
323   /// isUserClass() - Check if this is a user defined class.
324   bool isUserClass() const {
325     return Kind >= UserClass0;
326   }
327
328   /// getRootClass - Return the root class of this one.
329   const ClassInfo *getRootClass() const {
330     const ClassInfo *CI = this;
331     while (CI->SuperClass)
332       CI = CI->SuperClass;
333     return CI;
334   }
335
336   /// operator< - Compare two classes.
337   bool operator<(const ClassInfo &RHS) const {
338     // Incompatible kinds are comparable for classes in disjoint hierarchies.
339     if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
340       return Kind < RHS.Kind;
341
342     switch (Kind) {
343     case Invalid:
344       assert(0 && "Invalid kind!");
345     case Token:
346       // Tokens are comparable by value.
347       //
348       // FIXME: Compare by enum value.
349       return ValueName < RHS.ValueName;
350
351     default:
352       // This class preceeds the RHS if the RHS is a super class.
353       for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
354         if (Parent == &RHS)
355           return true;
356
357       return false;
358     }
359   }
360 };
361
362 /// InstructionInfo - Helper class for storing the necessary information for an
363 /// instruction which is capable of being matched.
364 struct InstructionInfo {
365   struct Operand {
366     /// The unique class instance this operand should match.
367     ClassInfo *Class;
368
369     /// The original operand this corresponds to, if any.
370     const CodeGenInstruction::OperandInfo *OperandInfo;
371   };
372
373   /// InstrName - The target name for this instruction.
374   std::string InstrName;
375
376   /// Instr - The instruction this matches.
377   const CodeGenInstruction *Instr;
378
379   /// AsmString - The assembly string for this instruction (with variants
380   /// removed).
381   std::string AsmString;
382
383   /// Tokens - The tokenized assembly pattern that this instruction matches.
384   SmallVector<StringRef, 4> Tokens;
385
386   /// Operands - The operands that this instruction matches.
387   SmallVector<Operand, 4> Operands;
388
389   /// ConversionFnKind - The enum value which is passed to the generated
390   /// ConvertToMCInst to convert parsed operands into an MCInst for this
391   /// function.
392   std::string ConversionFnKind;
393
394   /// operator< - Compare two instructions.
395   bool operator<(const InstructionInfo &RHS) const {
396     if (Operands.size() != RHS.Operands.size())
397       return Operands.size() < RHS.Operands.size();
398
399     // Compare lexicographically by operand. The matcher validates that other
400     // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
401     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
402       if (*Operands[i].Class < *RHS.Operands[i].Class)
403         return true;
404       if (*RHS.Operands[i].Class < *Operands[i].Class)
405         return false;
406     }
407
408     return false;
409   }
410
411   /// CouldMatchAmiguouslyWith - Check whether this instruction could
412   /// ambiguously match the same set of operands as \arg RHS (without being a
413   /// strictly superior match).
414   bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
415     // The number of operands is unambiguous.
416     if (Operands.size() != RHS.Operands.size())
417       return false;
418
419     // Tokens and operand kinds are unambiguous (assuming a correct target
420     // specific parser).
421     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
422       if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
423           Operands[i].Class->Kind == ClassInfo::Token)
424         if (*Operands[i].Class < *RHS.Operands[i].Class ||
425             *RHS.Operands[i].Class < *Operands[i].Class)
426           return false;
427     
428     // Otherwise, this operand could commute if all operands are equivalent, or
429     // there is a pair of operands that compare less than and a pair that
430     // compare greater than.
431     bool HasLT = false, HasGT = false;
432     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
433       if (*Operands[i].Class < *RHS.Operands[i].Class)
434         HasLT = true;
435       if (*RHS.Operands[i].Class < *Operands[i].Class)
436         HasGT = true;
437     }
438
439     return !(HasLT ^ HasGT);
440   }
441
442 public:
443   void dump();
444 };
445
446 class AsmMatcherInfo {
447 public:
448   /// The classes which are needed for matching.
449   std::vector<ClassInfo*> Classes;
450   
451   /// The information on the instruction to match.
452   std::vector<InstructionInfo*> Instructions;
453
454 private:
455   /// Map of token to class information which has already been constructed.
456   std::map<std::string, ClassInfo*> TokenClasses;
457
458   /// Map of operand name to class information which has already been
459   /// constructed.
460   std::map<std::string, ClassInfo*> OperandClasses;
461
462   /// Map of user class names to kind value.
463   std::map<std::string, unsigned> UserClasses;
464
465 private:
466   /// getTokenClass - Lookup or create the class for the given token.
467   ClassInfo *getTokenClass(const StringRef &Token);
468
469   /// getUserClassKind - Lookup or create the kind value for the given class
470   /// name.
471   unsigned getUserClassKind(const StringRef &Name);
472
473   /// getOperandClass - Lookup or create the class for the given operand.
474   ClassInfo *getOperandClass(const StringRef &Token,
475                              const CodeGenInstruction::OperandInfo &OI);
476
477 public:
478   /// BuildInfo - Construct the various tables used during matching.
479   void BuildInfo(CodeGenTarget &Target);
480 };
481
482 }
483
484 void InstructionInfo::dump() {
485   errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
486          << ", tokens:[";
487   for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
488     errs() << Tokens[i];
489     if (i + 1 != e)
490       errs() << ", ";
491   }
492   errs() << "]\n";
493
494   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
495     Operand &Op = Operands[i];
496     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
497     if (Op.Class->Kind == ClassInfo::Token) {
498       errs() << '\"' << Tokens[i] << "\"\n";
499       continue;
500     }
501
502     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
503     errs() << OI.Name << " " << OI.Rec->getName()
504            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
505   }
506 }
507
508 static std::string getEnumNameForToken(const StringRef &Str) {
509   std::string Res;
510   
511   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
512     switch (*it) {
513     case '*': Res += "_STAR_"; break;
514     case '%': Res += "_PCT_"; break;
515     case ':': Res += "_COLON_"; break;
516
517     default:
518       if (isalnum(*it))  {
519         Res += *it;
520       } else {
521         Res += "_" + utostr((unsigned) *it) + "_";
522       }
523     }
524   }
525
526   return Res;
527 }
528
529 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
530   ClassInfo *&Entry = TokenClasses[Token];
531   
532   if (!Entry) {
533     Entry = new ClassInfo();
534     Entry->Kind = ClassInfo::Token;
535     Entry->ClassName = "Token";
536     Entry->Name = "MCK_" + getEnumNameForToken(Token);
537     Entry->ValueName = Token;
538     Entry->PredicateMethod = "<invalid>";
539     Entry->RenderMethod = "<invalid>";
540     Classes.push_back(Entry);
541   }
542
543   return Entry;
544 }
545
546 unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
547   unsigned &Entry = UserClasses[Name];
548   
549   if (!Entry)
550     Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
551
552   return Entry;
553 }
554
555 ClassInfo *
556 AsmMatcherInfo::getOperandClass(const StringRef &Token,
557                                 const CodeGenInstruction::OperandInfo &OI) {
558   unsigned SuperClass = ClassInfo::Invalid;
559   std::string ClassName;
560   if (OI.Rec->isSubClassOf("RegisterClass")) {
561     ClassName = "Reg";
562   } else {
563     try {
564       ClassName = OI.Rec->getValueAsString("ParserMatchClass");
565       assert(ClassName != "Reg" && "'Reg' class name is reserved!");
566     } catch(...) {
567       PrintError(OI.Rec->getLoc(), "operand has no match class!");
568       ClassName = "Invalid";
569     }
570
571     // Determine the super class.
572     try {
573       std::string SuperClassName =
574         OI.Rec->getValueAsString("ParserMatchSuperClass");
575       SuperClass = getUserClassKind(SuperClassName);
576     } catch(...) { }
577   }
578
579   ClassInfo *&Entry = OperandClasses[ClassName];
580   
581   if (!Entry) {
582     Entry = new ClassInfo();
583     if (ClassName == "Reg") {
584       Entry->Kind = ClassInfo::Register;
585       Entry->SuperClassKind = SuperClass;
586     } else {
587       Entry->Kind = getUserClassKind(ClassName);
588       Entry->SuperClassKind = SuperClass;
589     }
590     Entry->ClassName = ClassName;
591     Entry->Name = "MCK_" + ClassName;
592     Entry->ValueName = OI.Rec->getName();
593     Entry->PredicateMethod = "is" + ClassName;
594     Entry->RenderMethod = "add" + ClassName + "Operands";
595     Classes.push_back(Entry);
596   } else {
597     // Verify the super class matches.
598     assert(SuperClass == Entry->SuperClassKind &&
599            "Cannot redefine super class kind!");
600   }
601   
602   return Entry;
603 }
604
605 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
606   for (std::map<std::string, CodeGenInstruction>::const_iterator 
607          it = Target.getInstructions().begin(), 
608          ie = Target.getInstructions().end(); 
609        it != ie; ++it) {
610     const CodeGenInstruction &CGI = it->second;
611
612     if (!StringRef(it->first).startswith(MatchPrefix))
613       continue;
614
615     OwningPtr<InstructionInfo> II(new InstructionInfo);
616     
617     II->InstrName = it->first;
618     II->Instr = &it->second;
619     II->AsmString = FlattenVariants(CGI.AsmString, 0);
620
621     TokenizeAsmString(II->AsmString, II->Tokens);
622
623     // Ignore instructions which shouldn't be matched.
624     if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
625       continue;
626
627     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
628       StringRef Token = II->Tokens[i];
629
630       // Check for simple tokens.
631       if (Token[0] != '$') {
632         InstructionInfo::Operand Op;
633         Op.Class = getTokenClass(Token);
634         Op.OperandInfo = 0;
635         II->Operands.push_back(Op);
636         continue;
637       }
638
639       // Otherwise this is an operand reference.
640       StringRef OperandName;
641       if (Token[1] == '{')
642         OperandName = Token.substr(2, Token.size() - 3);
643       else
644         OperandName = Token.substr(1);
645
646       // Map this token to an operand. FIXME: Move elsewhere.
647       unsigned Idx;
648       try {
649         Idx = CGI.getOperandNamed(OperandName);
650       } catch(...) {
651         errs() << "error: unable to find operand: '" << OperandName << "'!\n";
652         break;
653       }
654
655       const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];      
656       InstructionInfo::Operand Op;
657       Op.Class = getOperandClass(Token, OI);
658       Op.OperandInfo = &OI;
659       II->Operands.push_back(Op);
660     }
661
662     // If we broke out, ignore the instruction.
663     if (II->Operands.size() != II->Tokens.size())
664       continue;
665
666     Instructions.push_back(II.take());
667   }
668
669   // Bind user super classes.
670   std::map<unsigned, ClassInfo*> UserClasses;
671   for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
672     ClassInfo &CI = *Classes[i];
673     if (CI.isUserClass())
674       UserClasses[CI.Kind] = &CI;
675   }
676
677   for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
678     ClassInfo &CI = *Classes[i];
679     if (CI.isUserClass() && CI.SuperClassKind != ClassInfo::Invalid) {
680       CI.SuperClass = UserClasses[CI.SuperClassKind];
681       assert(CI.SuperClass && "Missing super class definition!");
682     } else {
683       CI.SuperClass = 0;
684     }
685   }
686
687   // Reorder classes so that classes preceed super classes.
688   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
689 }
690
691 static void EmitConvertToMCInst(CodeGenTarget &Target,
692                                 std::vector<InstructionInfo*> &Infos,
693                                 raw_ostream &OS) {
694   // Write the convert function to a separate stream, so we can drop it after
695   // the enum.
696   std::string ConvertFnBody;
697   raw_string_ostream CvtOS(ConvertFnBody);
698
699   // Function we have already generated.
700   std::set<std::string> GeneratedFns;
701
702   // Start the unified conversion function.
703
704   CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
705         << "unsigned Opcode,\n"
706         << "                            SmallVectorImpl<"
707         << Target.getName() << "Operand> &Operands) {\n";
708   CvtOS << "  Inst.setOpcode(Opcode);\n";
709   CvtOS << "  switch (Kind) {\n";
710   CvtOS << "  default:\n";
711
712   // Start the enum, which we will generate inline.
713
714   OS << "// Unified function for converting operants to MCInst instances.\n\n";
715   OS << "enum ConversionKind {\n";
716   
717   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
718          ie = Infos.end(); it != ie; ++it) {
719     InstructionInfo &II = **it;
720
721     // Order the (class) operands by the order to convert them into an MCInst.
722     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
723     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
724       InstructionInfo::Operand &Op = II.Operands[i];
725       if (Op.OperandInfo)
726         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
727     }
728     std::sort(MIOperandList.begin(), MIOperandList.end());
729
730     // Compute the total number of operands.
731     unsigned NumMIOperands = 0;
732     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
733       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
734       NumMIOperands = std::max(NumMIOperands, 
735                                OI.MIOperandNo + OI.MINumOperands);
736     }
737
738     // Build the conversion function signature.
739     std::string Signature = "Convert";
740     unsigned CurIndex = 0;
741     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
742       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
743       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
744              "Duplicate match for instruction operand!");
745       
746       Signature += "_";
747
748       // Skip operands which weren't matched by anything, this occurs when the
749       // .td file encodes "implicit" operands as explicit ones.
750       //
751       // FIXME: This should be removed from the MCInst structure.
752       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
753         Signature += "Imp";
754
755       Signature += Op.Class->ClassName;
756       Signature += utostr(Op.OperandInfo->MINumOperands);
757       Signature += "_" + utostr(MIOperandList[i].second);
758
759       CurIndex += Op.OperandInfo->MINumOperands;
760     }
761
762     // Add any trailing implicit operands.
763     for (; CurIndex != NumMIOperands; ++CurIndex)
764       Signature += "Imp";
765
766     II.ConversionFnKind = Signature;
767
768     // Check if we have already generated this signature.
769     if (!GeneratedFns.insert(Signature).second)
770       continue;
771
772     // If not, emit it now.
773
774     // Add to the enum list.
775     OS << "  " << Signature << ",\n";
776
777     // And to the convert function.
778     CvtOS << "  case " << Signature << ":\n";
779     CurIndex = 0;
780     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
781       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
782
783       // Add the implicit operands.
784       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
785         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
786
787       CvtOS << "    Operands[" << MIOperandList[i].second 
788          << "]." << Op.Class->RenderMethod 
789          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
790       CurIndex += Op.OperandInfo->MINumOperands;
791     }
792     
793     // And add trailing implicit operands.
794     for (; CurIndex != NumMIOperands; ++CurIndex)
795       CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
796     CvtOS << "    break;\n";
797   }
798
799   // Finish the convert function.
800
801   CvtOS << "  }\n";
802   CvtOS << "  return false;\n";
803   CvtOS << "}\n\n";
804
805   // Finish the enum, and drop the convert function after it.
806
807   OS << "  NumConversionVariants\n";
808   OS << "};\n\n";
809   
810   OS << CvtOS.str();
811 }
812
813 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
814 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
815                                       std::vector<ClassInfo*> &Infos,
816                                       raw_ostream &OS) {
817   OS << "namespace {\n\n";
818
819   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
820      << "/// instruction matching.\n";
821   OS << "enum MatchClassKind {\n";
822   OS << "  InvalidMatchClass = 0,\n";
823   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
824          ie = Infos.end(); it != ie; ++it) {
825     ClassInfo &CI = **it;
826     OS << "  " << CI.Name << ", // ";
827     if (CI.Kind == ClassInfo::Token) {
828       OS << "'" << CI.ValueName << "'\n";
829     } else if (CI.Kind == ClassInfo::Register) {
830       if (!CI.ValueName.empty())
831         OS << "register class '" << CI.ValueName << "'\n";
832       else
833         OS << "derived register class\n";
834     } else {
835       OS << "user defined class '" << CI.ValueName << "'\n";
836     }
837   }
838   OS << "  NumMatchClassKinds\n";
839   OS << "};\n\n";
840
841   OS << "}\n\n";
842 }
843
844 /// EmitClassifyOperand - Emit the function to classify an operand.
845 static void EmitClassifyOperand(CodeGenTarget &Target,
846                                 std::vector<ClassInfo*> &Infos,
847                                 raw_ostream &OS) {
848   OS << "static MatchClassKind ClassifyOperand("
849      << Target.getName() << "Operand &Operand) {\n";
850   OS << "  if (Operand.isToken())\n";
851   OS << "    return MatchTokenString(Operand.getToken());\n\n";
852   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
853          ie = Infos.end(); it != ie; ++it) {
854     ClassInfo &CI = **it;
855
856     if (CI.Kind != ClassInfo::Token) {
857       OS << "  // '" << CI.ClassName << "' class";
858       if (CI.SuperClass) {
859         OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
860         assert(CI < *CI.SuperClass && "Invalid class relation!");
861       }
862       OS << "\n";
863
864       OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
865       
866       // Validate subclass relationships.
867       if (CI.SuperClass)
868         OS << "    assert(Operand." << CI.SuperClass->PredicateMethod
869            << "() && \"Invalid class relationship!\");\n";
870
871       OS << "    return " << CI.Name << ";\n\n";
872       OS << "  }";
873     }
874   }
875   OS << "  return InvalidMatchClass;\n";
876   OS << "}\n\n";
877 }
878
879 /// EmitIsSubclass - Emit the subclass predicate function.
880 static void EmitIsSubclass(CodeGenTarget &Target,
881                            std::vector<ClassInfo*> &Infos,
882                            raw_ostream &OS) {
883   OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
884   OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
885   OS << "  if (A == B)\n";
886   OS << "    return true;\n\n";
887
888   OS << "  switch (A) {\n";
889   OS << "  default:\n";
890   OS << "    return false;\n";
891   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
892          ie = Infos.end(); it != ie; ++it) {
893     ClassInfo &A = **it;
894
895     if (A.Kind != ClassInfo::Token) {
896       std::vector<StringRef> SuperClasses;
897       for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
898              ie = Infos.end(); it != ie; ++it) {
899         ClassInfo &B = **it;
900
901         if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
902           SuperClasses.push_back(B.Name);
903       }
904
905       if (SuperClasses.empty())
906         continue;
907
908       OS << "\n  case " << A.Name << ":\n";
909
910       if (SuperClasses.size() == 1) {
911         OS << "    return B == " << SuperClasses.back() << ";\n\n";
912         continue;
913       }
914
915       OS << "      switch (B) {\n";
916       OS << "      default: return false;\n";
917       for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
918         OS << "      case " << SuperClasses[i] << ": return true;\n";
919       OS << "      }\n\n";
920     }
921   }
922   OS << "  }\n";
923   OS << "}\n\n";
924 }
925
926 typedef std::pair<std::string, std::string> StringPair;
927
928 /// FindFirstNonCommonLetter - Find the first character in the keys of the
929 /// string pairs that is not shared across the whole set of strings.  All
930 /// strings are assumed to have the same length.
931 static unsigned 
932 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
933   assert(!Matches.empty());
934   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
935     // Check to see if letter i is the same across the set.
936     char Letter = Matches[0]->first[i];
937     
938     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
939       if (Matches[str]->first[i] != Letter)
940         return i;
941   }
942   
943   return Matches[0]->first.size();
944 }
945
946 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
947 /// same length and whose characters leading up to CharNo are the same, emit
948 /// code to verify that CharNo and later are the same.
949 ///
950 /// \return - True if control can leave the emitted code fragment.
951 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
952                                   const std::vector<const StringPair*> &Matches,
953                                      unsigned CharNo, unsigned IndentCount,
954                                      raw_ostream &OS) {
955   assert(!Matches.empty() && "Must have at least one string to match!");
956   std::string Indent(IndentCount*2+4, ' ');
957
958   // If we have verified that the entire string matches, we're done: output the
959   // matching code.
960   if (CharNo == Matches[0]->first.size()) {
961     assert(Matches.size() == 1 && "Had duplicate keys to match on");
962     
963     // FIXME: If Matches[0].first has embeded \n, this will be bad.
964     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
965        << "\"\n";
966     return false;
967   }
968   
969   // Bucket the matches by the character we are comparing.
970   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
971   
972   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
973     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
974   
975
976   // If we have exactly one bucket to match, see how many characters are common
977   // across the whole set and match all of them at once.
978   if (MatchesByLetter.size() == 1) {
979     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
980     unsigned NumChars = FirstNonCommonLetter-CharNo;
981     
982     // Emit code to break out if the prefix doesn't match.
983     if (NumChars == 1) {
984       // Do the comparison with if (Str[1] != 'f')
985       // FIXME: Need to escape general characters.
986       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
987          << Matches[0]->first[CharNo] << "')\n";
988       OS << Indent << "  break;\n";
989     } else {
990       // Do the comparison with if (Str.substr(1,3) != "foo").    
991       // FIXME: Need to escape general strings.
992       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
993          << NumChars << ") != \"";
994       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
995       OS << Indent << "  break;\n";
996     }
997     
998     return EmitStringMatcherForChar(StrVariableName, Matches, 
999                                     FirstNonCommonLetter, IndentCount, OS);
1000   }
1001   
1002   // Otherwise, we have multiple possible things, emit a switch on the
1003   // character.
1004   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1005   OS << Indent << "default: break;\n";
1006   
1007   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
1008        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1009     // TODO: escape hard stuff (like \n) if we ever care about it.
1010     OS << Indent << "case '" << LI->first << "':\t // "
1011        << LI->second.size() << " strings to match.\n";
1012     if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1013                                  IndentCount+1, OS))
1014       OS << Indent << "  break;\n";
1015   }
1016   
1017   OS << Indent << "}\n";
1018   return true;
1019 }
1020
1021
1022 /// EmitStringMatcher - Given a list of strings and code to execute when they
1023 /// match, output a simple switch tree to classify the input string.
1024 /// 
1025 /// If a match is found, the code in Vals[i].second is executed; control must
1026 /// not exit this code fragment.  If nothing matches, execution falls through.
1027 ///
1028 /// \param StrVariableName - The name of the variable to test.
1029 static void EmitStringMatcher(const std::string &StrVariableName,
1030                               const std::vector<StringPair> &Matches,
1031                               raw_ostream &OS) {
1032   // First level categorization: group strings by length.
1033   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1034   
1035   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1036     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1037   
1038   // Output a switch statement on length and categorize the elements within each
1039   // bin.
1040   OS << "  switch (" << StrVariableName << ".size()) {\n";
1041   OS << "  default: break;\n";
1042   
1043   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1044        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1045     OS << "  case " << LI->first << ":\t // " << LI->second.size()
1046        << " strings to match.\n";
1047     if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1048       OS << "    break;\n";
1049   }
1050   
1051   OS << "  }\n";
1052 }
1053
1054
1055 /// EmitMatchTokenString - Emit the function to match a token string to the
1056 /// appropriate match class value.
1057 static void EmitMatchTokenString(CodeGenTarget &Target,
1058                                  std::vector<ClassInfo*> &Infos,
1059                                  raw_ostream &OS) {
1060   // Construct the match list.
1061   std::vector<StringPair> Matches;
1062   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1063          ie = Infos.end(); it != ie; ++it) {
1064     ClassInfo &CI = **it;
1065
1066     if (CI.Kind == ClassInfo::Token)
1067       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1068   }
1069
1070   OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1071
1072   EmitStringMatcher("Name", Matches, OS);
1073
1074   OS << "  return InvalidMatchClass;\n";
1075   OS << "}\n\n";
1076 }
1077
1078 /// EmitMatchRegisterName - Emit the function to match a string to the target
1079 /// specific register enum.
1080 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1081                                   raw_ostream &OS) {
1082   // Construct the match list.
1083   std::vector<StringPair> Matches;
1084   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1085     const CodeGenRegister &Reg = Target.getRegisters()[i];
1086     if (Reg.TheDef->getValueAsString("AsmName").empty())
1087       continue;
1088
1089     Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1090                                  "return " + utostr(i + 1) + ";"));
1091   }
1092   
1093   OS << "unsigned " << Target.getName() 
1094      << AsmParser->getValueAsString("AsmParserClassName")
1095      << "::MatchRegisterName(const StringRef &Name) {\n";
1096
1097   EmitStringMatcher("Name", Matches, OS);
1098   
1099   OS << "  return 0;\n";
1100   OS << "}\n\n";
1101 }
1102
1103 void AsmMatcherEmitter::run(raw_ostream &OS) {
1104   CodeGenTarget Target;
1105   Record *AsmParser = Target.getAsmParser();
1106   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1107
1108   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1109
1110   // Emit the function to match a register name to number.
1111   EmitMatchRegisterName(Target, AsmParser, OS);
1112
1113   // Compute the information on the instructions to match.
1114   AsmMatcherInfo Info;
1115   Info.BuildInfo(Target);
1116
1117   // Sort the instruction table using the partial order on classes.
1118   std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1119             less_ptr<InstructionInfo>());
1120   
1121   DEBUG_WITH_TYPE("instruction_info", {
1122       for (std::vector<InstructionInfo*>::iterator 
1123              it = Info.Instructions.begin(), ie = Info.Instructions.end(); 
1124            it != ie; ++it)
1125         (*it)->dump();
1126     });
1127
1128   // Check for ambiguous instructions.
1129   unsigned NumAmbiguous = 0;
1130   for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1131     for (unsigned j = i + 1; j != e; ++j) {
1132       InstructionInfo &A = *Info.Instructions[i];
1133       InstructionInfo &B = *Info.Instructions[j];
1134     
1135       if (A.CouldMatchAmiguouslyWith(B)) {
1136         DEBUG_WITH_TYPE("ambiguous_instrs", {
1137             errs() << "warning: ambiguous instruction match:\n";
1138             A.dump();
1139             errs() << "\nis incomparable with:\n";
1140             B.dump();
1141             errs() << "\n\n";
1142           });
1143         ++NumAmbiguous;
1144       }
1145     }
1146   }
1147   if (NumAmbiguous)
1148     DEBUG_WITH_TYPE("ambiguous_instrs", {
1149         errs() << "warning: " << NumAmbiguous 
1150                << " ambiguous instructions!\n";
1151       });
1152
1153   // Generate the unified function to convert operands into an MCInst.
1154   EmitConvertToMCInst(Target, Info.Instructions, OS);
1155
1156   // Emit the enumeration for classes which participate in matching.
1157   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1158
1159   // Emit the routine to match token strings to their match class.
1160   EmitMatchTokenString(Target, Info.Classes, OS);
1161
1162   // Emit the routine to classify an operand.
1163   EmitClassifyOperand(Target, Info.Classes, OS);
1164
1165   // Emit the subclass predicate routine.
1166   EmitIsSubclass(Target, Info.Classes, OS);
1167
1168   // Finally, build the match function.
1169
1170   size_t MaxNumOperands = 0;
1171   for (std::vector<InstructionInfo*>::const_iterator it =
1172          Info.Instructions.begin(), ie = Info.Instructions.end();
1173        it != ie; ++it)
1174     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1175   
1176   OS << "bool " << Target.getName() << ClassName
1177      << "::MatchInstruction(" 
1178      << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1179      << "MCInst &Inst) {\n";
1180
1181   // Emit the static match table; unused classes get initalized to 0 which is
1182   // guaranteed to be InvalidMatchClass.
1183   //
1184   // FIXME: We can reduce the size of this table very easily. First, we change
1185   // it so that store the kinds in separate bit-fields for each index, which
1186   // only needs to be the max width used for classes at that index (we also need
1187   // to reject based on this during classification). If we then make sure to
1188   // order the match kinds appropriately (putting mnemonics last), then we
1189   // should only end up using a few bits for each class, especially the ones
1190   // following the mnemonic.
1191   OS << "  static const struct MatchEntry {\n";
1192   OS << "    unsigned Opcode;\n";
1193   OS << "    ConversionKind ConvertFn;\n";
1194   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1195   OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1196
1197   for (std::vector<InstructionInfo*>::const_iterator it =
1198          Info.Instructions.begin(), ie = Info.Instructions.end();
1199        it != ie; ++it) {
1200     InstructionInfo &II = **it;
1201
1202     OS << "    { " << Target.getName() << "::" << II.InstrName
1203        << ", " << II.ConversionFnKind << ", { ";
1204     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1205       InstructionInfo::Operand &Op = II.Operands[i];
1206       
1207       if (i) OS << ", ";
1208       OS << Op.Class->Name;
1209     }
1210     OS << " } },\n";
1211   }
1212
1213   OS << "  };\n\n";
1214
1215   // Emit code to compute the class list for this operand vector.
1216   OS << "  // Eliminate obvious mismatches.\n";
1217   OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1218   OS << "    return true;\n\n";
1219
1220   OS << "  // Compute the class list for this operand vector.\n";
1221   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1222   OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1223   OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1224
1225   OS << "    // Check for invalid operands before matching.\n";
1226   OS << "    if (Classes[i] == InvalidMatchClass)\n";
1227   OS << "      return true;\n";
1228   OS << "  }\n\n";
1229
1230   OS << "  // Mark unused classes.\n";
1231   OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1232      << "i != e; ++i)\n";
1233   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1234
1235   // Emit code to search the table.
1236   OS << "  // Search the table.\n";
1237   OS << "  for (const MatchEntry *it = MatchTable, "
1238      << "*ie = MatchTable + " << Info.Instructions.size()
1239      << "; it != ie; ++it) {\n";
1240   for (unsigned i = 0; i != MaxNumOperands; ++i) {
1241     OS << "    if (!IsSubclass(Classes[" 
1242        << i << "], it->Classes[" << i << "]))\n";
1243     OS << "      continue;\n";
1244   }
1245   OS << "\n";
1246   OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
1247      << "it->Opcode, Operands);\n";
1248   OS << "  }\n\n";
1249
1250   OS << "  return true;\n";
1251   OS << "}\n\n";
1252 }