1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a target specifier matcher for converting parsed
11 // assembly operands in the MCInst structures.
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
20 // Some example inputs, for X86:
21 // 'addl' (immediate ...) (register ...)
22 // 'add' (immediate ...) (memory ...)
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:
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.
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
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.
48 // The matching is divided into two distinct phases:
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.
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).
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.
63 // In addition, the subset relation amongst classes induces a partial order
64 // on such tuples, which we use to resolve ambiguities.
66 // FIXME: What do we do if a crazy case shows up where this is the wrong
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.
74 //===----------------------------------------------------------------------===//
76 #include "AsmMatcherEmitter.h"
77 #include "CodeGenTarget.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"
90 static cl::opt<std::string>
91 MatchPrefix("match-prefix", cl::init(""),
92 cl::desc("Only match instructions with the given prefix"));
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,
98 StringRef Cur = AsmString;
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] != '\\')))
110 // Add the prefix to the result.
111 Res += Cur.slice(0, VariantsStart);
112 if (VariantsStart == Cur.size())
115 ++VariantsStart; // Skip the '{'.
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)
124 } else if (Cur[VariantsEnd] == '{')
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;
134 assert(VariantsEnd != Cur.size() &&
135 "Unterminated variants in assembly string!");
136 Cur = Cur.substr(VariantsEnd + 1);
142 /// TokenizeAsmString - Tokenize a simplified assembly string.
143 static void TokenizeAsmString(const StringRef &AsmString,
144 SmallVectorImpl<StringRef> &Tokens) {
147 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
148 switch (AsmString[i]) {
157 Tokens.push_back(AsmString.slice(Prev, i));
160 if (!isspace(AsmString[i]) && AsmString[i] != ',')
161 Tokens.push_back(AsmString.substr(i, 1));
167 Tokens.push_back(AsmString.slice(Prev, i));
171 assert(i != AsmString.size() && "Invalid quoted character");
172 Tokens.push_back(AsmString.substr(i, 1));
177 // If this isn't "${", treat like a normal token.
178 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
180 Tokens.push_back(AsmString.slice(Prev, i));
188 Tokens.push_back(AsmString.slice(Prev, i));
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));
206 if (InTok && Prev != AsmString.size())
207 Tokens.push_back(AsmString.substr(Prev));
210 static bool IsAssemblerInstruction(const StringRef &Name,
211 const CodeGenInstruction &CGI,
212 const SmallVectorImpl<StringRef> &Tokens) {
213 // Ignore psuedo ops.
215 // FIXME: This is a hack.
216 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
217 if (Form->getValue()->getAsString() == "Pseudo")
220 // Ignore "PHI" node.
222 // FIXME: This is also a hack.
226 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
228 // FIXME: This is a total hack.
229 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
232 // Ignore instructions with no .s string.
234 // FIXME: What are these?
235 if (CGI.AsmString.empty())
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())
243 // Ignore instructions with attributes, these are always fake instructions for
244 // simplifying codegen.
246 // FIXME: Is this true?
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.
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()) {
259 errs() << "warning: '" << Name << "': "
260 << "ignoring instruction; operand with attribute '"
261 << Tokens[i] << "', \n";
266 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
268 errs() << "warning: '" << Name << "': "
269 << "ignoring instruction; tied operand '"
270 << Tokens[i] << "'\n";
281 /// ClassInfo - Helper class for storing the information about a particular
282 /// class of operands which can be matched.
285 Invalid = 0, ///< Invalid kind, for use as a sentinel value.
286 Token, ///< The class for a particular token.
287 Register, ///< A register class.
288 UserClass0 ///< The (first) user defined class, subsequent user defined
289 /// classes are UserClass0+1, and so on.
292 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
293 /// N) for the Nth user defined class.
296 /// SuperClass - The super class, or 0.
297 ClassInfo *SuperClass;
299 /// Name - The full class name, suitable for use in an enum.
302 /// ClassName - The unadorned generic name for this class (e.g., Token).
303 std::string ClassName;
305 /// ValueName - The name of the value this class represents; for a token this
306 /// is the literal token string, for an operand it is the TableGen class (or
307 /// empty if this is a derived class).
308 std::string ValueName;
310 /// PredicateMethod - The name of the operand method to test whether the
311 /// operand matches this class; this is not valid for Token kinds.
312 std::string PredicateMethod;
314 /// RenderMethod - The name of the operand method to add this operand to an
315 /// MCInst; this is not valid for Token kinds.
316 std::string RenderMethod;
318 /// isUserClass() - Check if this is a user defined class.
319 bool isUserClass() const {
320 return Kind >= UserClass0;
323 /// getRootClass - Return the root class of this one.
324 const ClassInfo *getRootClass() const {
325 const ClassInfo *CI = this;
326 while (CI->SuperClass)
331 /// operator< - Compare two classes.
332 bool operator<(const ClassInfo &RHS) const {
333 // Incompatible kinds are comparable for classes in disjoint hierarchies.
334 if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
335 return Kind < RHS.Kind;
339 assert(0 && "Invalid kind!");
341 // Tokens are comparable by value.
343 // FIXME: Compare by enum value.
344 return ValueName < RHS.ValueName;
347 // This class preceeds the RHS if the RHS is a super class.
348 for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
357 /// InstructionInfo - Helper class for storing the necessary information for an
358 /// instruction which is capable of being matched.
359 struct InstructionInfo {
361 /// The unique class instance this operand should match.
364 /// The original operand this corresponds to, if any.
365 const CodeGenInstruction::OperandInfo *OperandInfo;
368 /// InstrName - The target name for this instruction.
369 std::string InstrName;
371 /// Instr - The instruction this matches.
372 const CodeGenInstruction *Instr;
374 /// AsmString - The assembly string for this instruction (with variants
376 std::string AsmString;
378 /// Tokens - The tokenized assembly pattern that this instruction matches.
379 SmallVector<StringRef, 4> Tokens;
381 /// Operands - The operands that this instruction matches.
382 SmallVector<Operand, 4> Operands;
384 /// ConversionFnKind - The enum value which is passed to the generated
385 /// ConvertToMCInst to convert parsed operands into an MCInst for this
387 std::string ConversionFnKind;
389 /// operator< - Compare two instructions.
390 bool operator<(const InstructionInfo &RHS) const {
391 if (Operands.size() != RHS.Operands.size())
392 return Operands.size() < RHS.Operands.size();
394 // Compare lexicographically by operand. The matcher validates that other
395 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
396 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
397 if (*Operands[i].Class < *RHS.Operands[i].Class)
399 if (*RHS.Operands[i].Class < *Operands[i].Class)
406 /// CouldMatchAmiguouslyWith - Check whether this instruction could
407 /// ambiguously match the same set of operands as \arg RHS (without being a
408 /// strictly superior match).
409 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
410 // The number of operands is unambiguous.
411 if (Operands.size() != RHS.Operands.size())
414 // Tokens and operand kinds are unambiguous (assuming a correct target
416 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
417 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
418 Operands[i].Class->Kind == ClassInfo::Token)
419 if (*Operands[i].Class < *RHS.Operands[i].Class ||
420 *RHS.Operands[i].Class < *Operands[i].Class)
423 // Otherwise, this operand could commute if all operands are equivalent, or
424 // there is a pair of operands that compare less than and a pair that
425 // compare greater than.
426 bool HasLT = false, HasGT = false;
427 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
428 if (*Operands[i].Class < *RHS.Operands[i].Class)
430 if (*RHS.Operands[i].Class < *Operands[i].Class)
434 return !(HasLT ^ HasGT);
441 class AsmMatcherInfo {
443 /// The classes which are needed for matching.
444 std::vector<ClassInfo*> Classes;
446 /// The information on the instruction to match.
447 std::vector<InstructionInfo*> Instructions;
450 /// Map of token to class information which has already been constructed.
451 std::map<std::string, ClassInfo*> TokenClasses;
453 /// The ClassInfo instance for registers.
454 ClassInfo *TheRegisterClass;
456 /// Map of AsmOperandClass records to their class information.
457 std::map<Record*, ClassInfo*> AsmOperandClasses;
460 /// getTokenClass - Lookup or create the class for the given token.
461 ClassInfo *getTokenClass(const StringRef &Token);
463 /// getOperandClass - Lookup or create the class for the given operand.
464 ClassInfo *getOperandClass(const StringRef &Token,
465 const CodeGenInstruction::OperandInfo &OI);
468 /// BuildInfo - Construct the various tables used during matching.
469 void BuildInfo(CodeGenTarget &Target);
474 void InstructionInfo::dump() {
475 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
477 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
484 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
485 Operand &Op = Operands[i];
486 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
487 if (Op.Class->Kind == ClassInfo::Token) {
488 errs() << '\"' << Tokens[i] << "\"\n";
492 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
493 errs() << OI.Name << " " << OI.Rec->getName()
494 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
498 static std::string getEnumNameForToken(const StringRef &Str) {
501 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
503 case '*': Res += "_STAR_"; break;
504 case '%': Res += "_PCT_"; break;
505 case ':': Res += "_COLON_"; break;
511 Res += "_" + utostr((unsigned) *it) + "_";
519 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
520 ClassInfo *&Entry = TokenClasses[Token];
523 Entry = new ClassInfo();
524 Entry->Kind = ClassInfo::Token;
525 Entry->SuperClass = 0;
526 Entry->ClassName = "Token";
527 Entry->Name = "MCK_" + getEnumNameForToken(Token);
528 Entry->ValueName = Token;
529 Entry->PredicateMethod = "<invalid>";
530 Entry->RenderMethod = "<invalid>";
531 Classes.push_back(Entry);
538 AsmMatcherInfo::getOperandClass(const StringRef &Token,
539 const CodeGenInstruction::OperandInfo &OI) {
540 if (OI.Rec->isSubClassOf("RegisterClass"))
541 return TheRegisterClass;
543 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
544 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
545 ClassInfo *CI = AsmOperandClasses[MatchClass];
548 PrintError(OI.Rec->getLoc(), "operand has no match class!");
549 throw std::string("ERROR: Missing match class!");
555 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
556 // Build the assembly match class information.
558 // Construct the "Reg" class.
560 // FIXME: This needs to dice up the RegisterClass instances.
561 ClassInfo *RegClass = TheRegisterClass = new ClassInfo();
562 RegClass->Kind = ClassInfo::Register;
563 RegClass->SuperClass = 0;
564 RegClass->ClassName = "Reg";
565 RegClass->Name = "MCK_Reg";
566 RegClass->ValueName = "<register class>";
567 RegClass->PredicateMethod = "isReg";
568 RegClass->RenderMethod = "addRegOperands";
569 Classes.push_back(RegClass);
571 // Build info for the user defined assembly operand classes.
572 std::vector<Record*> AsmOperands;
573 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
575 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
576 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
577 ClassInfo *CI = new ClassInfo();
578 CI->Kind = ClassInfo::UserClass0 + Index;
580 Init *Super = (*it)->getValueInit("SuperClass");
581 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
582 CI->SuperClass = AsmOperandClasses[DI->getDef()];
584 PrintError((*it)->getLoc(), "Invalid super class reference!");
586 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
589 CI->ClassName = (*it)->getValueAsString("Name");
590 CI->Name = "MCK_" + CI->ClassName;
591 CI->ValueName = (*it)->getName();
593 // Get or construct the predicate method name.
594 Init *PMName = (*it)->getValueInit("PredicateMethod");
595 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
596 CI->PredicateMethod = SI->getValue();
598 assert(dynamic_cast<UnsetInit*>(PMName) &&
599 "Unexpected PredicateMethod field!");
600 CI->PredicateMethod = "is" + CI->ClassName;
603 // Get or construct the render method name.
604 Init *RMName = (*it)->getValueInit("RenderMethod");
605 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
606 CI->RenderMethod = SI->getValue();
608 assert(dynamic_cast<UnsetInit*>(RMName) &&
609 "Unexpected RenderMethod field!");
610 CI->RenderMethod = "add" + CI->ClassName + "Operands";
613 AsmOperandClasses[*it] = CI;
614 Classes.push_back(CI);
617 // Build the instruction information.
618 for (std::map<std::string, CodeGenInstruction>::const_iterator
619 it = Target.getInstructions().begin(),
620 ie = Target.getInstructions().end();
622 const CodeGenInstruction &CGI = it->second;
624 if (!StringRef(it->first).startswith(MatchPrefix))
627 OwningPtr<InstructionInfo> II(new InstructionInfo);
629 II->InstrName = it->first;
630 II->Instr = &it->second;
631 II->AsmString = FlattenVariants(CGI.AsmString, 0);
633 TokenizeAsmString(II->AsmString, II->Tokens);
635 // Ignore instructions which shouldn't be matched.
636 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
639 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
640 StringRef Token = II->Tokens[i];
642 // Check for simple tokens.
643 if (Token[0] != '$') {
644 InstructionInfo::Operand Op;
645 Op.Class = getTokenClass(Token);
647 II->Operands.push_back(Op);
651 // Otherwise this is an operand reference.
652 StringRef OperandName;
654 OperandName = Token.substr(2, Token.size() - 3);
656 OperandName = Token.substr(1);
658 // Map this token to an operand. FIXME: Move elsewhere.
661 Idx = CGI.getOperandNamed(OperandName);
663 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
667 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
668 InstructionInfo::Operand Op;
669 Op.Class = getOperandClass(Token, OI);
670 Op.OperandInfo = &OI;
671 II->Operands.push_back(Op);
674 // If we broke out, ignore the instruction.
675 if (II->Operands.size() != II->Tokens.size())
678 Instructions.push_back(II.take());
681 // Reorder classes so that classes preceed super classes.
682 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
685 static void EmitConvertToMCInst(CodeGenTarget &Target,
686 std::vector<InstructionInfo*> &Infos,
688 // Write the convert function to a separate stream, so we can drop it after
690 std::string ConvertFnBody;
691 raw_string_ostream CvtOS(ConvertFnBody);
693 // Function we have already generated.
694 std::set<std::string> GeneratedFns;
696 // Start the unified conversion function.
698 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
699 << "unsigned Opcode,\n"
700 << " SmallVectorImpl<"
701 << Target.getName() << "Operand> &Operands) {\n";
702 CvtOS << " Inst.setOpcode(Opcode);\n";
703 CvtOS << " switch (Kind) {\n";
704 CvtOS << " default:\n";
706 // Start the enum, which we will generate inline.
708 OS << "// Unified function for converting operants to MCInst instances.\n\n";
709 OS << "enum ConversionKind {\n";
711 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
712 ie = Infos.end(); it != ie; ++it) {
713 InstructionInfo &II = **it;
715 // Order the (class) operands by the order to convert them into an MCInst.
716 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
717 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
718 InstructionInfo::Operand &Op = II.Operands[i];
720 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
722 std::sort(MIOperandList.begin(), MIOperandList.end());
724 // Compute the total number of operands.
725 unsigned NumMIOperands = 0;
726 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
727 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
728 NumMIOperands = std::max(NumMIOperands,
729 OI.MIOperandNo + OI.MINumOperands);
732 // Build the conversion function signature.
733 std::string Signature = "Convert";
734 unsigned CurIndex = 0;
735 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
736 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
737 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
738 "Duplicate match for instruction operand!");
742 // Skip operands which weren't matched by anything, this occurs when the
743 // .td file encodes "implicit" operands as explicit ones.
745 // FIXME: This should be removed from the MCInst structure.
746 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
749 Signature += Op.Class->ClassName;
750 Signature += utostr(Op.OperandInfo->MINumOperands);
751 Signature += "_" + utostr(MIOperandList[i].second);
753 CurIndex += Op.OperandInfo->MINumOperands;
756 // Add any trailing implicit operands.
757 for (; CurIndex != NumMIOperands; ++CurIndex)
760 II.ConversionFnKind = Signature;
762 // Check if we have already generated this signature.
763 if (!GeneratedFns.insert(Signature).second)
766 // If not, emit it now.
768 // Add to the enum list.
769 OS << " " << Signature << ",\n";
771 // And to the convert function.
772 CvtOS << " case " << Signature << ":\n";
774 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
775 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
777 // Add the implicit operands.
778 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
779 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
781 CvtOS << " Operands[" << MIOperandList[i].second
782 << "]." << Op.Class->RenderMethod
783 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
784 CurIndex += Op.OperandInfo->MINumOperands;
787 // And add trailing implicit operands.
788 for (; CurIndex != NumMIOperands; ++CurIndex)
789 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
790 CvtOS << " break;\n";
793 // Finish the convert function.
796 CvtOS << " return false;\n";
799 // Finish the enum, and drop the convert function after it.
801 OS << " NumConversionVariants\n";
807 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
808 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
809 std::vector<ClassInfo*> &Infos,
811 OS << "namespace {\n\n";
813 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
814 << "/// instruction matching.\n";
815 OS << "enum MatchClassKind {\n";
816 OS << " InvalidMatchClass = 0,\n";
817 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
818 ie = Infos.end(); it != ie; ++it) {
819 ClassInfo &CI = **it;
820 OS << " " << CI.Name << ", // ";
821 if (CI.Kind == ClassInfo::Token) {
822 OS << "'" << CI.ValueName << "'\n";
823 } else if (CI.Kind == ClassInfo::Register) {
824 if (!CI.ValueName.empty())
825 OS << "register class '" << CI.ValueName << "'\n";
827 OS << "derived register class\n";
829 OS << "user defined class '" << CI.ValueName << "'\n";
832 OS << " NumMatchClassKinds\n";
838 /// EmitClassifyOperand - Emit the function to classify an operand.
839 static void EmitClassifyOperand(CodeGenTarget &Target,
840 std::vector<ClassInfo*> &Infos,
842 OS << "static MatchClassKind ClassifyOperand("
843 << Target.getName() << "Operand &Operand) {\n";
844 OS << " if (Operand.isToken())\n";
845 OS << " return MatchTokenString(Operand.getToken());\n\n";
846 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
847 ie = Infos.end(); it != ie; ++it) {
848 ClassInfo &CI = **it;
850 if (CI.Kind != ClassInfo::Token) {
851 OS << " // '" << CI.ClassName << "' class";
853 OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
854 assert(CI < *CI.SuperClass && "Invalid class relation!");
858 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
860 // Validate subclass relationships.
862 OS << " assert(Operand." << CI.SuperClass->PredicateMethod
863 << "() && \"Invalid class relationship!\");\n";
865 OS << " return " << CI.Name << ";\n";
869 OS << " return InvalidMatchClass;\n";
873 /// EmitIsSubclass - Emit the subclass predicate function.
874 static void EmitIsSubclass(CodeGenTarget &Target,
875 std::vector<ClassInfo*> &Infos,
877 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
878 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
879 OS << " if (A == B)\n";
880 OS << " return true;\n\n";
882 OS << " switch (A) {\n";
884 OS << " return false;\n";
885 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
886 ie = Infos.end(); it != ie; ++it) {
889 if (A.Kind != ClassInfo::Token) {
890 std::vector<StringRef> SuperClasses;
891 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
892 ie = Infos.end(); it != ie; ++it) {
895 if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
896 SuperClasses.push_back(B.Name);
899 if (SuperClasses.empty())
902 OS << "\n case " << A.Name << ":\n";
904 if (SuperClasses.size() == 1) {
905 OS << " return B == " << SuperClasses.back() << ";\n\n";
909 OS << " switch (B) {\n";
910 OS << " default: return false;\n";
911 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
912 OS << " case " << SuperClasses[i] << ": return true;\n";
920 typedef std::pair<std::string, std::string> StringPair;
922 /// FindFirstNonCommonLetter - Find the first character in the keys of the
923 /// string pairs that is not shared across the whole set of strings. All
924 /// strings are assumed to have the same length.
926 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
927 assert(!Matches.empty());
928 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
929 // Check to see if letter i is the same across the set.
930 char Letter = Matches[0]->first[i];
932 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
933 if (Matches[str]->first[i] != Letter)
937 return Matches[0]->first.size();
940 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
941 /// same length and whose characters leading up to CharNo are the same, emit
942 /// code to verify that CharNo and later are the same.
944 /// \return - True if control can leave the emitted code fragment.
945 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
946 const std::vector<const StringPair*> &Matches,
947 unsigned CharNo, unsigned IndentCount,
949 assert(!Matches.empty() && "Must have at least one string to match!");
950 std::string Indent(IndentCount*2+4, ' ');
952 // If we have verified that the entire string matches, we're done: output the
954 if (CharNo == Matches[0]->first.size()) {
955 assert(Matches.size() == 1 && "Had duplicate keys to match on");
957 // FIXME: If Matches[0].first has embeded \n, this will be bad.
958 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
963 // Bucket the matches by the character we are comparing.
964 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
966 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
967 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
970 // If we have exactly one bucket to match, see how many characters are common
971 // across the whole set and match all of them at once.
972 if (MatchesByLetter.size() == 1) {
973 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
974 unsigned NumChars = FirstNonCommonLetter-CharNo;
976 // Emit code to break out if the prefix doesn't match.
978 // Do the comparison with if (Str[1] != 'f')
979 // FIXME: Need to escape general characters.
980 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
981 << Matches[0]->first[CharNo] << "')\n";
982 OS << Indent << " break;\n";
984 // Do the comparison with if (Str.substr(1,3) != "foo").
985 // FIXME: Need to escape general strings.
986 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
987 << NumChars << ") != \"";
988 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
989 OS << Indent << " break;\n";
992 return EmitStringMatcherForChar(StrVariableName, Matches,
993 FirstNonCommonLetter, IndentCount, OS);
996 // Otherwise, we have multiple possible things, emit a switch on the
998 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
999 OS << Indent << "default: break;\n";
1001 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1002 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1003 // TODO: escape hard stuff (like \n) if we ever care about it.
1004 OS << Indent << "case '" << LI->first << "':\t // "
1005 << LI->second.size() << " strings to match.\n";
1006 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1008 OS << Indent << " break;\n";
1011 OS << Indent << "}\n";
1016 /// EmitStringMatcher - Given a list of strings and code to execute when they
1017 /// match, output a simple switch tree to classify the input string.
1019 /// If a match is found, the code in Vals[i].second is executed; control must
1020 /// not exit this code fragment. If nothing matches, execution falls through.
1022 /// \param StrVariableName - The name of the variable to test.
1023 static void EmitStringMatcher(const std::string &StrVariableName,
1024 const std::vector<StringPair> &Matches,
1026 // First level categorization: group strings by length.
1027 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1029 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1030 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1032 // Output a switch statement on length and categorize the elements within each
1034 OS << " switch (" << StrVariableName << ".size()) {\n";
1035 OS << " default: break;\n";
1037 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1038 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1039 OS << " case " << LI->first << ":\t // " << LI->second.size()
1040 << " strings to match.\n";
1041 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1049 /// EmitMatchTokenString - Emit the function to match a token string to the
1050 /// appropriate match class value.
1051 static void EmitMatchTokenString(CodeGenTarget &Target,
1052 std::vector<ClassInfo*> &Infos,
1054 // Construct the match list.
1055 std::vector<StringPair> Matches;
1056 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1057 ie = Infos.end(); it != ie; ++it) {
1058 ClassInfo &CI = **it;
1060 if (CI.Kind == ClassInfo::Token)
1061 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1064 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1066 EmitStringMatcher("Name", Matches, OS);
1068 OS << " return InvalidMatchClass;\n";
1072 /// EmitMatchRegisterName - Emit the function to match a string to the target
1073 /// specific register enum.
1074 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1076 // Construct the match list.
1077 std::vector<StringPair> Matches;
1078 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1079 const CodeGenRegister &Reg = Target.getRegisters()[i];
1080 if (Reg.TheDef->getValueAsString("AsmName").empty())
1083 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1084 "return " + utostr(i + 1) + ";"));
1087 OS << "unsigned " << Target.getName()
1088 << AsmParser->getValueAsString("AsmParserClassName")
1089 << "::MatchRegisterName(const StringRef &Name) {\n";
1091 EmitStringMatcher("Name", Matches, OS);
1093 OS << " return 0;\n";
1097 void AsmMatcherEmitter::run(raw_ostream &OS) {
1098 CodeGenTarget Target;
1099 Record *AsmParser = Target.getAsmParser();
1100 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1102 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1104 // Emit the function to match a register name to number.
1105 EmitMatchRegisterName(Target, AsmParser, OS);
1107 // Compute the information on the instructions to match.
1108 AsmMatcherInfo Info;
1109 Info.BuildInfo(Target);
1111 // Sort the instruction table using the partial order on classes.
1112 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1113 less_ptr<InstructionInfo>());
1115 DEBUG_WITH_TYPE("instruction_info", {
1116 for (std::vector<InstructionInfo*>::iterator
1117 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1122 // Check for ambiguous instructions.
1123 unsigned NumAmbiguous = 0;
1124 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1125 for (unsigned j = i + 1; j != e; ++j) {
1126 InstructionInfo &A = *Info.Instructions[i];
1127 InstructionInfo &B = *Info.Instructions[j];
1129 if (A.CouldMatchAmiguouslyWith(B)) {
1130 DEBUG_WITH_TYPE("ambiguous_instrs", {
1131 errs() << "warning: ambiguous instruction match:\n";
1133 errs() << "\nis incomparable with:\n";
1142 DEBUG_WITH_TYPE("ambiguous_instrs", {
1143 errs() << "warning: " << NumAmbiguous
1144 << " ambiguous instructions!\n";
1147 // Generate the unified function to convert operands into an MCInst.
1148 EmitConvertToMCInst(Target, Info.Instructions, OS);
1150 // Emit the enumeration for classes which participate in matching.
1151 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1153 // Emit the routine to match token strings to their match class.
1154 EmitMatchTokenString(Target, Info.Classes, OS);
1156 // Emit the routine to classify an operand.
1157 EmitClassifyOperand(Target, Info.Classes, OS);
1159 // Emit the subclass predicate routine.
1160 EmitIsSubclass(Target, Info.Classes, OS);
1162 // Finally, build the match function.
1164 size_t MaxNumOperands = 0;
1165 for (std::vector<InstructionInfo*>::const_iterator it =
1166 Info.Instructions.begin(), ie = Info.Instructions.end();
1168 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1170 OS << "bool " << Target.getName() << ClassName
1171 << "::MatchInstruction("
1172 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1173 << "MCInst &Inst) {\n";
1175 // Emit the static match table; unused classes get initalized to 0 which is
1176 // guaranteed to be InvalidMatchClass.
1178 // FIXME: We can reduce the size of this table very easily. First, we change
1179 // it so that store the kinds in separate bit-fields for each index, which
1180 // only needs to be the max width used for classes at that index (we also need
1181 // to reject based on this during classification). If we then make sure to
1182 // order the match kinds appropriately (putting mnemonics last), then we
1183 // should only end up using a few bits for each class, especially the ones
1184 // following the mnemonic.
1185 OS << " static const struct MatchEntry {\n";
1186 OS << " unsigned Opcode;\n";
1187 OS << " ConversionKind ConvertFn;\n";
1188 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1189 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1191 for (std::vector<InstructionInfo*>::const_iterator it =
1192 Info.Instructions.begin(), ie = Info.Instructions.end();
1194 InstructionInfo &II = **it;
1196 OS << " { " << Target.getName() << "::" << II.InstrName
1197 << ", " << II.ConversionFnKind << ", { ";
1198 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1199 InstructionInfo::Operand &Op = II.Operands[i];
1202 OS << Op.Class->Name;
1209 // Emit code to compute the class list for this operand vector.
1210 OS << " // Eliminate obvious mismatches.\n";
1211 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1212 OS << " return true;\n\n";
1214 OS << " // Compute the class list for this operand vector.\n";
1215 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1216 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1217 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1219 OS << " // Check for invalid operands before matching.\n";
1220 OS << " if (Classes[i] == InvalidMatchClass)\n";
1221 OS << " return true;\n";
1224 OS << " // Mark unused classes.\n";
1225 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1226 << "i != e; ++i)\n";
1227 OS << " Classes[i] = InvalidMatchClass;\n\n";
1229 // Emit code to search the table.
1230 OS << " // Search the table.\n";
1231 OS << " for (const MatchEntry *it = MatchTable, "
1232 << "*ie = MatchTable + " << Info.Instructions.size()
1233 << "; it != ie; ++it) {\n";
1234 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1235 OS << " if (!IsSubclass(Classes["
1236 << i << "], it->Classes[" << i << "]))\n";
1237 OS << " continue;\n";
1240 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1241 << "it->Opcode, Operands);\n";
1244 OS << " return true;\n";