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