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