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 /// Operands - The operands that this instruction matches.
351 SmallVector<Operand, 4> Operands;
353 /// Predicates - The required subtarget features to match this instruction.
354 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
356 /// ConversionFnKind - The enum value which is passed to the generated
357 /// ConvertToMCInst to convert parsed operands into an MCInst for this
359 std::string ConversionFnKind;
361 MatchableInfo(const CodeGenInstruction &CGI)
362 : TheDef(CGI.TheDef), OperandList(CGI.Operands), AsmString(CGI.AsmString) {
363 InstrName = TheDef->getName();
366 MatchableInfo(const CodeGenInstAlias *Alias)
367 : TheDef(Alias->TheDef), OperandList(Alias->Operands),
368 AsmString(Alias->AsmString) {
371 DefInit *DI = dynamic_cast<DefInit*>(Alias->Result->getOperator());
374 InstrName = DI->getDef()->getName();
377 void Initialize(const AsmMatcherInfo &Info,
378 SmallPtrSet<Record*, 16> &SingletonRegisters);
380 /// Validate - Return true if this matchable is a valid thing to match against
381 /// and perform a bunch of validity checking.
382 bool Validate(StringRef CommentDelimiter, bool Hack) const;
384 /// getSingletonRegisterForToken - If the specified token is a singleton
385 /// register, return the Record for it, otherwise return null.
386 Record *getSingletonRegisterForToken(unsigned i,
387 const AsmMatcherInfo &Info) const;
389 /// operator< - Compare two matchables.
390 bool operator<(const MatchableInfo &RHS) const {
391 // The primary comparator is the instruction mnemonic.
392 if (Tokens[0] != RHS.Tokens[0])
393 return Tokens[0] < RHS.Tokens[0];
395 if (Operands.size() != RHS.Operands.size())
396 return Operands.size() < RHS.Operands.size();
398 // Compare lexicographically by operand. The matcher validates that other
399 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
400 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
401 if (*Operands[i].Class < *RHS.Operands[i].Class)
403 if (*RHS.Operands[i].Class < *Operands[i].Class)
410 /// CouldMatchAmiguouslyWith - Check whether this matchable could
411 /// ambiguously match the same set of operands as \arg RHS (without being a
412 /// strictly superior match).
413 bool CouldMatchAmiguouslyWith(const MatchableInfo &RHS) {
414 // The number of operands is unambiguous.
415 if (Operands.size() != RHS.Operands.size())
418 // Otherwise, make sure the ordering of the two instructions is unambiguous
419 // by checking that either (a) a token or operand kind discriminates them,
420 // or (b) the ordering among equivalent kinds is consistent.
422 // Tokens and operand kinds are unambiguous (assuming a correct target
424 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
425 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
426 Operands[i].Class->Kind == ClassInfo::Token)
427 if (*Operands[i].Class < *RHS.Operands[i].Class ||
428 *RHS.Operands[i].Class < *Operands[i].Class)
431 // Otherwise, this operand could commute if all operands are equivalent, or
432 // there is a pair of operands that compare less than and a pair that
433 // compare greater than.
434 bool HasLT = false, HasGT = false;
435 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
436 if (*Operands[i].Class < *RHS.Operands[i].Class)
438 if (*RHS.Operands[i].Class < *Operands[i].Class)
442 return !(HasLT ^ HasGT);
448 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
449 /// feature which participates in instruction matching.
450 struct SubtargetFeatureInfo {
451 /// \brief The predicate record for this feature.
454 /// \brief An unique index assigned to represent this feature.
457 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
459 /// \brief The name of the enumerated constant identifying this feature.
460 std::string getEnumName() const {
461 return "Feature_" + TheDef->getName();
465 class AsmMatcherInfo {
467 /// The tablegen AsmParser record.
470 /// Target - The target information.
471 CodeGenTarget &Target;
473 /// The AsmParser "RegisterPrefix" value.
474 std::string RegisterPrefix;
476 /// The classes which are needed for matching.
477 std::vector<ClassInfo*> Classes;
479 /// The information on the matchables to match.
480 std::vector<MatchableInfo*> Matchables;
482 /// Map of Register records to their class information.
483 std::map<Record*, ClassInfo*> RegisterClasses;
485 /// Map of Predicate records to their subtarget information.
486 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
489 /// Map of token to class information which has already been constructed.
490 std::map<std::string, ClassInfo*> TokenClasses;
492 /// Map of RegisterClass records to their class information.
493 std::map<Record*, ClassInfo*> RegisterClassClasses;
495 /// Map of AsmOperandClass records to their class information.
496 std::map<Record*, ClassInfo*> AsmOperandClasses;
499 /// getTokenClass - Lookup or create the class for the given token.
500 ClassInfo *getTokenClass(StringRef Token);
502 /// getOperandClass - Lookup or create the class for the given operand.
503 ClassInfo *getOperandClass(StringRef Token,
504 const CGIOperandList::OperandInfo &OI);
506 /// BuildRegisterClasses - Build the ClassInfo* instances for register
508 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
510 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
512 void BuildOperandClasses();
515 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
517 /// BuildInfo - Construct the various tables used during matching.
520 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
522 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
523 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
524 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
525 SubtargetFeatures.find(Def);
526 return I == SubtargetFeatures.end() ? 0 : I->second;
532 void MatchableInfo::dump() {
533 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
535 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
542 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
543 Operand &Op = Operands[i];
544 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
545 if (Op.Class->Kind == ClassInfo::Token) {
546 errs() << '\"' << Tokens[i] << "\"\n";
550 if (!Op.OperandInfo) {
551 errs() << "(singleton register)\n";
555 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo;
556 errs() << OI.Name << " " << OI.Rec->getName()
557 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
561 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
562 SmallPtrSet<Record*, 16> &SingletonRegisters) {
563 // TODO: Eventually support asmparser for Variant != 0.
564 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
566 TokenizeAsmString(AsmString, Tokens);
568 // Compute the require features.
569 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
570 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
571 if (SubtargetFeatureInfo *Feature =
572 Info.getSubtargetFeature(Predicates[i]))
573 RequiredFeatures.push_back(Feature);
575 // Collect singleton registers, if used.
576 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
577 if (Record *Reg = getSingletonRegisterForToken(i, Info))
578 SingletonRegisters.insert(Reg);
583 /// getRegisterRecord - Get the register record for \arg name, or 0.
584 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
585 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
586 const CodeGenRegister &Reg = Target.getRegisters()[i];
587 if (Name == Reg.TheDef->getValueAsString("AsmName"))
594 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
595 // Reject matchables with no .s string.
596 if (AsmString.empty())
597 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
599 // Reject any matchables with a newline in them, they should be marked
600 // isCodeGenOnly if they are pseudo instructions.
601 if (AsmString.find('\n') != std::string::npos)
602 throw TGError(TheDef->getLoc(),
603 "multiline instruction is not valid for the asmparser, "
604 "mark it isCodeGenOnly");
606 // Remove comments from the asm string. We know that the asmstring only
608 if (!CommentDelimiter.empty() &&
609 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
610 throw TGError(TheDef->getLoc(),
611 "asmstring for instruction has comment character in it, "
612 "mark it isCodeGenOnly");
614 // Reject matchables with operand modifiers, these aren't something we can
615 /// handle, the target should be refactored to use operands instead of
618 // Also, check for instructions which reference the operand multiple times;
619 // this implies a constraint we would not honor.
620 std::set<std::string> OperandNames;
621 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
622 if (Tokens[i][0] == '$' && Tokens[i].find(':') != StringRef::npos)
623 throw TGError(TheDef->getLoc(),
624 "matchable with operand modifier '" + Tokens[i].str() +
625 "' not supported by asm matcher. Mark isCodeGenOnly!");
627 // Verify that any operand is only mentioned once.
628 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
630 throw TGError(TheDef->getLoc(),
631 "ERROR: matchable with tied operand '" + Tokens[i].str() +
632 "' can never be matched!");
633 // FIXME: Should reject these. The ARM backend hits this with $lane in a
634 // bunch of instructions. It is unclear what the right answer is.
636 errs() << "warning: '" << InstrName << "': "
637 << "ignoring instruction with tied operand '"
638 << Tokens[i].str() << "'\n";
648 /// getSingletonRegisterForToken - If the specified token is a singleton
649 /// register, return the register name, otherwise return a null StringRef.
650 Record *MatchableInfo::
651 getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
652 StringRef Tok = Tokens[i];
653 if (!Tok.startswith(Info.RegisterPrefix))
656 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
657 if (Record *Rec = getRegisterRecord(Info.Target, RegName))
660 // If there is no register prefix (i.e. "%" in "%eax"), then this may
661 // be some random non-register token, just ignore it.
662 if (Info.RegisterPrefix.empty())
665 std::string Err = "unable to find register for '" + RegName.str() +
666 "' (which matches register prefix)";
667 throw TGError(TheDef->getLoc(), Err);
671 static std::string getEnumNameForToken(StringRef Str) {
674 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
676 case '*': Res += "_STAR_"; break;
677 case '%': Res += "_PCT_"; break;
678 case ':': Res += "_COLON_"; break;
683 Res += "_" + utostr((unsigned) *it) + "_";
690 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
691 ClassInfo *&Entry = TokenClasses[Token];
694 Entry = new ClassInfo();
695 Entry->Kind = ClassInfo::Token;
696 Entry->ClassName = "Token";
697 Entry->Name = "MCK_" + getEnumNameForToken(Token);
698 Entry->ValueName = Token;
699 Entry->PredicateMethod = "<invalid>";
700 Entry->RenderMethod = "<invalid>";
701 Classes.push_back(Entry);
708 AsmMatcherInfo::getOperandClass(StringRef Token,
709 const CGIOperandList::OperandInfo &OI) {
710 if (OI.Rec->isSubClassOf("RegisterClass")) {
711 ClassInfo *CI = RegisterClassClasses[OI.Rec];
714 throw TGError(OI.Rec->getLoc(), "register class has no class info!");
719 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
720 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
721 ClassInfo *CI = AsmOperandClasses[MatchClass];
724 throw TGError(OI.Rec->getLoc(), "operand has no match class!");
729 void AsmMatcherInfo::
730 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
731 std::vector<CodeGenRegisterClass> RegisterClasses;
732 std::vector<CodeGenRegister> Registers;
734 RegisterClasses = Target.getRegisterClasses();
735 Registers = Target.getRegisters();
737 // The register sets used for matching.
738 std::set< std::set<Record*> > RegisterSets;
740 // Gather the defined sets.
741 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
742 ie = RegisterClasses.end(); it != ie; ++it)
743 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
744 it->Elements.end()));
746 // Add any required singleton sets.
747 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
748 ie = SingletonRegisters.end(); it != ie; ++it) {
750 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
753 // Introduce derived sets where necessary (when a register does not determine
754 // a unique register set class), and build the mapping of registers to the set
755 // they should classify to.
756 std::map<Record*, std::set<Record*> > RegisterMap;
757 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
758 ie = Registers.end(); it != ie; ++it) {
759 CodeGenRegister &CGR = *it;
760 // Compute the intersection of all sets containing this register.
761 std::set<Record*> ContainingSet;
763 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
764 ie = RegisterSets.end(); it != ie; ++it) {
765 if (!it->count(CGR.TheDef))
768 if (ContainingSet.empty()) {
771 std::set<Record*> Tmp;
772 std::swap(Tmp, ContainingSet);
773 std::insert_iterator< std::set<Record*> > II(ContainingSet,
774 ContainingSet.begin());
775 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
780 if (!ContainingSet.empty()) {
781 RegisterSets.insert(ContainingSet);
782 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
786 // Construct the register classes.
787 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
789 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
790 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
791 ClassInfo *CI = new ClassInfo();
792 CI->Kind = ClassInfo::RegisterClass0 + Index;
793 CI->ClassName = "Reg" + utostr(Index);
794 CI->Name = "MCK_Reg" + utostr(Index);
796 CI->PredicateMethod = ""; // unused
797 CI->RenderMethod = "addRegOperands";
799 Classes.push_back(CI);
800 RegisterSetClasses.insert(std::make_pair(*it, CI));
803 // Find the superclasses; we could compute only the subgroup lattice edges,
804 // but there isn't really a point.
805 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
806 ie = RegisterSets.end(); it != ie; ++it) {
807 ClassInfo *CI = RegisterSetClasses[*it];
808 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
809 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
811 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
812 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
815 // Name the register classes which correspond to a user defined RegisterClass.
816 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
817 ie = RegisterClasses.end(); it != ie; ++it) {
818 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
819 it->Elements.end())];
820 if (CI->ValueName.empty()) {
821 CI->ClassName = it->getName();
822 CI->Name = "MCK_" + it->getName();
823 CI->ValueName = it->getName();
825 CI->ValueName = CI->ValueName + "," + it->getName();
827 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
830 // Populate the map for individual registers.
831 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
832 ie = RegisterMap.end(); it != ie; ++it)
833 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
835 // Name the register classes which correspond to singleton registers.
836 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
837 ie = SingletonRegisters.end(); it != ie; ++it) {
839 ClassInfo *CI = this->RegisterClasses[Rec];
840 assert(CI && "Missing singleton register class info!");
842 if (CI->ValueName.empty()) {
843 CI->ClassName = Rec->getName();
844 CI->Name = "MCK_" + Rec->getName();
845 CI->ValueName = Rec->getName();
847 CI->ValueName = CI->ValueName + "," + Rec->getName();
851 void AsmMatcherInfo::BuildOperandClasses() {
852 std::vector<Record*> AsmOperands;
853 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
855 // Pre-populate AsmOperandClasses map.
856 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
857 ie = AsmOperands.end(); it != ie; ++it)
858 AsmOperandClasses[*it] = new ClassInfo();
861 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
862 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
863 ClassInfo *CI = AsmOperandClasses[*it];
864 CI->Kind = ClassInfo::UserClass0 + Index;
866 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
867 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
868 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
870 PrintError((*it)->getLoc(), "Invalid super class reference!");
874 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
876 PrintError((*it)->getLoc(), "Invalid super class reference!");
878 CI->SuperClasses.push_back(SC);
880 CI->ClassName = (*it)->getValueAsString("Name");
881 CI->Name = "MCK_" + CI->ClassName;
882 CI->ValueName = (*it)->getName();
884 // Get or construct the predicate method name.
885 Init *PMName = (*it)->getValueInit("PredicateMethod");
886 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
887 CI->PredicateMethod = SI->getValue();
889 assert(dynamic_cast<UnsetInit*>(PMName) &&
890 "Unexpected PredicateMethod field!");
891 CI->PredicateMethod = "is" + CI->ClassName;
894 // Get or construct the render method name.
895 Init *RMName = (*it)->getValueInit("RenderMethod");
896 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
897 CI->RenderMethod = SI->getValue();
899 assert(dynamic_cast<UnsetInit*>(RMName) &&
900 "Unexpected RenderMethod field!");
901 CI->RenderMethod = "add" + CI->ClassName + "Operands";
904 AsmOperandClasses[*it] = CI;
905 Classes.push_back(CI);
909 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
910 : AsmParser(asmParser), Target(target),
911 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
915 void AsmMatcherInfo::BuildInfo() {
916 // Build information about all of the AssemblerPredicates.
917 std::vector<Record*> AllPredicates =
918 Records.getAllDerivedDefinitions("Predicate");
919 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
920 Record *Pred = AllPredicates[i];
921 // Ignore predicates that are not intended for the assembler.
922 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
925 if (Pred->getName().empty())
926 throw TGError(Pred->getLoc(), "Predicate has no name!");
928 unsigned FeatureNo = SubtargetFeatures.size();
929 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
930 assert(FeatureNo < 32 && "Too many subtarget features!");
933 StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
935 // Parse the instructions; we need to do this first so that we can gather the
936 // singleton register classes.
937 SmallPtrSet<Record*, 16> SingletonRegisters;
938 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
939 E = Target.inst_end(); I != E; ++I) {
940 const CodeGenInstruction &CGI = **I;
942 // If the tblgen -match-prefix option is specified (for tblgen hackers),
943 // filter the set of instructions we consider.
944 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
947 // Ignore "codegen only" instructions.
948 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
951 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
953 II->Initialize(*this, SingletonRegisters);
955 // Ignore instructions which shouldn't be matched and diagnose invalid
956 // instruction definitions with an error.
957 if (!II->Validate(CommentDelimiter, true))
960 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
962 // FIXME: This is a total hack.
963 if (StringRef(II->InstrName).startswith("Int_") ||
964 StringRef(II->InstrName).endswith("_Int"))
967 Matchables.push_back(II.take());
970 // Parse all of the InstAlias definitions and stick them in the list of
972 std::vector<Record*> AllInstAliases =
973 Records.getAllDerivedDefinitions("InstAlias");
974 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
975 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i]);
977 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
979 II->Initialize(*this, SingletonRegisters);
981 // Validate the alias definitions.
982 II->Validate(CommentDelimiter, false);
984 Matchables.push_back(II.take());
987 // Build info for the register classes.
988 BuildRegisterClasses(SingletonRegisters);
990 // Build info for the user defined assembly operand classes.
991 BuildOperandClasses();
993 // Build the information about matchables.
994 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
995 ie = Matchables.end(); it != ie; ++it) {
996 MatchableInfo *II = *it;
998 // The first token of the instruction is the mnemonic, which must be a
999 // simple string, not a $foo variable or a singleton register.
1000 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1001 StringRef Mnemonic = II->Tokens[0];
1002 if (Mnemonic[0] == '$' || II->getSingletonRegisterForToken(0, *this))
1003 throw TGError(II->TheDef->getLoc(),
1004 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
1006 // Parse the tokens after the mnemonic.
1007 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1008 StringRef Token = II->Tokens[i];
1010 // Check for singleton registers.
1011 if (Record *RegRecord = II->getSingletonRegisterForToken(i, *this)) {
1012 MatchableInfo::Operand Op(RegisterClasses[RegRecord], 0);
1013 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1014 "Unexpected class for singleton register");
1015 II->Operands.push_back(Op);
1019 // Check for simple tokens.
1020 if (Token[0] != '$') {
1021 II->Operands.push_back(MatchableInfo::Operand(getTokenClass(Token), 0));
1025 // Otherwise this is an operand reference.
1026 StringRef OperandName;
1027 if (Token[1] == '{')
1028 OperandName = Token.substr(2, Token.size() - 3);
1030 OperandName = Token.substr(1);
1032 // Map this token to an operand. FIXME: Move elsewhere.
1034 if (!II->OperandList.hasOperandNamed(OperandName, Idx))
1035 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1036 OperandName.str() + "'");
1038 // FIXME: This is annoying, the named operand may be tied (e.g.,
1039 // XCHG8rm). What we want is the untied operand, which we now have to
1040 // grovel for. Only worry about this for single entry operands, we have to
1041 // clean this up anyway.
1042 const CGIOperandList::OperandInfo *OI = &II->OperandList[Idx];
1043 if (OI->Constraints[0].isTied()) {
1044 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1046 // The tied operand index is an MIOperand index, find the operand that
1048 for (unsigned i = 0, e = II->OperandList.size(); i != e; ++i) {
1049 if (II->OperandList[i].MIOperandNo == TiedOp) {
1050 OI = &II->OperandList[i];
1055 assert(OI && "Unable to find tied operand target!");
1058 II->Operands.push_back(MatchableInfo::Operand(getOperandClass(Token,
1063 // Reorder classes so that classes preceed super classes.
1064 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1067 static std::pair<unsigned, unsigned> *
1068 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1070 for (unsigned i = 0, e = List.size(); i != e; ++i)
1071 if (Index == List[i].first)
1077 static void EmitConvertToMCInst(CodeGenTarget &Target,
1078 std::vector<MatchableInfo*> &Infos,
1080 // Write the convert function to a separate stream, so we can drop it after
1082 std::string ConvertFnBody;
1083 raw_string_ostream CvtOS(ConvertFnBody);
1085 // Function we have already generated.
1086 std::set<std::string> GeneratedFns;
1088 // Start the unified conversion function.
1090 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1091 << "unsigned Opcode,\n"
1092 << " const SmallVectorImpl<MCParsedAsmOperand*"
1093 << "> &Operands) {\n";
1094 CvtOS << " Inst.setOpcode(Opcode);\n";
1095 CvtOS << " switch (Kind) {\n";
1096 CvtOS << " default:\n";
1098 // Start the enum, which we will generate inline.
1100 OS << "// Unified function for converting operants to MCInst instances.\n\n";
1101 OS << "enum ConversionKind {\n";
1103 // TargetOperandClass - This is the target's operand class, like X86Operand.
1104 std::string TargetOperandClass = Target.getName() + "Operand";
1106 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1107 ie = Infos.end(); it != ie; ++it) {
1108 MatchableInfo &II = **it;
1110 // Order the (class) operands by the order to convert them into an MCInst.
1111 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1112 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1113 MatchableInfo::Operand &Op = II.Operands[i];
1115 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1118 // Find any tied operands.
1119 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1120 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1121 const CGIOperandList::OperandInfo &OpInfo = II.OperandList[i];
1122 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1123 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j];
1125 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1126 CI.getTiedOperand()));
1130 std::sort(MIOperandList.begin(), MIOperandList.end());
1132 // Compute the total number of operands.
1133 unsigned NumMIOperands = 0;
1134 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1135 const CGIOperandList::OperandInfo &OI = II.OperandList[i];
1136 NumMIOperands = std::max(NumMIOperands,
1137 OI.MIOperandNo + OI.MINumOperands);
1140 // Build the conversion function signature.
1141 std::string Signature = "Convert";
1142 unsigned CurIndex = 0;
1143 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1144 MatchableInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1145 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1146 "Duplicate match for instruction operand!");
1148 // Skip operands which weren't matched by anything, this occurs when the
1149 // .td file encodes "implicit" operands as explicit ones.
1151 // FIXME: This should be removed from the MCInst structure.
1152 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1153 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1156 Signature += "__Imp";
1158 Signature += "__Tie" + utostr(Tie->second);
1163 // Registers are always converted the same, don't duplicate the conversion
1164 // function based on them.
1166 // FIXME: We could generalize this based on the render method, if it
1168 if (Op.Class->isRegisterClass())
1171 Signature += Op.Class->ClassName;
1172 Signature += utostr(Op.OperandInfo->MINumOperands);
1173 Signature += "_" + utostr(MIOperandList[i].second);
1175 CurIndex += Op.OperandInfo->MINumOperands;
1178 // Add any trailing implicit operands.
1179 for (; CurIndex != NumMIOperands; ++CurIndex) {
1180 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1183 Signature += "__Imp";
1185 Signature += "__Tie" + utostr(Tie->second);
1188 II.ConversionFnKind = Signature;
1190 // Check if we have already generated this signature.
1191 if (!GeneratedFns.insert(Signature).second)
1194 // If not, emit it now.
1196 // Add to the enum list.
1197 OS << " " << Signature << ",\n";
1199 // And to the convert function.
1200 CvtOS << " case " << Signature << ":\n";
1202 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1203 MatchableInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1205 // Add the implicit operands.
1206 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1207 // See if this is a tied operand.
1208 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1212 // If not, this is some implicit operand. Just assume it is a register
1214 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1216 // Copy the tied operand.
1217 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1218 CvtOS << " Inst.addOperand(Inst.getOperand("
1219 << Tie->second << "));\n";
1223 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1224 << MIOperandList[i].second
1225 << "+1])->" << Op.Class->RenderMethod
1226 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1227 CurIndex += Op.OperandInfo->MINumOperands;
1230 // And add trailing implicit operands.
1231 for (; CurIndex != NumMIOperands; ++CurIndex) {
1232 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1236 // If not, this is some implicit operand. Just assume it is a register
1238 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1240 // Copy the tied operand.
1241 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1242 CvtOS << " Inst.addOperand(Inst.getOperand("
1243 << Tie->second << "));\n";
1247 CvtOS << " return;\n";
1250 // Finish the convert function.
1255 // Finish the enum, and drop the convert function after it.
1257 OS << " NumConversionVariants\n";
1263 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1264 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1265 std::vector<ClassInfo*> &Infos,
1267 OS << "namespace {\n\n";
1269 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1270 << "/// instruction matching.\n";
1271 OS << "enum MatchClassKind {\n";
1272 OS << " InvalidMatchClass = 0,\n";
1273 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1274 ie = Infos.end(); it != ie; ++it) {
1275 ClassInfo &CI = **it;
1276 OS << " " << CI.Name << ", // ";
1277 if (CI.Kind == ClassInfo::Token) {
1278 OS << "'" << CI.ValueName << "'\n";
1279 } else if (CI.isRegisterClass()) {
1280 if (!CI.ValueName.empty())
1281 OS << "register class '" << CI.ValueName << "'\n";
1283 OS << "derived register class\n";
1285 OS << "user defined class '" << CI.ValueName << "'\n";
1288 OS << " NumMatchClassKinds\n";
1294 /// EmitClassifyOperand - Emit the function to classify an operand.
1295 static void EmitClassifyOperand(AsmMatcherInfo &Info,
1297 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1298 << " " << Info.Target.getName() << "Operand &Operand = *("
1299 << Info.Target.getName() << "Operand*)GOp;\n";
1302 OS << " if (Operand.isToken())\n";
1303 OS << " return MatchTokenString(Operand.getToken());\n\n";
1305 // Classify registers.
1307 // FIXME: Don't hardcode isReg, getReg.
1308 OS << " if (Operand.isReg()) {\n";
1309 OS << " switch (Operand.getReg()) {\n";
1310 OS << " default: return InvalidMatchClass;\n";
1311 for (std::map<Record*, ClassInfo*>::iterator
1312 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1314 OS << " case " << Info.Target.getName() << "::"
1315 << it->first->getName() << ": return " << it->second->Name << ";\n";
1319 // Classify user defined operands.
1320 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1321 ie = Info.Classes.end(); it != ie; ++it) {
1322 ClassInfo &CI = **it;
1324 if (!CI.isUserClass())
1327 OS << " // '" << CI.ClassName << "' class";
1328 if (!CI.SuperClasses.empty()) {
1329 OS << ", subclass of ";
1330 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1332 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1333 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1338 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1340 // Validate subclass relationships.
1341 if (!CI.SuperClasses.empty()) {
1342 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1343 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1344 << "() && \"Invalid class relationship!\");\n";
1347 OS << " return " << CI.Name << ";\n";
1350 OS << " return InvalidMatchClass;\n";
1354 /// EmitIsSubclass - Emit the subclass predicate function.
1355 static void EmitIsSubclass(CodeGenTarget &Target,
1356 std::vector<ClassInfo*> &Infos,
1358 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1359 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1360 OS << " if (A == B)\n";
1361 OS << " return true;\n\n";
1363 OS << " switch (A) {\n";
1364 OS << " default:\n";
1365 OS << " return false;\n";
1366 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1367 ie = Infos.end(); it != ie; ++it) {
1368 ClassInfo &A = **it;
1370 if (A.Kind != ClassInfo::Token) {
1371 std::vector<StringRef> SuperClasses;
1372 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1373 ie = Infos.end(); it != ie; ++it) {
1374 ClassInfo &B = **it;
1376 if (&A != &B && A.isSubsetOf(B))
1377 SuperClasses.push_back(B.Name);
1380 if (SuperClasses.empty())
1383 OS << "\n case " << A.Name << ":\n";
1385 if (SuperClasses.size() == 1) {
1386 OS << " return B == " << SuperClasses.back() << ";\n";
1390 OS << " switch (B) {\n";
1391 OS << " default: return false;\n";
1392 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1393 OS << " case " << SuperClasses[i] << ": return true;\n";
1403 /// EmitMatchTokenString - Emit the function to match a token string to the
1404 /// appropriate match class value.
1405 static void EmitMatchTokenString(CodeGenTarget &Target,
1406 std::vector<ClassInfo*> &Infos,
1408 // Construct the match list.
1409 std::vector<StringMatcher::StringPair> Matches;
1410 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1411 ie = Infos.end(); it != ie; ++it) {
1412 ClassInfo &CI = **it;
1414 if (CI.Kind == ClassInfo::Token)
1415 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1416 "return " + CI.Name + ";"));
1419 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1421 StringMatcher("Name", Matches, OS).Emit();
1423 OS << " return InvalidMatchClass;\n";
1427 /// EmitMatchRegisterName - Emit the function to match a string to the target
1428 /// specific register enum.
1429 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1431 // Construct the match list.
1432 std::vector<StringMatcher::StringPair> Matches;
1433 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1434 const CodeGenRegister &Reg = Target.getRegisters()[i];
1435 if (Reg.TheDef->getValueAsString("AsmName").empty())
1438 Matches.push_back(StringMatcher::StringPair(
1439 Reg.TheDef->getValueAsString("AsmName"),
1440 "return " + utostr(i + 1) + ";"));
1443 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1445 StringMatcher("Name", Matches, OS).Emit();
1447 OS << " return 0;\n";
1451 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1453 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1455 OS << "// Flags for subtarget features that participate in "
1456 << "instruction matching.\n";
1457 OS << "enum SubtargetFeatureFlag {\n";
1458 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1459 it = Info.SubtargetFeatures.begin(),
1460 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1461 SubtargetFeatureInfo &SFI = *it->second;
1462 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1464 OS << " Feature_None = 0\n";
1468 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1469 /// available features given a subtarget.
1470 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1472 std::string ClassName =
1473 Info.AsmParser->getValueAsString("AsmParserClassName");
1475 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1476 << "ComputeAvailableFeatures(const " << Info.Target.getName()
1477 << "Subtarget *Subtarget) const {\n";
1478 OS << " unsigned Features = 0;\n";
1479 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1480 it = Info.SubtargetFeatures.begin(),
1481 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1482 SubtargetFeatureInfo &SFI = *it->second;
1483 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1485 OS << " Features |= " << SFI.getEnumName() << ";\n";
1487 OS << " return Features;\n";
1491 static std::string GetAliasRequiredFeatures(Record *R,
1492 const AsmMatcherInfo &Info) {
1493 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1495 unsigned NumFeatures = 0;
1496 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1497 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1500 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1501 "' is not marked as an AssemblerPredicate!");
1506 Result += F->getEnumName();
1510 if (NumFeatures > 1)
1511 Result = '(' + Result + ')';
1515 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1516 /// emit a function for them and return true, otherwise return false.
1517 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1518 std::vector<Record*> Aliases =
1519 Records.getAllDerivedDefinitions("MnemonicAlias");
1520 if (Aliases.empty()) return false;
1522 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1523 "unsigned Features) {\n";
1525 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1526 // iteration order of the map is stable.
1527 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1529 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1530 Record *R = Aliases[i];
1531 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1534 // Process each alias a "from" mnemonic at a time, building the code executed
1535 // by the string remapper.
1536 std::vector<StringMatcher::StringPair> Cases;
1537 for (std::map<std::string, std::vector<Record*> >::iterator
1538 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1540 const std::vector<Record*> &ToVec = I->second;
1542 // Loop through each alias and emit code that handles each case. If there
1543 // are two instructions without predicates, emit an error. If there is one,
1545 std::string MatchCode;
1546 int AliasWithNoPredicate = -1;
1548 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1549 Record *R = ToVec[i];
1550 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1552 // If this unconditionally matches, remember it for later and diagnose
1554 if (FeatureMask.empty()) {
1555 if (AliasWithNoPredicate != -1) {
1556 // We can't have two aliases from the same mnemonic with no predicate.
1557 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1558 "two MnemonicAliases with the same 'from' mnemonic!");
1559 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1562 AliasWithNoPredicate = i;
1566 if (!MatchCode.empty())
1567 MatchCode += "else ";
1568 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1569 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1572 if (AliasWithNoPredicate != -1) {
1573 Record *R = ToVec[AliasWithNoPredicate];
1574 if (!MatchCode.empty())
1575 MatchCode += "else\n ";
1576 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1579 MatchCode += "return;";
1581 Cases.push_back(std::make_pair(I->first, MatchCode));
1585 StringMatcher("Mnemonic", Cases, OS).Emit();
1591 void AsmMatcherEmitter::run(raw_ostream &OS) {
1592 CodeGenTarget Target;
1593 Record *AsmParser = Target.getAsmParser();
1594 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1596 // Compute the information on the instructions to match.
1597 AsmMatcherInfo Info(AsmParser, Target);
1600 // Sort the instruction table using the partial order on classes. We use
1601 // stable_sort to ensure that ambiguous instructions are still
1602 // deterministically ordered.
1603 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
1604 less_ptr<MatchableInfo>());
1606 DEBUG_WITH_TYPE("instruction_info", {
1607 for (std::vector<MatchableInfo*>::iterator
1608 it = Info.Matchables.begin(), ie = Info.Matchables.end();
1613 // Check for ambiguous matchables.
1614 DEBUG_WITH_TYPE("ambiguous_instrs", {
1615 unsigned NumAmbiguous = 0;
1616 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
1617 for (unsigned j = i + 1; j != e; ++j) {
1618 MatchableInfo &A = *Info.Matchables[i];
1619 MatchableInfo &B = *Info.Matchables[j];
1621 if (A.CouldMatchAmiguouslyWith(B)) {
1622 errs() << "warning: ambiguous matchables:\n";
1624 errs() << "\nis incomparable with:\n";
1632 errs() << "warning: " << NumAmbiguous
1633 << " ambiguous matchables!\n";
1636 // Write the output.
1638 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1640 // Information for the class declaration.
1641 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1642 OS << "#undef GET_ASSEMBLER_HEADER\n";
1643 OS << " // This should be included into the middle of the declaration of \n";
1644 OS << " // your subclasses implementation of TargetAsmParser.\n";
1645 OS << " unsigned ComputeAvailableFeatures(const " <<
1646 Target.getName() << "Subtarget *Subtarget) const;\n";
1647 OS << " enum MatchResultTy {\n";
1648 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1649 OS << " Match_MissingFeature\n";
1651 OS << " MatchResultTy MatchInstructionImpl(const "
1652 << "SmallVectorImpl<MCParsedAsmOperand*>"
1653 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1654 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1659 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1660 OS << "#undef GET_REGISTER_MATCHER\n\n";
1662 // Emit the subtarget feature enumeration.
1663 EmitSubtargetFeatureFlagEnumeration(Info, OS);
1665 // Emit the function to match a register name to number.
1666 EmitMatchRegisterName(Target, AsmParser, OS);
1668 OS << "#endif // GET_REGISTER_MATCHER\n\n";
1671 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1672 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1674 // Generate the function that remaps for mnemonic aliases.
1675 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1677 // Generate the unified function to convert operands into an MCInst.
1678 EmitConvertToMCInst(Target, Info.Matchables, OS);
1680 // Emit the enumeration for classes which participate in matching.
1681 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1683 // Emit the routine to match token strings to their match class.
1684 EmitMatchTokenString(Target, Info.Classes, OS);
1686 // Emit the routine to classify an operand.
1687 EmitClassifyOperand(Info, OS);
1689 // Emit the subclass predicate routine.
1690 EmitIsSubclass(Target, Info.Classes, OS);
1692 // Emit the available features compute function.
1693 EmitComputeAvailableFeatures(Info, OS);
1696 size_t MaxNumOperands = 0;
1697 for (std::vector<MatchableInfo*>::const_iterator it =
1698 Info.Matchables.begin(), ie = Info.Matchables.end();
1700 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1703 // Emit the static match table; unused classes get initalized to 0 which is
1704 // guaranteed to be InvalidMatchClass.
1706 // FIXME: We can reduce the size of this table very easily. First, we change
1707 // it so that store the kinds in separate bit-fields for each index, which
1708 // only needs to be the max width used for classes at that index (we also need
1709 // to reject based on this during classification). If we then make sure to
1710 // order the match kinds appropriately (putting mnemonics last), then we
1711 // should only end up using a few bits for each class, especially the ones
1712 // following the mnemonic.
1713 OS << "namespace {\n";
1714 OS << " struct MatchEntry {\n";
1715 OS << " unsigned Opcode;\n";
1716 OS << " const char *Mnemonic;\n";
1717 OS << " ConversionKind ConvertFn;\n";
1718 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1719 OS << " unsigned RequiredFeatures;\n";
1722 OS << "// Predicate for searching for an opcode.\n";
1723 OS << " struct LessOpcode {\n";
1724 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1725 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1727 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1728 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1730 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1731 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1735 OS << "} // end anonymous namespace.\n\n";
1737 OS << "static const MatchEntry MatchTable["
1738 << Info.Matchables.size() << "] = {\n";
1740 for (std::vector<MatchableInfo*>::const_iterator it =
1741 Info.Matchables.begin(), ie = Info.Matchables.end();
1743 MatchableInfo &II = **it;
1745 OS << " { " << Target.getName() << "::" << II.InstrName
1746 << ", \"" << II.Tokens[0] << "\""
1747 << ", " << II.ConversionFnKind << ", { ";
1748 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1749 MatchableInfo::Operand &Op = II.Operands[i];
1752 OS << Op.Class->Name;
1756 // Write the required features mask.
1757 if (!II.RequiredFeatures.empty()) {
1758 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1760 OS << II.RequiredFeatures[i]->getEnumName();
1770 // Finally, build the match function.
1771 OS << Target.getName() << ClassName << "::MatchResultTy "
1772 << Target.getName() << ClassName << "::\n"
1773 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1775 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
1777 // Emit code to get the available features.
1778 OS << " // Get the current feature set.\n";
1779 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1781 OS << " // Get the instruction mnemonic, which is the first token.\n";
1782 OS << " StringRef Mnemonic = ((" << Target.getName()
1783 << "Operand*)Operands[0])->getToken();\n\n";
1785 if (HasMnemonicAliases) {
1786 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1787 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1790 // Emit code to compute the class list for this operand vector.
1791 OS << " // Eliminate obvious mismatches.\n";
1792 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1793 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1794 OS << " return Match_InvalidOperand;\n";
1797 OS << " // Compute the class list for this operand vector.\n";
1798 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1799 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1800 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1802 OS << " // Check for invalid operands before matching.\n";
1803 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1804 OS << " ErrorInfo = i;\n";
1805 OS << " return Match_InvalidOperand;\n";
1809 OS << " // Mark unused classes.\n";
1810 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1811 << "i != e; ++i)\n";
1812 OS << " Classes[i] = InvalidMatchClass;\n\n";
1814 OS << " // Some state to try to produce better error messages.\n";
1815 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
1816 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1817 OS << " // wrong for all instances of the instruction.\n";
1818 OS << " ErrorInfo = ~0U;\n";
1820 // Emit code to search the table.
1821 OS << " // Search the table.\n";
1822 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1823 OS << " std::equal_range(MatchTable, MatchTable+"
1824 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
1826 OS << " // Return a more specific error code if no mnemonics match.\n";
1827 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1828 OS << " return Match_MnemonicFail;\n\n";
1830 OS << " for (const MatchEntry *it = MnemonicRange.first, "
1831 << "*ie = MnemonicRange.second;\n";
1832 OS << " it != ie; ++it) {\n";
1834 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
1835 OS << " assert(Mnemonic == it->Mnemonic);\n";
1837 // Emit check that the subclasses match.
1838 OS << " bool OperandsValid = true;\n";
1839 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1840 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1841 OS << " continue;\n";
1842 OS << " // If this operand is broken for all of the instances of this\n";
1843 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1844 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1845 OS << " ErrorInfo = i+1;\n";
1847 OS << " ErrorInfo = ~0U;";
1848 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1849 OS << " OperandsValid = false;\n";
1853 OS << " if (!OperandsValid) continue;\n";
1855 // Emit check that the required features are available.
1856 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1857 << "!= it->RequiredFeatures) {\n";
1858 OS << " HadMatchOtherThanFeatures = true;\n";
1859 OS << " continue;\n";
1863 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1865 // Call the post-processing function, if used.
1866 std::string InsnCleanupFn =
1867 AsmParser->getValueAsString("AsmParserInstCleanup");
1868 if (!InsnCleanupFn.empty())
1869 OS << " " << InsnCleanupFn << "(Inst);\n";
1871 OS << " return Match_Success;\n";
1874 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1875 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1876 OS << " return Match_InvalidOperand;\n";
1879 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";