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. It also emits a matcher for
12 // custom operand parsing.
14 // Converting assembly operands into MCInst structures
15 // ---------------------------------------------------
17 // The input to the target specific matcher is a list of literal tokens and
18 // operands. The target specific parser should generally eliminate any syntax
19 // which is not relevant for matching; for example, comma tokens should have
20 // already been consumed and eliminated by the parser. Most instructions will
21 // end up with a single literal token (the instruction name) and some number of
24 // Some example inputs, for X86:
25 // 'addl' (immediate ...) (register ...)
26 // 'add' (immediate ...) (memory ...)
29 // The assembly matcher is responsible for converting this input into a precise
30 // machine instruction (i.e., an instruction with a well defined encoding). This
31 // mapping has several properties which complicate matching:
33 // - It may be ambiguous; many architectures can legally encode particular
34 // variants of an instruction in different ways (for example, using a smaller
35 // encoding for small immediates). Such ambiguities should never be
36 // arbitrarily resolved by the assembler, the assembler is always responsible
37 // for choosing the "best" available instruction.
39 // - It may depend on the subtarget or the assembler context. Instructions
40 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
41 // an SSE instruction in a file being assembled for i486) should be accepted
42 // and rejected by the assembler front end. However, if the proper encoding
43 // for an instruction is dependent on the assembler context then the matcher
44 // is responsible for selecting the correct machine instruction for the
47 // The core matching algorithm attempts to exploit the regularity in most
48 // instruction sets to quickly determine the set of possibly matching
49 // instructions, and the simplify the generated code. Additionally, this helps
50 // to ensure that the ambiguities are intentionally resolved by the user.
52 // The matching is divided into two distinct phases:
54 // 1. Classification: Each operand is mapped to the unique set which (a)
55 // contains it, and (b) is the largest such subset for which a single
56 // instruction could match all members.
58 // For register classes, we can generate these subgroups automatically. For
59 // arbitrary operands, we expect the user to define the classes and their
60 // relations to one another (for example, 8-bit signed immediates as a
61 // subset of 32-bit immediates).
63 // By partitioning the operands in this way, we guarantee that for any
64 // tuple of classes, any single instruction must match either all or none
65 // of the sets of operands which could classify to that tuple.
67 // In addition, the subset relation amongst classes induces a partial order
68 // on such tuples, which we use to resolve ambiguities.
70 // 2. The input can now be treated as a tuple of classes (static tokens are
71 // simple singleton sets). Each such tuple should generally map to a single
72 // instruction (we currently ignore cases where this isn't true, whee!!!),
73 // which we can emit a simple matcher for.
75 // Custom Operand Parsing
76 // ----------------------
78 // Some targets need a custom way to parse operands, some specific instructions
79 // can contain arguments that can represent processor flags and other kinds of
80 // identifiers that need to be mapped to specific valeus in the final encoded
81 // instructions. The target specific custom operand parsing works in the
84 // 1. A operand match table is built, each entry contains a mnemonic, an
85 // operand class, a mask for all operand positions for that same
86 // class/mnemonic and target features to be checked while trying to match.
88 // 2. The operand matcher will try every possible entry with the same
89 // mnemonic and will check if the target feature for this mnemonic also
90 // matches. After that, if the operand to be matched has its index
91 // present in the mask, a successful match occurs. Otherwise, fallback
92 // to the regular operand parsing.
94 // 3. For a match success, each operand class that has a 'ParserMethod'
95 // becomes part of a switch from where the custom method is called.
97 //===----------------------------------------------------------------------===//
99 #include "AsmMatcherEmitter.h"
100 #include "CodeGenTarget.h"
102 #include "StringMatcher.h"
103 #include "llvm/ADT/OwningPtr.h"
104 #include "llvm/ADT/PointerUnion.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallVector.h"
107 #include "llvm/ADT/STLExtras.h"
108 #include "llvm/ADT/StringExtras.h"
109 #include "llvm/Support/CommandLine.h"
110 #include "llvm/Support/Debug.h"
113 using namespace llvm;
115 static cl::opt<std::string>
116 MatchPrefix("match-prefix", cl::init(""),
117 cl::desc("Only match instructions with the given prefix"));
120 class AsmMatcherInfo;
121 struct SubtargetFeatureInfo;
123 /// ClassInfo - Helper class for storing the information about a particular
124 /// class of operands which can be matched.
127 /// Invalid kind, for use as a sentinel value.
130 /// The class for a particular token.
133 /// The (first) register class, subsequent register classes are
134 /// RegisterClass0+1, and so on.
137 /// The (first) user defined class, subsequent user defined classes are
138 /// UserClass0+1, and so on.
142 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
143 /// N) for the Nth user defined class.
146 /// SuperClasses - The super classes of this class. Note that for simplicities
147 /// sake user operands only record their immediate super class, while register
148 /// operands include all superclasses.
149 std::vector<ClassInfo*> SuperClasses;
151 /// Name - The full class name, suitable for use in an enum.
154 /// ClassName - The unadorned generic name for this class (e.g., Token).
155 std::string ClassName;
157 /// ValueName - The name of the value this class represents; for a token this
158 /// is the literal token string, for an operand it is the TableGen class (or
159 /// empty if this is a derived class).
160 std::string ValueName;
162 /// PredicateMethod - The name of the operand method to test whether the
163 /// operand matches this class; this is not valid for Token or register kinds.
164 std::string PredicateMethod;
166 /// RenderMethod - The name of the operand method to add this operand to an
167 /// MCInst; this is not valid for Token or register kinds.
168 std::string RenderMethod;
170 /// ParserMethod - The name of the operand method to do a target specific
171 /// parsing on the operand.
172 std::string ParserMethod;
174 /// For register classes, the records for all the registers in this class.
175 std::set<Record*> Registers;
178 /// isRegisterClass() - Check if this is a register class.
179 bool isRegisterClass() const {
180 return Kind >= RegisterClass0 && Kind < UserClass0;
183 /// isUserClass() - Check if this is a user defined class.
184 bool isUserClass() const {
185 return Kind >= UserClass0;
188 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
189 /// are related if they are in the same class hierarchy.
190 bool isRelatedTo(const ClassInfo &RHS) const {
191 // Tokens are only related to tokens.
192 if (Kind == Token || RHS.Kind == Token)
193 return Kind == Token && RHS.Kind == Token;
195 // Registers classes are only related to registers classes, and only if
196 // their intersection is non-empty.
197 if (isRegisterClass() || RHS.isRegisterClass()) {
198 if (!isRegisterClass() || !RHS.isRegisterClass())
201 std::set<Record*> Tmp;
202 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
203 std::set_intersection(Registers.begin(), Registers.end(),
204 RHS.Registers.begin(), RHS.Registers.end(),
210 // Otherwise we have two users operands; they are related if they are in the
211 // same class hierarchy.
213 // FIXME: This is an oversimplification, they should only be related if they
214 // intersect, however we don't have that information.
215 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
216 const ClassInfo *Root = this;
217 while (!Root->SuperClasses.empty())
218 Root = Root->SuperClasses.front();
220 const ClassInfo *RHSRoot = &RHS;
221 while (!RHSRoot->SuperClasses.empty())
222 RHSRoot = RHSRoot->SuperClasses.front();
224 return Root == RHSRoot;
227 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
228 bool isSubsetOf(const ClassInfo &RHS) const {
229 // This is a subset of RHS if it is the same class...
233 // ... or if any of its super classes are a subset of RHS.
234 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
235 ie = SuperClasses.end(); it != ie; ++it)
236 if ((*it)->isSubsetOf(RHS))
242 /// operator< - Compare two classes.
243 bool operator<(const ClassInfo &RHS) const {
247 // Unrelated classes can be ordered by kind.
248 if (!isRelatedTo(RHS))
249 return Kind < RHS.Kind;
253 assert(0 && "Invalid kind!");
255 // Tokens are comparable by value.
257 // FIXME: Compare by enum value.
258 return ValueName < RHS.ValueName;
261 // This class precedes the RHS if it is a proper subset of the RHS.
264 if (RHS.isSubsetOf(*this))
267 // Otherwise, order by name to ensure we have a total ordering.
268 return ValueName < RHS.ValueName;
273 /// MatchableInfo - Helper class for storing the necessary information for an
274 /// instruction or alias which is capable of being matched.
275 struct MatchableInfo {
277 /// Token - This is the token that the operand came from.
280 /// The unique class instance this operand should match.
283 /// The operand name this is, if anything.
286 /// The suboperand index within SrcOpName, or -1 for the entire operand.
289 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1) {}
292 /// ResOperand - This represents a single operand in the result instruction
293 /// generated by the match. In cases (like addressing modes) where a single
294 /// assembler operand expands to multiple MCOperands, this represents the
295 /// single assembler operand, not the MCOperand.
298 /// RenderAsmOperand - This represents an operand result that is
299 /// generated by calling the render method on the assembly operand. The
300 /// corresponding AsmOperand is specified by AsmOperandNum.
303 /// TiedOperand - This represents a result operand that is a duplicate of
304 /// a previous result operand.
307 /// ImmOperand - This represents an immediate value that is dumped into
311 /// RegOperand - This represents a fixed register that is dumped in.
316 /// This is the operand # in the AsmOperands list that this should be
318 unsigned AsmOperandNum;
320 /// TiedOperandNum - This is the (earlier) result operand that should be
322 unsigned TiedOperandNum;
324 /// ImmVal - This is the immediate value added to the instruction.
327 /// Register - This is the register record.
331 /// MINumOperands - The number of MCInst operands populated by this
333 unsigned MINumOperands;
335 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
337 X.Kind = RenderAsmOperand;
338 X.AsmOperandNum = AsmOpNum;
339 X.MINumOperands = NumOperands;
343 static ResOperand getTiedOp(unsigned TiedOperandNum) {
345 X.Kind = TiedOperand;
346 X.TiedOperandNum = TiedOperandNum;
351 static ResOperand getImmOp(int64_t Val) {
359 static ResOperand getRegOp(Record *Reg) {
368 /// TheDef - This is the definition of the instruction or InstAlias that this
369 /// matchable came from.
370 Record *const TheDef;
372 /// DefRec - This is the definition that it came from.
373 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
375 const CodeGenInstruction *getResultInst() const {
376 if (DefRec.is<const CodeGenInstruction*>())
377 return DefRec.get<const CodeGenInstruction*>();
378 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
381 /// ResOperands - This is the operand list that should be built for the result
383 std::vector<ResOperand> ResOperands;
385 /// AsmString - The assembly string for this instruction (with variants
386 /// removed), e.g. "movsx $src, $dst".
387 std::string AsmString;
389 /// Mnemonic - This is the first token of the matched instruction, its
393 /// AsmOperands - The textual operands that this instruction matches,
394 /// annotated with a class and where in the OperandList they were defined.
395 /// This directly corresponds to the tokenized AsmString after the mnemonic is
397 SmallVector<AsmOperand, 4> AsmOperands;
399 /// Predicates - The required subtarget features to match this instruction.
400 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
402 /// ConversionFnKind - The enum value which is passed to the generated
403 /// ConvertToMCInst to convert parsed operands into an MCInst for this
405 std::string ConversionFnKind;
407 MatchableInfo(const CodeGenInstruction &CGI)
408 : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) {
411 MatchableInfo(const CodeGenInstAlias *Alias)
412 : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) {
415 void Initialize(const AsmMatcherInfo &Info,
416 SmallPtrSet<Record*, 16> &SingletonRegisters);
418 /// Validate - Return true if this matchable is a valid thing to match against
419 /// and perform a bunch of validity checking.
420 bool Validate(StringRef CommentDelimiter, bool Hack) const;
422 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
423 /// register, return the Record for it, otherwise return null.
424 Record *getSingletonRegisterForAsmOperand(unsigned i,
425 const AsmMatcherInfo &Info) const;
427 /// FindAsmOperand - Find the AsmOperand with the specified name and
428 /// suboperand index.
429 int FindAsmOperand(StringRef N, int SubOpIdx) const {
430 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
431 if (N == AsmOperands[i].SrcOpName &&
432 SubOpIdx == AsmOperands[i].SubOpIdx)
437 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
438 /// This does not check the suboperand index.
439 int FindAsmOperandNamed(StringRef N) const {
440 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
441 if (N == AsmOperands[i].SrcOpName)
446 void BuildInstructionResultOperands();
447 void BuildAliasResultOperands();
449 /// operator< - Compare two matchables.
450 bool operator<(const MatchableInfo &RHS) const {
451 // The primary comparator is the instruction mnemonic.
452 if (Mnemonic != RHS.Mnemonic)
453 return Mnemonic < RHS.Mnemonic;
455 if (AsmOperands.size() != RHS.AsmOperands.size())
456 return AsmOperands.size() < RHS.AsmOperands.size();
458 // Compare lexicographically by operand. The matcher validates that other
459 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
460 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
461 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
463 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
470 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
471 /// ambiguously match the same set of operands as \arg RHS (without being a
472 /// strictly superior match).
473 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
474 // The primary comparator is the instruction mnemonic.
475 if (Mnemonic != RHS.Mnemonic)
478 // The number of operands is unambiguous.
479 if (AsmOperands.size() != RHS.AsmOperands.size())
482 // Otherwise, make sure the ordering of the two instructions is unambiguous
483 // by checking that either (a) a token or operand kind discriminates them,
484 // or (b) the ordering among equivalent kinds is consistent.
486 // Tokens and operand kinds are unambiguous (assuming a correct target
488 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
489 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
490 AsmOperands[i].Class->Kind == ClassInfo::Token)
491 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
492 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
495 // Otherwise, this operand could commute if all operands are equivalent, or
496 // there is a pair of operands that compare less than and a pair that
497 // compare greater than.
498 bool HasLT = false, HasGT = false;
499 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
500 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
502 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
506 return !(HasLT ^ HasGT);
512 void TokenizeAsmString(const AsmMatcherInfo &Info);
515 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
516 /// feature which participates in instruction matching.
517 struct SubtargetFeatureInfo {
518 /// \brief The predicate record for this feature.
521 /// \brief An unique index assigned to represent this feature.
524 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
526 /// \brief The name of the enumerated constant identifying this feature.
527 std::string getEnumName() const {
528 return "Feature_" + TheDef->getName();
532 struct OperandMatchEntry {
533 unsigned OperandMask;
537 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
540 X.OperandMask = opMask;
548 class AsmMatcherInfo {
551 RecordKeeper &Records;
553 /// The tablegen AsmParser record.
556 /// Target - The target information.
557 CodeGenTarget &Target;
559 /// The AsmParser "RegisterPrefix" value.
560 std::string RegisterPrefix;
562 /// The classes which are needed for matching.
563 std::vector<ClassInfo*> Classes;
565 /// The information on the matchables to match.
566 std::vector<MatchableInfo*> Matchables;
568 /// Info for custom matching operands by user defined methods.
569 std::vector<OperandMatchEntry> OperandMatchInfo;
571 /// Map of Register records to their class information.
572 std::map<Record*, ClassInfo*> RegisterClasses;
574 /// Map of Predicate records to their subtarget information.
575 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
578 /// Map of token to class information which has already been constructed.
579 std::map<std::string, ClassInfo*> TokenClasses;
581 /// Map of RegisterClass records to their class information.
582 std::map<Record*, ClassInfo*> RegisterClassClasses;
584 /// Map of AsmOperandClass records to their class information.
585 std::map<Record*, ClassInfo*> AsmOperandClasses;
588 /// getTokenClass - Lookup or create the class for the given token.
589 ClassInfo *getTokenClass(StringRef Token);
591 /// getOperandClass - Lookup or create the class for the given operand.
592 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
595 /// BuildRegisterClasses - Build the ClassInfo* instances for register
597 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
599 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
601 void BuildOperandClasses();
603 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
605 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
606 MatchableInfo::AsmOperand &Op);
609 AsmMatcherInfo(Record *AsmParser,
610 CodeGenTarget &Target,
611 RecordKeeper &Records);
613 /// BuildInfo - Construct the various tables used during matching.
616 /// BuildOperandMatchInfo - Build the necessary information to handle user
617 /// defined operand parsing methods.
618 void BuildOperandMatchInfo();
620 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
622 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
623 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
624 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
625 SubtargetFeatures.find(Def);
626 return I == SubtargetFeatures.end() ? 0 : I->second;
629 RecordKeeper &getRecords() const {
636 void MatchableInfo::dump() {
637 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
639 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
640 AsmOperand &Op = AsmOperands[i];
641 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
642 errs() << '\"' << Op.Token << "\"\n";
646 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
647 SmallPtrSet<Record*, 16> &SingletonRegisters) {
648 // TODO: Eventually support asmparser for Variant != 0.
649 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
651 TokenizeAsmString(Info);
653 // Compute the require features.
654 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
655 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
656 if (SubtargetFeatureInfo *Feature =
657 Info.getSubtargetFeature(Predicates[i]))
658 RequiredFeatures.push_back(Feature);
660 // Collect singleton registers, if used.
661 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
662 if (Record *Reg = getSingletonRegisterForAsmOperand(i, Info))
663 SingletonRegisters.insert(Reg);
667 /// TokenizeAsmString - Tokenize a simplified assembly string.
668 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
669 StringRef String = AsmString;
672 for (unsigned i = 0, e = String.size(); i != e; ++i) {
682 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
685 if (!isspace(String[i]) && String[i] != ',')
686 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
692 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
696 assert(i != String.size() && "Invalid quoted character");
697 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
703 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
707 // If this isn't "${", treat like a normal token.
708 if (i + 1 == String.size() || String[i + 1] != '{') {
713 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
714 assert(End != String.end() && "Missing brace in operand reference!");
715 size_t EndPos = End - String.begin();
716 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
724 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
733 if (InTok && Prev != String.size())
734 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
736 // The first token of the instruction is the mnemonic, which must be a
737 // simple string, not a $foo variable or a singleton register.
738 assert(!AsmOperands.empty() && "Instruction has no tokens?");
739 Mnemonic = AsmOperands[0].Token;
740 if (Mnemonic[0] == '$' || getSingletonRegisterForAsmOperand(0, Info))
741 throw TGError(TheDef->getLoc(),
742 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
744 // Remove the first operand, it is tracked in the mnemonic field.
745 AsmOperands.erase(AsmOperands.begin());
748 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
749 // Reject matchables with no .s string.
750 if (AsmString.empty())
751 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
753 // Reject any matchables with a newline in them, they should be marked
754 // isCodeGenOnly if they are pseudo instructions.
755 if (AsmString.find('\n') != std::string::npos)
756 throw TGError(TheDef->getLoc(),
757 "multiline instruction is not valid for the asmparser, "
758 "mark it isCodeGenOnly");
760 // Remove comments from the asm string. We know that the asmstring only
762 if (!CommentDelimiter.empty() &&
763 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
764 throw TGError(TheDef->getLoc(),
765 "asmstring for instruction has comment character in it, "
766 "mark it isCodeGenOnly");
768 // Reject matchables with operand modifiers, these aren't something we can
769 // handle, the target should be refactored to use operands instead of
772 // Also, check for instructions which reference the operand multiple times;
773 // this implies a constraint we would not honor.
774 std::set<std::string> OperandNames;
775 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
776 StringRef Tok = AsmOperands[i].Token;
777 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
778 throw TGError(TheDef->getLoc(),
779 "matchable with operand modifier '" + Tok.str() +
780 "' not supported by asm matcher. Mark isCodeGenOnly!");
782 // Verify that any operand is only mentioned once.
783 // We reject aliases and ignore instructions for now.
784 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
786 throw TGError(TheDef->getLoc(),
787 "ERROR: matchable with tied operand '" + Tok.str() +
788 "' can never be matched!");
789 // FIXME: Should reject these. The ARM backend hits this with $lane in a
790 // bunch of instructions. It is unclear what the right answer is.
792 errs() << "warning: '" << TheDef->getName() << "': "
793 << "ignoring instruction with tied operand '"
794 << Tok.str() << "'\n";
803 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
804 /// register, return the register name, otherwise return a null StringRef.
805 Record *MatchableInfo::
806 getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) const{
807 StringRef Tok = AsmOperands[i].Token;
808 if (!Tok.startswith(Info.RegisterPrefix))
811 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
812 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
815 // If there is no register prefix (i.e. "%" in "%eax"), then this may
816 // be some random non-register token, just ignore it.
817 if (Info.RegisterPrefix.empty())
820 // Otherwise, we have something invalid prefixed with the register prefix,
822 std::string Err = "unable to find register for '" + RegName.str() +
823 "' (which matches register prefix)";
824 throw TGError(TheDef->getLoc(), Err);
827 static std::string getEnumNameForToken(StringRef Str) {
830 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
832 case '*': Res += "_STAR_"; break;
833 case '%': Res += "_PCT_"; break;
834 case ':': Res += "_COLON_"; break;
835 case '!': Res += "_EXCLAIM_"; break;
836 case '.': Res += "_DOT_"; break;
841 Res += "_" + utostr((unsigned) *it) + "_";
848 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
849 ClassInfo *&Entry = TokenClasses[Token];
852 Entry = new ClassInfo();
853 Entry->Kind = ClassInfo::Token;
854 Entry->ClassName = "Token";
855 Entry->Name = "MCK_" + getEnumNameForToken(Token);
856 Entry->ValueName = Token;
857 Entry->PredicateMethod = "<invalid>";
858 Entry->RenderMethod = "<invalid>";
859 Entry->ParserMethod = "";
860 Classes.push_back(Entry);
867 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
869 Record *Rec = OI.Rec;
871 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
873 if (Rec->isSubClassOf("RegisterClass")) {
874 if (ClassInfo *CI = RegisterClassClasses[Rec])
876 throw TGError(Rec->getLoc(), "register class has no class info!");
879 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
880 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
881 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
884 throw TGError(Rec->getLoc(), "operand has no match class!");
887 void AsmMatcherInfo::
888 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
889 const std::vector<CodeGenRegister*> &Registers =
890 Target.getRegBank().getRegisters();
891 const std::vector<CodeGenRegisterClass> &RegClassList =
892 Target.getRegisterClasses();
894 // The register sets used for matching.
895 std::set< std::set<Record*> > RegisterSets;
897 // Gather the defined sets.
898 for (std::vector<CodeGenRegisterClass>::const_iterator it =
899 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
900 RegisterSets.insert(std::set<Record*>(it->getOrder().begin(),
901 it->getOrder().end()));
903 // Add any required singleton sets.
904 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
905 ie = SingletonRegisters.end(); it != ie; ++it) {
907 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
910 // Introduce derived sets where necessary (when a register does not determine
911 // a unique register set class), and build the mapping of registers to the set
912 // they should classify to.
913 std::map<Record*, std::set<Record*> > RegisterMap;
914 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
915 ie = Registers.end(); it != ie; ++it) {
916 const CodeGenRegister &CGR = **it;
917 // Compute the intersection of all sets containing this register.
918 std::set<Record*> ContainingSet;
920 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
921 ie = RegisterSets.end(); it != ie; ++it) {
922 if (!it->count(CGR.TheDef))
925 if (ContainingSet.empty()) {
930 std::set<Record*> Tmp;
931 std::swap(Tmp, ContainingSet);
932 std::insert_iterator< std::set<Record*> > II(ContainingSet,
933 ContainingSet.begin());
934 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
937 if (!ContainingSet.empty()) {
938 RegisterSets.insert(ContainingSet);
939 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
943 // Construct the register classes.
944 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
946 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
947 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
948 ClassInfo *CI = new ClassInfo();
949 CI->Kind = ClassInfo::RegisterClass0 + Index;
950 CI->ClassName = "Reg" + utostr(Index);
951 CI->Name = "MCK_Reg" + utostr(Index);
953 CI->PredicateMethod = ""; // unused
954 CI->RenderMethod = "addRegOperands";
956 Classes.push_back(CI);
957 RegisterSetClasses.insert(std::make_pair(*it, CI));
960 // Find the superclasses; we could compute only the subgroup lattice edges,
961 // but there isn't really a point.
962 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
963 ie = RegisterSets.end(); it != ie; ++it) {
964 ClassInfo *CI = RegisterSetClasses[*it];
965 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
966 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
968 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
969 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
972 // Name the register classes which correspond to a user defined RegisterClass.
973 for (std::vector<CodeGenRegisterClass>::const_iterator
974 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
975 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->getOrder().begin(),
976 it->getOrder().end())];
977 if (CI->ValueName.empty()) {
978 CI->ClassName = it->getName();
979 CI->Name = "MCK_" + it->getName();
980 CI->ValueName = it->getName();
982 CI->ValueName = CI->ValueName + "," + it->getName();
984 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
987 // Populate the map for individual registers.
988 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
989 ie = RegisterMap.end(); it != ie; ++it)
990 RegisterClasses[it->first] = RegisterSetClasses[it->second];
992 // Name the register classes which correspond to singleton registers.
993 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
994 ie = SingletonRegisters.end(); it != ie; ++it) {
996 ClassInfo *CI = RegisterClasses[Rec];
997 assert(CI && "Missing singleton register class info!");
999 if (CI->ValueName.empty()) {
1000 CI->ClassName = Rec->getName();
1001 CI->Name = "MCK_" + Rec->getName();
1002 CI->ValueName = Rec->getName();
1004 CI->ValueName = CI->ValueName + "," + Rec->getName();
1008 void AsmMatcherInfo::BuildOperandClasses() {
1009 std::vector<Record*> AsmOperands =
1010 Records.getAllDerivedDefinitions("AsmOperandClass");
1012 // Pre-populate AsmOperandClasses map.
1013 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1014 ie = AsmOperands.end(); it != ie; ++it)
1015 AsmOperandClasses[*it] = new ClassInfo();
1018 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1019 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1020 ClassInfo *CI = AsmOperandClasses[*it];
1021 CI->Kind = ClassInfo::UserClass0 + Index;
1023 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1024 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1025 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1027 PrintError((*it)->getLoc(), "Invalid super class reference!");
1031 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1033 PrintError((*it)->getLoc(), "Invalid super class reference!");
1035 CI->SuperClasses.push_back(SC);
1037 CI->ClassName = (*it)->getValueAsString("Name");
1038 CI->Name = "MCK_" + CI->ClassName;
1039 CI->ValueName = (*it)->getName();
1041 // Get or construct the predicate method name.
1042 Init *PMName = (*it)->getValueInit("PredicateMethod");
1043 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1044 CI->PredicateMethod = SI->getValue();
1046 assert(dynamic_cast<UnsetInit*>(PMName) &&
1047 "Unexpected PredicateMethod field!");
1048 CI->PredicateMethod = "is" + CI->ClassName;
1051 // Get or construct the render method name.
1052 Init *RMName = (*it)->getValueInit("RenderMethod");
1053 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1054 CI->RenderMethod = SI->getValue();
1056 assert(dynamic_cast<UnsetInit*>(RMName) &&
1057 "Unexpected RenderMethod field!");
1058 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1061 // Get the parse method name or leave it as empty.
1062 Init *PRMName = (*it)->getValueInit("ParserMethod");
1063 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1064 CI->ParserMethod = SI->getValue();
1066 AsmOperandClasses[*it] = CI;
1067 Classes.push_back(CI);
1071 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1072 CodeGenTarget &target,
1073 RecordKeeper &records)
1074 : Records(records), AsmParser(asmParser), Target(target),
1075 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
1078 /// BuildOperandMatchInfo - Build the necessary information to handle user
1079 /// defined operand parsing methods.
1080 void AsmMatcherInfo::BuildOperandMatchInfo() {
1082 /// Map containing a mask with all operands indicies that can be found for
1083 /// that class inside a instruction.
1084 std::map<ClassInfo*, unsigned> OpClassMask;
1086 for (std::vector<MatchableInfo*>::const_iterator it =
1087 Matchables.begin(), ie = Matchables.end();
1089 MatchableInfo &II = **it;
1090 OpClassMask.clear();
1092 // Keep track of all operands of this instructions which belong to the
1094 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1095 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1096 if (Op.Class->ParserMethod.empty())
1098 unsigned &OperandMask = OpClassMask[Op.Class];
1099 OperandMask |= (1 << i);
1102 // Generate operand match info for each mnemonic/operand class pair.
1103 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1104 iie = OpClassMask.end(); iit != iie; ++iit) {
1105 unsigned OpMask = iit->second;
1106 ClassInfo *CI = iit->first;
1107 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1112 void AsmMatcherInfo::BuildInfo() {
1113 // Build information about all of the AssemblerPredicates.
1114 std::vector<Record*> AllPredicates =
1115 Records.getAllDerivedDefinitions("Predicate");
1116 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1117 Record *Pred = AllPredicates[i];
1118 // Ignore predicates that are not intended for the assembler.
1119 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1122 if (Pred->getName().empty())
1123 throw TGError(Pred->getLoc(), "Predicate has no name!");
1125 unsigned FeatureNo = SubtargetFeatures.size();
1126 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1127 assert(FeatureNo < 32 && "Too many subtarget features!");
1130 StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
1132 // Parse the instructions; we need to do this first so that we can gather the
1133 // singleton register classes.
1134 SmallPtrSet<Record*, 16> SingletonRegisters;
1135 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1136 E = Target.inst_end(); I != E; ++I) {
1137 const CodeGenInstruction &CGI = **I;
1139 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1140 // filter the set of instructions we consider.
1141 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1144 // Ignore "codegen only" instructions.
1145 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1148 // Validate the operand list to ensure we can handle this instruction.
1149 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1150 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1152 // Validate tied operands.
1153 if (OI.getTiedRegister() != -1) {
1154 // If we have a tied operand that consists of multiple MCOperands,
1155 // reject it. We reject aliases and ignore instructions for now.
1156 if (OI.MINumOperands != 1) {
1157 // FIXME: Should reject these. The ARM backend hits this with $lane
1158 // in a bunch of instructions. It is unclear what the right answer is.
1160 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1161 << "ignoring instruction with multi-operand tied operand '"
1162 << OI.Name << "'\n";
1169 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1171 II->Initialize(*this, SingletonRegisters);
1173 // Ignore instructions which shouldn't be matched and diagnose invalid
1174 // instruction definitions with an error.
1175 if (!II->Validate(CommentDelimiter, true))
1178 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1180 // FIXME: This is a total hack.
1181 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1182 StringRef(II->TheDef->getName()).endswith("_Int"))
1185 Matchables.push_back(II.take());
1188 // Parse all of the InstAlias definitions and stick them in the list of
1190 std::vector<Record*> AllInstAliases =
1191 Records.getAllDerivedDefinitions("InstAlias");
1192 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1193 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1195 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1196 // filter the set of instruction aliases we consider, based on the target
1198 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1202 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1204 II->Initialize(*this, SingletonRegisters);
1206 // Validate the alias definitions.
1207 II->Validate(CommentDelimiter, false);
1209 Matchables.push_back(II.take());
1212 // Build info for the register classes.
1213 BuildRegisterClasses(SingletonRegisters);
1215 // Build info for the user defined assembly operand classes.
1216 BuildOperandClasses();
1218 // Build the information about matchables, now that we have fully formed
1220 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1221 ie = Matchables.end(); it != ie; ++it) {
1222 MatchableInfo *II = *it;
1224 // Parse the tokens after the mnemonic.
1225 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1226 // don't precompute the loop bound.
1227 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1228 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1229 StringRef Token = Op.Token;
1231 // Check for singleton registers.
1232 if (Record *RegRecord = II->getSingletonRegisterForAsmOperand(i, *this)) {
1233 Op.Class = RegisterClasses[RegRecord];
1234 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1235 "Unexpected class for singleton register");
1239 // Check for simple tokens.
1240 if (Token[0] != '$') {
1241 Op.Class = getTokenClass(Token);
1245 if (Token.size() > 1 && isdigit(Token[1])) {
1246 Op.Class = getTokenClass(Token);
1250 // Otherwise this is an operand reference.
1251 StringRef OperandName;
1252 if (Token[1] == '{')
1253 OperandName = Token.substr(2, Token.size() - 3);
1255 OperandName = Token.substr(1);
1257 if (II->DefRec.is<const CodeGenInstruction*>())
1258 BuildInstructionOperandReference(II, OperandName, i);
1260 BuildAliasOperandReference(II, OperandName, Op);
1263 if (II->DefRec.is<const CodeGenInstruction*>())
1264 II->BuildInstructionResultOperands();
1266 II->BuildAliasResultOperands();
1269 // Reorder classes so that classes precede super classes.
1270 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1273 /// BuildInstructionOperandReference - The specified operand is a reference to a
1274 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1275 void AsmMatcherInfo::
1276 BuildInstructionOperandReference(MatchableInfo *II,
1277 StringRef OperandName,
1278 unsigned AsmOpIdx) {
1279 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1280 const CGIOperandList &Operands = CGI.Operands;
1281 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1283 // Map this token to an operand.
1285 if (!Operands.hasOperandNamed(OperandName, Idx))
1286 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1287 OperandName.str() + "'");
1289 // If the instruction operand has multiple suboperands, but the parser
1290 // match class for the asm operand is still the default "ImmAsmOperand",
1291 // then handle each suboperand separately.
1292 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1293 Record *Rec = Operands[Idx].Rec;
1294 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1295 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1296 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1297 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1298 StringRef Token = Op->Token; // save this in case Op gets moved
1299 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1300 MatchableInfo::AsmOperand NewAsmOp(Token);
1301 NewAsmOp.SubOpIdx = SI;
1302 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1304 // Replace Op with first suboperand.
1305 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1310 // Set up the operand class.
1311 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1313 // If the named operand is tied, canonicalize it to the untied operand.
1314 // For example, something like:
1315 // (outs GPR:$dst), (ins GPR:$src)
1316 // with an asmstring of
1318 // we want to canonicalize to:
1320 // so that we know how to provide the $dst operand when filling in the result.
1321 int OITied = Operands[Idx].getTiedRegister();
1323 // The tied operand index is an MIOperand index, find the operand that
1325 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1326 OperandName = Operands[Idx.first].Name;
1327 Op->SubOpIdx = Idx.second;
1330 Op->SrcOpName = OperandName;
1333 /// BuildAliasOperandReference - When parsing an operand reference out of the
1334 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1335 /// operand reference is by looking it up in the result pattern definition.
1336 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1337 StringRef OperandName,
1338 MatchableInfo::AsmOperand &Op) {
1339 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1341 // Set up the operand class.
1342 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1343 if (CGA.ResultOperands[i].isRecord() &&
1344 CGA.ResultOperands[i].getName() == OperandName) {
1345 // It's safe to go with the first one we find, because CodeGenInstAlias
1346 // validates that all operands with the same name have the same record.
1347 unsigned ResultIdx = CGA.ResultInstOperandIndex[i].first;
1348 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1349 Op.Class = getOperandClass(CGA.ResultInst->Operands[ResultIdx],
1351 Op.SrcOpName = OperandName;
1355 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1356 OperandName.str() + "'");
1359 void MatchableInfo::BuildInstructionResultOperands() {
1360 const CodeGenInstruction *ResultInst = getResultInst();
1362 // Loop over all operands of the result instruction, determining how to
1364 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1365 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1367 // If this is a tied operand, just copy from the previously handled operand.
1368 int TiedOp = OpInfo.getTiedRegister();
1370 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1374 // Find out what operand from the asmparser this MCInst operand comes from.
1375 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1376 if (OpInfo.Name.empty() || SrcOperand == -1)
1377 throw TGError(TheDef->getLoc(), "Instruction '" +
1378 TheDef->getName() + "' has operand '" + OpInfo.Name +
1379 "' that doesn't appear in asm string!");
1381 // Check if the one AsmOperand populates the entire operand.
1382 unsigned NumOperands = OpInfo.MINumOperands;
1383 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1384 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1388 // Add a separate ResOperand for each suboperand.
1389 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1390 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1391 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1392 "unexpected AsmOperands for suboperands");
1393 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1398 void MatchableInfo::BuildAliasResultOperands() {
1399 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1400 const CodeGenInstruction *ResultInst = getResultInst();
1402 // Loop over all operands of the result instruction, determining how to
1404 unsigned AliasOpNo = 0;
1405 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1406 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1407 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1409 // If this is a tied operand, just copy from the previously handled operand.
1410 int TiedOp = OpInfo->getTiedRegister();
1412 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1416 // Handle all the suboperands for this operand.
1417 const std::string &OpName = OpInfo->Name;
1418 for ( ; AliasOpNo < LastOpNo &&
1419 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1420 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1422 // Find out what operand from the asmparser that this MCInst operand
1424 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1425 default: assert(0 && "unexpected InstAlias operand kind");
1426 case CodeGenInstAlias::ResultOperand::K_Record: {
1427 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1428 int SrcOperand = FindAsmOperand(Name, SubIdx);
1429 if (SrcOperand == -1)
1430 throw TGError(TheDef->getLoc(), "Instruction '" +
1431 TheDef->getName() + "' has operand '" + OpName +
1432 "' that doesn't appear in asm string!");
1433 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1434 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1438 case CodeGenInstAlias::ResultOperand::K_Imm: {
1439 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1440 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1443 case CodeGenInstAlias::ResultOperand::K_Reg: {
1444 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1445 ResOperands.push_back(ResOperand::getRegOp(Reg));
1453 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1454 std::vector<MatchableInfo*> &Infos,
1456 // Write the convert function to a separate stream, so we can drop it after
1458 std::string ConvertFnBody;
1459 raw_string_ostream CvtOS(ConvertFnBody);
1461 // Function we have already generated.
1462 std::set<std::string> GeneratedFns;
1464 // Start the unified conversion function.
1465 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1466 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1467 << "unsigned Opcode,\n"
1468 << " const SmallVectorImpl<MCParsedAsmOperand*"
1469 << "> &Operands) {\n";
1470 CvtOS << " Inst.setOpcode(Opcode);\n";
1471 CvtOS << " switch (Kind) {\n";
1472 CvtOS << " default:\n";
1474 // Start the enum, which we will generate inline.
1476 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1477 OS << "enum ConversionKind {\n";
1479 // TargetOperandClass - This is the target's operand class, like X86Operand.
1480 std::string TargetOperandClass = Target.getName() + "Operand";
1482 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1483 ie = Infos.end(); it != ie; ++it) {
1484 MatchableInfo &II = **it;
1486 // Check if we have a custom match function.
1487 std::string AsmMatchConverter =
1488 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1489 if (!AsmMatchConverter.empty()) {
1490 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1491 II.ConversionFnKind = Signature;
1493 // Check if we have already generated this signature.
1494 if (!GeneratedFns.insert(Signature).second)
1497 // If not, emit it now. Add to the enum list.
1498 OS << " " << Signature << ",\n";
1500 CvtOS << " case " << Signature << ":\n";
1501 CvtOS << " return " << AsmMatchConverter
1502 << "(Inst, Opcode, Operands);\n";
1506 // Build the conversion function signature.
1507 std::string Signature = "Convert";
1508 std::string CaseBody;
1509 raw_string_ostream CaseOS(CaseBody);
1511 // Compute the convert enum and the case body.
1512 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1513 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1515 // Generate code to populate each result operand.
1516 switch (OpInfo.Kind) {
1517 case MatchableInfo::ResOperand::RenderAsmOperand: {
1518 // This comes from something we parsed.
1519 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1521 // Registers are always converted the same, don't duplicate the
1522 // conversion function based on them.
1524 if (Op.Class->isRegisterClass())
1527 Signature += Op.Class->ClassName;
1528 Signature += utostr(OpInfo.MINumOperands);
1529 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1531 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1532 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1533 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1537 case MatchableInfo::ResOperand::TiedOperand: {
1538 // If this operand is tied to a previous one, just copy the MCInst
1539 // operand from the earlier one.We can only tie single MCOperand values.
1540 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1541 unsigned TiedOp = OpInfo.TiedOperandNum;
1542 assert(i > TiedOp && "Tied operand precedes its target!");
1543 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1544 Signature += "__Tie" + utostr(TiedOp);
1547 case MatchableInfo::ResOperand::ImmOperand: {
1548 int64_t Val = OpInfo.ImmVal;
1549 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1550 Signature += "__imm" + itostr(Val);
1553 case MatchableInfo::ResOperand::RegOperand: {
1554 if (OpInfo.Register == 0) {
1555 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1556 Signature += "__reg0";
1558 std::string N = getQualifiedName(OpInfo.Register);
1559 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1560 Signature += "__reg" + OpInfo.Register->getName();
1566 II.ConversionFnKind = Signature;
1568 // Check if we have already generated this signature.
1569 if (!GeneratedFns.insert(Signature).second)
1572 // If not, emit it now. Add to the enum list.
1573 OS << " " << Signature << ",\n";
1575 CvtOS << " case " << Signature << ":\n";
1576 CvtOS << CaseOS.str();
1577 CvtOS << " return true;\n";
1580 // Finish the convert function.
1583 CvtOS << " return false;\n";
1586 // Finish the enum, and drop the convert function after it.
1588 OS << " NumConversionVariants\n";
1594 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1595 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1596 std::vector<ClassInfo*> &Infos,
1598 OS << "namespace {\n\n";
1600 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1601 << "/// instruction matching.\n";
1602 OS << "enum MatchClassKind {\n";
1603 OS << " InvalidMatchClass = 0,\n";
1604 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1605 ie = Infos.end(); it != ie; ++it) {
1606 ClassInfo &CI = **it;
1607 OS << " " << CI.Name << ", // ";
1608 if (CI.Kind == ClassInfo::Token) {
1609 OS << "'" << CI.ValueName << "'\n";
1610 } else if (CI.isRegisterClass()) {
1611 if (!CI.ValueName.empty())
1612 OS << "register class '" << CI.ValueName << "'\n";
1614 OS << "derived register class\n";
1616 OS << "user defined class '" << CI.ValueName << "'\n";
1619 OS << " NumMatchClassKinds\n";
1625 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1626 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1628 OS << "static bool ValidateOperandClass(MCParsedAsmOperand *GOp, "
1629 << "MatchClassKind Kind) {\n";
1630 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1631 << Info.Target.getName() << "Operand*)GOp;\n";
1633 // Check for Token operands first.
1634 OS << " if (Operand.isToken())\n";
1635 OS << " return MatchTokenString(Operand.getToken()) == Kind;\n\n";
1637 // Check for register operands, including sub-classes.
1638 OS << " if (Operand.isReg()) {\n";
1639 OS << " MatchClassKind OpKind;\n";
1640 OS << " switch (Operand.getReg()) {\n";
1641 OS << " default: OpKind = InvalidMatchClass; break;\n";
1642 for (std::map<Record*, ClassInfo*>::iterator
1643 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1645 OS << " case " << Info.Target.getName() << "::"
1646 << it->first->getName() << ": OpKind = " << it->second->Name
1649 OS << " return IsSubclass(OpKind, Kind);\n";
1652 // Check the user classes. We don't care what order since we're only
1653 // actually matching against one of them.
1654 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1655 ie = Info.Classes.end(); it != ie; ++it) {
1656 ClassInfo &CI = **it;
1658 if (!CI.isUserClass())
1661 OS << " // '" << CI.ClassName << "' class\n";
1662 OS << " if (Kind == " << CI.Name
1663 << " && Operand." << CI.PredicateMethod << "()) {\n";
1664 OS << " return true;\n";
1668 OS << " return false;\n";
1672 /// EmitIsSubclass - Emit the subclass predicate function.
1673 static void EmitIsSubclass(CodeGenTarget &Target,
1674 std::vector<ClassInfo*> &Infos,
1676 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1677 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1678 OS << " if (A == B)\n";
1679 OS << " return true;\n\n";
1681 OS << " switch (A) {\n";
1682 OS << " default:\n";
1683 OS << " return false;\n";
1684 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1685 ie = Infos.end(); it != ie; ++it) {
1686 ClassInfo &A = **it;
1688 if (A.Kind != ClassInfo::Token) {
1689 std::vector<StringRef> SuperClasses;
1690 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1691 ie = Infos.end(); it != ie; ++it) {
1692 ClassInfo &B = **it;
1694 if (&A != &B && A.isSubsetOf(B))
1695 SuperClasses.push_back(B.Name);
1698 if (SuperClasses.empty())
1701 OS << "\n case " << A.Name << ":\n";
1703 if (SuperClasses.size() == 1) {
1704 OS << " return B == " << SuperClasses.back() << ";\n";
1708 OS << " switch (B) {\n";
1709 OS << " default: return false;\n";
1710 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1711 OS << " case " << SuperClasses[i] << ": return true;\n";
1719 /// EmitMatchTokenString - Emit the function to match a token string to the
1720 /// appropriate match class value.
1721 static void EmitMatchTokenString(CodeGenTarget &Target,
1722 std::vector<ClassInfo*> &Infos,
1724 // Construct the match list.
1725 std::vector<StringMatcher::StringPair> Matches;
1726 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1727 ie = Infos.end(); it != ie; ++it) {
1728 ClassInfo &CI = **it;
1730 if (CI.Kind == ClassInfo::Token)
1731 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1732 "return " + CI.Name + ";"));
1735 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1737 StringMatcher("Name", Matches, OS).Emit();
1739 OS << " return InvalidMatchClass;\n";
1743 /// EmitMatchRegisterName - Emit the function to match a string to the target
1744 /// specific register enum.
1745 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1747 // Construct the match list.
1748 std::vector<StringMatcher::StringPair> Matches;
1749 const std::vector<CodeGenRegister*> &Regs =
1750 Target.getRegBank().getRegisters();
1751 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1752 const CodeGenRegister *Reg = Regs[i];
1753 if (Reg->TheDef->getValueAsString("AsmName").empty())
1756 Matches.push_back(StringMatcher::StringPair(
1757 Reg->TheDef->getValueAsString("AsmName"),
1758 "return " + utostr(Reg->EnumValue) + ";"));
1761 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1763 StringMatcher("Name", Matches, OS).Emit();
1765 OS << " return 0;\n";
1769 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1771 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1773 OS << "// Flags for subtarget features that participate in "
1774 << "instruction matching.\n";
1775 OS << "enum SubtargetFeatureFlag {\n";
1776 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1777 it = Info.SubtargetFeatures.begin(),
1778 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1779 SubtargetFeatureInfo &SFI = *it->second;
1780 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1782 OS << " Feature_None = 0\n";
1786 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1787 /// available features given a subtarget.
1788 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1790 std::string ClassName =
1791 Info.AsmParser->getValueAsString("AsmParserClassName");
1793 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1794 << "ComputeAvailableFeatures(const " << Info.Target.getName()
1795 << "Subtarget *Subtarget) const {\n";
1796 OS << " unsigned Features = 0;\n";
1797 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1798 it = Info.SubtargetFeatures.begin(),
1799 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1800 SubtargetFeatureInfo &SFI = *it->second;
1801 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1803 OS << " Features |= " << SFI.getEnumName() << ";\n";
1805 OS << " return Features;\n";
1809 static std::string GetAliasRequiredFeatures(Record *R,
1810 const AsmMatcherInfo &Info) {
1811 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1813 unsigned NumFeatures = 0;
1814 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1815 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1818 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1819 "' is not marked as an AssemblerPredicate!");
1824 Result += F->getEnumName();
1828 if (NumFeatures > 1)
1829 Result = '(' + Result + ')';
1833 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1834 /// emit a function for them and return true, otherwise return false.
1835 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1836 // Ignore aliases when match-prefix is set.
1837 if (!MatchPrefix.empty())
1840 std::vector<Record*> Aliases =
1841 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1842 if (Aliases.empty()) return false;
1844 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1845 "unsigned Features) {\n";
1847 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1848 // iteration order of the map is stable.
1849 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1851 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1852 Record *R = Aliases[i];
1853 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1856 // Process each alias a "from" mnemonic at a time, building the code executed
1857 // by the string remapper.
1858 std::vector<StringMatcher::StringPair> Cases;
1859 for (std::map<std::string, std::vector<Record*> >::iterator
1860 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1862 const std::vector<Record*> &ToVec = I->second;
1864 // Loop through each alias and emit code that handles each case. If there
1865 // are two instructions without predicates, emit an error. If there is one,
1867 std::string MatchCode;
1868 int AliasWithNoPredicate = -1;
1870 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1871 Record *R = ToVec[i];
1872 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1874 // If this unconditionally matches, remember it for later and diagnose
1876 if (FeatureMask.empty()) {
1877 if (AliasWithNoPredicate != -1) {
1878 // We can't have two aliases from the same mnemonic with no predicate.
1879 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1880 "two MnemonicAliases with the same 'from' mnemonic!");
1881 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1884 AliasWithNoPredicate = i;
1887 if (R->getValueAsString("ToMnemonic") == I->first)
1888 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1890 if (!MatchCode.empty())
1891 MatchCode += "else ";
1892 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1893 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1896 if (AliasWithNoPredicate != -1) {
1897 Record *R = ToVec[AliasWithNoPredicate];
1898 if (!MatchCode.empty())
1899 MatchCode += "else\n ";
1900 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1903 MatchCode += "return;";
1905 Cases.push_back(std::make_pair(I->first, MatchCode));
1908 StringMatcher("Mnemonic", Cases, OS).Emit();
1914 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
1915 const AsmMatcherInfo &Info, StringRef ClassName) {
1916 // Emit the static custom operand parsing table;
1917 OS << "namespace {\n";
1918 OS << " struct OperandMatchEntry {\n";
1919 OS << " const char *Mnemonic;\n";
1920 OS << " unsigned OperandMask;\n";
1921 OS << " MatchClassKind Class;\n";
1922 OS << " unsigned RequiredFeatures;\n";
1925 OS << " // Predicate for searching for an opcode.\n";
1926 OS << " struct LessOpcodeOperand {\n";
1927 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
1928 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1930 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
1931 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1933 OS << " bool operator()(const OperandMatchEntry &LHS,";
1934 OS << " const OperandMatchEntry &RHS) {\n";
1935 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1939 OS << "} // end anonymous namespace.\n\n";
1941 OS << "static const OperandMatchEntry OperandMatchTable["
1942 << Info.OperandMatchInfo.size() << "] = {\n";
1944 OS << " /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
1945 for (std::vector<OperandMatchEntry>::const_iterator it =
1946 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
1948 const OperandMatchEntry &OMI = *it;
1949 const MatchableInfo &II = *OMI.MI;
1951 OS << " { \"" << II.Mnemonic << "\""
1952 << ", " << OMI.OperandMask;
1955 bool printComma = false;
1956 for (int i = 0, e = 31; i !=e; ++i)
1957 if (OMI.OperandMask & (1 << i)) {
1965 OS << ", " << OMI.CI->Name
1968 // Write the required features mask.
1969 if (!II.RequiredFeatures.empty()) {
1970 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1972 OS << II.RequiredFeatures[i]->getEnumName();
1980 // Emit the operand class switch to call the correct custom parser for
1981 // the found operand class.
1982 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
1983 << Target.getName() << ClassName << "::\n"
1984 << "TryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
1985 << " &Operands,\n unsigned MCK) {\n\n"
1986 << " switch(MCK) {\n";
1988 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
1989 ie = Info.Classes.end(); it != ie; ++it) {
1990 ClassInfo *CI = *it;
1991 if (CI->ParserMethod.empty())
1993 OS << " case " << CI->Name << ":\n"
1994 << " return " << CI->ParserMethod << "(Operands);\n";
1997 OS << " default:\n";
1998 OS << " return MatchOperand_NoMatch;\n";
2000 OS << " return MatchOperand_NoMatch;\n";
2003 // Emit the static custom operand parser. This code is very similar with
2004 // the other matcher. Also use MatchResultTy here just in case we go for
2005 // a better error handling.
2006 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2007 << Target.getName() << ClassName << "::\n"
2008 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2009 << " &Operands,\n StringRef Mnemonic) {\n";
2011 // Emit code to get the available features.
2012 OS << " // Get the current feature set.\n";
2013 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2015 OS << " // Get the next operand index.\n";
2016 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2018 // Emit code to search the table.
2019 OS << " // Search the table.\n";
2020 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2021 OS << " MnemonicRange =\n";
2022 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2023 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2024 << " LessOpcodeOperand());\n\n";
2026 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2027 OS << " return MatchOperand_NoMatch;\n\n";
2029 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2030 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2032 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2033 OS << " assert(Mnemonic == it->Mnemonic);\n\n";
2035 // Emit check that the required features are available.
2036 OS << " // check if the available features match\n";
2037 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2038 << "!= it->RequiredFeatures) {\n";
2039 OS << " continue;\n";
2042 // Emit check to ensure the operand number matches.
2043 OS << " // check if the operand in question has a custom parser.\n";
2044 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2045 OS << " continue;\n\n";
2047 // Emit call to the custom parser method
2048 OS << " // call custom parse method to handle the operand\n";
2049 OS << " OperandMatchResultTy Result = ";
2050 OS << "TryCustomParseOperand(Operands, it->Class);\n";
2051 OS << " if (Result != MatchOperand_NoMatch)\n";
2052 OS << " return Result;\n";
2055 OS << " // Okay, we had no match.\n";
2056 OS << " return MatchOperand_NoMatch;\n";
2060 void AsmMatcherEmitter::run(raw_ostream &OS) {
2061 CodeGenTarget Target(Records);
2062 Record *AsmParser = Target.getAsmParser();
2063 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2065 // Compute the information on the instructions to match.
2066 AsmMatcherInfo Info(AsmParser, Target, Records);
2069 // Sort the instruction table using the partial order on classes. We use
2070 // stable_sort to ensure that ambiguous instructions are still
2071 // deterministically ordered.
2072 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2073 less_ptr<MatchableInfo>());
2075 DEBUG_WITH_TYPE("instruction_info", {
2076 for (std::vector<MatchableInfo*>::iterator
2077 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2082 // Check for ambiguous matchables.
2083 DEBUG_WITH_TYPE("ambiguous_instrs", {
2084 unsigned NumAmbiguous = 0;
2085 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2086 for (unsigned j = i + 1; j != e; ++j) {
2087 MatchableInfo &A = *Info.Matchables[i];
2088 MatchableInfo &B = *Info.Matchables[j];
2090 if (A.CouldMatchAmbiguouslyWith(B)) {
2091 errs() << "warning: ambiguous matchables:\n";
2093 errs() << "\nis incomparable with:\n";
2101 errs() << "warning: " << NumAmbiguous
2102 << " ambiguous matchables!\n";
2105 // Compute the information on the custom operand parsing.
2106 Info.BuildOperandMatchInfo();
2108 // Write the output.
2110 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2112 // Information for the class declaration.
2113 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2114 OS << "#undef GET_ASSEMBLER_HEADER\n";
2115 OS << " // This should be included into the middle of the declaration of\n";
2116 OS << " // your subclasses implementation of TargetAsmParser.\n";
2117 OS << " unsigned ComputeAvailableFeatures(const " <<
2118 Target.getName() << "Subtarget *Subtarget) const;\n";
2119 OS << " enum MatchResultTy {\n";
2120 OS << " Match_ConversionFail,\n";
2121 OS << " Match_InvalidOperand,\n";
2122 OS << " Match_MissingFeature,\n";
2123 OS << " Match_MnemonicFail,\n";
2124 OS << " Match_Success\n";
2126 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2127 << "unsigned Opcode,\n"
2128 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2130 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2131 OS << " MatchResultTy MatchInstructionImpl(\n";
2132 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2133 OS << " MCInst &Inst, unsigned &ErrorInfo);\n";
2135 if (Info.OperandMatchInfo.size()) {
2136 OS << "\n enum OperandMatchResultTy {\n";
2137 OS << " MatchOperand_Success, // operand matched successfully\n";
2138 OS << " MatchOperand_NoMatch, // operand did not match\n";
2139 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2141 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2142 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2143 OS << " StringRef Mnemonic);\n";
2145 OS << " OperandMatchResultTy TryCustomParseOperand(\n";
2146 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2147 OS << " unsigned MCK);\n\n";
2150 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2152 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2153 OS << "#undef GET_REGISTER_MATCHER\n\n";
2155 // Emit the subtarget feature enumeration.
2156 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2158 // Emit the function to match a register name to number.
2159 EmitMatchRegisterName(Target, AsmParser, OS);
2161 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2164 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2165 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2167 // Generate the function that remaps for mnemonic aliases.
2168 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2170 // Generate the unified function to convert operands into an MCInst.
2171 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2173 // Emit the enumeration for classes which participate in matching.
2174 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2176 // Emit the routine to match token strings to their match class.
2177 EmitMatchTokenString(Target, Info.Classes, OS);
2179 // Emit the subclass predicate routine.
2180 EmitIsSubclass(Target, Info.Classes, OS);
2182 // Emit the routine to validate an operand against a match class.
2183 EmitValidateOperandClass(Info, OS);
2185 // Emit the available features compute function.
2186 EmitComputeAvailableFeatures(Info, OS);
2189 size_t MaxNumOperands = 0;
2190 for (std::vector<MatchableInfo*>::const_iterator it =
2191 Info.Matchables.begin(), ie = Info.Matchables.end();
2193 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2195 // Emit the static match table; unused classes get initalized to 0 which is
2196 // guaranteed to be InvalidMatchClass.
2198 // FIXME: We can reduce the size of this table very easily. First, we change
2199 // it so that store the kinds in separate bit-fields for each index, which
2200 // only needs to be the max width used for classes at that index (we also need
2201 // to reject based on this during classification). If we then make sure to
2202 // order the match kinds appropriately (putting mnemonics last), then we
2203 // should only end up using a few bits for each class, especially the ones
2204 // following the mnemonic.
2205 OS << "namespace {\n";
2206 OS << " struct MatchEntry {\n";
2207 OS << " unsigned Opcode;\n";
2208 OS << " const char *Mnemonic;\n";
2209 OS << " ConversionKind ConvertFn;\n";
2210 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
2211 OS << " unsigned RequiredFeatures;\n";
2214 OS << " // Predicate for searching for an opcode.\n";
2215 OS << " struct LessOpcode {\n";
2216 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2217 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2219 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2220 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2222 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2223 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2227 OS << "} // end anonymous namespace.\n\n";
2229 OS << "static const MatchEntry MatchTable["
2230 << Info.Matchables.size() << "] = {\n";
2232 for (std::vector<MatchableInfo*>::const_iterator it =
2233 Info.Matchables.begin(), ie = Info.Matchables.end();
2235 MatchableInfo &II = **it;
2237 OS << " { " << Target.getName() << "::"
2238 << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2239 << ", " << II.ConversionFnKind << ", { ";
2240 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2241 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2244 OS << Op.Class->Name;
2248 // Write the required features mask.
2249 if (!II.RequiredFeatures.empty()) {
2250 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2252 OS << II.RequiredFeatures[i]->getEnumName();
2262 // A method to determine if a mnemonic is in the list.
2263 OS << "bool " << Target.getName() << ClassName << "::\n"
2264 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2265 OS << " // Search the table.\n";
2266 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2267 OS << " std::equal_range(MatchTable, MatchTable+"
2268 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2269 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2272 // Finally, build the match function.
2273 OS << Target.getName() << ClassName << "::MatchResultTy "
2274 << Target.getName() << ClassName << "::\n"
2275 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2277 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
2279 // Emit code to get the available features.
2280 OS << " // Get the current feature set.\n";
2281 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2283 OS << " // Get the instruction mnemonic, which is the first token.\n";
2284 OS << " StringRef Mnemonic = ((" << Target.getName()
2285 << "Operand*)Operands[0])->getToken();\n\n";
2287 if (HasMnemonicAliases) {
2288 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2289 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2292 // Emit code to compute the class list for this operand vector.
2293 OS << " // Eliminate obvious mismatches.\n";
2294 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2295 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2296 OS << " return Match_InvalidOperand;\n";
2299 OS << " // Some state to try to produce better error messages.\n";
2300 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
2301 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2302 OS << " // wrong for all instances of the instruction.\n";
2303 OS << " ErrorInfo = ~0U;\n";
2305 // Emit code to search the table.
2306 OS << " // Search the table.\n";
2307 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2308 OS << " std::equal_range(MatchTable, MatchTable+"
2309 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2311 OS << " // Return a more specific error code if no mnemonics match.\n";
2312 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2313 OS << " return Match_MnemonicFail;\n\n";
2315 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2316 << "*ie = MnemonicRange.second;\n";
2317 OS << " it != ie; ++it) {\n";
2319 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2320 OS << " assert(Mnemonic == it->Mnemonic);\n";
2322 // Emit check that the subclasses match.
2323 OS << " bool OperandsValid = true;\n";
2324 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2325 OS << " if (i + 1 >= Operands.size()) {\n";
2326 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2329 OS << " if (ValidateOperandClass(Operands[i+1], it->Classes[i]))\n";
2330 OS << " continue;\n";
2331 OS << " // If this operand is broken for all of the instances of this\n";
2332 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2333 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2334 OS << " ErrorInfo = i+1;\n";
2335 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2336 OS << " OperandsValid = false;\n";
2340 OS << " if (!OperandsValid) continue;\n";
2342 // Emit check that the required features are available.
2343 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2344 << "!= it->RequiredFeatures) {\n";
2345 OS << " HadMatchOtherThanFeatures = true;\n";
2346 OS << " continue;\n";
2349 OS << " // We have selected a definite instruction, convert the parsed\n"
2350 << " // operands into the appropriate MCInst.\n";
2351 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2352 << " it->Opcode, Operands))\n";
2353 OS << " return Match_ConversionFail;\n";
2356 // Call the post-processing function, if used.
2357 std::string InsnCleanupFn =
2358 AsmParser->getValueAsString("AsmParserInstCleanup");
2359 if (!InsnCleanupFn.empty())
2360 OS << " " << InsnCleanupFn << "(Inst);\n";
2362 OS << " return Match_Success;\n";
2365 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2366 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
2367 OS << " return Match_InvalidOperand;\n";
2370 if (Info.OperandMatchInfo.size())
2371 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2373 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";