llvm-mc/AsmParser: Add hack to ignore Int_* and *_Int instructions for now, to
[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     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
400       if (*Operands[i].Class < *RHS.Operands[i].Class)
401         return true;
402     
403     return false;
404   }
405
406   /// CouldMatchAmiguouslyWith - Check whether this instruction could
407   /// ambiguously match the same set of operands as \arg RHS (without being a
408   /// strictly superior match).
409   bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
410     // The number of operands is unambiguous.
411     if (Operands.size() != RHS.Operands.size())
412       return false;
413
414     // Tokens and operand kinds are unambiguous (assuming a correct target
415     // specific parser).
416     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
417       if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
418           Operands[i].Class->Kind == ClassInfo::Token)
419         if (*Operands[i].Class < *RHS.Operands[i].Class ||
420             *RHS.Operands[i].Class < *Operands[i].Class)
421           return false;
422     
423     // Otherwise, this operand could commute if all operands are equivalent, or
424     // there is a pair of operands that compare less than and a pair that
425     // compare greater than.
426     bool HasLT = false, HasGT = false;
427     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
428       if (*Operands[i].Class < *RHS.Operands[i].Class)
429         HasLT = true;
430       if (*RHS.Operands[i].Class < *Operands[i].Class)
431         HasGT = true;
432     }
433
434     return !(HasLT ^ HasGT);
435   }
436
437 public:
438   void dump();
439 };
440
441 class AsmMatcherInfo {
442 public:
443   /// The classes which are needed for matching.
444   std::vector<ClassInfo*> Classes;
445   
446   /// The information on the instruction to match.
447   std::vector<InstructionInfo*> Instructions;
448
449 private:
450   /// Map of token to class information which has already been constructed.
451   std::map<std::string, ClassInfo*> TokenClasses;
452
453   /// Map of operand name to class information which has already been
454   /// constructed.
455   std::map<std::string, ClassInfo*> OperandClasses;
456
457   /// Map of user class names to kind value.
458   std::map<std::string, unsigned> UserClasses;
459
460 private:
461   /// getTokenClass - Lookup or create the class for the given token.
462   ClassInfo *getTokenClass(const StringRef &Token);
463
464   /// getUserClassKind - Lookup or create the kind value for the given class
465   /// name.
466   unsigned getUserClassKind(const StringRef &Name);
467
468   /// getOperandClass - Lookup or create the class for the given operand.
469   ClassInfo *getOperandClass(const StringRef &Token,
470                              const CodeGenInstruction::OperandInfo &OI);
471
472 public:
473   /// BuildInfo - Construct the various tables used during matching.
474   void BuildInfo(CodeGenTarget &Target);
475 };
476
477 }
478
479 void InstructionInfo::dump() {
480   errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
481          << ", tokens:[";
482   for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
483     errs() << Tokens[i];
484     if (i + 1 != e)
485       errs() << ", ";
486   }
487   errs() << "]\n";
488
489   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
490     Operand &Op = Operands[i];
491     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
492     if (Op.Class->Kind == ClassInfo::Token) {
493       errs() << '\"' << Tokens[i] << "\"\n";
494       continue;
495     }
496
497     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
498     errs() << OI.Name << " " << OI.Rec->getName()
499            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
500   }
501 }
502
503 static std::string getEnumNameForToken(const StringRef &Str) {
504   std::string Res;
505   
506   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
507     switch (*it) {
508     case '*': Res += "_STAR_"; break;
509     case '%': Res += "_PCT_"; break;
510     case ':': Res += "_COLON_"; break;
511
512     default:
513       if (isalnum(*it))  {
514         Res += *it;
515       } else {
516         Res += "_" + utostr((unsigned) *it) + "_";
517       }
518     }
519   }
520
521   return Res;
522 }
523
524 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
525   ClassInfo *&Entry = TokenClasses[Token];
526   
527   if (!Entry) {
528     Entry = new ClassInfo();
529     Entry->Kind = ClassInfo::Token;
530     Entry->ClassName = "Token";
531     Entry->Name = "MCK_" + getEnumNameForToken(Token);
532     Entry->ValueName = Token;
533     Entry->PredicateMethod = "<invalid>";
534     Entry->RenderMethod = "<invalid>";
535     Classes.push_back(Entry);
536   }
537
538   return Entry;
539 }
540
541 unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
542   unsigned &Entry = UserClasses[Name];
543   
544   if (!Entry)
545     Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
546
547   return Entry;
548 }
549
550 ClassInfo *
551 AsmMatcherInfo::getOperandClass(const StringRef &Token,
552                                 const CodeGenInstruction::OperandInfo &OI) {
553   unsigned SuperClass = ClassInfo::Invalid;
554   std::string ClassName;
555   if (OI.Rec->isSubClassOf("RegisterClass")) {
556     ClassName = "Reg";
557   } else {
558     try {
559       ClassName = OI.Rec->getValueAsString("ParserMatchClass");
560       assert(ClassName != "Reg" && "'Reg' class name is reserved!");
561     } catch(...) {
562       PrintError(OI.Rec->getLoc(), "operand has no match class!");
563       ClassName = "Invalid";
564     }
565
566     // Determine the super class.
567     try {
568       std::string SuperClassName =
569         OI.Rec->getValueAsString("ParserMatchSuperClass");
570       SuperClass = getUserClassKind(SuperClassName);
571     } catch(...) { }
572   }
573
574   ClassInfo *&Entry = OperandClasses[ClassName];
575   
576   if (!Entry) {
577     Entry = new ClassInfo();
578     if (ClassName == "Reg") {
579       Entry->Kind = ClassInfo::Register;
580       Entry->SuperClassKind = SuperClass;
581     } else {
582       Entry->Kind = getUserClassKind(ClassName);
583       Entry->SuperClassKind = SuperClass;
584     }
585     Entry->ClassName = ClassName;
586     Entry->Name = "MCK_" + ClassName;
587     Entry->ValueName = OI.Rec->getName();
588     Entry->PredicateMethod = "is" + ClassName;
589     Entry->RenderMethod = "add" + ClassName + "Operands";
590     Classes.push_back(Entry);
591   } else {
592     // Verify the super class matches.
593     assert(SuperClass == Entry->SuperClassKind &&
594            "Cannot redefine super class kind!");
595   }
596   
597   return Entry;
598 }
599
600 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
601   for (std::map<std::string, CodeGenInstruction>::const_iterator 
602          it = Target.getInstructions().begin(), 
603          ie = Target.getInstructions().end(); 
604        it != ie; ++it) {
605     const CodeGenInstruction &CGI = it->second;
606
607     if (!StringRef(it->first).startswith(MatchPrefix))
608       continue;
609
610     OwningPtr<InstructionInfo> II(new InstructionInfo);
611     
612     II->InstrName = it->first;
613     II->Instr = &it->second;
614     II->AsmString = FlattenVariants(CGI.AsmString, 0);
615
616     TokenizeAsmString(II->AsmString, II->Tokens);
617
618     // Ignore instructions which shouldn't be matched.
619     if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
620       continue;
621
622     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
623       StringRef Token = II->Tokens[i];
624
625       // Check for simple tokens.
626       if (Token[0] != '$') {
627         InstructionInfo::Operand Op;
628         Op.Class = getTokenClass(Token);
629         Op.OperandInfo = 0;
630         II->Operands.push_back(Op);
631         continue;
632       }
633
634       // Otherwise this is an operand reference.
635       StringRef OperandName;
636       if (Token[1] == '{')
637         OperandName = Token.substr(2, Token.size() - 3);
638       else
639         OperandName = Token.substr(1);
640
641       // Map this token to an operand. FIXME: Move elsewhere.
642       unsigned Idx;
643       try {
644         Idx = CGI.getOperandNamed(OperandName);
645       } catch(...) {
646         errs() << "error: unable to find operand: '" << OperandName << "'!\n";
647         break;
648       }
649
650       const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];      
651       InstructionInfo::Operand Op;
652       Op.Class = getOperandClass(Token, OI);
653       Op.OperandInfo = &OI;
654       II->Operands.push_back(Op);
655     }
656
657     // If we broke out, ignore the instruction.
658     if (II->Operands.size() != II->Tokens.size())
659       continue;
660
661     Instructions.push_back(II.take());
662   }
663
664   // Bind user super classes.
665   std::map<unsigned, ClassInfo*> UserClasses;
666   for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
667     ClassInfo &CI = *Classes[i];
668     if (CI.isUserClass())
669       UserClasses[CI.Kind] = &CI;
670   }
671
672   for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
673     ClassInfo &CI = *Classes[i];
674     if (CI.isUserClass() && CI.SuperClassKind != ClassInfo::Invalid) {
675       CI.SuperClass = UserClasses[CI.SuperClassKind];
676       assert(CI.SuperClass && "Missing super class definition!");
677     } else {
678       CI.SuperClass = 0;
679     }
680   }
681
682   // Reorder classes so that classes preceed super classes.
683   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
684 }
685
686 static void EmitConvertToMCInst(CodeGenTarget &Target,
687                                 std::vector<InstructionInfo*> &Infos,
688                                 raw_ostream &OS) {
689   // Write the convert function to a separate stream, so we can drop it after
690   // the enum.
691   std::string ConvertFnBody;
692   raw_string_ostream CvtOS(ConvertFnBody);
693
694   // Function we have already generated.
695   std::set<std::string> GeneratedFns;
696
697   // Start the unified conversion function.
698
699   CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
700         << "unsigned Opcode,\n"
701         << "                            SmallVectorImpl<"
702         << Target.getName() << "Operand> &Operands) {\n";
703   CvtOS << "  Inst.setOpcode(Opcode);\n";
704   CvtOS << "  switch (Kind) {\n";
705   CvtOS << "  default:\n";
706
707   // Start the enum, which we will generate inline.
708
709   OS << "// Unified function for converting operants to MCInst instances.\n\n";
710   OS << "enum ConversionKind {\n";
711   
712   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
713          ie = Infos.end(); it != ie; ++it) {
714     InstructionInfo &II = **it;
715
716     // Order the (class) operands by the order to convert them into an MCInst.
717     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
718     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
719       InstructionInfo::Operand &Op = II.Operands[i];
720       if (Op.OperandInfo)
721         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
722     }
723     std::sort(MIOperandList.begin(), MIOperandList.end());
724
725     // Compute the total number of operands.
726     unsigned NumMIOperands = 0;
727     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
728       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
729       NumMIOperands = std::max(NumMIOperands, 
730                                OI.MIOperandNo + OI.MINumOperands);
731     }
732
733     // Build the conversion function signature.
734     std::string Signature = "Convert";
735     unsigned CurIndex = 0;
736     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
737       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
738       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
739              "Duplicate match for instruction operand!");
740       
741       Signature += "_";
742
743       // Skip operands which weren't matched by anything, this occurs when the
744       // .td file encodes "implicit" operands as explicit ones.
745       //
746       // FIXME: This should be removed from the MCInst structure.
747       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
748         Signature += "Imp";
749
750       Signature += Op.Class->ClassName;
751       Signature += utostr(Op.OperandInfo->MINumOperands);
752       Signature += "_" + utostr(MIOperandList[i].second);
753
754       CurIndex += Op.OperandInfo->MINumOperands;
755     }
756
757     // Add any trailing implicit operands.
758     for (; CurIndex != NumMIOperands; ++CurIndex)
759       Signature += "Imp";
760
761     II.ConversionFnKind = Signature;
762
763     // Check if we have already generated this signature.
764     if (!GeneratedFns.insert(Signature).second)
765       continue;
766
767     // If not, emit it now.
768
769     // Add to the enum list.
770     OS << "  " << Signature << ",\n";
771
772     // And to the convert function.
773     CvtOS << "  case " << Signature << ":\n";
774     CurIndex = 0;
775     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
776       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
777
778       // Add the implicit operands.
779       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
780         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
781
782       CvtOS << "    Operands[" << MIOperandList[i].second 
783          << "]." << Op.Class->RenderMethod 
784          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
785       CurIndex += Op.OperandInfo->MINumOperands;
786     }
787     
788     // And add trailing implicit operands.
789     for (; CurIndex != NumMIOperands; ++CurIndex)
790       CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
791     CvtOS << "    break;\n";
792   }
793
794   // Finish the convert function.
795
796   CvtOS << "  }\n";
797   CvtOS << "  return false;\n";
798   CvtOS << "}\n\n";
799
800   // Finish the enum, and drop the convert function after it.
801
802   OS << "  NumConversionVariants\n";
803   OS << "};\n\n";
804   
805   OS << CvtOS.str();
806 }
807
808 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
809 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
810                                       std::vector<ClassInfo*> &Infos,
811                                       raw_ostream &OS) {
812   OS << "namespace {\n\n";
813
814   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
815      << "/// instruction matching.\n";
816   OS << "enum MatchClassKind {\n";
817   OS << "  InvalidMatchClass = 0,\n";
818   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
819          ie = Infos.end(); it != ie; ++it) {
820     ClassInfo &CI = **it;
821     OS << "  " << CI.Name << ", // ";
822     if (CI.Kind == ClassInfo::Token) {
823       OS << "'" << CI.ValueName << "'\n";
824     } else if (CI.Kind == ClassInfo::Register) {
825       if (!CI.ValueName.empty())
826         OS << "register class '" << CI.ValueName << "'\n";
827       else
828         OS << "derived register class\n";
829     } else {
830       OS << "user defined class '" << CI.ValueName << "'\n";
831     }
832   }
833   OS << "  NumMatchClassKinds\n";
834   OS << "};\n\n";
835
836   OS << "}\n\n";
837 }
838
839 /// EmitClassifyOperand - Emit the function to classify an operand.
840 static void EmitClassifyOperand(CodeGenTarget &Target,
841                                 std::vector<ClassInfo*> &Infos,
842                                 raw_ostream &OS) {
843   OS << "static MatchClassKind ClassifyOperand("
844      << Target.getName() << "Operand &Operand) {\n";
845   OS << "  if (Operand.isToken())\n";
846   OS << "    return MatchTokenString(Operand.getToken());\n\n";
847   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
848          ie = Infos.end(); it != ie; ++it) {
849     ClassInfo &CI = **it;
850
851     if (CI.Kind != ClassInfo::Token) {
852       OS << "  // '" << CI.ClassName << "' class";
853       if (CI.SuperClass) {
854         OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
855         assert(CI < *CI.SuperClass && "Invalid class relation!");
856       }
857       OS << "\n";
858
859       OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
860       
861       // Validate subclass relationships.
862       if (CI.SuperClass)
863         OS << "    assert(Operand." << CI.SuperClass->PredicateMethod
864            << "() && \"Invalid class relationship!\");\n";
865
866       OS << "    return " << CI.Name << ";\n\n";
867       OS << "  }";
868     }
869   }
870   OS << "  return InvalidMatchClass;\n";
871   OS << "}\n\n";
872 }
873
874 typedef std::pair<std::string, std::string> StringPair;
875
876 /// FindFirstNonCommonLetter - Find the first character in the keys of the
877 /// string pairs that is not shared across the whole set of strings.  All
878 /// strings are assumed to have the same length.
879 static unsigned 
880 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
881   assert(!Matches.empty());
882   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
883     // Check to see if letter i is the same across the set.
884     char Letter = Matches[0]->first[i];
885     
886     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
887       if (Matches[str]->first[i] != Letter)
888         return i;
889   }
890   
891   return Matches[0]->first.size();
892 }
893
894 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
895 /// same length and whose characters leading up to CharNo are the same, emit
896 /// code to verify that CharNo and later are the same.
897 ///
898 /// \return - True if control can leave the emitted code fragment.
899 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
900                                   const std::vector<const StringPair*> &Matches,
901                                      unsigned CharNo, unsigned IndentCount,
902                                      raw_ostream &OS) {
903   assert(!Matches.empty() && "Must have at least one string to match!");
904   std::string Indent(IndentCount*2+4, ' ');
905
906   // If we have verified that the entire string matches, we're done: output the
907   // matching code.
908   if (CharNo == Matches[0]->first.size()) {
909     assert(Matches.size() == 1 && "Had duplicate keys to match on");
910     
911     // FIXME: If Matches[0].first has embeded \n, this will be bad.
912     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
913        << "\"\n";
914     return false;
915   }
916   
917   // Bucket the matches by the character we are comparing.
918   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
919   
920   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
921     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
922   
923
924   // If we have exactly one bucket to match, see how many characters are common
925   // across the whole set and match all of them at once.
926   if (MatchesByLetter.size() == 1) {
927     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
928     unsigned NumChars = FirstNonCommonLetter-CharNo;
929     
930     // Emit code to break out if the prefix doesn't match.
931     if (NumChars == 1) {
932       // Do the comparison with if (Str[1] != 'f')
933       // FIXME: Need to escape general characters.
934       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
935          << Matches[0]->first[CharNo] << "')\n";
936       OS << Indent << "  break;\n";
937     } else {
938       // Do the comparison with if (Str.substr(1,3) != "foo").    
939       // FIXME: Need to escape general strings.
940       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
941          << NumChars << ") != \"";
942       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
943       OS << Indent << "  break;\n";
944     }
945     
946     return EmitStringMatcherForChar(StrVariableName, Matches, 
947                                     FirstNonCommonLetter, IndentCount, OS);
948   }
949   
950   // Otherwise, we have multiple possible things, emit a switch on the
951   // character.
952   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
953   OS << Indent << "default: break;\n";
954   
955   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
956        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
957     // TODO: escape hard stuff (like \n) if we ever care about it.
958     OS << Indent << "case '" << LI->first << "':\t // "
959        << LI->second.size() << " strings to match.\n";
960     if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
961                                  IndentCount+1, OS))
962       OS << Indent << "  break;\n";
963   }
964   
965   OS << Indent << "}\n";
966   return true;
967 }
968
969
970 /// EmitStringMatcher - Given a list of strings and code to execute when they
971 /// match, output a simple switch tree to classify the input string.
972 /// 
973 /// If a match is found, the code in Vals[i].second is executed; control must
974 /// not exit this code fragment.  If nothing matches, execution falls through.
975 ///
976 /// \param StrVariableName - The name of the variable to test.
977 static void EmitStringMatcher(const std::string &StrVariableName,
978                               const std::vector<StringPair> &Matches,
979                               raw_ostream &OS) {
980   // First level categorization: group strings by length.
981   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
982   
983   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
984     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
985   
986   // Output a switch statement on length and categorize the elements within each
987   // bin.
988   OS << "  switch (" << StrVariableName << ".size()) {\n";
989   OS << "  default: break;\n";
990   
991   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
992        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
993     OS << "  case " << LI->first << ":\t // " << LI->second.size()
994        << " strings to match.\n";
995     if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
996       OS << "    break;\n";
997   }
998   
999   OS << "  }\n";
1000 }
1001
1002
1003 /// EmitMatchTokenString - Emit the function to match a token string to the
1004 /// appropriate match class value.
1005 static void EmitMatchTokenString(CodeGenTarget &Target,
1006                                  std::vector<ClassInfo*> &Infos,
1007                                  raw_ostream &OS) {
1008   // Construct the match list.
1009   std::vector<StringPair> Matches;
1010   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1011          ie = Infos.end(); it != ie; ++it) {
1012     ClassInfo &CI = **it;
1013
1014     if (CI.Kind == ClassInfo::Token)
1015       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1016   }
1017
1018   OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1019
1020   EmitStringMatcher("Name", Matches, OS);
1021
1022   OS << "  return InvalidMatchClass;\n";
1023   OS << "}\n\n";
1024 }
1025
1026 /// EmitMatchRegisterName - Emit the function to match a string to the target
1027 /// specific register enum.
1028 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1029                                   raw_ostream &OS) {
1030   // Construct the match list.
1031   std::vector<StringPair> Matches;
1032   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1033     const CodeGenRegister &Reg = Target.getRegisters()[i];
1034     if (Reg.TheDef->getValueAsString("AsmName").empty())
1035       continue;
1036
1037     Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1038                                  "return " + utostr(i + 1) + ";"));
1039   }
1040   
1041   OS << "unsigned " << Target.getName() 
1042      << AsmParser->getValueAsString("AsmParserClassName")
1043      << "::MatchRegisterName(const StringRef &Name) {\n";
1044
1045   EmitStringMatcher("Name", Matches, OS);
1046   
1047   OS << "  return 0;\n";
1048   OS << "}\n\n";
1049 }
1050
1051 void AsmMatcherEmitter::run(raw_ostream &OS) {
1052   CodeGenTarget Target;
1053   Record *AsmParser = Target.getAsmParser();
1054   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1055
1056   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1057
1058   // Emit the function to match a register name to number.
1059   EmitMatchRegisterName(Target, AsmParser, OS);
1060
1061   // Compute the information on the instructions to match.
1062   AsmMatcherInfo Info;
1063   Info.BuildInfo(Target);
1064
1065   // Sort the instruction table using the partial order on classes.
1066   std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1067             less_ptr<InstructionInfo>());
1068   
1069   DEBUG_WITH_TYPE("instruction_info", {
1070       for (std::vector<InstructionInfo*>::iterator 
1071              it = Info.Instructions.begin(), ie = Info.Instructions.end(); 
1072            it != ie; ++it)
1073         (*it)->dump();
1074     });
1075
1076   // Check for ambiguous instructions.
1077   unsigned NumAmbiguous = 0;
1078   for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1079     for (unsigned j = i + 1; j != e; ++j) {
1080       InstructionInfo &A = *Info.Instructions[i];
1081       InstructionInfo &B = *Info.Instructions[j];
1082     
1083       if (A.CouldMatchAmiguouslyWith(B)) {
1084         DEBUG_WITH_TYPE("ambiguous_instrs", {
1085             errs() << "warning: ambiguous instruction match:\n";
1086             A.dump();
1087             errs() << "\nis incomparable with:\n";
1088             B.dump();
1089             errs() << "\n\n";
1090           });
1091         ++NumAmbiguous;
1092       }
1093     }
1094   }
1095   if (NumAmbiguous)
1096     DEBUG_WITH_TYPE("ambiguous_instrs", {
1097         errs() << "warning: " << NumAmbiguous 
1098                << " ambiguous instructions!\n";
1099       });
1100
1101   // Generate the unified function to convert operands into an MCInst.
1102   EmitConvertToMCInst(Target, Info.Instructions, OS);
1103
1104   // Emit the enumeration for classes which participate in matching.
1105   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1106
1107   // Emit the routine to match token strings to their match class.
1108   EmitMatchTokenString(Target, Info.Classes, OS);
1109
1110   // Emit the routine to classify an operand.
1111   EmitClassifyOperand(Target, Info.Classes, OS);
1112
1113   // Finally, build the match function.
1114
1115   size_t MaxNumOperands = 0;
1116   for (std::vector<InstructionInfo*>::const_iterator it =
1117          Info.Instructions.begin(), ie = Info.Instructions.end();
1118        it != ie; ++it)
1119     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1120   
1121   OS << "bool " << Target.getName() << ClassName
1122      << "::MatchInstruction(" 
1123      << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1124      << "MCInst &Inst) {\n";
1125
1126   // Emit the static match table; unused classes get initalized to 0 which is
1127   // guaranteed to be InvalidMatchClass.
1128   //
1129   // FIXME: We can reduce the size of this table very easily. First, we change
1130   // it so that store the kinds in separate bit-fields for each index, which
1131   // only needs to be the max width used for classes at that index (we also need
1132   // to reject based on this during classification). If we then make sure to
1133   // order the match kinds appropriately (putting mnemonics last), then we
1134   // should only end up using a few bits for each class, especially the ones
1135   // following the mnemonic.
1136   OS << "  static const struct MatchEntry {\n";
1137   OS << "    unsigned Opcode;\n";
1138   OS << "    ConversionKind ConvertFn;\n";
1139   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1140   OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1141
1142   for (std::vector<InstructionInfo*>::const_iterator it =
1143          Info.Instructions.begin(), ie = Info.Instructions.end();
1144        it != ie; ++it) {
1145     InstructionInfo &II = **it;
1146
1147     OS << "    { " << Target.getName() << "::" << II.InstrName
1148        << ", " << II.ConversionFnKind << ", { ";
1149     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1150       InstructionInfo::Operand &Op = II.Operands[i];
1151       
1152       if (i) OS << ", ";
1153       OS << Op.Class->Name;
1154     }
1155     OS << " } },\n";
1156   }
1157
1158   OS << "  };\n\n";
1159
1160   // Emit code to compute the class list for this operand vector.
1161   OS << "  // Eliminate obvious mismatches.\n";
1162   OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1163   OS << "    return true;\n\n";
1164
1165   OS << "  // Compute the class list for this operand vector.\n";
1166   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1167   OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1168   OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1169
1170   OS << "    // Check for invalid operands before matching.\n";
1171   OS << "    if (Classes[i] == InvalidMatchClass)\n";
1172   OS << "      return true;\n";
1173   OS << "  }\n\n";
1174
1175   OS << "  // Mark unused classes.\n";
1176   OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1177      << "i != e; ++i)\n";
1178   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1179
1180   // Emit code to search the table.
1181   OS << "  // Search the table.\n";
1182   OS << "  for (const MatchEntry *it = MatchTable, "
1183      << "*ie = MatchTable + " << Info.Instructions.size()
1184      << "; it != ie; ++it) {\n";
1185   for (unsigned i = 0; i != MaxNumOperands; ++i) {
1186     OS << "    if (Classes[" << i << "] != it->Classes[" << i << "])\n";
1187     OS << "      continue;\n";
1188   }
1189   OS << "\n";
1190   OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
1191      << "it->Opcode, Operands);\n";
1192   OS << "  }\n\n";
1193
1194   OS << "  return true;\n";
1195   OS << "}\n\n";
1196 }