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 "StringMatcher.h"
80 #include "llvm/ADT/OwningPtr.h"
81 #include "llvm/ADT/SmallPtrSet.h"
82 #include "llvm/ADT/SmallVector.h"
83 #include "llvm/ADT/STLExtras.h"
84 #include "llvm/ADT/StringExtras.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
92 static cl::opt<std::string>
93 MatchPrefix("match-prefix", cl::init(""),
94 cl::desc("Only match instructions with the given prefix"));
96 /// TokenizeAsmString - Tokenize a simplified assembly string.
97 static void TokenizeAsmString(StringRef AsmString,
98 SmallVectorImpl<StringRef> &Tokens) {
101 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
102 switch (AsmString[i]) {
111 Tokens.push_back(AsmString.slice(Prev, i));
114 if (!isspace(AsmString[i]) && AsmString[i] != ',')
115 Tokens.push_back(AsmString.substr(i, 1));
121 Tokens.push_back(AsmString.slice(Prev, i));
125 assert(i != AsmString.size() && "Invalid quoted character");
126 Tokens.push_back(AsmString.substr(i, 1));
131 // If this isn't "${", treat like a normal token.
132 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
134 Tokens.push_back(AsmString.slice(Prev, i));
142 Tokens.push_back(AsmString.slice(Prev, i));
146 StringRef::iterator End =
147 std::find(AsmString.begin() + i, AsmString.end(), '}');
148 assert(End != AsmString.end() && "Missing brace in operand reference!");
149 size_t EndPos = End - AsmString.begin();
150 Tokens.push_back(AsmString.slice(i, EndPos+1));
158 Tokens.push_back(AsmString.slice(Prev, i));
168 if (InTok && Prev != AsmString.size())
169 Tokens.push_back(AsmString.substr(Prev));
174 class AsmMatcherInfo;
175 struct SubtargetFeatureInfo;
177 /// ClassInfo - Helper class for storing the information about a particular
178 /// class of operands which can be matched.
181 /// Invalid kind, for use as a sentinel value.
184 /// The class for a particular token.
187 /// The (first) register class, subsequent register classes are
188 /// RegisterClass0+1, and so on.
191 /// The (first) user defined class, subsequent user defined classes are
192 /// UserClass0+1, and so on.
196 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
197 /// N) for the Nth user defined class.
200 /// SuperClasses - The super classes of this class. Note that for simplicities
201 /// sake user operands only record their immediate super class, while register
202 /// operands include all superclasses.
203 std::vector<ClassInfo*> SuperClasses;
205 /// Name - The full class name, suitable for use in an enum.
208 /// ClassName - The unadorned generic name for this class (e.g., Token).
209 std::string ClassName;
211 /// ValueName - The name of the value this class represents; for a token this
212 /// is the literal token string, for an operand it is the TableGen class (or
213 /// empty if this is a derived class).
214 std::string ValueName;
216 /// PredicateMethod - The name of the operand method to test whether the
217 /// operand matches this class; this is not valid for Token or register kinds.
218 std::string PredicateMethod;
220 /// RenderMethod - The name of the operand method to add this operand to an
221 /// MCInst; this is not valid for Token or register kinds.
222 std::string RenderMethod;
224 /// For register classes, the records for all the registers in this class.
225 std::set<Record*> Registers;
228 /// isRegisterClass() - Check if this is a register class.
229 bool isRegisterClass() const {
230 return Kind >= RegisterClass0 && Kind < UserClass0;
233 /// isUserClass() - Check if this is a user defined class.
234 bool isUserClass() const {
235 return Kind >= UserClass0;
238 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
239 /// are related if they are in the same class hierarchy.
240 bool isRelatedTo(const ClassInfo &RHS) const {
241 // Tokens are only related to tokens.
242 if (Kind == Token || RHS.Kind == Token)
243 return Kind == Token && RHS.Kind == Token;
245 // Registers classes are only related to registers classes, and only if
246 // their intersection is non-empty.
247 if (isRegisterClass() || RHS.isRegisterClass()) {
248 if (!isRegisterClass() || !RHS.isRegisterClass())
251 std::set<Record*> Tmp;
252 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
253 std::set_intersection(Registers.begin(), Registers.end(),
254 RHS.Registers.begin(), RHS.Registers.end(),
260 // Otherwise we have two users operands; they are related if they are in the
261 // same class hierarchy.
263 // FIXME: This is an oversimplification, they should only be related if they
264 // intersect, however we don't have that information.
265 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
266 const ClassInfo *Root = this;
267 while (!Root->SuperClasses.empty())
268 Root = Root->SuperClasses.front();
270 const ClassInfo *RHSRoot = &RHS;
271 while (!RHSRoot->SuperClasses.empty())
272 RHSRoot = RHSRoot->SuperClasses.front();
274 return Root == RHSRoot;
277 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
278 bool isSubsetOf(const ClassInfo &RHS) const {
279 // This is a subset of RHS if it is the same class...
283 // ... or if any of its super classes are a subset of RHS.
284 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
285 ie = SuperClasses.end(); it != ie; ++it)
286 if ((*it)->isSubsetOf(RHS))
292 /// operator< - Compare two classes.
293 bool operator<(const ClassInfo &RHS) const {
297 // Unrelated classes can be ordered by kind.
298 if (!isRelatedTo(RHS))
299 return Kind < RHS.Kind;
303 assert(0 && "Invalid kind!");
305 // Tokens are comparable by value.
307 // FIXME: Compare by enum value.
308 return ValueName < RHS.ValueName;
311 // This class preceeds the RHS if it is a proper subset of the RHS.
314 if (RHS.isSubsetOf(*this))
317 // Otherwise, order by name to ensure we have a total ordering.
318 return ValueName < RHS.ValueName;
323 /// MatchableInfo - Helper class for storing the necessary information for an
324 /// instruction or alias which is capable of being matched.
325 struct MatchableInfo {
327 /// The unique class instance this operand should match.
330 /// The original operand this corresponds to, if any.
331 const CGIOperandList::OperandInfo *OperandInfo;
333 Operand(ClassInfo *C, const CGIOperandList::OperandInfo *OpInfo)
334 : Class(C), OperandInfo(OpInfo) {}
337 /// InstrName - The target name for this instruction.
338 std::string InstrName;
340 Record *const TheDef;
341 const CGIOperandList &OperandList;
343 /// AsmString - The assembly string for this instruction (with variants
345 std::string AsmString;
347 /// Tokens - The tokenized assembly pattern that this instruction matches.
348 SmallVector<StringRef, 4> Tokens;
350 /// AsmOperands - The textual operands that this instruction matches,
351 /// including literal tokens for the mnemonic, etc.
352 SmallVector<Operand, 4> AsmOperands;
354 /// Predicates - The required subtarget features to match this instruction.
355 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
357 /// ConversionFnKind - The enum value which is passed to the generated
358 /// ConvertToMCInst to convert parsed operands into an MCInst for this
360 std::string ConversionFnKind;
362 MatchableInfo(const CodeGenInstruction &CGI)
363 : TheDef(CGI.TheDef), OperandList(CGI.Operands), AsmString(CGI.AsmString) {
364 InstrName = TheDef->getName();
367 MatchableInfo(const CodeGenInstAlias *Alias)
368 : TheDef(Alias->TheDef), OperandList(Alias->Operands),
369 AsmString(Alias->AsmString) {
372 DefInit *DI = dynamic_cast<DefInit*>(Alias->Result->getOperator());
375 InstrName = DI->getDef()->getName();
378 void Initialize(const AsmMatcherInfo &Info,
379 SmallPtrSet<Record*, 16> &SingletonRegisters);
381 /// Validate - Return true if this matchable is a valid thing to match against
382 /// and perform a bunch of validity checking.
383 bool Validate(StringRef CommentDelimiter, bool Hack) const;
385 /// getSingletonRegisterForToken - If the specified token is a singleton
386 /// register, return the Record for it, otherwise return null.
387 Record *getSingletonRegisterForToken(unsigned i,
388 const AsmMatcherInfo &Info) const;
390 /// operator< - Compare two matchables.
391 bool operator<(const MatchableInfo &RHS) const {
392 // The primary comparator is the instruction mnemonic.
393 if (Tokens[0] != RHS.Tokens[0])
394 return Tokens[0] < RHS.Tokens[0];
396 if (AsmOperands.size() != RHS.AsmOperands.size())
397 return AsmOperands.size() < RHS.AsmOperands.size();
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 = AsmOperands.size(); i != e; ++i) {
402 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
404 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
411 /// CouldMatchAmiguouslyWith - Check whether this matchable could
412 /// ambiguously match the same set of operands as \arg RHS (without being a
413 /// strictly superior match).
414 bool CouldMatchAmiguouslyWith(const MatchableInfo &RHS) {
415 // The primary comparator is the instruction mnemonic.
416 if (Tokens[0] != RHS.Tokens[0])
419 // The number of operands is unambiguous.
420 if (AsmOperands.size() != RHS.AsmOperands.size())
423 // Otherwise, make sure the ordering of the two instructions is unambiguous
424 // by checking that either (a) a token or operand kind discriminates them,
425 // or (b) the ordering among equivalent kinds is consistent.
427 // Tokens and operand kinds are unambiguous (assuming a correct target
429 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
430 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
431 AsmOperands[i].Class->Kind == ClassInfo::Token)
432 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
433 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
436 // Otherwise, this operand could commute if all operands are equivalent, or
437 // there is a pair of operands that compare less than and a pair that
438 // compare greater than.
439 bool HasLT = false, HasGT = false;
440 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
441 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
443 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
447 return !(HasLT ^ HasGT);
453 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
454 /// feature which participates in instruction matching.
455 struct SubtargetFeatureInfo {
456 /// \brief The predicate record for this feature.
459 /// \brief An unique index assigned to represent this feature.
462 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
464 /// \brief The name of the enumerated constant identifying this feature.
465 std::string getEnumName() const {
466 return "Feature_" + TheDef->getName();
470 class AsmMatcherInfo {
472 /// The tablegen AsmParser record.
475 /// Target - The target information.
476 CodeGenTarget &Target;
478 /// The AsmParser "RegisterPrefix" value.
479 std::string RegisterPrefix;
481 /// The classes which are needed for matching.
482 std::vector<ClassInfo*> Classes;
484 /// The information on the matchables to match.
485 std::vector<MatchableInfo*> Matchables;
487 /// Map of Register records to their class information.
488 std::map<Record*, ClassInfo*> RegisterClasses;
490 /// Map of Predicate records to their subtarget information.
491 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
494 /// Map of token to class information which has already been constructed.
495 std::map<std::string, ClassInfo*> TokenClasses;
497 /// Map of RegisterClass records to their class information.
498 std::map<Record*, ClassInfo*> RegisterClassClasses;
500 /// Map of AsmOperandClass records to their class information.
501 std::map<Record*, ClassInfo*> AsmOperandClasses;
504 /// getTokenClass - Lookup or create the class for the given token.
505 ClassInfo *getTokenClass(StringRef Token);
507 /// getOperandClass - Lookup or create the class for the given operand.
508 ClassInfo *getOperandClass(StringRef Token,
509 const CGIOperandList::OperandInfo &OI);
511 /// BuildRegisterClasses - Build the ClassInfo* instances for register
513 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
515 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
517 void BuildOperandClasses();
520 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
522 /// BuildInfo - Construct the various tables used during matching.
525 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
527 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
528 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
529 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
530 SubtargetFeatures.find(Def);
531 return I == SubtargetFeatures.end() ? 0 : I->second;
537 void MatchableInfo::dump() {
538 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
540 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
547 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
548 Operand &Op = AsmOperands[i];
549 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
550 if (Op.Class->Kind == ClassInfo::Token) {
551 errs() << '\"' << Tokens[i] << "\"\n";
555 if (!Op.OperandInfo) {
556 errs() << "(singleton register)\n";
560 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo;
561 errs() << OI.Name << " " << OI.Rec->getName()
562 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
566 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
567 SmallPtrSet<Record*, 16> &SingletonRegisters) {
568 // TODO: Eventually support asmparser for Variant != 0.
569 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
571 TokenizeAsmString(AsmString, Tokens);
573 // Compute the require features.
574 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
575 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
576 if (SubtargetFeatureInfo *Feature =
577 Info.getSubtargetFeature(Predicates[i]))
578 RequiredFeatures.push_back(Feature);
580 // Collect singleton registers, if used.
581 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
582 if (Record *Reg = getSingletonRegisterForToken(i, Info))
583 SingletonRegisters.insert(Reg);
588 /// getRegisterRecord - Get the register record for \arg name, or 0.
589 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
590 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
591 const CodeGenRegister &Reg = Target.getRegisters()[i];
592 if (Name == Reg.TheDef->getValueAsString("AsmName"))
599 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
600 // Reject matchables with no .s string.
601 if (AsmString.empty())
602 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
604 // Reject any matchables with a newline in them, they should be marked
605 // isCodeGenOnly if they are pseudo instructions.
606 if (AsmString.find('\n') != std::string::npos)
607 throw TGError(TheDef->getLoc(),
608 "multiline instruction is not valid for the asmparser, "
609 "mark it isCodeGenOnly");
611 // Remove comments from the asm string. We know that the asmstring only
613 if (!CommentDelimiter.empty() &&
614 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
615 throw TGError(TheDef->getLoc(),
616 "asmstring for instruction has comment character in it, "
617 "mark it isCodeGenOnly");
619 // Reject matchables with operand modifiers, these aren't something we can
620 /// handle, the target should be refactored to use operands instead of
623 // Also, check for instructions which reference the operand multiple times;
624 // this implies a constraint we would not honor.
625 std::set<std::string> OperandNames;
626 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
627 if (Tokens[i][0] == '$' && Tokens[i].find(':') != StringRef::npos)
628 throw TGError(TheDef->getLoc(),
629 "matchable with operand modifier '" + Tokens[i].str() +
630 "' not supported by asm matcher. Mark isCodeGenOnly!");
632 // Verify that any operand is only mentioned once.
633 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
635 throw TGError(TheDef->getLoc(),
636 "ERROR: matchable with tied operand '" + Tokens[i].str() +
637 "' can never be matched!");
638 // FIXME: Should reject these. The ARM backend hits this with $lane in a
639 // bunch of instructions. It is unclear what the right answer is.
641 errs() << "warning: '" << InstrName << "': "
642 << "ignoring instruction with tied operand '"
643 << Tokens[i].str() << "'\n";
653 /// getSingletonRegisterForToken - If the specified token is a singleton
654 /// register, return the register name, otherwise return a null StringRef.
655 Record *MatchableInfo::
656 getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
657 StringRef Tok = Tokens[i];
658 if (!Tok.startswith(Info.RegisterPrefix))
661 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
662 if (Record *Rec = getRegisterRecord(Info.Target, RegName))
665 // If there is no register prefix (i.e. "%" in "%eax"), then this may
666 // be some random non-register token, just ignore it.
667 if (Info.RegisterPrefix.empty())
670 std::string Err = "unable to find register for '" + RegName.str() +
671 "' (which matches register prefix)";
672 throw TGError(TheDef->getLoc(), Err);
676 static std::string getEnumNameForToken(StringRef Str) {
679 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
681 case '*': Res += "_STAR_"; break;
682 case '%': Res += "_PCT_"; break;
683 case ':': Res += "_COLON_"; break;
688 Res += "_" + utostr((unsigned) *it) + "_";
695 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
696 ClassInfo *&Entry = TokenClasses[Token];
699 Entry = new ClassInfo();
700 Entry->Kind = ClassInfo::Token;
701 Entry->ClassName = "Token";
702 Entry->Name = "MCK_" + getEnumNameForToken(Token);
703 Entry->ValueName = Token;
704 Entry->PredicateMethod = "<invalid>";
705 Entry->RenderMethod = "<invalid>";
706 Classes.push_back(Entry);
713 AsmMatcherInfo::getOperandClass(StringRef Token,
714 const CGIOperandList::OperandInfo &OI) {
715 if (OI.Rec->isSubClassOf("RegisterClass")) {
716 ClassInfo *CI = RegisterClassClasses[OI.Rec];
719 throw TGError(OI.Rec->getLoc(), "register class has no class info!");
724 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
725 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
726 ClassInfo *CI = AsmOperandClasses[MatchClass];
729 throw TGError(OI.Rec->getLoc(), "operand has no match class!");
734 void AsmMatcherInfo::
735 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
736 std::vector<CodeGenRegisterClass> RegisterClasses;
737 std::vector<CodeGenRegister> Registers;
739 RegisterClasses = Target.getRegisterClasses();
740 Registers = Target.getRegisters();
742 // The register sets used for matching.
743 std::set< std::set<Record*> > RegisterSets;
745 // Gather the defined sets.
746 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
747 ie = RegisterClasses.end(); it != ie; ++it)
748 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
749 it->Elements.end()));
751 // Add any required singleton sets.
752 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
753 ie = SingletonRegisters.end(); it != ie; ++it) {
755 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
758 // Introduce derived sets where necessary (when a register does not determine
759 // a unique register set class), and build the mapping of registers to the set
760 // they should classify to.
761 std::map<Record*, std::set<Record*> > RegisterMap;
762 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
763 ie = Registers.end(); it != ie; ++it) {
764 CodeGenRegister &CGR = *it;
765 // Compute the intersection of all sets containing this register.
766 std::set<Record*> ContainingSet;
768 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
769 ie = RegisterSets.end(); it != ie; ++it) {
770 if (!it->count(CGR.TheDef))
773 if (ContainingSet.empty()) {
776 std::set<Record*> Tmp;
777 std::swap(Tmp, ContainingSet);
778 std::insert_iterator< std::set<Record*> > II(ContainingSet,
779 ContainingSet.begin());
780 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
785 if (!ContainingSet.empty()) {
786 RegisterSets.insert(ContainingSet);
787 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
791 // Construct the register classes.
792 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
794 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
795 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
796 ClassInfo *CI = new ClassInfo();
797 CI->Kind = ClassInfo::RegisterClass0 + Index;
798 CI->ClassName = "Reg" + utostr(Index);
799 CI->Name = "MCK_Reg" + utostr(Index);
801 CI->PredicateMethod = ""; // unused
802 CI->RenderMethod = "addRegOperands";
804 Classes.push_back(CI);
805 RegisterSetClasses.insert(std::make_pair(*it, CI));
808 // Find the superclasses; we could compute only the subgroup lattice edges,
809 // but there isn't really a point.
810 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
811 ie = RegisterSets.end(); it != ie; ++it) {
812 ClassInfo *CI = RegisterSetClasses[*it];
813 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
814 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
816 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
817 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
820 // Name the register classes which correspond to a user defined RegisterClass.
821 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
822 ie = RegisterClasses.end(); it != ie; ++it) {
823 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
824 it->Elements.end())];
825 if (CI->ValueName.empty()) {
826 CI->ClassName = it->getName();
827 CI->Name = "MCK_" + it->getName();
828 CI->ValueName = it->getName();
830 CI->ValueName = CI->ValueName + "," + it->getName();
832 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
835 // Populate the map for individual registers.
836 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
837 ie = RegisterMap.end(); it != ie; ++it)
838 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
840 // Name the register classes which correspond to singleton registers.
841 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
842 ie = SingletonRegisters.end(); it != ie; ++it) {
844 ClassInfo *CI = this->RegisterClasses[Rec];
845 assert(CI && "Missing singleton register class info!");
847 if (CI->ValueName.empty()) {
848 CI->ClassName = Rec->getName();
849 CI->Name = "MCK_" + Rec->getName();
850 CI->ValueName = Rec->getName();
852 CI->ValueName = CI->ValueName + "," + Rec->getName();
856 void AsmMatcherInfo::BuildOperandClasses() {
857 std::vector<Record*> AsmOperands =
858 Records.getAllDerivedDefinitions("AsmOperandClass");
860 // Pre-populate AsmOperandClasses map.
861 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
862 ie = AsmOperands.end(); it != ie; ++it)
863 AsmOperandClasses[*it] = new ClassInfo();
866 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
867 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
868 ClassInfo *CI = AsmOperandClasses[*it];
869 CI->Kind = ClassInfo::UserClass0 + Index;
871 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
872 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
873 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
875 PrintError((*it)->getLoc(), "Invalid super class reference!");
879 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
881 PrintError((*it)->getLoc(), "Invalid super class reference!");
883 CI->SuperClasses.push_back(SC);
885 CI->ClassName = (*it)->getValueAsString("Name");
886 CI->Name = "MCK_" + CI->ClassName;
887 CI->ValueName = (*it)->getName();
889 // Get or construct the predicate method name.
890 Init *PMName = (*it)->getValueInit("PredicateMethod");
891 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
892 CI->PredicateMethod = SI->getValue();
894 assert(dynamic_cast<UnsetInit*>(PMName) &&
895 "Unexpected PredicateMethod field!");
896 CI->PredicateMethod = "is" + CI->ClassName;
899 // Get or construct the render method name.
900 Init *RMName = (*it)->getValueInit("RenderMethod");
901 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
902 CI->RenderMethod = SI->getValue();
904 assert(dynamic_cast<UnsetInit*>(RMName) &&
905 "Unexpected RenderMethod field!");
906 CI->RenderMethod = "add" + CI->ClassName + "Operands";
909 AsmOperandClasses[*it] = CI;
910 Classes.push_back(CI);
914 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
915 : AsmParser(asmParser), Target(target),
916 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
920 void AsmMatcherInfo::BuildInfo() {
921 // Build information about all of the AssemblerPredicates.
922 std::vector<Record*> AllPredicates =
923 Records.getAllDerivedDefinitions("Predicate");
924 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
925 Record *Pred = AllPredicates[i];
926 // Ignore predicates that are not intended for the assembler.
927 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
930 if (Pred->getName().empty())
931 throw TGError(Pred->getLoc(), "Predicate has no name!");
933 unsigned FeatureNo = SubtargetFeatures.size();
934 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
935 assert(FeatureNo < 32 && "Too many subtarget features!");
938 StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
940 // Parse the instructions; we need to do this first so that we can gather the
941 // singleton register classes.
942 SmallPtrSet<Record*, 16> SingletonRegisters;
943 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
944 E = Target.inst_end(); I != E; ++I) {
945 const CodeGenInstruction &CGI = **I;
947 // If the tblgen -match-prefix option is specified (for tblgen hackers),
948 // filter the set of instructions we consider.
949 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
952 // Ignore "codegen only" instructions.
953 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
956 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
958 II->Initialize(*this, SingletonRegisters);
960 // Ignore instructions which shouldn't be matched and diagnose invalid
961 // instruction definitions with an error.
962 if (!II->Validate(CommentDelimiter, true))
965 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
967 // FIXME: This is a total hack.
968 if (StringRef(II->InstrName).startswith("Int_") ||
969 StringRef(II->InstrName).endswith("_Int"))
972 Matchables.push_back(II.take());
975 // Parse all of the InstAlias definitions and stick them in the list of
977 std::vector<Record*> AllInstAliases =
978 Records.getAllDerivedDefinitions("InstAlias");
979 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
980 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i]);
982 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
984 II->Initialize(*this, SingletonRegisters);
986 // Validate the alias definitions.
987 II->Validate(CommentDelimiter, false);
989 Matchables.push_back(II.take());
992 // Build info for the register classes.
993 BuildRegisterClasses(SingletonRegisters);
995 // Build info for the user defined assembly operand classes.
996 BuildOperandClasses();
998 // Build the information about matchables.
999 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1000 ie = Matchables.end(); it != ie; ++it) {
1001 MatchableInfo *II = *it;
1003 // The first token of the instruction is the mnemonic, which must be a
1004 // simple string, not a $foo variable or a singleton register.
1005 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1006 StringRef Mnemonic = II->Tokens[0];
1007 if (Mnemonic[0] == '$' || II->getSingletonRegisterForToken(0, *this))
1008 throw TGError(II->TheDef->getLoc(),
1009 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
1011 // Parse the tokens after the mnemonic.
1012 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1013 StringRef Token = II->Tokens[i];
1015 // Check for singleton registers.
1016 if (Record *RegRecord = II->getSingletonRegisterForToken(i, *this)) {
1017 MatchableInfo::Operand Op(RegisterClasses[RegRecord], 0);
1018 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1019 "Unexpected class for singleton register");
1020 II->AsmOperands.push_back(Op);
1024 // Check for simple tokens.
1025 if (Token[0] != '$') {
1026 II->AsmOperands.push_back(MatchableInfo::Operand(getTokenClass(Token),
1031 // Otherwise this is an operand reference.
1032 StringRef OperandName;
1033 if (Token[1] == '{')
1034 OperandName = Token.substr(2, Token.size() - 3);
1036 OperandName = Token.substr(1);
1038 // Map this token to an operand. FIXME: Move elsewhere.
1040 if (!II->OperandList.hasOperandNamed(OperandName, Idx))
1041 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1042 OperandName.str() + "'");
1044 // FIXME: This is annoying, the named operand may be tied (e.g.,
1045 // XCHG8rm). What we want is the untied operand, which we now have to
1046 // grovel for. Only worry about this for single entry operands, we have to
1047 // clean this up anyway.
1048 const CGIOperandList::OperandInfo *OI = &II->OperandList[Idx];
1049 if (OI->Constraints[0].isTied()) {
1050 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1052 // The tied operand index is an MIOperand index, find the operand that
1054 for (unsigned i = 0, e = II->OperandList.size(); i != e; ++i) {
1055 if (II->OperandList[i].MIOperandNo == TiedOp) {
1056 OI = &II->OperandList[i];
1061 assert(OI && "Unable to find tied operand target!");
1064 II->AsmOperands.push_back(MatchableInfo::Operand(getOperandClass(Token,
1069 // Reorder classes so that classes preceed super classes.
1070 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1073 static std::pair<unsigned, unsigned> *
1074 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1076 for (unsigned i = 0, e = List.size(); i != e; ++i)
1077 if (Index == List[i].first)
1083 static void EmitConvertToMCInst(CodeGenTarget &Target,
1084 std::vector<MatchableInfo*> &Infos,
1086 // Write the convert function to a separate stream, so we can drop it after
1088 std::string ConvertFnBody;
1089 raw_string_ostream CvtOS(ConvertFnBody);
1091 // Function we have already generated.
1092 std::set<std::string> GeneratedFns;
1094 // Start the unified conversion function.
1096 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1097 << "unsigned Opcode,\n"
1098 << " const SmallVectorImpl<MCParsedAsmOperand*"
1099 << "> &Operands) {\n";
1100 CvtOS << " Inst.setOpcode(Opcode);\n";
1101 CvtOS << " switch (Kind) {\n";
1102 CvtOS << " default:\n";
1104 // Start the enum, which we will generate inline.
1106 OS << "// Unified function for converting operants to MCInst instances.\n\n";
1107 OS << "enum ConversionKind {\n";
1109 // TargetOperandClass - This is the target's operand class, like X86Operand.
1110 std::string TargetOperandClass = Target.getName() + "Operand";
1112 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1113 ie = Infos.end(); it != ie; ++it) {
1114 MatchableInfo &II = **it;
1116 // Order the (class) operands by the order to convert them into an MCInst.
1117 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1118 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1119 MatchableInfo::Operand &Op = II.AsmOperands[i];
1121 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1124 // Find any tied operands.
1125 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1126 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1127 const CGIOperandList::OperandInfo &OpInfo = II.OperandList[i];
1128 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1129 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j];
1131 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1132 CI.getTiedOperand()));
1136 array_pod_sort(MIOperandList.begin(), MIOperandList.end());
1138 // Compute the total number of operands.
1139 unsigned NumMIOperands = 0;
1140 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1141 const CGIOperandList::OperandInfo &OI = II.OperandList[i];
1142 NumMIOperands = std::max(NumMIOperands,
1143 OI.MIOperandNo + OI.MINumOperands);
1146 // Build the conversion function signature.
1147 std::string Signature = "Convert";
1148 unsigned CurIndex = 0;
1149 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1150 MatchableInfo::Operand &Op = II.AsmOperands[MIOperandList[i].second];
1151 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1152 "Duplicate match for instruction operand!");
1154 // Skip operands which weren't matched by anything, this occurs when the
1155 // .td file encodes "implicit" operands as explicit ones.
1157 // FIXME: This should be removed from the MCInst structure.
1158 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1159 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1162 Signature += "__Imp";
1164 Signature += "__Tie" + utostr(Tie->second);
1169 // Registers are always converted the same, don't duplicate the conversion
1170 // function based on them.
1172 // FIXME: We could generalize this based on the render method, if it
1174 if (Op.Class->isRegisterClass())
1177 Signature += Op.Class->ClassName;
1178 Signature += utostr(Op.OperandInfo->MINumOperands);
1179 Signature += "_" + utostr(MIOperandList[i].second);
1181 CurIndex += Op.OperandInfo->MINumOperands;
1184 // Add any trailing implicit operands.
1185 for (; CurIndex != NumMIOperands; ++CurIndex) {
1186 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1189 Signature += "__Imp";
1191 Signature += "__Tie" + utostr(Tie->second);
1194 II.ConversionFnKind = Signature;
1196 // Check if we have already generated this signature.
1197 if (!GeneratedFns.insert(Signature).second)
1200 // If not, emit it now.
1202 // Add to the enum list.
1203 OS << " " << Signature << ",\n";
1205 // And to the convert function.
1206 CvtOS << " case " << Signature << ":\n";
1208 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1209 MatchableInfo::Operand &Op = II.AsmOperands[MIOperandList[i].second];
1211 // Add the implicit operands.
1212 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1213 // See if this is a tied operand.
1214 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1218 // If not, this is some implicit operand. Just assume it is a register
1220 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1222 // Copy the tied operand.
1223 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1224 CvtOS << " Inst.addOperand(Inst.getOperand("
1225 << Tie->second << "));\n";
1229 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1230 << MIOperandList[i].second
1231 << "+1])->" << Op.Class->RenderMethod
1232 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1233 CurIndex += Op.OperandInfo->MINumOperands;
1236 // And add trailing implicit operands.
1237 for (; CurIndex != NumMIOperands; ++CurIndex) {
1238 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1242 // If not, this is some implicit operand. Just assume it is a register
1244 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1246 // Copy the tied operand.
1247 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1248 CvtOS << " Inst.addOperand(Inst.getOperand("
1249 << Tie->second << "));\n";
1253 CvtOS << " return;\n";
1256 // Finish the convert function.
1261 // Finish the enum, and drop the convert function after it.
1263 OS << " NumConversionVariants\n";
1269 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1270 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1271 std::vector<ClassInfo*> &Infos,
1273 OS << "namespace {\n\n";
1275 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1276 << "/// instruction matching.\n";
1277 OS << "enum MatchClassKind {\n";
1278 OS << " InvalidMatchClass = 0,\n";
1279 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1280 ie = Infos.end(); it != ie; ++it) {
1281 ClassInfo &CI = **it;
1282 OS << " " << CI.Name << ", // ";
1283 if (CI.Kind == ClassInfo::Token) {
1284 OS << "'" << CI.ValueName << "'\n";
1285 } else if (CI.isRegisterClass()) {
1286 if (!CI.ValueName.empty())
1287 OS << "register class '" << CI.ValueName << "'\n";
1289 OS << "derived register class\n";
1291 OS << "user defined class '" << CI.ValueName << "'\n";
1294 OS << " NumMatchClassKinds\n";
1300 /// EmitClassifyOperand - Emit the function to classify an operand.
1301 static void EmitClassifyOperand(AsmMatcherInfo &Info,
1303 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1304 << " " << Info.Target.getName() << "Operand &Operand = *("
1305 << Info.Target.getName() << "Operand*)GOp;\n";
1308 OS << " if (Operand.isToken())\n";
1309 OS << " return MatchTokenString(Operand.getToken());\n\n";
1311 // Classify registers.
1313 // FIXME: Don't hardcode isReg, getReg.
1314 OS << " if (Operand.isReg()) {\n";
1315 OS << " switch (Operand.getReg()) {\n";
1316 OS << " default: return InvalidMatchClass;\n";
1317 for (std::map<Record*, ClassInfo*>::iterator
1318 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1320 OS << " case " << Info.Target.getName() << "::"
1321 << it->first->getName() << ": return " << it->second->Name << ";\n";
1325 // Classify user defined operands.
1326 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1327 ie = Info.Classes.end(); it != ie; ++it) {
1328 ClassInfo &CI = **it;
1330 if (!CI.isUserClass())
1333 OS << " // '" << CI.ClassName << "' class";
1334 if (!CI.SuperClasses.empty()) {
1335 OS << ", subclass of ";
1336 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1338 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1339 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1344 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1346 // Validate subclass relationships.
1347 if (!CI.SuperClasses.empty()) {
1348 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1349 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1350 << "() && \"Invalid class relationship!\");\n";
1353 OS << " return " << CI.Name << ";\n";
1356 OS << " return InvalidMatchClass;\n";
1360 /// EmitIsSubclass - Emit the subclass predicate function.
1361 static void EmitIsSubclass(CodeGenTarget &Target,
1362 std::vector<ClassInfo*> &Infos,
1364 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1365 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1366 OS << " if (A == B)\n";
1367 OS << " return true;\n\n";
1369 OS << " switch (A) {\n";
1370 OS << " default:\n";
1371 OS << " return false;\n";
1372 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1373 ie = Infos.end(); it != ie; ++it) {
1374 ClassInfo &A = **it;
1376 if (A.Kind != ClassInfo::Token) {
1377 std::vector<StringRef> SuperClasses;
1378 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1379 ie = Infos.end(); it != ie; ++it) {
1380 ClassInfo &B = **it;
1382 if (&A != &B && A.isSubsetOf(B))
1383 SuperClasses.push_back(B.Name);
1386 if (SuperClasses.empty())
1389 OS << "\n case " << A.Name << ":\n";
1391 if (SuperClasses.size() == 1) {
1392 OS << " return B == " << SuperClasses.back() << ";\n";
1396 OS << " switch (B) {\n";
1397 OS << " default: return false;\n";
1398 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1399 OS << " case " << SuperClasses[i] << ": return true;\n";
1409 /// EmitMatchTokenString - Emit the function to match a token string to the
1410 /// appropriate match class value.
1411 static void EmitMatchTokenString(CodeGenTarget &Target,
1412 std::vector<ClassInfo*> &Infos,
1414 // Construct the match list.
1415 std::vector<StringMatcher::StringPair> Matches;
1416 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1417 ie = Infos.end(); it != ie; ++it) {
1418 ClassInfo &CI = **it;
1420 if (CI.Kind == ClassInfo::Token)
1421 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1422 "return " + CI.Name + ";"));
1425 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1427 StringMatcher("Name", Matches, OS).Emit();
1429 OS << " return InvalidMatchClass;\n";
1433 /// EmitMatchRegisterName - Emit the function to match a string to the target
1434 /// specific register enum.
1435 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1437 // Construct the match list.
1438 std::vector<StringMatcher::StringPair> Matches;
1439 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1440 const CodeGenRegister &Reg = Target.getRegisters()[i];
1441 if (Reg.TheDef->getValueAsString("AsmName").empty())
1444 Matches.push_back(StringMatcher::StringPair(
1445 Reg.TheDef->getValueAsString("AsmName"),
1446 "return " + utostr(i + 1) + ";"));
1449 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1451 StringMatcher("Name", Matches, OS).Emit();
1453 OS << " return 0;\n";
1457 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1459 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1461 OS << "// Flags for subtarget features that participate in "
1462 << "instruction matching.\n";
1463 OS << "enum SubtargetFeatureFlag {\n";
1464 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1465 it = Info.SubtargetFeatures.begin(),
1466 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1467 SubtargetFeatureInfo &SFI = *it->second;
1468 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1470 OS << " Feature_None = 0\n";
1474 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1475 /// available features given a subtarget.
1476 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1478 std::string ClassName =
1479 Info.AsmParser->getValueAsString("AsmParserClassName");
1481 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1482 << "ComputeAvailableFeatures(const " << Info.Target.getName()
1483 << "Subtarget *Subtarget) const {\n";
1484 OS << " unsigned Features = 0;\n";
1485 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1486 it = Info.SubtargetFeatures.begin(),
1487 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1488 SubtargetFeatureInfo &SFI = *it->second;
1489 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1491 OS << " Features |= " << SFI.getEnumName() << ";\n";
1493 OS << " return Features;\n";
1497 static std::string GetAliasRequiredFeatures(Record *R,
1498 const AsmMatcherInfo &Info) {
1499 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1501 unsigned NumFeatures = 0;
1502 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1503 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1506 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1507 "' is not marked as an AssemblerPredicate!");
1512 Result += F->getEnumName();
1516 if (NumFeatures > 1)
1517 Result = '(' + Result + ')';
1521 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1522 /// emit a function for them and return true, otherwise return false.
1523 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1524 std::vector<Record*> Aliases =
1525 Records.getAllDerivedDefinitions("MnemonicAlias");
1526 if (Aliases.empty()) return false;
1528 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1529 "unsigned Features) {\n";
1531 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1532 // iteration order of the map is stable.
1533 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1535 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1536 Record *R = Aliases[i];
1537 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1540 // Process each alias a "from" mnemonic at a time, building the code executed
1541 // by the string remapper.
1542 std::vector<StringMatcher::StringPair> Cases;
1543 for (std::map<std::string, std::vector<Record*> >::iterator
1544 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1546 const std::vector<Record*> &ToVec = I->second;
1548 // Loop through each alias and emit code that handles each case. If there
1549 // are two instructions without predicates, emit an error. If there is one,
1551 std::string MatchCode;
1552 int AliasWithNoPredicate = -1;
1554 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1555 Record *R = ToVec[i];
1556 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1558 // If this unconditionally matches, remember it for later and diagnose
1560 if (FeatureMask.empty()) {
1561 if (AliasWithNoPredicate != -1) {
1562 // We can't have two aliases from the same mnemonic with no predicate.
1563 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1564 "two MnemonicAliases with the same 'from' mnemonic!");
1565 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1568 AliasWithNoPredicate = i;
1572 if (!MatchCode.empty())
1573 MatchCode += "else ";
1574 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1575 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1578 if (AliasWithNoPredicate != -1) {
1579 Record *R = ToVec[AliasWithNoPredicate];
1580 if (!MatchCode.empty())
1581 MatchCode += "else\n ";
1582 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1585 MatchCode += "return;";
1587 Cases.push_back(std::make_pair(I->first, MatchCode));
1591 StringMatcher("Mnemonic", Cases, OS).Emit();
1597 void AsmMatcherEmitter::run(raw_ostream &OS) {
1598 CodeGenTarget Target;
1599 Record *AsmParser = Target.getAsmParser();
1600 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1602 // Compute the information on the instructions to match.
1603 AsmMatcherInfo Info(AsmParser, Target);
1606 // Sort the instruction table using the partial order on classes. We use
1607 // stable_sort to ensure that ambiguous instructions are still
1608 // deterministically ordered.
1609 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
1610 less_ptr<MatchableInfo>());
1612 DEBUG_WITH_TYPE("instruction_info", {
1613 for (std::vector<MatchableInfo*>::iterator
1614 it = Info.Matchables.begin(), ie = Info.Matchables.end();
1619 // Check for ambiguous matchables.
1620 DEBUG_WITH_TYPE("ambiguous_instrs", {
1621 unsigned NumAmbiguous = 0;
1622 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
1623 for (unsigned j = i + 1; j != e; ++j) {
1624 MatchableInfo &A = *Info.Matchables[i];
1625 MatchableInfo &B = *Info.Matchables[j];
1627 if (A.CouldMatchAmiguouslyWith(B)) {
1628 errs() << "warning: ambiguous matchables:\n";
1630 errs() << "\nis incomparable with:\n";
1638 errs() << "warning: " << NumAmbiguous
1639 << " ambiguous matchables!\n";
1642 // Write the output.
1644 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1646 // Information for the class declaration.
1647 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1648 OS << "#undef GET_ASSEMBLER_HEADER\n";
1649 OS << " // This should be included into the middle of the declaration of \n";
1650 OS << " // your subclasses implementation of TargetAsmParser.\n";
1651 OS << " unsigned ComputeAvailableFeatures(const " <<
1652 Target.getName() << "Subtarget *Subtarget) const;\n";
1653 OS << " enum MatchResultTy {\n";
1654 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1655 OS << " Match_MissingFeature\n";
1657 OS << " MatchResultTy MatchInstructionImpl(const "
1658 << "SmallVectorImpl<MCParsedAsmOperand*>"
1659 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1660 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1665 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1666 OS << "#undef GET_REGISTER_MATCHER\n\n";
1668 // Emit the subtarget feature enumeration.
1669 EmitSubtargetFeatureFlagEnumeration(Info, OS);
1671 // Emit the function to match a register name to number.
1672 EmitMatchRegisterName(Target, AsmParser, OS);
1674 OS << "#endif // GET_REGISTER_MATCHER\n\n";
1677 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1678 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1680 // Generate the function that remaps for mnemonic aliases.
1681 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1683 // Generate the unified function to convert operands into an MCInst.
1684 EmitConvertToMCInst(Target, Info.Matchables, OS);
1686 // Emit the enumeration for classes which participate in matching.
1687 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1689 // Emit the routine to match token strings to their match class.
1690 EmitMatchTokenString(Target, Info.Classes, OS);
1692 // Emit the routine to classify an operand.
1693 EmitClassifyOperand(Info, OS);
1695 // Emit the subclass predicate routine.
1696 EmitIsSubclass(Target, Info.Classes, OS);
1698 // Emit the available features compute function.
1699 EmitComputeAvailableFeatures(Info, OS);
1702 size_t MaxNumOperands = 0;
1703 for (std::vector<MatchableInfo*>::const_iterator it =
1704 Info.Matchables.begin(), ie = Info.Matchables.end();
1706 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
1709 // Emit the static match table; unused classes get initalized to 0 which is
1710 // guaranteed to be InvalidMatchClass.
1712 // FIXME: We can reduce the size of this table very easily. First, we change
1713 // it so that store the kinds in separate bit-fields for each index, which
1714 // only needs to be the max width used for classes at that index (we also need
1715 // to reject based on this during classification). If we then make sure to
1716 // order the match kinds appropriately (putting mnemonics last), then we
1717 // should only end up using a few bits for each class, especially the ones
1718 // following the mnemonic.
1719 OS << "namespace {\n";
1720 OS << " struct MatchEntry {\n";
1721 OS << " unsigned Opcode;\n";
1722 OS << " const char *Mnemonic;\n";
1723 OS << " ConversionKind ConvertFn;\n";
1724 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1725 OS << " unsigned RequiredFeatures;\n";
1728 OS << "// Predicate for searching for an opcode.\n";
1729 OS << " struct LessOpcode {\n";
1730 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1731 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1733 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1734 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1736 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1737 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1741 OS << "} // end anonymous namespace.\n\n";
1743 OS << "static const MatchEntry MatchTable["
1744 << Info.Matchables.size() << "] = {\n";
1746 for (std::vector<MatchableInfo*>::const_iterator it =
1747 Info.Matchables.begin(), ie = Info.Matchables.end();
1749 MatchableInfo &II = **it;
1751 OS << " { " << Target.getName() << "::" << II.InstrName
1752 << ", \"" << II.Tokens[0] << "\""
1753 << ", " << II.ConversionFnKind << ", { ";
1754 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1755 MatchableInfo::Operand &Op = II.AsmOperands[i];
1758 OS << Op.Class->Name;
1762 // Write the required features mask.
1763 if (!II.RequiredFeatures.empty()) {
1764 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1766 OS << II.RequiredFeatures[i]->getEnumName();
1776 // Finally, build the match function.
1777 OS << Target.getName() << ClassName << "::MatchResultTy "
1778 << Target.getName() << ClassName << "::\n"
1779 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1781 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
1783 // Emit code to get the available features.
1784 OS << " // Get the current feature set.\n";
1785 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1787 OS << " // Get the instruction mnemonic, which is the first token.\n";
1788 OS << " StringRef Mnemonic = ((" << Target.getName()
1789 << "Operand*)Operands[0])->getToken();\n\n";
1791 if (HasMnemonicAliases) {
1792 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1793 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1796 // Emit code to compute the class list for this operand vector.
1797 OS << " // Eliminate obvious mismatches.\n";
1798 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1799 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1800 OS << " return Match_InvalidOperand;\n";
1803 OS << " // Compute the class list for this operand vector.\n";
1804 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1805 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1806 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1808 OS << " // Check for invalid operands before matching.\n";
1809 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1810 OS << " ErrorInfo = i;\n";
1811 OS << " return Match_InvalidOperand;\n";
1815 OS << " // Mark unused classes.\n";
1816 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1817 << "i != e; ++i)\n";
1818 OS << " Classes[i] = InvalidMatchClass;\n\n";
1820 OS << " // Some state to try to produce better error messages.\n";
1821 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
1822 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1823 OS << " // wrong for all instances of the instruction.\n";
1824 OS << " ErrorInfo = ~0U;\n";
1826 // Emit code to search the table.
1827 OS << " // Search the table.\n";
1828 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1829 OS << " std::equal_range(MatchTable, MatchTable+"
1830 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
1832 OS << " // Return a more specific error code if no mnemonics match.\n";
1833 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1834 OS << " return Match_MnemonicFail;\n\n";
1836 OS << " for (const MatchEntry *it = MnemonicRange.first, "
1837 << "*ie = MnemonicRange.second;\n";
1838 OS << " it != ie; ++it) {\n";
1840 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
1841 OS << " assert(Mnemonic == it->Mnemonic);\n";
1843 // Emit check that the subclasses match.
1844 OS << " bool OperandsValid = true;\n";
1845 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1846 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1847 OS << " continue;\n";
1848 OS << " // If this operand is broken for all of the instances of this\n";
1849 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1850 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1851 OS << " ErrorInfo = i+1;\n";
1853 OS << " ErrorInfo = ~0U;";
1854 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1855 OS << " OperandsValid = false;\n";
1859 OS << " if (!OperandsValid) continue;\n";
1861 // Emit check that the required features are available.
1862 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1863 << "!= it->RequiredFeatures) {\n";
1864 OS << " HadMatchOtherThanFeatures = true;\n";
1865 OS << " continue;\n";
1869 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1871 // Call the post-processing function, if used.
1872 std::string InsnCleanupFn =
1873 AsmParser->getValueAsString("AsmParserInstCleanup");
1874 if (!InsnCleanupFn.empty())
1875 OS << " " << InsnCleanupFn << "(Inst);\n";
1877 OS << " return Match_Success;\n";
1880 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1881 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1882 OS << " return Match_InvalidOperand;\n";
1885 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";