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"
101 #include "StringMatcher.h"
102 #include "StringToOffsetTable.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"
111 #include "llvm/Support/ErrorHandling.h"
112 #include "llvm/TableGen/Error.h"
113 #include "llvm/TableGen/Record.h"
116 using namespace llvm;
118 static cl::opt<std::string>
119 MatchPrefix("match-prefix", cl::init(""),
120 cl::desc("Only match instructions with the given prefix"));
123 class AsmMatcherInfo;
124 struct SubtargetFeatureInfo;
126 /// ClassInfo - Helper class for storing the information about a particular
127 /// class of operands which can be matched.
130 /// Invalid kind, for use as a sentinel value.
133 /// The class for a particular token.
136 /// The (first) register class, subsequent register classes are
137 /// RegisterClass0+1, and so on.
140 /// The (first) user defined class, subsequent user defined classes are
141 /// UserClass0+1, and so on.
145 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
146 /// N) for the Nth user defined class.
149 /// SuperClasses - The super classes of this class. Note that for simplicities
150 /// sake user operands only record their immediate super class, while register
151 /// operands include all superclasses.
152 std::vector<ClassInfo*> SuperClasses;
154 /// Name - The full class name, suitable for use in an enum.
157 /// ClassName - The unadorned generic name for this class (e.g., Token).
158 std::string ClassName;
160 /// ValueName - The name of the value this class represents; for a token this
161 /// is the literal token string, for an operand it is the TableGen class (or
162 /// empty if this is a derived class).
163 std::string ValueName;
165 /// PredicateMethod - The name of the operand method to test whether the
166 /// operand matches this class; this is not valid for Token or register kinds.
167 std::string PredicateMethod;
169 /// RenderMethod - The name of the operand method to add this operand to an
170 /// MCInst; this is not valid for Token or register kinds.
171 std::string RenderMethod;
173 /// ParserMethod - The name of the operand method to do a target specific
174 /// parsing on the operand.
175 std::string ParserMethod;
177 /// For register classes, the records for all the registers in this class.
178 std::set<Record*> Registers;
181 /// isRegisterClass() - Check if this is a register class.
182 bool isRegisterClass() const {
183 return Kind >= RegisterClass0 && Kind < UserClass0;
186 /// isUserClass() - Check if this is a user defined class.
187 bool isUserClass() const {
188 return Kind >= UserClass0;
191 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
192 /// are related if they are in the same class hierarchy.
193 bool isRelatedTo(const ClassInfo &RHS) const {
194 // Tokens are only related to tokens.
195 if (Kind == Token || RHS.Kind == Token)
196 return Kind == Token && RHS.Kind == Token;
198 // Registers classes are only related to registers classes, and only if
199 // their intersection is non-empty.
200 if (isRegisterClass() || RHS.isRegisterClass()) {
201 if (!isRegisterClass() || !RHS.isRegisterClass())
204 std::set<Record*> Tmp;
205 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
206 std::set_intersection(Registers.begin(), Registers.end(),
207 RHS.Registers.begin(), RHS.Registers.end(),
213 // Otherwise we have two users operands; they are related if they are in the
214 // same class hierarchy.
216 // FIXME: This is an oversimplification, they should only be related if they
217 // intersect, however we don't have that information.
218 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
219 const ClassInfo *Root = this;
220 while (!Root->SuperClasses.empty())
221 Root = Root->SuperClasses.front();
223 const ClassInfo *RHSRoot = &RHS;
224 while (!RHSRoot->SuperClasses.empty())
225 RHSRoot = RHSRoot->SuperClasses.front();
227 return Root == RHSRoot;
230 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
231 bool isSubsetOf(const ClassInfo &RHS) const {
232 // This is a subset of RHS if it is the same class...
236 // ... or if any of its super classes are a subset of RHS.
237 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
238 ie = SuperClasses.end(); it != ie; ++it)
239 if ((*it)->isSubsetOf(RHS))
245 /// operator< - Compare two classes.
246 bool operator<(const ClassInfo &RHS) const {
250 // Unrelated classes can be ordered by kind.
251 if (!isRelatedTo(RHS))
252 return Kind < RHS.Kind;
256 llvm_unreachable("Invalid kind!");
259 // This class precedes the RHS if it is a proper subset of the RHS.
262 if (RHS.isSubsetOf(*this))
265 // Otherwise, order by name to ensure we have a total ordering.
266 return ValueName < RHS.ValueName;
271 /// MatchableInfo - Helper class for storing the necessary information for an
272 /// instruction or alias which is capable of being matched.
273 struct MatchableInfo {
275 /// Token - This is the token that the operand came from.
278 /// The unique class instance this operand should match.
281 /// The operand name this is, if anything.
284 /// The suboperand index within SrcOpName, or -1 for the entire operand.
287 /// Register record if this token is singleton register.
288 Record *SingletonReg;
290 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
294 /// ResOperand - This represents a single operand in the result instruction
295 /// generated by the match. In cases (like addressing modes) where a single
296 /// assembler operand expands to multiple MCOperands, this represents the
297 /// single assembler operand, not the MCOperand.
300 /// RenderAsmOperand - This represents an operand result that is
301 /// generated by calling the render method on the assembly operand. The
302 /// corresponding AsmOperand is specified by AsmOperandNum.
305 /// TiedOperand - This represents a result operand that is a duplicate of
306 /// a previous result operand.
309 /// ImmOperand - This represents an immediate value that is dumped into
313 /// RegOperand - This represents a fixed register that is dumped in.
318 /// This is the operand # in the AsmOperands list that this should be
320 unsigned AsmOperandNum;
322 /// TiedOperandNum - This is the (earlier) result operand that should be
324 unsigned TiedOperandNum;
326 /// ImmVal - This is the immediate value added to the instruction.
329 /// Register - This is the register record.
333 /// MINumOperands - The number of MCInst operands populated by this
335 unsigned MINumOperands;
337 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
339 X.Kind = RenderAsmOperand;
340 X.AsmOperandNum = AsmOpNum;
341 X.MINumOperands = NumOperands;
345 static ResOperand getTiedOp(unsigned TiedOperandNum) {
347 X.Kind = TiedOperand;
348 X.TiedOperandNum = TiedOperandNum;
353 static ResOperand getImmOp(int64_t Val) {
361 static ResOperand getRegOp(Record *Reg) {
370 /// AsmVariantID - Target's assembly syntax variant no.
373 /// TheDef - This is the definition of the instruction or InstAlias that this
374 /// matchable came from.
375 Record *const TheDef;
377 /// DefRec - This is the definition that it came from.
378 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
380 const CodeGenInstruction *getResultInst() const {
381 if (DefRec.is<const CodeGenInstruction*>())
382 return DefRec.get<const CodeGenInstruction*>();
383 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
386 /// ResOperands - This is the operand list that should be built for the result
388 std::vector<ResOperand> ResOperands;
390 /// AsmString - The assembly string for this instruction (with variants
391 /// removed), e.g. "movsx $src, $dst".
392 std::string AsmString;
394 /// Mnemonic - This is the first token of the matched instruction, its
398 /// AsmOperands - The textual operands that this instruction matches,
399 /// annotated with a class and where in the OperandList they were defined.
400 /// This directly corresponds to the tokenized AsmString after the mnemonic is
402 SmallVector<AsmOperand, 4> AsmOperands;
404 /// Predicates - The required subtarget features to match this instruction.
405 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
407 /// ConversionFnKind - The enum value which is passed to the generated
408 /// ConvertToMCInst to convert parsed operands into an MCInst for this
410 std::string ConversionFnKind;
412 MatchableInfo(const CodeGenInstruction &CGI)
413 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
414 AsmString(CGI.AsmString) {
417 MatchableInfo(const CodeGenInstAlias *Alias)
418 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
419 AsmString(Alias->AsmString) {
422 void Initialize(const AsmMatcherInfo &Info,
423 SmallPtrSet<Record*, 16> &SingletonRegisters,
424 int AsmVariantNo, std::string &RegisterPrefix);
426 /// Validate - Return true if this matchable is a valid thing to match against
427 /// and perform a bunch of validity checking.
428 bool Validate(StringRef CommentDelimiter, bool Hack) const;
430 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
431 /// if present, from specified token.
433 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
434 std::string &RegisterPrefix);
436 /// FindAsmOperand - Find the AsmOperand with the specified name and
437 /// suboperand index.
438 int FindAsmOperand(StringRef N, int SubOpIdx) const {
439 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
440 if (N == AsmOperands[i].SrcOpName &&
441 SubOpIdx == AsmOperands[i].SubOpIdx)
446 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
447 /// This does not check the suboperand index.
448 int FindAsmOperandNamed(StringRef N) const {
449 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
450 if (N == AsmOperands[i].SrcOpName)
455 void BuildInstructionResultOperands();
456 void BuildAliasResultOperands();
458 /// operator< - Compare two matchables.
459 bool operator<(const MatchableInfo &RHS) const {
460 // The primary comparator is the instruction mnemonic.
461 if (Mnemonic != RHS.Mnemonic)
462 return Mnemonic < RHS.Mnemonic;
464 if (AsmOperands.size() != RHS.AsmOperands.size())
465 return AsmOperands.size() < RHS.AsmOperands.size();
467 // Compare lexicographically by operand. The matcher validates that other
468 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
469 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
470 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
472 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
479 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
480 /// ambiguously match the same set of operands as \arg RHS (without being a
481 /// strictly superior match).
482 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
483 // The primary comparator is the instruction mnemonic.
484 if (Mnemonic != RHS.Mnemonic)
487 // The number of operands is unambiguous.
488 if (AsmOperands.size() != RHS.AsmOperands.size())
491 // Otherwise, make sure the ordering of the two instructions is unambiguous
492 // by checking that either (a) a token or operand kind discriminates them,
493 // or (b) the ordering among equivalent kinds is consistent.
495 // Tokens and operand kinds are unambiguous (assuming a correct target
497 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
498 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
499 AsmOperands[i].Class->Kind == ClassInfo::Token)
500 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
501 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
504 // Otherwise, this operand could commute if all operands are equivalent, or
505 // there is a pair of operands that compare less than and a pair that
506 // compare greater than.
507 bool HasLT = false, HasGT = false;
508 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
509 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
511 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
515 return !(HasLT ^ HasGT);
521 void TokenizeAsmString(const AsmMatcherInfo &Info);
524 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
525 /// feature which participates in instruction matching.
526 struct SubtargetFeatureInfo {
527 /// \brief The predicate record for this feature.
530 /// \brief An unique index assigned to represent this feature.
533 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
535 /// \brief The name of the enumerated constant identifying this feature.
536 std::string getEnumName() const {
537 return "Feature_" + TheDef->getName();
541 struct OperandMatchEntry {
542 unsigned OperandMask;
546 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
549 X.OperandMask = opMask;
557 class AsmMatcherInfo {
560 RecordKeeper &Records;
562 /// The tablegen AsmParser record.
565 /// Target - The target information.
566 CodeGenTarget &Target;
568 /// The classes which are needed for matching.
569 std::vector<ClassInfo*> Classes;
571 /// The information on the matchables to match.
572 std::vector<MatchableInfo*> Matchables;
574 /// Info for custom matching operands by user defined methods.
575 std::vector<OperandMatchEntry> OperandMatchInfo;
577 /// Map of Register records to their class information.
578 std::map<Record*, ClassInfo*> RegisterClasses;
580 /// Map of Predicate records to their subtarget information.
581 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
584 /// Map of token to class information which has already been constructed.
585 std::map<std::string, ClassInfo*> TokenClasses;
587 /// Map of RegisterClass records to their class information.
588 std::map<Record*, ClassInfo*> RegisterClassClasses;
590 /// Map of AsmOperandClass records to their class information.
591 std::map<Record*, ClassInfo*> AsmOperandClasses;
594 /// getTokenClass - Lookup or create the class for the given token.
595 ClassInfo *getTokenClass(StringRef Token);
597 /// getOperandClass - Lookup or create the class for the given operand.
598 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
600 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
602 /// BuildRegisterClasses - Build the ClassInfo* instances for register
604 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
606 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
608 void BuildOperandClasses();
610 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
612 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
613 MatchableInfo::AsmOperand &Op);
616 AsmMatcherInfo(Record *AsmParser,
617 CodeGenTarget &Target,
618 RecordKeeper &Records);
620 /// BuildInfo - Construct the various tables used during matching.
623 /// BuildOperandMatchInfo - Build the necessary information to handle user
624 /// defined operand parsing methods.
625 void BuildOperandMatchInfo();
627 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
629 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
630 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
631 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
632 SubtargetFeatures.find(Def);
633 return I == SubtargetFeatures.end() ? 0 : I->second;
636 RecordKeeper &getRecords() const {
643 void MatchableInfo::dump() {
644 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
646 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
647 AsmOperand &Op = AsmOperands[i];
648 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
649 errs() << '\"' << Op.Token << "\"\n";
653 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
654 SmallPtrSet<Record*, 16> &SingletonRegisters,
655 int AsmVariantNo, std::string &RegisterPrefix) {
656 AsmVariantID = AsmVariantNo;
658 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
660 TokenizeAsmString(Info);
662 // Compute the require features.
663 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
664 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
665 if (SubtargetFeatureInfo *Feature =
666 Info.getSubtargetFeature(Predicates[i]))
667 RequiredFeatures.push_back(Feature);
669 // Collect singleton registers, if used.
670 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
671 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
672 if (Record *Reg = AsmOperands[i].SingletonReg)
673 SingletonRegisters.insert(Reg);
677 /// TokenizeAsmString - Tokenize a simplified assembly string.
678 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
679 StringRef String = AsmString;
682 for (unsigned i = 0, e = String.size(); i != e; ++i) {
692 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
695 if (!isspace(String[i]) && String[i] != ',')
696 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
702 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
706 assert(i != String.size() && "Invalid quoted character");
707 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
713 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
717 // If this isn't "${", treat like a normal token.
718 if (i + 1 == String.size() || String[i + 1] != '{') {
723 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
724 assert(End != String.end() && "Missing brace in operand reference!");
725 size_t EndPos = End - String.begin();
726 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
734 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
743 if (InTok && Prev != String.size())
744 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
746 // The first token of the instruction is the mnemonic, which must be a
747 // simple string, not a $foo variable or a singleton register.
748 if (AsmOperands.empty())
749 throw TGError(TheDef->getLoc(),
750 "Instruction '" + TheDef->getName() + "' has no tokens");
751 Mnemonic = AsmOperands[0].Token;
752 // FIXME : Check and raise an error if it is a register.
753 if (Mnemonic[0] == '$')
754 throw TGError(TheDef->getLoc(),
755 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
757 // Remove the first operand, it is tracked in the mnemonic field.
758 AsmOperands.erase(AsmOperands.begin());
761 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
762 // Reject matchables with no .s string.
763 if (AsmString.empty())
764 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
766 // Reject any matchables with a newline in them, they should be marked
767 // isCodeGenOnly if they are pseudo instructions.
768 if (AsmString.find('\n') != std::string::npos)
769 throw TGError(TheDef->getLoc(),
770 "multiline instruction is not valid for the asmparser, "
771 "mark it isCodeGenOnly");
773 // Remove comments from the asm string. We know that the asmstring only
775 if (!CommentDelimiter.empty() &&
776 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
777 throw TGError(TheDef->getLoc(),
778 "asmstring for instruction has comment character in it, "
779 "mark it isCodeGenOnly");
781 // Reject matchables with operand modifiers, these aren't something we can
782 // handle, the target should be refactored to use operands instead of
785 // Also, check for instructions which reference the operand multiple times;
786 // this implies a constraint we would not honor.
787 std::set<std::string> OperandNames;
788 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
789 StringRef Tok = AsmOperands[i].Token;
790 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
791 throw TGError(TheDef->getLoc(),
792 "matchable with operand modifier '" + Tok.str() +
793 "' not supported by asm matcher. Mark isCodeGenOnly!");
795 // Verify that any operand is only mentioned once.
796 // We reject aliases and ignore instructions for now.
797 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
799 throw TGError(TheDef->getLoc(),
800 "ERROR: matchable with tied operand '" + Tok.str() +
801 "' can never be matched!");
802 // FIXME: Should reject these. The ARM backend hits this with $lane in a
803 // bunch of instructions. It is unclear what the right answer is.
805 errs() << "warning: '" << TheDef->getName() << "': "
806 << "ignoring instruction with tied operand '"
807 << Tok.str() << "'\n";
816 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
817 /// if present, from specified token.
819 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
820 const AsmMatcherInfo &Info,
821 std::string &RegisterPrefix) {
822 StringRef Tok = AsmOperands[OperandNo].Token;
823 if (RegisterPrefix.empty()) {
824 std::string LoweredTok = Tok.lower();
825 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
826 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
830 if (!Tok.startswith(RegisterPrefix))
833 StringRef RegName = Tok.substr(RegisterPrefix.size());
834 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
835 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
837 // If there is no register prefix (i.e. "%" in "%eax"), then this may
838 // be some random non-register token, just ignore it.
842 static std::string getEnumNameForToken(StringRef Str) {
845 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
847 case '*': Res += "_STAR_"; break;
848 case '%': Res += "_PCT_"; break;
849 case ':': Res += "_COLON_"; break;
850 case '!': Res += "_EXCLAIM_"; break;
851 case '.': Res += "_DOT_"; break;
856 Res += "_" + utostr((unsigned) *it) + "_";
863 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
864 ClassInfo *&Entry = TokenClasses[Token];
867 Entry = new ClassInfo();
868 Entry->Kind = ClassInfo::Token;
869 Entry->ClassName = "Token";
870 Entry->Name = "MCK_" + getEnumNameForToken(Token);
871 Entry->ValueName = Token;
872 Entry->PredicateMethod = "<invalid>";
873 Entry->RenderMethod = "<invalid>";
874 Entry->ParserMethod = "";
875 Classes.push_back(Entry);
882 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
884 Record *Rec = OI.Rec;
886 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
887 return getOperandClass(Rec, SubOpIdx);
891 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
892 if (Rec->isSubClassOf("RegisterOperand")) {
893 // RegisterOperand may have an associated ParserMatchClass. If it does,
894 // use it, else just fall back to the underlying register class.
895 const RecordVal *R = Rec->getValue("ParserMatchClass");
896 if (R == 0 || R->getValue() == 0)
897 throw "Record `" + Rec->getName() +
898 "' does not have a ParserMatchClass!\n";
900 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
901 Record *MatchClass = DI->getDef();
902 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
906 // No custom match class. Just use the register class.
907 Record *ClassRec = Rec->getValueAsDef("RegClass");
909 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
910 "' has no associated register class!\n");
911 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
913 throw TGError(Rec->getLoc(), "register class has no class info!");
917 if (Rec->isSubClassOf("RegisterClass")) {
918 if (ClassInfo *CI = RegisterClassClasses[Rec])
920 throw TGError(Rec->getLoc(), "register class has no class info!");
923 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
924 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
925 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
928 throw TGError(Rec->getLoc(), "operand has no match class!");
931 void AsmMatcherInfo::
932 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
933 const std::vector<CodeGenRegister*> &Registers =
934 Target.getRegBank().getRegisters();
935 ArrayRef<CodeGenRegisterClass*> RegClassList =
936 Target.getRegBank().getRegClasses();
938 // The register sets used for matching.
939 std::set< std::set<Record*> > RegisterSets;
941 // Gather the defined sets.
942 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
943 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
944 RegisterSets.insert(std::set<Record*>(
945 (*it)->getOrder().begin(), (*it)->getOrder().end()));
947 // Add any required singleton sets.
948 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
949 ie = SingletonRegisters.end(); it != ie; ++it) {
951 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
954 // Introduce derived sets where necessary (when a register does not determine
955 // a unique register set class), and build the mapping of registers to the set
956 // they should classify to.
957 std::map<Record*, std::set<Record*> > RegisterMap;
958 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
959 ie = Registers.end(); it != ie; ++it) {
960 const CodeGenRegister &CGR = **it;
961 // Compute the intersection of all sets containing this register.
962 std::set<Record*> ContainingSet;
964 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
965 ie = RegisterSets.end(); it != ie; ++it) {
966 if (!it->count(CGR.TheDef))
969 if (ContainingSet.empty()) {
974 std::set<Record*> Tmp;
975 std::swap(Tmp, ContainingSet);
976 std::insert_iterator< std::set<Record*> > II(ContainingSet,
977 ContainingSet.begin());
978 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
981 if (!ContainingSet.empty()) {
982 RegisterSets.insert(ContainingSet);
983 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
987 // Construct the register classes.
988 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
990 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
991 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
992 ClassInfo *CI = new ClassInfo();
993 CI->Kind = ClassInfo::RegisterClass0 + Index;
994 CI->ClassName = "Reg" + utostr(Index);
995 CI->Name = "MCK_Reg" + utostr(Index);
997 CI->PredicateMethod = ""; // unused
998 CI->RenderMethod = "addRegOperands";
1000 Classes.push_back(CI);
1001 RegisterSetClasses.insert(std::make_pair(*it, CI));
1004 // Find the superclasses; we could compute only the subgroup lattice edges,
1005 // but there isn't really a point.
1006 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1007 ie = RegisterSets.end(); it != ie; ++it) {
1008 ClassInfo *CI = RegisterSetClasses[*it];
1009 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1010 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1012 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1013 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1016 // Name the register classes which correspond to a user defined RegisterClass.
1017 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1018 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1019 const CodeGenRegisterClass &RC = **it;
1020 // Def will be NULL for non-user defined register classes.
1021 Record *Def = RC.getDef();
1024 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1025 RC.getOrder().end())];
1026 if (CI->ValueName.empty()) {
1027 CI->ClassName = RC.getName();
1028 CI->Name = "MCK_" + RC.getName();
1029 CI->ValueName = RC.getName();
1031 CI->ValueName = CI->ValueName + "," + RC.getName();
1033 RegisterClassClasses.insert(std::make_pair(Def, CI));
1036 // Populate the map for individual registers.
1037 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1038 ie = RegisterMap.end(); it != ie; ++it)
1039 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1041 // Name the register classes which correspond to singleton registers.
1042 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1043 ie = SingletonRegisters.end(); it != ie; ++it) {
1045 ClassInfo *CI = RegisterClasses[Rec];
1046 assert(CI && "Missing singleton register class info!");
1048 if (CI->ValueName.empty()) {
1049 CI->ClassName = Rec->getName();
1050 CI->Name = "MCK_" + Rec->getName();
1051 CI->ValueName = Rec->getName();
1053 CI->ValueName = CI->ValueName + "," + Rec->getName();
1057 void AsmMatcherInfo::BuildOperandClasses() {
1058 std::vector<Record*> AsmOperands =
1059 Records.getAllDerivedDefinitions("AsmOperandClass");
1061 // Pre-populate AsmOperandClasses map.
1062 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1063 ie = AsmOperands.end(); it != ie; ++it)
1064 AsmOperandClasses[*it] = new ClassInfo();
1067 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1068 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1069 ClassInfo *CI = AsmOperandClasses[*it];
1070 CI->Kind = ClassInfo::UserClass0 + Index;
1072 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1073 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1074 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1076 PrintError((*it)->getLoc(), "Invalid super class reference!");
1080 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1082 PrintError((*it)->getLoc(), "Invalid super class reference!");
1084 CI->SuperClasses.push_back(SC);
1086 CI->ClassName = (*it)->getValueAsString("Name");
1087 CI->Name = "MCK_" + CI->ClassName;
1088 CI->ValueName = (*it)->getName();
1090 // Get or construct the predicate method name.
1091 Init *PMName = (*it)->getValueInit("PredicateMethod");
1092 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1093 CI->PredicateMethod = SI->getValue();
1095 assert(dynamic_cast<UnsetInit*>(PMName) &&
1096 "Unexpected PredicateMethod field!");
1097 CI->PredicateMethod = "is" + CI->ClassName;
1100 // Get or construct the render method name.
1101 Init *RMName = (*it)->getValueInit("RenderMethod");
1102 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1103 CI->RenderMethod = SI->getValue();
1105 assert(dynamic_cast<UnsetInit*>(RMName) &&
1106 "Unexpected RenderMethod field!");
1107 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1110 // Get the parse method name or leave it as empty.
1111 Init *PRMName = (*it)->getValueInit("ParserMethod");
1112 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1113 CI->ParserMethod = SI->getValue();
1115 AsmOperandClasses[*it] = CI;
1116 Classes.push_back(CI);
1120 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1121 CodeGenTarget &target,
1122 RecordKeeper &records)
1123 : Records(records), AsmParser(asmParser), Target(target) {
1126 /// BuildOperandMatchInfo - Build the necessary information to handle user
1127 /// defined operand parsing methods.
1128 void AsmMatcherInfo::BuildOperandMatchInfo() {
1130 /// Map containing a mask with all operands indicies that can be found for
1131 /// that class inside a instruction.
1132 std::map<ClassInfo*, unsigned> OpClassMask;
1134 for (std::vector<MatchableInfo*>::const_iterator it =
1135 Matchables.begin(), ie = Matchables.end();
1137 MatchableInfo &II = **it;
1138 OpClassMask.clear();
1140 // Keep track of all operands of this instructions which belong to the
1142 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1143 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1144 if (Op.Class->ParserMethod.empty())
1146 unsigned &OperandMask = OpClassMask[Op.Class];
1147 OperandMask |= (1 << i);
1150 // Generate operand match info for each mnemonic/operand class pair.
1151 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1152 iie = OpClassMask.end(); iit != iie; ++iit) {
1153 unsigned OpMask = iit->second;
1154 ClassInfo *CI = iit->first;
1155 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1160 void AsmMatcherInfo::BuildInfo() {
1161 // Build information about all of the AssemblerPredicates.
1162 std::vector<Record*> AllPredicates =
1163 Records.getAllDerivedDefinitions("Predicate");
1164 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1165 Record *Pred = AllPredicates[i];
1166 // Ignore predicates that are not intended for the assembler.
1167 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1170 if (Pred->getName().empty())
1171 throw TGError(Pred->getLoc(), "Predicate has no name!");
1173 unsigned FeatureNo = SubtargetFeatures.size();
1174 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1175 assert(FeatureNo < 32 && "Too many subtarget features!");
1178 // Parse the instructions; we need to do this first so that we can gather the
1179 // singleton register classes.
1180 SmallPtrSet<Record*, 16> SingletonRegisters;
1181 unsigned VariantCount = Target.getAsmParserVariantCount();
1182 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1183 Record *AsmVariant = Target.getAsmParserVariant(VC);
1184 std::string CommentDelimiter =
1185 AsmVariant->getValueAsString("CommentDelimiter");
1186 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1187 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1189 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1190 E = Target.inst_end(); I != E; ++I) {
1191 const CodeGenInstruction &CGI = **I;
1193 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1194 // filter the set of instructions we consider.
1195 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1198 // Ignore "codegen only" instructions.
1199 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1202 // Validate the operand list to ensure we can handle this instruction.
1203 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1204 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1206 // Validate tied operands.
1207 if (OI.getTiedRegister() != -1) {
1208 // If we have a tied operand that consists of multiple MCOperands,
1209 // reject it. We reject aliases and ignore instructions for now.
1210 if (OI.MINumOperands != 1) {
1211 // FIXME: Should reject these. The ARM backend hits this with $lane
1212 // in a bunch of instructions. The right answer is unclear.
1214 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1215 << "ignoring instruction with multi-operand tied operand '"
1216 << OI.Name << "'\n";
1223 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1225 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1227 // Ignore instructions which shouldn't be matched and diagnose invalid
1228 // instruction definitions with an error.
1229 if (!II->Validate(CommentDelimiter, true))
1232 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1234 // FIXME: This is a total hack.
1235 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1236 StringRef(II->TheDef->getName()).endswith("_Int"))
1239 Matchables.push_back(II.take());
1242 // Parse all of the InstAlias definitions and stick them in the list of
1244 std::vector<Record*> AllInstAliases =
1245 Records.getAllDerivedDefinitions("InstAlias");
1246 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1247 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1249 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1250 // filter the set of instruction aliases we consider, based on the target
1252 if (!StringRef(Alias->ResultInst->TheDef->getName())
1253 .startswith( MatchPrefix))
1256 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1258 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1260 // Validate the alias definitions.
1261 II->Validate(CommentDelimiter, false);
1263 Matchables.push_back(II.take());
1267 // Build info for the register classes.
1268 BuildRegisterClasses(SingletonRegisters);
1270 // Build info for the user defined assembly operand classes.
1271 BuildOperandClasses();
1273 // Build the information about matchables, now that we have fully formed
1275 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1276 ie = Matchables.end(); it != ie; ++it) {
1277 MatchableInfo *II = *it;
1279 // Parse the tokens after the mnemonic.
1280 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1281 // don't precompute the loop bound.
1282 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1283 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1284 StringRef Token = Op.Token;
1286 // Check for singleton registers.
1287 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1288 Op.Class = RegisterClasses[RegRecord];
1289 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1290 "Unexpected class for singleton register");
1294 // Check for simple tokens.
1295 if (Token[0] != '$') {
1296 Op.Class = getTokenClass(Token);
1300 if (Token.size() > 1 && isdigit(Token[1])) {
1301 Op.Class = getTokenClass(Token);
1305 // Otherwise this is an operand reference.
1306 StringRef OperandName;
1307 if (Token[1] == '{')
1308 OperandName = Token.substr(2, Token.size() - 3);
1310 OperandName = Token.substr(1);
1312 if (II->DefRec.is<const CodeGenInstruction*>())
1313 BuildInstructionOperandReference(II, OperandName, i);
1315 BuildAliasOperandReference(II, OperandName, Op);
1318 if (II->DefRec.is<const CodeGenInstruction*>())
1319 II->BuildInstructionResultOperands();
1321 II->BuildAliasResultOperands();
1324 // Process token alias definitions and set up the associated superclass
1326 std::vector<Record*> AllTokenAliases =
1327 Records.getAllDerivedDefinitions("TokenAlias");
1328 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1329 Record *Rec = AllTokenAliases[i];
1330 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1331 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1332 FromClass->SuperClasses.push_back(ToClass);
1335 // Reorder classes so that classes precede super classes.
1336 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1339 /// BuildInstructionOperandReference - The specified operand is a reference to a
1340 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1341 void AsmMatcherInfo::
1342 BuildInstructionOperandReference(MatchableInfo *II,
1343 StringRef OperandName,
1344 unsigned AsmOpIdx) {
1345 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1346 const CGIOperandList &Operands = CGI.Operands;
1347 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1349 // Map this token to an operand.
1351 if (!Operands.hasOperandNamed(OperandName, Idx))
1352 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1353 OperandName.str() + "'");
1355 // If the instruction operand has multiple suboperands, but the parser
1356 // match class for the asm operand is still the default "ImmAsmOperand",
1357 // then handle each suboperand separately.
1358 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1359 Record *Rec = Operands[Idx].Rec;
1360 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1361 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1362 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1363 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1364 StringRef Token = Op->Token; // save this in case Op gets moved
1365 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1366 MatchableInfo::AsmOperand NewAsmOp(Token);
1367 NewAsmOp.SubOpIdx = SI;
1368 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1370 // Replace Op with first suboperand.
1371 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1376 // Set up the operand class.
1377 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1379 // If the named operand is tied, canonicalize it to the untied operand.
1380 // For example, something like:
1381 // (outs GPR:$dst), (ins GPR:$src)
1382 // with an asmstring of
1384 // we want to canonicalize to:
1386 // so that we know how to provide the $dst operand when filling in the result.
1387 int OITied = Operands[Idx].getTiedRegister();
1389 // The tied operand index is an MIOperand index, find the operand that
1391 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1392 OperandName = Operands[Idx.first].Name;
1393 Op->SubOpIdx = Idx.second;
1396 Op->SrcOpName = OperandName;
1399 /// BuildAliasOperandReference - When parsing an operand reference out of the
1400 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1401 /// operand reference is by looking it up in the result pattern definition.
1402 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1403 StringRef OperandName,
1404 MatchableInfo::AsmOperand &Op) {
1405 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1407 // Set up the operand class.
1408 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1409 if (CGA.ResultOperands[i].isRecord() &&
1410 CGA.ResultOperands[i].getName() == OperandName) {
1411 // It's safe to go with the first one we find, because CodeGenInstAlias
1412 // validates that all operands with the same name have the same record.
1413 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1414 // Use the match class from the Alias definition, not the
1415 // destination instruction, as we may have an immediate that's
1416 // being munged by the match class.
1417 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1419 Op.SrcOpName = OperandName;
1423 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1424 OperandName.str() + "'");
1427 void MatchableInfo::BuildInstructionResultOperands() {
1428 const CodeGenInstruction *ResultInst = getResultInst();
1430 // Loop over all operands of the result instruction, determining how to
1432 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1433 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1435 // If this is a tied operand, just copy from the previously handled operand.
1436 int TiedOp = OpInfo.getTiedRegister();
1438 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1442 // Find out what operand from the asmparser this MCInst operand comes from.
1443 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1444 if (OpInfo.Name.empty() || SrcOperand == -1)
1445 throw TGError(TheDef->getLoc(), "Instruction '" +
1446 TheDef->getName() + "' has operand '" + OpInfo.Name +
1447 "' that doesn't appear in asm string!");
1449 // Check if the one AsmOperand populates the entire operand.
1450 unsigned NumOperands = OpInfo.MINumOperands;
1451 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1452 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1456 // Add a separate ResOperand for each suboperand.
1457 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1458 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1459 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1460 "unexpected AsmOperands for suboperands");
1461 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1466 void MatchableInfo::BuildAliasResultOperands() {
1467 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1468 const CodeGenInstruction *ResultInst = getResultInst();
1470 // Loop over all operands of the result instruction, determining how to
1472 unsigned AliasOpNo = 0;
1473 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1474 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1475 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1477 // If this is a tied operand, just copy from the previously handled operand.
1478 int TiedOp = OpInfo->getTiedRegister();
1480 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1484 // Handle all the suboperands for this operand.
1485 const std::string &OpName = OpInfo->Name;
1486 for ( ; AliasOpNo < LastOpNo &&
1487 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1488 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1490 // Find out what operand from the asmparser that this MCInst operand
1492 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1493 case CodeGenInstAlias::ResultOperand::K_Record: {
1494 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1495 int SrcOperand = FindAsmOperand(Name, SubIdx);
1496 if (SrcOperand == -1)
1497 throw TGError(TheDef->getLoc(), "Instruction '" +
1498 TheDef->getName() + "' has operand '" + OpName +
1499 "' that doesn't appear in asm string!");
1500 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1501 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1505 case CodeGenInstAlias::ResultOperand::K_Imm: {
1506 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1507 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1510 case CodeGenInstAlias::ResultOperand::K_Reg: {
1511 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1512 ResOperands.push_back(ResOperand::getRegOp(Reg));
1520 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1521 std::vector<MatchableInfo*> &Infos,
1523 // Write the convert function to a separate stream, so we can drop it after
1525 std::string ConvertFnBody;
1526 raw_string_ostream CvtOS(ConvertFnBody);
1528 // Function we have already generated.
1529 std::set<std::string> GeneratedFns;
1531 // Start the unified conversion function.
1532 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1533 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1534 << "unsigned Opcode,\n"
1535 << " const SmallVectorImpl<MCParsedAsmOperand*"
1536 << "> &Operands) {\n";
1537 CvtOS << " Inst.setOpcode(Opcode);\n";
1538 CvtOS << " switch (Kind) {\n";
1539 CvtOS << " default:\n";
1541 // Start the enum, which we will generate inline.
1543 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1544 OS << "enum ConversionKind {\n";
1546 // TargetOperandClass - This is the target's operand class, like X86Operand.
1547 std::string TargetOperandClass = Target.getName() + "Operand";
1549 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1550 ie = Infos.end(); it != ie; ++it) {
1551 MatchableInfo &II = **it;
1553 // Check if we have a custom match function.
1554 std::string AsmMatchConverter =
1555 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1556 if (!AsmMatchConverter.empty()) {
1557 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1558 II.ConversionFnKind = Signature;
1560 // Check if we have already generated this signature.
1561 if (!GeneratedFns.insert(Signature).second)
1564 // If not, emit it now. Add to the enum list.
1565 OS << " " << Signature << ",\n";
1567 CvtOS << " case " << Signature << ":\n";
1568 CvtOS << " return " << AsmMatchConverter
1569 << "(Inst, Opcode, Operands);\n";
1573 // Build the conversion function signature.
1574 std::string Signature = "Convert";
1575 std::string CaseBody;
1576 raw_string_ostream CaseOS(CaseBody);
1578 // Compute the convert enum and the case body.
1579 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1580 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1582 // Generate code to populate each result operand.
1583 switch (OpInfo.Kind) {
1584 case MatchableInfo::ResOperand::RenderAsmOperand: {
1585 // This comes from something we parsed.
1586 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1588 // Registers are always converted the same, don't duplicate the
1589 // conversion function based on them.
1591 if (Op.Class->isRegisterClass())
1594 Signature += Op.Class->ClassName;
1595 Signature += utostr(OpInfo.MINumOperands);
1596 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1598 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1599 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1600 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1604 case MatchableInfo::ResOperand::TiedOperand: {
1605 // If this operand is tied to a previous one, just copy the MCInst
1606 // operand from the earlier one.We can only tie single MCOperand values.
1607 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1608 unsigned TiedOp = OpInfo.TiedOperandNum;
1609 assert(i > TiedOp && "Tied operand precedes its target!");
1610 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1611 Signature += "__Tie" + utostr(TiedOp);
1614 case MatchableInfo::ResOperand::ImmOperand: {
1615 int64_t Val = OpInfo.ImmVal;
1616 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1617 Signature += "__imm" + itostr(Val);
1620 case MatchableInfo::ResOperand::RegOperand: {
1621 if (OpInfo.Register == 0) {
1622 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1623 Signature += "__reg0";
1625 std::string N = getQualifiedName(OpInfo.Register);
1626 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1627 Signature += "__reg" + OpInfo.Register->getName();
1633 II.ConversionFnKind = Signature;
1635 // Check if we have already generated this signature.
1636 if (!GeneratedFns.insert(Signature).second)
1639 // If not, emit it now. Add to the enum list.
1640 OS << " " << Signature << ",\n";
1642 CvtOS << " case " << Signature << ":\n";
1643 CvtOS << CaseOS.str();
1644 CvtOS << " return true;\n";
1647 // Finish the convert function.
1650 CvtOS << " return false;\n";
1653 // Finish the enum, and drop the convert function after it.
1655 OS << " NumConversionVariants\n";
1661 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1662 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1663 std::vector<ClassInfo*> &Infos,
1665 OS << "namespace {\n\n";
1667 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1668 << "/// instruction matching.\n";
1669 OS << "enum MatchClassKind {\n";
1670 OS << " InvalidMatchClass = 0,\n";
1671 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1672 ie = Infos.end(); it != ie; ++it) {
1673 ClassInfo &CI = **it;
1674 OS << " " << CI.Name << ", // ";
1675 if (CI.Kind == ClassInfo::Token) {
1676 OS << "'" << CI.ValueName << "'\n";
1677 } else if (CI.isRegisterClass()) {
1678 if (!CI.ValueName.empty())
1679 OS << "register class '" << CI.ValueName << "'\n";
1681 OS << "derived register class\n";
1683 OS << "user defined class '" << CI.ValueName << "'\n";
1686 OS << " NumMatchClassKinds\n";
1692 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1693 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1695 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1696 << "MatchClassKind Kind) {\n";
1697 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1698 << Info.Target.getName() << "Operand*)GOp;\n";
1700 // The InvalidMatchClass is not to match any operand.
1701 OS << " if (Kind == InvalidMatchClass)\n";
1702 OS << " return false;\n\n";
1704 // Check for Token operands first.
1705 OS << " if (Operand.isToken())\n";
1706 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1709 // Check for register operands, including sub-classes.
1710 OS << " if (Operand.isReg()) {\n";
1711 OS << " MatchClassKind OpKind;\n";
1712 OS << " switch (Operand.getReg()) {\n";
1713 OS << " default: OpKind = InvalidMatchClass; break;\n";
1714 for (std::map<Record*, ClassInfo*>::iterator
1715 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1717 OS << " case " << Info.Target.getName() << "::"
1718 << it->first->getName() << ": OpKind = " << it->second->Name
1721 OS << " return isSubclass(OpKind, Kind);\n";
1724 // Check the user classes. We don't care what order since we're only
1725 // actually matching against one of them.
1726 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1727 ie = Info.Classes.end(); it != ie; ++it) {
1728 ClassInfo &CI = **it;
1730 if (!CI.isUserClass())
1733 OS << " // '" << CI.ClassName << "' class\n";
1734 OS << " if (Kind == " << CI.Name
1735 << " && Operand." << CI.PredicateMethod << "()) {\n";
1736 OS << " return true;\n";
1740 OS << " return false;\n";
1744 /// EmitIsSubclass - Emit the subclass predicate function.
1745 static void EmitIsSubclass(CodeGenTarget &Target,
1746 std::vector<ClassInfo*> &Infos,
1748 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1749 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1750 OS << " if (A == B)\n";
1751 OS << " return true;\n\n";
1753 OS << " switch (A) {\n";
1754 OS << " default:\n";
1755 OS << " return false;\n";
1756 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1757 ie = Infos.end(); it != ie; ++it) {
1758 ClassInfo &A = **it;
1760 std::vector<StringRef> SuperClasses;
1761 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1762 ie = Infos.end(); it != ie; ++it) {
1763 ClassInfo &B = **it;
1765 if (&A != &B && A.isSubsetOf(B))
1766 SuperClasses.push_back(B.Name);
1769 if (SuperClasses.empty())
1772 OS << "\n case " << A.Name << ":\n";
1774 if (SuperClasses.size() == 1) {
1775 OS << " return B == " << SuperClasses.back() << ";\n";
1779 OS << " switch (B) {\n";
1780 OS << " default: return false;\n";
1781 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1782 OS << " case " << SuperClasses[i] << ": return true;\n";
1789 /// EmitMatchTokenString - Emit the function to match a token string to the
1790 /// appropriate match class value.
1791 static void EmitMatchTokenString(CodeGenTarget &Target,
1792 std::vector<ClassInfo*> &Infos,
1794 // Construct the match list.
1795 std::vector<StringMatcher::StringPair> Matches;
1796 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1797 ie = Infos.end(); it != ie; ++it) {
1798 ClassInfo &CI = **it;
1800 if (CI.Kind == ClassInfo::Token)
1801 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1802 "return " + CI.Name + ";"));
1805 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1807 StringMatcher("Name", Matches, OS).Emit();
1809 OS << " return InvalidMatchClass;\n";
1813 /// EmitMatchRegisterName - Emit the function to match a string to the target
1814 /// specific register enum.
1815 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1817 // Construct the match list.
1818 std::vector<StringMatcher::StringPair> Matches;
1819 const std::vector<CodeGenRegister*> &Regs =
1820 Target.getRegBank().getRegisters();
1821 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1822 const CodeGenRegister *Reg = Regs[i];
1823 if (Reg->TheDef->getValueAsString("AsmName").empty())
1826 Matches.push_back(StringMatcher::StringPair(
1827 Reg->TheDef->getValueAsString("AsmName"),
1828 "return " + utostr(Reg->EnumValue) + ";"));
1831 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1833 StringMatcher("Name", Matches, OS).Emit();
1835 OS << " return 0;\n";
1839 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1841 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1843 OS << "// Flags for subtarget features that participate in "
1844 << "instruction matching.\n";
1845 OS << "enum SubtargetFeatureFlag {\n";
1846 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1847 it = Info.SubtargetFeatures.begin(),
1848 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1849 SubtargetFeatureInfo &SFI = *it->second;
1850 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1852 OS << " Feature_None = 0\n";
1856 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1857 /// available features given a subtarget.
1858 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1860 std::string ClassName =
1861 Info.AsmParser->getValueAsString("AsmParserClassName");
1863 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1864 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1865 OS << " unsigned Features = 0;\n";
1866 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1867 it = Info.SubtargetFeatures.begin(),
1868 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1869 SubtargetFeatureInfo &SFI = *it->second;
1872 std::string CondStorage =
1873 SFI.TheDef->getValueAsString("AssemblerCondString");
1874 StringRef Conds = CondStorage;
1875 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1882 StringRef Cond = Comma.first;
1883 if (Cond[0] == '!') {
1885 Cond = Cond.substr(1);
1888 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1895 if (Comma.second.empty())
1899 Comma = Comma.second.split(',');
1903 OS << " Features |= " << SFI.getEnumName() << ";\n";
1905 OS << " return Features;\n";
1909 static std::string GetAliasRequiredFeatures(Record *R,
1910 const AsmMatcherInfo &Info) {
1911 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1913 unsigned NumFeatures = 0;
1914 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1915 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1918 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1919 "' is not marked as an AssemblerPredicate!");
1924 Result += F->getEnumName();
1928 if (NumFeatures > 1)
1929 Result = '(' + Result + ')';
1933 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1934 /// emit a function for them and return true, otherwise return false.
1935 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1936 // Ignore aliases when match-prefix is set.
1937 if (!MatchPrefix.empty())
1940 std::vector<Record*> Aliases =
1941 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1942 if (Aliases.empty()) return false;
1944 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1945 "unsigned Features) {\n";
1947 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1948 // iteration order of the map is stable.
1949 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1951 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1952 Record *R = Aliases[i];
1953 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1956 // Process each alias a "from" mnemonic at a time, building the code executed
1957 // by the string remapper.
1958 std::vector<StringMatcher::StringPair> Cases;
1959 for (std::map<std::string, std::vector<Record*> >::iterator
1960 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1962 const std::vector<Record*> &ToVec = I->second;
1964 // Loop through each alias and emit code that handles each case. If there
1965 // are two instructions without predicates, emit an error. If there is one,
1967 std::string MatchCode;
1968 int AliasWithNoPredicate = -1;
1970 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1971 Record *R = ToVec[i];
1972 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1974 // If this unconditionally matches, remember it for later and diagnose
1976 if (FeatureMask.empty()) {
1977 if (AliasWithNoPredicate != -1) {
1978 // We can't have two aliases from the same mnemonic with no predicate.
1979 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1980 "two MnemonicAliases with the same 'from' mnemonic!");
1981 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1984 AliasWithNoPredicate = i;
1987 if (R->getValueAsString("ToMnemonic") == I->first)
1988 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1990 if (!MatchCode.empty())
1991 MatchCode += "else ";
1992 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1993 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1996 if (AliasWithNoPredicate != -1) {
1997 Record *R = ToVec[AliasWithNoPredicate];
1998 if (!MatchCode.empty())
1999 MatchCode += "else\n ";
2000 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2003 MatchCode += "return;";
2005 Cases.push_back(std::make_pair(I->first, MatchCode));
2008 StringMatcher("Mnemonic", Cases, OS).Emit();
2014 static const char *getMinimalTypeForRange(uint64_t Range) {
2015 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2023 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2024 const AsmMatcherInfo &Info, StringRef ClassName) {
2025 // Emit the static custom operand parsing table;
2026 OS << "namespace {\n";
2027 OS << " struct OperandMatchEntry {\n";
2028 OS << " static const char *const MnemonicTable;\n";
2029 OS << " uint32_t OperandMask;\n";
2030 OS << " uint32_t Mnemonic;\n";
2031 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2032 << " RequiredFeatures;\n";
2033 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2035 OS << " StringRef getMnemonic() const {\n";
2036 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2037 OS << " MnemonicTable[Mnemonic]);\n";
2041 OS << " // Predicate for searching for an opcode.\n";
2042 OS << " struct LessOpcodeOperand {\n";
2043 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2044 OS << " return LHS.getMnemonic() < RHS;\n";
2046 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2047 OS << " return LHS < RHS.getMnemonic();\n";
2049 OS << " bool operator()(const OperandMatchEntry &LHS,";
2050 OS << " const OperandMatchEntry &RHS) {\n";
2051 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2055 OS << "} // end anonymous namespace.\n\n";
2057 StringToOffsetTable StringTable;
2059 OS << "static const OperandMatchEntry OperandMatchTable["
2060 << Info.OperandMatchInfo.size() << "] = {\n";
2062 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2063 for (std::vector<OperandMatchEntry>::const_iterator it =
2064 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2066 const OperandMatchEntry &OMI = *it;
2067 const MatchableInfo &II = *OMI.MI;
2069 OS << " { " << OMI.OperandMask;
2072 bool printComma = false;
2073 for (int i = 0, e = 31; i !=e; ++i)
2074 if (OMI.OperandMask & (1 << i)) {
2082 // Store a pascal-style length byte in the mnemonic.
2083 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2084 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2085 << " /* " << II.Mnemonic << " */, ";
2087 // Write the required features mask.
2088 if (!II.RequiredFeatures.empty()) {
2089 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2091 OS << II.RequiredFeatures[i]->getEnumName();
2096 OS << ", " << OMI.CI->Name;
2102 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
2103 StringTable.EmitString(OS);
2106 // Emit the operand class switch to call the correct custom parser for
2107 // the found operand class.
2108 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2109 << Target.getName() << ClassName << "::\n"
2110 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2111 << " &Operands,\n unsigned MCK) {\n\n"
2112 << " switch(MCK) {\n";
2114 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2115 ie = Info.Classes.end(); it != ie; ++it) {
2116 ClassInfo *CI = *it;
2117 if (CI->ParserMethod.empty())
2119 OS << " case " << CI->Name << ":\n"
2120 << " return " << CI->ParserMethod << "(Operands);\n";
2123 OS << " default:\n";
2124 OS << " return MatchOperand_NoMatch;\n";
2126 OS << " return MatchOperand_NoMatch;\n";
2129 // Emit the static custom operand parser. This code is very similar with
2130 // the other matcher. Also use MatchResultTy here just in case we go for
2131 // a better error handling.
2132 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2133 << Target.getName() << ClassName << "::\n"
2134 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2135 << " &Operands,\n StringRef Mnemonic) {\n";
2137 // Emit code to get the available features.
2138 OS << " // Get the current feature set.\n";
2139 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2141 OS << " // Get the next operand index.\n";
2142 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2144 // Emit code to search the table.
2145 OS << " // Search the table.\n";
2146 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2147 OS << " MnemonicRange =\n";
2148 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2149 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2150 << " LessOpcodeOperand());\n\n";
2152 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2153 OS << " return MatchOperand_NoMatch;\n\n";
2155 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2156 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2158 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2159 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2161 // Emit check that the required features are available.
2162 OS << " // check if the available features match\n";
2163 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2164 << "!= it->RequiredFeatures) {\n";
2165 OS << " continue;\n";
2168 // Emit check to ensure the operand number matches.
2169 OS << " // check if the operand in question has a custom parser.\n";
2170 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2171 OS << " continue;\n\n";
2173 // Emit call to the custom parser method
2174 OS << " // call custom parse method to handle the operand\n";
2175 OS << " OperandMatchResultTy Result = ";
2176 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2177 OS << " if (Result != MatchOperand_NoMatch)\n";
2178 OS << " return Result;\n";
2181 OS << " // Okay, we had no match.\n";
2182 OS << " return MatchOperand_NoMatch;\n";
2186 void AsmMatcherEmitter::run(raw_ostream &OS) {
2187 CodeGenTarget Target(Records);
2188 Record *AsmParser = Target.getAsmParser();
2189 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2191 // Compute the information on the instructions to match.
2192 AsmMatcherInfo Info(AsmParser, Target, Records);
2195 // Sort the instruction table using the partial order on classes. We use
2196 // stable_sort to ensure that ambiguous instructions are still
2197 // deterministically ordered.
2198 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2199 less_ptr<MatchableInfo>());
2201 DEBUG_WITH_TYPE("instruction_info", {
2202 for (std::vector<MatchableInfo*>::iterator
2203 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2208 // Check for ambiguous matchables.
2209 DEBUG_WITH_TYPE("ambiguous_instrs", {
2210 unsigned NumAmbiguous = 0;
2211 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2212 for (unsigned j = i + 1; j != e; ++j) {
2213 MatchableInfo &A = *Info.Matchables[i];
2214 MatchableInfo &B = *Info.Matchables[j];
2216 if (A.CouldMatchAmbiguouslyWith(B)) {
2217 errs() << "warning: ambiguous matchables:\n";
2219 errs() << "\nis incomparable with:\n";
2227 errs() << "warning: " << NumAmbiguous
2228 << " ambiguous matchables!\n";
2231 // Compute the information on the custom operand parsing.
2232 Info.BuildOperandMatchInfo();
2234 // Write the output.
2236 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2238 // Information for the class declaration.
2239 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2240 OS << "#undef GET_ASSEMBLER_HEADER\n";
2241 OS << " // This should be included into the middle of the declaration of\n";
2242 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2243 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2244 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2245 << "unsigned Opcode,\n"
2246 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2248 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2249 OS << " unsigned MatchInstructionImpl(\n";
2250 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2251 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2253 if (Info.OperandMatchInfo.size()) {
2254 OS << "\n enum OperandMatchResultTy {\n";
2255 OS << " MatchOperand_Success, // operand matched successfully\n";
2256 OS << " MatchOperand_NoMatch, // operand did not match\n";
2257 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2259 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2260 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2261 OS << " StringRef Mnemonic);\n";
2263 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2264 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2265 OS << " unsigned MCK);\n\n";
2268 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2270 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2271 OS << "#undef GET_REGISTER_MATCHER\n\n";
2273 // Emit the subtarget feature enumeration.
2274 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2276 // Emit the function to match a register name to number.
2277 EmitMatchRegisterName(Target, AsmParser, OS);
2279 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2282 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2283 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2285 // Generate the function that remaps for mnemonic aliases.
2286 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2288 // Generate the unified function to convert operands into an MCInst.
2289 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2291 // Emit the enumeration for classes which participate in matching.
2292 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2294 // Emit the routine to match token strings to their match class.
2295 EmitMatchTokenString(Target, Info.Classes, OS);
2297 // Emit the subclass predicate routine.
2298 EmitIsSubclass(Target, Info.Classes, OS);
2300 // Emit the routine to validate an operand against a match class.
2301 EmitValidateOperandClass(Info, OS);
2303 // Emit the available features compute function.
2304 EmitComputeAvailableFeatures(Info, OS);
2307 size_t MaxNumOperands = 0;
2308 for (std::vector<MatchableInfo*>::const_iterator it =
2309 Info.Matchables.begin(), ie = Info.Matchables.end();
2311 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2313 // Emit the static match table; unused classes get initalized to 0 which is
2314 // guaranteed to be InvalidMatchClass.
2316 // FIXME: We can reduce the size of this table very easily. First, we change
2317 // it so that store the kinds in separate bit-fields for each index, which
2318 // only needs to be the max width used for classes at that index (we also need
2319 // to reject based on this during classification). If we then make sure to
2320 // order the match kinds appropriately (putting mnemonics last), then we
2321 // should only end up using a few bits for each class, especially the ones
2322 // following the mnemonic.
2323 OS << "namespace {\n";
2324 OS << " struct MatchEntry {\n";
2325 OS << " static const char *const MnemonicTable;\n";
2326 OS << " uint32_t Mnemonic;\n";
2327 OS << " uint16_t Opcode;\n";
2328 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2330 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2331 << " RequiredFeatures;\n";
2332 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2333 << " Classes[" << MaxNumOperands << "];\n";
2334 OS << " uint8_t AsmVariantID;\n\n";
2335 OS << " StringRef getMnemonic() const {\n";
2336 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2337 OS << " MnemonicTable[Mnemonic]);\n";
2341 OS << " // Predicate for searching for an opcode.\n";
2342 OS << " struct LessOpcode {\n";
2343 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2344 OS << " return LHS.getMnemonic() < RHS;\n";
2346 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2347 OS << " return LHS < RHS.getMnemonic();\n";
2349 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2350 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2354 OS << "} // end anonymous namespace.\n\n";
2356 StringToOffsetTable StringTable;
2358 OS << "static const MatchEntry MatchTable["
2359 << Info.Matchables.size() << "] = {\n";
2361 for (std::vector<MatchableInfo*>::const_iterator it =
2362 Info.Matchables.begin(), ie = Info.Matchables.end();
2364 MatchableInfo &II = **it;
2366 // Store a pascal-style length byte in the mnemonic.
2367 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2368 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2369 << " /* " << II.Mnemonic << " */, "
2370 << Target.getName() << "::"
2371 << II.getResultInst()->TheDef->getName() << ", "
2372 << II.ConversionFnKind << ", ";
2374 // Write the required features mask.
2375 if (!II.RequiredFeatures.empty()) {
2376 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2378 OS << II.RequiredFeatures[i]->getEnumName();
2384 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2385 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2388 OS << Op.Class->Name;
2390 OS << " }, " << II.AsmVariantID;
2396 OS << "const char *const MatchEntry::MnemonicTable =\n";
2397 StringTable.EmitString(OS);
2400 // A method to determine if a mnemonic is in the list.
2401 OS << "bool " << Target.getName() << ClassName << "::\n"
2402 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2403 OS << " // Search the table.\n";
2404 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2405 OS << " std::equal_range(MatchTable, MatchTable+"
2406 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2407 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2410 // Finally, build the match function.
2412 << Target.getName() << ClassName << "::\n"
2413 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2415 OS << " MCInst &Inst, unsigned &ErrorInfo,\n";
2416 OS << " unsigned VariantID) {\n";
2418 // Emit code to get the available features.
2419 OS << " // Get the current feature set.\n";
2420 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2422 OS << " // Get the instruction mnemonic, which is the first token.\n";
2423 OS << " StringRef Mnemonic = ((" << Target.getName()
2424 << "Operand*)Operands[0])->getToken();\n\n";
2426 if (HasMnemonicAliases) {
2427 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2428 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2429 OS << " if (!VariantID)\n";
2430 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2433 // Emit code to compute the class list for this operand vector.
2434 OS << " // Eliminate obvious mismatches.\n";
2435 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2436 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2437 OS << " return Match_InvalidOperand;\n";
2440 OS << " // Some state to try to produce better error messages.\n";
2441 OS << " bool HadMatchOtherThanFeatures = false;\n";
2442 OS << " bool HadMatchOtherThanPredicate = false;\n";
2443 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2444 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2445 OS << " // wrong for all instances of the instruction.\n";
2446 OS << " ErrorInfo = ~0U;\n";
2448 // Emit code to search the table.
2449 OS << " // Search the table.\n";
2450 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2451 OS << " std::equal_range(MatchTable, MatchTable+"
2452 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2454 OS << " // Return a more specific error code if no mnemonics match.\n";
2455 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2456 OS << " return Match_MnemonicFail;\n\n";
2458 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2459 << "*ie = MnemonicRange.second;\n";
2460 OS << " it != ie; ++it) {\n";
2462 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2463 OS << " assert(Mnemonic == it->getMnemonic());\n";
2465 // Emit check that the subclasses match.
2466 OS << " if (VariantID != it->AsmVariantID) continue;\n";
2467 OS << " bool OperandsValid = true;\n";
2468 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2469 OS << " if (i + 1 >= Operands.size()) {\n";
2470 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2473 OS << " if (validateOperandClass(Operands[i+1], "
2474 "(MatchClassKind)it->Classes[i]))\n";
2475 OS << " continue;\n";
2476 OS << " // If this operand is broken for all of the instances of this\n";
2477 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2478 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2479 OS << " ErrorInfo = i+1;\n";
2480 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2481 OS << " OperandsValid = false;\n";
2485 OS << " if (!OperandsValid) continue;\n";
2487 // Emit check that the required features are available.
2488 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2489 << "!= it->RequiredFeatures) {\n";
2490 OS << " HadMatchOtherThanFeatures = true;\n";
2491 OS << " continue;\n";
2494 OS << " // We have selected a definite instruction, convert the parsed\n"
2495 << " // operands into the appropriate MCInst.\n";
2496 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2497 << " it->Opcode, Operands))\n";
2498 OS << " return Match_ConversionFail;\n";
2501 // Verify the instruction with the target-specific match predicate function.
2502 OS << " // We have a potential match. Check the target predicate to\n"
2503 << " // handle any context sensitive constraints.\n"
2504 << " unsigned MatchResult;\n"
2505 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2506 << " Match_Success) {\n"
2507 << " Inst.clear();\n"
2508 << " RetCode = MatchResult;\n"
2509 << " HadMatchOtherThanPredicate = true;\n"
2513 // Call the post-processing function, if used.
2514 std::string InsnCleanupFn =
2515 AsmParser->getValueAsString("AsmParserInstCleanup");
2516 if (!InsnCleanupFn.empty())
2517 OS << " " << InsnCleanupFn << "(Inst);\n";
2519 OS << " return Match_Success;\n";
2522 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2523 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2524 OS << " return RetCode;\n";
2525 OS << " return Match_MissingFeature;\n";
2528 if (Info.OperandMatchInfo.size())
2529 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2531 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";