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 values 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 "CodeGenTarget.h"
100 #include "llvm/ADT/OwningPtr.h"
101 #include "llvm/ADT/PointerUnion.h"
102 #include "llvm/ADT/STLExtras.h"
103 #include "llvm/ADT/SmallPtrSet.h"
104 #include "llvm/ADT/SmallVector.h"
105 #include "llvm/ADT/StringExtras.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/TableGen/Error.h"
110 #include "llvm/TableGen/Record.h"
111 #include "llvm/TableGen/StringMatcher.h"
112 #include "llvm/TableGen/StringToOffsetTable.h"
113 #include "llvm/TableGen/TableGenBackend.h"
119 using namespace llvm;
121 static cl::opt<std::string>
122 MatchPrefix("match-prefix", cl::init(""),
123 cl::desc("Only match instructions with the given prefix"));
126 class AsmMatcherInfo;
127 struct SubtargetFeatureInfo;
129 // Register sets are used as keys in some second-order sets TableGen creates
130 // when generating its data structures. This means that the order of two
131 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
132 // can even affect compiler output (at least seen in diagnostics produced when
133 // all matches fail). So we use a type that sorts them consistently.
134 typedef std::set<Record*, LessRecordByID> RegisterSet;
136 class AsmMatcherEmitter {
137 RecordKeeper &Records;
139 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
141 void run(raw_ostream &o);
144 /// ClassInfo - Helper class for storing the information about a particular
145 /// class of operands which can be matched.
148 /// Invalid kind, for use as a sentinel value.
151 /// The class for a particular token.
154 /// The (first) register class, subsequent register classes are
155 /// RegisterClass0+1, and so on.
158 /// The (first) user defined class, subsequent user defined classes are
159 /// UserClass0+1, and so on.
163 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
164 /// N) for the Nth user defined class.
167 /// SuperClasses - The super classes of this class. Note that for simplicities
168 /// sake user operands only record their immediate super class, while register
169 /// operands include all superclasses.
170 std::vector<ClassInfo*> SuperClasses;
172 /// Name - The full class name, suitable for use in an enum.
175 /// ClassName - The unadorned generic name for this class (e.g., Token).
176 std::string ClassName;
178 /// ValueName - The name of the value this class represents; for a token this
179 /// is the literal token string, for an operand it is the TableGen class (or
180 /// empty if this is a derived class).
181 std::string ValueName;
183 /// PredicateMethod - The name of the operand method to test whether the
184 /// operand matches this class; this is not valid for Token or register kinds.
185 std::string PredicateMethod;
187 /// RenderMethod - The name of the operand method to add this operand to an
188 /// MCInst; this is not valid for Token or register kinds.
189 std::string RenderMethod;
191 /// ParserMethod - The name of the operand method to do a target specific
192 /// parsing on the operand.
193 std::string ParserMethod;
195 /// For register classes, the records for all the registers in this class.
196 RegisterSet Registers;
198 /// For custom match classes, he diagnostic kind for when the predicate fails.
199 std::string DiagnosticType;
201 /// isRegisterClass() - Check if this is a register class.
202 bool isRegisterClass() const {
203 return Kind >= RegisterClass0 && Kind < UserClass0;
206 /// isUserClass() - Check if this is a user defined class.
207 bool isUserClass() const {
208 return Kind >= UserClass0;
211 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
212 /// are related if they are in the same class hierarchy.
213 bool isRelatedTo(const ClassInfo &RHS) const {
214 // Tokens are only related to tokens.
215 if (Kind == Token || RHS.Kind == Token)
216 return Kind == Token && RHS.Kind == Token;
218 // Registers classes are only related to registers classes, and only if
219 // their intersection is non-empty.
220 if (isRegisterClass() || RHS.isRegisterClass()) {
221 if (!isRegisterClass() || !RHS.isRegisterClass())
225 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
226 std::set_intersection(Registers.begin(), Registers.end(),
227 RHS.Registers.begin(), RHS.Registers.end(),
228 II, LessRecordByID());
233 // Otherwise we have two users operands; they are related if they are in the
234 // same class hierarchy.
236 // FIXME: This is an oversimplification, they should only be related if they
237 // intersect, however we don't have that information.
238 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
239 const ClassInfo *Root = this;
240 while (!Root->SuperClasses.empty())
241 Root = Root->SuperClasses.front();
243 const ClassInfo *RHSRoot = &RHS;
244 while (!RHSRoot->SuperClasses.empty())
245 RHSRoot = RHSRoot->SuperClasses.front();
247 return Root == RHSRoot;
250 /// isSubsetOf - Test whether this class is a subset of \p RHS.
251 bool isSubsetOf(const ClassInfo &RHS) const {
252 // This is a subset of RHS if it is the same class...
256 // ... or if any of its super classes are a subset of RHS.
257 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
258 ie = SuperClasses.end(); it != ie; ++it)
259 if ((*it)->isSubsetOf(RHS))
265 /// operator< - Compare two classes.
266 bool operator<(const ClassInfo &RHS) const {
270 // Unrelated classes can be ordered by kind.
271 if (!isRelatedTo(RHS))
272 return Kind < RHS.Kind;
276 llvm_unreachable("Invalid kind!");
279 // This class precedes the RHS if it is a proper subset of the RHS.
282 if (RHS.isSubsetOf(*this))
285 // Otherwise, order by name to ensure we have a total ordering.
286 return ValueName < RHS.ValueName;
291 /// MatchableInfo - Helper class for storing the necessary information for an
292 /// instruction or alias which is capable of being matched.
293 struct MatchableInfo {
295 /// Token - This is the token that the operand came from.
298 /// The unique class instance this operand should match.
301 /// The operand name this is, if anything.
304 /// The suboperand index within SrcOpName, or -1 for the entire operand.
307 /// Register record if this token is singleton register.
308 Record *SingletonReg;
310 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
314 /// ResOperand - This represents a single operand in the result instruction
315 /// generated by the match. In cases (like addressing modes) where a single
316 /// assembler operand expands to multiple MCOperands, this represents the
317 /// single assembler operand, not the MCOperand.
320 /// RenderAsmOperand - This represents an operand result that is
321 /// generated by calling the render method on the assembly operand. The
322 /// corresponding AsmOperand is specified by AsmOperandNum.
325 /// TiedOperand - This represents a result operand that is a duplicate of
326 /// a previous result operand.
329 /// ImmOperand - This represents an immediate value that is dumped into
333 /// RegOperand - This represents a fixed register that is dumped in.
338 /// This is the operand # in the AsmOperands list that this should be
340 unsigned AsmOperandNum;
342 /// TiedOperandNum - This is the (earlier) result operand that should be
344 unsigned TiedOperandNum;
346 /// ImmVal - This is the immediate value added to the instruction.
349 /// Register - This is the register record.
353 /// MINumOperands - The number of MCInst operands populated by this
355 unsigned MINumOperands;
357 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
359 X.Kind = RenderAsmOperand;
360 X.AsmOperandNum = AsmOpNum;
361 X.MINumOperands = NumOperands;
365 static ResOperand getTiedOp(unsigned TiedOperandNum) {
367 X.Kind = TiedOperand;
368 X.TiedOperandNum = TiedOperandNum;
373 static ResOperand getImmOp(int64_t Val) {
381 static ResOperand getRegOp(Record *Reg) {
390 /// AsmVariantID - Target's assembly syntax variant no.
393 /// TheDef - This is the definition of the instruction or InstAlias that this
394 /// matchable came from.
395 Record *const TheDef;
397 /// DefRec - This is the definition that it came from.
398 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
400 const CodeGenInstruction *getResultInst() const {
401 if (DefRec.is<const CodeGenInstruction*>())
402 return DefRec.get<const CodeGenInstruction*>();
403 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
406 /// ResOperands - This is the operand list that should be built for the result
408 SmallVector<ResOperand, 8> ResOperands;
410 /// AsmString - The assembly string for this instruction (with variants
411 /// removed), e.g. "movsx $src, $dst".
412 std::string AsmString;
414 /// Mnemonic - This is the first token of the matched instruction, its
418 /// AsmOperands - The textual operands that this instruction matches,
419 /// annotated with a class and where in the OperandList they were defined.
420 /// This directly corresponds to the tokenized AsmString after the mnemonic is
422 SmallVector<AsmOperand, 8> AsmOperands;
424 /// Predicates - The required subtarget features to match this instruction.
425 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
427 /// ConversionFnKind - The enum value which is passed to the generated
428 /// convertToMCInst to convert parsed operands into an MCInst for this
430 std::string ConversionFnKind;
432 /// If this instruction is deprecated in some form.
435 MatchableInfo(const CodeGenInstruction &CGI)
436 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
437 AsmString(CGI.AsmString) {
440 MatchableInfo(const CodeGenInstAlias *Alias)
441 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
442 AsmString(Alias->AsmString) {
445 // Two-operand aliases clone from the main matchable, but mark the second
446 // operand as a tied operand of the first for purposes of the assembler.
447 void formTwoOperandAlias(StringRef Constraint);
449 void initialize(const AsmMatcherInfo &Info,
450 SmallPtrSet<Record*, 16> &SingletonRegisters,
451 int AsmVariantNo, std::string &RegisterPrefix);
453 /// validate - Return true if this matchable is a valid thing to match against
454 /// and perform a bunch of validity checking.
455 bool validate(StringRef CommentDelimiter, bool Hack) const;
457 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
458 /// if present, from specified token.
460 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
461 std::string &RegisterPrefix);
463 /// findAsmOperand - Find the AsmOperand with the specified name and
464 /// suboperand index.
465 int findAsmOperand(StringRef N, int SubOpIdx) const {
466 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
467 if (N == AsmOperands[i].SrcOpName &&
468 SubOpIdx == AsmOperands[i].SubOpIdx)
473 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
474 /// This does not check the suboperand index.
475 int findAsmOperandNamed(StringRef N) const {
476 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
477 if (N == AsmOperands[i].SrcOpName)
482 void buildInstructionResultOperands();
483 void buildAliasResultOperands();
485 /// operator< - Compare two matchables.
486 bool operator<(const MatchableInfo &RHS) const {
487 // The primary comparator is the instruction mnemonic.
488 if (Mnemonic != RHS.Mnemonic)
489 return Mnemonic < RHS.Mnemonic;
491 if (AsmOperands.size() != RHS.AsmOperands.size())
492 return AsmOperands.size() < RHS.AsmOperands.size();
494 // Compare lexicographically by operand. The matcher validates that other
495 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
496 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
497 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
499 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
503 // Give matches that require more features higher precedence. This is useful
504 // because we cannot define AssemblerPredicates with the negation of
505 // processor features. For example, ARM v6 "nop" may be either a HINT or
506 // MOV. With v6, we want to match HINT. The assembler has no way to
507 // predicate MOV under "NoV6", but HINT will always match first because it
508 // requires V6 while MOV does not.
509 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
510 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
515 /// couldMatchAmbiguouslyWith - Check whether this matchable could
516 /// ambiguously match the same set of operands as \p RHS (without being a
517 /// strictly superior match).
518 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
519 // The primary comparator is the instruction mnemonic.
520 if (Mnemonic != RHS.Mnemonic)
523 // The number of operands is unambiguous.
524 if (AsmOperands.size() != RHS.AsmOperands.size())
527 // Otherwise, make sure the ordering of the two instructions is unambiguous
528 // by checking that either (a) a token or operand kind discriminates them,
529 // or (b) the ordering among equivalent kinds is consistent.
531 // Tokens and operand kinds are unambiguous (assuming a correct target
533 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
534 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
535 AsmOperands[i].Class->Kind == ClassInfo::Token)
536 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
537 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
540 // Otherwise, this operand could commute if all operands are equivalent, or
541 // there is a pair of operands that compare less than and a pair that
542 // compare greater than.
543 bool HasLT = false, HasGT = false;
544 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
545 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
547 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
551 return !(HasLT ^ HasGT);
557 void tokenizeAsmString(const AsmMatcherInfo &Info);
560 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
561 /// feature which participates in instruction matching.
562 struct SubtargetFeatureInfo {
563 /// \brief The predicate record for this feature.
566 /// \brief An unique index assigned to represent this feature.
569 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
571 /// \brief The name of the enumerated constant identifying this feature.
572 std::string getEnumName() const {
573 return "Feature_" + TheDef->getName();
577 struct OperandMatchEntry {
578 unsigned OperandMask;
582 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
585 X.OperandMask = opMask;
593 class AsmMatcherInfo {
596 RecordKeeper &Records;
598 /// The tablegen AsmParser record.
601 /// Target - The target information.
602 CodeGenTarget &Target;
604 /// The classes which are needed for matching.
605 std::vector<ClassInfo*> Classes;
607 /// The information on the matchables to match.
608 std::vector<MatchableInfo*> Matchables;
610 /// Info for custom matching operands by user defined methods.
611 std::vector<OperandMatchEntry> OperandMatchInfo;
613 /// Map of Register records to their class information.
614 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
615 RegisterClassesTy RegisterClasses;
617 /// Map of Predicate records to their subtarget information.
618 std::map<Record*, SubtargetFeatureInfo*, LessRecordByID> SubtargetFeatures;
620 /// Map of AsmOperandClass records to their class information.
621 std::map<Record*, ClassInfo*> AsmOperandClasses;
624 /// Map of token to class information which has already been constructed.
625 std::map<std::string, ClassInfo*> TokenClasses;
627 /// Map of RegisterClass records to their class information.
628 std::map<Record*, ClassInfo*> RegisterClassClasses;
631 /// getTokenClass - Lookup or create the class for the given token.
632 ClassInfo *getTokenClass(StringRef Token);
634 /// getOperandClass - Lookup or create the class for the given operand.
635 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
637 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
639 /// buildRegisterClasses - Build the ClassInfo* instances for register
641 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
643 /// buildOperandClasses - Build the ClassInfo* instances for user defined
645 void buildOperandClasses();
647 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
649 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
650 MatchableInfo::AsmOperand &Op);
653 AsmMatcherInfo(Record *AsmParser,
654 CodeGenTarget &Target,
655 RecordKeeper &Records);
657 /// buildInfo - Construct the various tables used during matching.
660 /// buildOperandMatchInfo - Build the necessary information to handle user
661 /// defined operand parsing methods.
662 void buildOperandMatchInfo();
664 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
666 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
667 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
668 std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator I =
669 SubtargetFeatures.find(Def);
670 return I == SubtargetFeatures.end() ? 0 : I->second;
673 RecordKeeper &getRecords() const {
678 } // End anonymous namespace
680 void MatchableInfo::dump() {
681 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
683 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
684 AsmOperand &Op = AsmOperands[i];
685 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
686 errs() << '\"' << Op.Token << "\"\n";
690 static std::pair<StringRef, StringRef>
691 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
692 // Split via the '='.
693 std::pair<StringRef, StringRef> Ops = S.split('=');
694 if (Ops.second == "")
695 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
696 // Trim whitespace and the leading '$' on the operand names.
697 size_t start = Ops.first.find_first_of('$');
698 if (start == std::string::npos)
699 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
700 Ops.first = Ops.first.slice(start + 1, std::string::npos);
701 size_t end = Ops.first.find_last_of(" \t");
702 Ops.first = Ops.first.slice(0, end);
703 // Now the second operand.
704 start = Ops.second.find_first_of('$');
705 if (start == std::string::npos)
706 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
707 Ops.second = Ops.second.slice(start + 1, std::string::npos);
708 end = Ops.second.find_last_of(" \t");
709 Ops.first = Ops.first.slice(0, end);
713 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
714 // Figure out which operands are aliased and mark them as tied.
715 std::pair<StringRef, StringRef> Ops =
716 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
718 // Find the AsmOperands that refer to the operands we're aliasing.
719 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
720 int DstAsmOperand = findAsmOperandNamed(Ops.second);
721 if (SrcAsmOperand == -1)
722 PrintFatalError(TheDef->getLoc(),
723 "unknown source two-operand alias operand '" +
724 Ops.first.str() + "'.");
725 if (DstAsmOperand == -1)
726 PrintFatalError(TheDef->getLoc(),
727 "unknown destination two-operand alias operand '" +
728 Ops.second.str() + "'.");
730 // Find the ResOperand that refers to the operand we're aliasing away
731 // and update it to refer to the combined operand instead.
732 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
733 ResOperand &Op = ResOperands[i];
734 if (Op.Kind == ResOperand::RenderAsmOperand &&
735 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
736 Op.AsmOperandNum = DstAsmOperand;
740 // Remove the AsmOperand for the alias operand.
741 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
742 // Adjust the ResOperand references to any AsmOperands that followed
743 // the one we just deleted.
744 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
745 ResOperand &Op = ResOperands[i];
748 // Nothing to do for operands that don't reference AsmOperands.
750 case ResOperand::RenderAsmOperand:
751 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
754 case ResOperand::TiedOperand:
755 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
762 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
763 SmallPtrSet<Record*, 16> &SingletonRegisters,
764 int AsmVariantNo, std::string &RegisterPrefix) {
765 AsmVariantID = AsmVariantNo;
767 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
769 tokenizeAsmString(Info);
771 // Compute the require features.
772 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
773 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
774 if (SubtargetFeatureInfo *Feature =
775 Info.getSubtargetFeature(Predicates[i]))
776 RequiredFeatures.push_back(Feature);
778 // Collect singleton registers, if used.
779 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
780 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
781 if (Record *Reg = AsmOperands[i].SingletonReg)
782 SingletonRegisters.insert(Reg);
785 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
787 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
790 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
793 /// tokenizeAsmString - Tokenize a simplified assembly string.
794 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
795 StringRef String = AsmString;
798 for (unsigned i = 0, e = String.size(); i != e; ++i) {
808 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
811 if (!isspace(String[i]) && String[i] != ',')
812 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
818 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
822 assert(i != String.size() && "Invalid quoted character");
823 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
829 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
833 // If this isn't "${", treat like a normal token.
834 if (i + 1 == String.size() || String[i + 1] != '{') {
839 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
840 assert(End != String.end() && "Missing brace in operand reference!");
841 size_t EndPos = End - String.begin();
842 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
849 if (!Info.AsmParser->getValueAsBit("MnemonicContainsDot")) {
851 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
861 if (InTok && Prev != String.size())
862 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
864 // The first token of the instruction is the mnemonic, which must be a
865 // simple string, not a $foo variable or a singleton register.
866 if (AsmOperands.empty())
867 PrintFatalError(TheDef->getLoc(),
868 "Instruction '" + TheDef->getName() + "' has no tokens");
869 Mnemonic = AsmOperands[0].Token;
870 if (Mnemonic.empty())
871 PrintFatalError(TheDef->getLoc(),
872 "Missing instruction mnemonic");
873 // FIXME : Check and raise an error if it is a register.
874 if (Mnemonic[0] == '$')
875 PrintFatalError(TheDef->getLoc(),
876 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
878 // Remove the first operand, it is tracked in the mnemonic field.
879 AsmOperands.erase(AsmOperands.begin());
882 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
883 // Reject matchables with no .s string.
884 if (AsmString.empty())
885 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
887 // Reject any matchables with a newline in them, they should be marked
888 // isCodeGenOnly if they are pseudo instructions.
889 if (AsmString.find('\n') != std::string::npos)
890 PrintFatalError(TheDef->getLoc(),
891 "multiline instruction is not valid for the asmparser, "
892 "mark it isCodeGenOnly");
894 // Remove comments from the asm string. We know that the asmstring only
896 if (!CommentDelimiter.empty() &&
897 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
898 PrintFatalError(TheDef->getLoc(),
899 "asmstring for instruction has comment character in it, "
900 "mark it isCodeGenOnly");
902 // Reject matchables with operand modifiers, these aren't something we can
903 // handle, the target should be refactored to use operands instead of
906 // Also, check for instructions which reference the operand multiple times;
907 // this implies a constraint we would not honor.
908 std::set<std::string> OperandNames;
909 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
910 StringRef Tok = AsmOperands[i].Token;
911 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
912 PrintFatalError(TheDef->getLoc(),
913 "matchable with operand modifier '" + Tok.str() +
914 "' not supported by asm matcher. Mark isCodeGenOnly!");
916 // Verify that any operand is only mentioned once.
917 // We reject aliases and ignore instructions for now.
918 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
920 PrintFatalError(TheDef->getLoc(),
921 "ERROR: matchable with tied operand '" + Tok.str() +
922 "' can never be matched!");
923 // FIXME: Should reject these. The ARM backend hits this with $lane in a
924 // bunch of instructions. It is unclear what the right answer is.
926 errs() << "warning: '" << TheDef->getName() << "': "
927 << "ignoring instruction with tied operand '"
928 << Tok.str() << "'\n";
937 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
938 /// if present, from specified token.
940 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
941 const AsmMatcherInfo &Info,
942 std::string &RegisterPrefix) {
943 StringRef Tok = AsmOperands[OperandNo].Token;
944 if (RegisterPrefix.empty()) {
945 std::string LoweredTok = Tok.lower();
946 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
947 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
951 if (!Tok.startswith(RegisterPrefix))
954 StringRef RegName = Tok.substr(RegisterPrefix.size());
955 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
956 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
958 // If there is no register prefix (i.e. "%" in "%eax"), then this may
959 // be some random non-register token, just ignore it.
963 static std::string getEnumNameForToken(StringRef Str) {
966 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
968 case '*': Res += "_STAR_"; break;
969 case '%': Res += "_PCT_"; break;
970 case ':': Res += "_COLON_"; break;
971 case '!': Res += "_EXCLAIM_"; break;
972 case '.': Res += "_DOT_"; break;
973 case '<': Res += "_LT_"; break;
974 case '>': Res += "_GT_"; break;
976 if ((*it >= 'A' && *it <= 'Z') ||
977 (*it >= 'a' && *it <= 'z') ||
978 (*it >= '0' && *it <= '9'))
981 Res += "_" + utostr((unsigned) *it) + "_";
988 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
989 ClassInfo *&Entry = TokenClasses[Token];
992 Entry = new ClassInfo();
993 Entry->Kind = ClassInfo::Token;
994 Entry->ClassName = "Token";
995 Entry->Name = "MCK_" + getEnumNameForToken(Token);
996 Entry->ValueName = Token;
997 Entry->PredicateMethod = "<invalid>";
998 Entry->RenderMethod = "<invalid>";
999 Entry->ParserMethod = "";
1000 Entry->DiagnosticType = "";
1001 Classes.push_back(Entry);
1008 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1010 Record *Rec = OI.Rec;
1012 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1013 return getOperandClass(Rec, SubOpIdx);
1017 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1018 if (Rec->isSubClassOf("RegisterOperand")) {
1019 // RegisterOperand may have an associated ParserMatchClass. If it does,
1020 // use it, else just fall back to the underlying register class.
1021 const RecordVal *R = Rec->getValue("ParserMatchClass");
1022 if (R == 0 || R->getValue() == 0)
1023 PrintFatalError("Record `" + Rec->getName() +
1024 "' does not have a ParserMatchClass!\n");
1026 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1027 Record *MatchClass = DI->getDef();
1028 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1032 // No custom match class. Just use the register class.
1033 Record *ClassRec = Rec->getValueAsDef("RegClass");
1035 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1036 "' has no associated register class!\n");
1037 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1039 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1043 if (Rec->isSubClassOf("RegisterClass")) {
1044 if (ClassInfo *CI = RegisterClassClasses[Rec])
1046 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1049 if (!Rec->isSubClassOf("Operand"))
1050 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1051 "' does not derive from class Operand!\n");
1052 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1053 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1056 PrintFatalError(Rec->getLoc(), "operand has no match class!");
1059 struct LessRegisterSet {
1060 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1061 // std::set<T> defines its own compariso "operator<", but it
1062 // performs a lexicographical comparison by T's innate comparison
1063 // for some reason. We don't want non-deterministic pointer
1064 // comparisons so use this instead.
1065 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1066 RHS.begin(), RHS.end(),
1071 void AsmMatcherInfo::
1072 buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
1073 const std::vector<CodeGenRegister*> &Registers =
1074 Target.getRegBank().getRegisters();
1075 ArrayRef<CodeGenRegisterClass*> RegClassList =
1076 Target.getRegBank().getRegClasses();
1078 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1080 // The register sets used for matching.
1081 RegisterSetSet RegisterSets;
1083 // Gather the defined sets.
1084 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
1085 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
1086 RegisterSets.insert(RegisterSet(
1087 (*it)->getOrder().begin(), (*it)->getOrder().end()));
1089 // Add any required singleton sets.
1090 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1091 ie = SingletonRegisters.end(); it != ie; ++it) {
1093 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1096 // Introduce derived sets where necessary (when a register does not determine
1097 // a unique register set class), and build the mapping of registers to the set
1098 // they should classify to.
1099 std::map<Record*, RegisterSet> RegisterMap;
1100 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
1101 ie = Registers.end(); it != ie; ++it) {
1102 const CodeGenRegister &CGR = **it;
1103 // Compute the intersection of all sets containing this register.
1104 RegisterSet ContainingSet;
1106 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1107 ie = RegisterSets.end(); it != ie; ++it) {
1108 if (!it->count(CGR.TheDef))
1111 if (ContainingSet.empty()) {
1112 ContainingSet = *it;
1117 std::swap(Tmp, ContainingSet);
1118 std::insert_iterator<RegisterSet> II(ContainingSet,
1119 ContainingSet.begin());
1120 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II,
1124 if (!ContainingSet.empty()) {
1125 RegisterSets.insert(ContainingSet);
1126 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1130 // Construct the register classes.
1131 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1133 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1134 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1135 ClassInfo *CI = new ClassInfo();
1136 CI->Kind = ClassInfo::RegisterClass0 + Index;
1137 CI->ClassName = "Reg" + utostr(Index);
1138 CI->Name = "MCK_Reg" + utostr(Index);
1140 CI->PredicateMethod = ""; // unused
1141 CI->RenderMethod = "addRegOperands";
1142 CI->Registers = *it;
1143 // FIXME: diagnostic type.
1144 CI->DiagnosticType = "";
1145 Classes.push_back(CI);
1146 RegisterSetClasses.insert(std::make_pair(*it, CI));
1149 // Find the superclasses; we could compute only the subgroup lattice edges,
1150 // but there isn't really a point.
1151 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1152 ie = RegisterSets.end(); it != ie; ++it) {
1153 ClassInfo *CI = RegisterSetClasses[*it];
1154 for (RegisterSetSet::iterator it2 = RegisterSets.begin(),
1155 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1157 std::includes(it2->begin(), it2->end(), it->begin(), it->end(),
1159 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1162 // Name the register classes which correspond to a user defined RegisterClass.
1163 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1164 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1165 const CodeGenRegisterClass &RC = **it;
1166 // Def will be NULL for non-user defined register classes.
1167 Record *Def = RC.getDef();
1170 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1171 RC.getOrder().end())];
1172 if (CI->ValueName.empty()) {
1173 CI->ClassName = RC.getName();
1174 CI->Name = "MCK_" + RC.getName();
1175 CI->ValueName = RC.getName();
1177 CI->ValueName = CI->ValueName + "," + RC.getName();
1179 RegisterClassClasses.insert(std::make_pair(Def, CI));
1182 // Populate the map for individual registers.
1183 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
1184 ie = RegisterMap.end(); it != ie; ++it)
1185 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1187 // Name the register classes which correspond to singleton registers.
1188 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1189 ie = SingletonRegisters.end(); it != ie; ++it) {
1191 ClassInfo *CI = RegisterClasses[Rec];
1192 assert(CI && "Missing singleton register class info!");
1194 if (CI->ValueName.empty()) {
1195 CI->ClassName = Rec->getName();
1196 CI->Name = "MCK_" + Rec->getName();
1197 CI->ValueName = Rec->getName();
1199 CI->ValueName = CI->ValueName + "," + Rec->getName();
1203 void AsmMatcherInfo::buildOperandClasses() {
1204 std::vector<Record*> AsmOperands =
1205 Records.getAllDerivedDefinitions("AsmOperandClass");
1207 // Pre-populate AsmOperandClasses map.
1208 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1209 ie = AsmOperands.end(); it != ie; ++it)
1210 AsmOperandClasses[*it] = new ClassInfo();
1213 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1214 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1215 ClassInfo *CI = AsmOperandClasses[*it];
1216 CI->Kind = ClassInfo::UserClass0 + Index;
1218 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1219 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1220 DefInit *DI = dyn_cast<DefInit>(Supers->getElement(i));
1222 PrintError((*it)->getLoc(), "Invalid super class reference!");
1226 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1228 PrintError((*it)->getLoc(), "Invalid super class reference!");
1230 CI->SuperClasses.push_back(SC);
1232 CI->ClassName = (*it)->getValueAsString("Name");
1233 CI->Name = "MCK_" + CI->ClassName;
1234 CI->ValueName = (*it)->getName();
1236 // Get or construct the predicate method name.
1237 Init *PMName = (*it)->getValueInit("PredicateMethod");
1238 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1239 CI->PredicateMethod = SI->getValue();
1241 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1242 CI->PredicateMethod = "is" + CI->ClassName;
1245 // Get or construct the render method name.
1246 Init *RMName = (*it)->getValueInit("RenderMethod");
1247 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1248 CI->RenderMethod = SI->getValue();
1250 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1251 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1254 // Get the parse method name or leave it as empty.
1255 Init *PRMName = (*it)->getValueInit("ParserMethod");
1256 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1257 CI->ParserMethod = SI->getValue();
1259 // Get the diagnostic type or leave it as empty.
1260 // Get the parse method name or leave it as empty.
1261 Init *DiagnosticType = (*it)->getValueInit("DiagnosticType");
1262 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1263 CI->DiagnosticType = SI->getValue();
1265 AsmOperandClasses[*it] = CI;
1266 Classes.push_back(CI);
1270 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1271 CodeGenTarget &target,
1272 RecordKeeper &records)
1273 : Records(records), AsmParser(asmParser), Target(target) {
1276 /// buildOperandMatchInfo - Build the necessary information to handle user
1277 /// defined operand parsing methods.
1278 void AsmMatcherInfo::buildOperandMatchInfo() {
1280 /// Map containing a mask with all operands indices that can be found for
1281 /// that class inside a instruction.
1282 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
1283 OpClassMaskTy OpClassMask;
1285 for (std::vector<MatchableInfo*>::const_iterator it =
1286 Matchables.begin(), ie = Matchables.end();
1288 MatchableInfo &II = **it;
1289 OpClassMask.clear();
1291 // Keep track of all operands of this instructions which belong to the
1293 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1294 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1295 if (Op.Class->ParserMethod.empty())
1297 unsigned &OperandMask = OpClassMask[Op.Class];
1298 OperandMask |= (1 << i);
1301 // Generate operand match info for each mnemonic/operand class pair.
1302 for (OpClassMaskTy::iterator iit = OpClassMask.begin(),
1303 iie = OpClassMask.end(); iit != iie; ++iit) {
1304 unsigned OpMask = iit->second;
1305 ClassInfo *CI = iit->first;
1306 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
1311 void AsmMatcherInfo::buildInfo() {
1312 // Build information about all of the AssemblerPredicates.
1313 std::vector<Record*> AllPredicates =
1314 Records.getAllDerivedDefinitions("Predicate");
1315 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1316 Record *Pred = AllPredicates[i];
1317 // Ignore predicates that are not intended for the assembler.
1318 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1321 if (Pred->getName().empty())
1322 PrintFatalError(Pred->getLoc(), "Predicate has no name!");
1324 unsigned FeatureNo = SubtargetFeatures.size();
1325 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1326 assert(FeatureNo < 32 && "Too many subtarget features!");
1329 // Parse the instructions; we need to do this first so that we can gather the
1330 // singleton register classes.
1331 SmallPtrSet<Record*, 16> SingletonRegisters;
1332 unsigned VariantCount = Target.getAsmParserVariantCount();
1333 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1334 Record *AsmVariant = Target.getAsmParserVariant(VC);
1335 std::string CommentDelimiter =
1336 AsmVariant->getValueAsString("CommentDelimiter");
1337 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1338 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1340 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1341 E = Target.inst_end(); I != E; ++I) {
1342 const CodeGenInstruction &CGI = **I;
1344 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1345 // filter the set of instructions we consider.
1346 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1349 // Ignore "codegen only" instructions.
1350 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1353 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1355 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1357 // Ignore instructions which shouldn't be matched and diagnose invalid
1358 // instruction definitions with an error.
1359 if (!II->validate(CommentDelimiter, true))
1362 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1364 // FIXME: This is a total hack.
1365 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1366 StringRef(II->TheDef->getName()).endswith("_Int"))
1369 Matchables.push_back(II.release());
1372 // Parse all of the InstAlias definitions and stick them in the list of
1374 std::vector<Record*> AllInstAliases =
1375 Records.getAllDerivedDefinitions("InstAlias");
1376 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1377 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1379 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1380 // filter the set of instruction aliases we consider, based on the target
1382 if (!StringRef(Alias->ResultInst->TheDef->getName())
1383 .startswith( MatchPrefix))
1386 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1388 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1390 // Validate the alias definitions.
1391 II->validate(CommentDelimiter, false);
1393 Matchables.push_back(II.release());
1397 // Build info for the register classes.
1398 buildRegisterClasses(SingletonRegisters);
1400 // Build info for the user defined assembly operand classes.
1401 buildOperandClasses();
1403 // Build the information about matchables, now that we have fully formed
1405 std::vector<MatchableInfo*> NewMatchables;
1406 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1407 ie = Matchables.end(); it != ie; ++it) {
1408 MatchableInfo *II = *it;
1410 // Parse the tokens after the mnemonic.
1411 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1412 // don't precompute the loop bound.
1413 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1414 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1415 StringRef Token = Op.Token;
1417 // Check for singleton registers.
1418 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1419 Op.Class = RegisterClasses[RegRecord];
1420 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1421 "Unexpected class for singleton register");
1425 // Check for simple tokens.
1426 if (Token[0] != '$') {
1427 Op.Class = getTokenClass(Token);
1431 if (Token.size() > 1 && isdigit(Token[1])) {
1432 Op.Class = getTokenClass(Token);
1436 // Otherwise this is an operand reference.
1437 StringRef OperandName;
1438 if (Token[1] == '{')
1439 OperandName = Token.substr(2, Token.size() - 3);
1441 OperandName = Token.substr(1);
1443 if (II->DefRec.is<const CodeGenInstruction*>())
1444 buildInstructionOperandReference(II, OperandName, i);
1446 buildAliasOperandReference(II, OperandName, Op);
1449 if (II->DefRec.is<const CodeGenInstruction*>()) {
1450 II->buildInstructionResultOperands();
1451 // If the instruction has a two-operand alias, build up the
1452 // matchable here. We'll add them in bulk at the end to avoid
1453 // confusing this loop.
1454 std::string Constraint =
1455 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1456 if (Constraint != "") {
1457 // Start by making a copy of the original matchable.
1458 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II));
1460 // Adjust it to be a two-operand alias.
1461 AliasII->formTwoOperandAlias(Constraint);
1463 // Add the alias to the matchables list.
1464 NewMatchables.push_back(AliasII.release());
1467 II->buildAliasResultOperands();
1469 if (!NewMatchables.empty())
1470 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1471 NewMatchables.end());
1473 // Process token alias definitions and set up the associated superclass
1475 std::vector<Record*> AllTokenAliases =
1476 Records.getAllDerivedDefinitions("TokenAlias");
1477 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1478 Record *Rec = AllTokenAliases[i];
1479 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1480 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1481 if (FromClass == ToClass)
1482 PrintFatalError(Rec->getLoc(),
1483 "error: Destination value identical to source value.");
1484 FromClass->SuperClasses.push_back(ToClass);
1487 // Reorder classes so that classes precede super classes.
1488 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1491 /// buildInstructionOperandReference - The specified operand is a reference to a
1492 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1493 void AsmMatcherInfo::
1494 buildInstructionOperandReference(MatchableInfo *II,
1495 StringRef OperandName,
1496 unsigned AsmOpIdx) {
1497 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1498 const CGIOperandList &Operands = CGI.Operands;
1499 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1501 // Map this token to an operand.
1503 if (!Operands.hasOperandNamed(OperandName, Idx))
1504 PrintFatalError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1505 OperandName.str() + "'");
1507 // If the instruction operand has multiple suboperands, but the parser
1508 // match class for the asm operand is still the default "ImmAsmOperand",
1509 // then handle each suboperand separately.
1510 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1511 Record *Rec = Operands[Idx].Rec;
1512 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1513 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1514 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1515 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1516 StringRef Token = Op->Token; // save this in case Op gets moved
1517 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1518 MatchableInfo::AsmOperand NewAsmOp(Token);
1519 NewAsmOp.SubOpIdx = SI;
1520 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1522 // Replace Op with first suboperand.
1523 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1528 // Set up the operand class.
1529 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1531 // If the named operand is tied, canonicalize it to the untied operand.
1532 // For example, something like:
1533 // (outs GPR:$dst), (ins GPR:$src)
1534 // with an asmstring of
1536 // we want to canonicalize to:
1538 // so that we know how to provide the $dst operand when filling in the result.
1540 if (Operands[Idx].MINumOperands == 1)
1541 OITied = Operands[Idx].getTiedRegister();
1543 // The tied operand index is an MIOperand index, find the operand that
1545 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1546 OperandName = Operands[Idx.first].Name;
1547 Op->SubOpIdx = Idx.second;
1550 Op->SrcOpName = OperandName;
1553 /// buildAliasOperandReference - When parsing an operand reference out of the
1554 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1555 /// operand reference is by looking it up in the result pattern definition.
1556 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1557 StringRef OperandName,
1558 MatchableInfo::AsmOperand &Op) {
1559 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1561 // Set up the operand class.
1562 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1563 if (CGA.ResultOperands[i].isRecord() &&
1564 CGA.ResultOperands[i].getName() == OperandName) {
1565 // It's safe to go with the first one we find, because CodeGenInstAlias
1566 // validates that all operands with the same name have the same record.
1567 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1568 // Use the match class from the Alias definition, not the
1569 // destination instruction, as we may have an immediate that's
1570 // being munged by the match class.
1571 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1573 Op.SrcOpName = OperandName;
1577 PrintFatalError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1578 OperandName.str() + "'");
1581 void MatchableInfo::buildInstructionResultOperands() {
1582 const CodeGenInstruction *ResultInst = getResultInst();
1584 // Loop over all operands of the result instruction, determining how to
1586 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1587 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1589 // If this is a tied operand, just copy from the previously handled operand.
1591 if (OpInfo.MINumOperands == 1)
1592 TiedOp = OpInfo.getTiedRegister();
1594 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1598 // Find out what operand from the asmparser this MCInst operand comes from.
1599 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1600 if (OpInfo.Name.empty() || SrcOperand == -1) {
1601 // This may happen for operands that are tied to a suboperand of a
1602 // complex operand. Simply use a dummy value here; nobody should
1603 // use this operand slot.
1604 // FIXME: The long term goal is for the MCOperand list to not contain
1605 // tied operands at all.
1606 ResOperands.push_back(ResOperand::getImmOp(0));
1610 // Check if the one AsmOperand populates the entire operand.
1611 unsigned NumOperands = OpInfo.MINumOperands;
1612 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1613 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1617 // Add a separate ResOperand for each suboperand.
1618 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1619 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1620 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1621 "unexpected AsmOperands for suboperands");
1622 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1627 void MatchableInfo::buildAliasResultOperands() {
1628 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1629 const CodeGenInstruction *ResultInst = getResultInst();
1631 // Loop over all operands of the result instruction, determining how to
1633 unsigned AliasOpNo = 0;
1634 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1635 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1636 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1638 // If this is a tied operand, just copy from the previously handled operand.
1640 if (OpInfo->MINumOperands == 1)
1641 TiedOp = OpInfo->getTiedRegister();
1643 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1647 // Handle all the suboperands for this operand.
1648 const std::string &OpName = OpInfo->Name;
1649 for ( ; AliasOpNo < LastOpNo &&
1650 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1651 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1653 // Find out what operand from the asmparser that this MCInst operand
1655 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1656 case CodeGenInstAlias::ResultOperand::K_Record: {
1657 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1658 int SrcOperand = findAsmOperand(Name, SubIdx);
1659 if (SrcOperand == -1)
1660 PrintFatalError(TheDef->getLoc(), "Instruction '" +
1661 TheDef->getName() + "' has operand '" + OpName +
1662 "' that doesn't appear in asm string!");
1663 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1664 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1668 case CodeGenInstAlias::ResultOperand::K_Imm: {
1669 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1670 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1673 case CodeGenInstAlias::ResultOperand::K_Reg: {
1674 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1675 ResOperands.push_back(ResOperand::getRegOp(Reg));
1683 static unsigned getConverterOperandID(const std::string &Name,
1684 SetVector<std::string> &Table,
1686 IsNew = Table.insert(Name);
1688 unsigned ID = IsNew ? Table.size() - 1 :
1689 std::find(Table.begin(), Table.end(), Name) - Table.begin();
1691 assert(ID < Table.size());
1697 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1698 std::vector<MatchableInfo*> &Infos,
1700 SetVector<std::string> OperandConversionKinds;
1701 SetVector<std::string> InstructionConversionKinds;
1702 std::vector<std::vector<uint8_t> > ConversionTable;
1703 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1705 // TargetOperandClass - This is the target's operand class, like X86Operand.
1706 std::string TargetOperandClass = Target.getName() + "Operand";
1708 // Write the convert function to a separate stream, so we can drop it after
1709 // the enum. We'll build up the conversion handlers for the individual
1710 // operand types opportunistically as we encounter them.
1711 std::string ConvertFnBody;
1712 raw_string_ostream CvtOS(ConvertFnBody);
1713 // Start the unified conversion function.
1714 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1715 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1716 << "unsigned Opcode,\n"
1717 << " const SmallVectorImpl<MCParsedAsmOperand*"
1718 << "> &Operands) {\n"
1719 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
1720 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1721 << " Inst.setOpcode(Opcode);\n"
1722 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
1723 << " switch (*p) {\n"
1724 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1725 << " case CVT_Reg:\n"
1726 << " static_cast<" << TargetOperandClass
1727 << "*>(Operands[*(p + 1)])->addRegOperands(Inst, 1);\n"
1729 << " case CVT_Tied:\n"
1730 << " Inst.addOperand(Inst.getOperand(*(p + 1)));\n"
1733 std::string OperandFnBody;
1734 raw_string_ostream OpOS(OperandFnBody);
1735 // Start the operand number lookup function.
1736 OpOS << "void " << Target.getName() << ClassName << "::\n"
1737 << "convertToMapAndConstraints(unsigned Kind,\n";
1739 OpOS << "const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {\n"
1740 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
1741 << " unsigned NumMCOperands = 0;\n"
1742 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1743 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
1744 << " switch (*p) {\n"
1745 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1746 << " case CVT_Reg:\n"
1747 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1748 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
1749 << " ++NumMCOperands;\n"
1751 << " case CVT_Tied:\n"
1752 << " ++NumMCOperands;\n"
1755 // Pre-populate the operand conversion kinds with the standard always
1756 // available entries.
1757 OperandConversionKinds.insert("CVT_Done");
1758 OperandConversionKinds.insert("CVT_Reg");
1759 OperandConversionKinds.insert("CVT_Tied");
1760 enum { CVT_Done, CVT_Reg, CVT_Tied };
1762 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1763 ie = Infos.end(); it != ie; ++it) {
1764 MatchableInfo &II = **it;
1766 // Check if we have a custom match function.
1767 std::string AsmMatchConverter =
1768 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1769 if (!AsmMatchConverter.empty()) {
1770 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1771 II.ConversionFnKind = Signature;
1773 // Check if we have already generated this signature.
1774 if (!InstructionConversionKinds.insert(Signature))
1777 // Remember this converter for the kind enum.
1778 unsigned KindID = OperandConversionKinds.size();
1779 OperandConversionKinds.insert("CVT_" +
1780 getEnumNameForToken(AsmMatchConverter));
1782 // Add the converter row for this instruction.
1783 ConversionTable.push_back(std::vector<uint8_t>());
1784 ConversionTable.back().push_back(KindID);
1785 ConversionTable.back().push_back(CVT_Done);
1787 // Add the handler to the conversion driver function.
1788 CvtOS << " case CVT_"
1789 << getEnumNameForToken(AsmMatchConverter) << ":\n"
1790 << " " << AsmMatchConverter << "(Inst, Operands);\n"
1793 // FIXME: Handle the operand number lookup for custom match functions.
1797 // Build the conversion function signature.
1798 std::string Signature = "Convert";
1800 std::vector<uint8_t> ConversionRow;
1802 // Compute the convert enum and the case body.
1803 MaxRowLength = std::max(MaxRowLength, II.ResOperands.size()*2 + 1 );
1805 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1806 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1808 // Generate code to populate each result operand.
1809 switch (OpInfo.Kind) {
1810 case MatchableInfo::ResOperand::RenderAsmOperand: {
1811 // This comes from something we parsed.
1812 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1814 // Registers are always converted the same, don't duplicate the
1815 // conversion function based on them.
1818 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1820 Signature += utostr(OpInfo.MINumOperands);
1821 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1823 // Add the conversion kind, if necessary, and get the associated ID
1824 // the index of its entry in the vector).
1825 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1826 Op.Class->RenderMethod);
1827 Name = getEnumNameForToken(Name);
1829 bool IsNewConverter = false;
1830 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1833 // Add the operand entry to the instruction kind conversion row.
1834 ConversionRow.push_back(ID);
1835 ConversionRow.push_back(OpInfo.AsmOperandNum + 1);
1837 if (!IsNewConverter)
1840 // This is a new operand kind. Add a handler for it to the
1841 // converter driver.
1842 CvtOS << " case " << Name << ":\n"
1843 << " static_cast<" << TargetOperandClass
1844 << "*>(Operands[*(p + 1)])->"
1845 << Op.Class->RenderMethod << "(Inst, " << OpInfo.MINumOperands
1849 // Add a handler for the operand number lookup.
1850 OpOS << " case " << Name << ":\n"
1851 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
1853 if (Op.Class->isRegisterClass())
1854 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
1856 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
1857 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
1861 case MatchableInfo::ResOperand::TiedOperand: {
1862 // If this operand is tied to a previous one, just copy the MCInst
1863 // operand from the earlier one.We can only tie single MCOperand values.
1864 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1865 unsigned TiedOp = OpInfo.TiedOperandNum;
1866 assert(i > TiedOp && "Tied operand precedes its target!");
1867 Signature += "__Tie" + utostr(TiedOp);
1868 ConversionRow.push_back(CVT_Tied);
1869 ConversionRow.push_back(TiedOp);
1872 case MatchableInfo::ResOperand::ImmOperand: {
1873 int64_t Val = OpInfo.ImmVal;
1874 std::string Ty = "imm_" + itostr(Val);
1875 Signature += "__" + Ty;
1877 std::string Name = "CVT_" + Ty;
1878 bool IsNewConverter = false;
1879 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1881 // Add the operand entry to the instruction kind conversion row.
1882 ConversionRow.push_back(ID);
1883 ConversionRow.push_back(0);
1885 if (!IsNewConverter)
1888 CvtOS << " case " << Name << ":\n"
1889 << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n"
1892 OpOS << " case " << Name << ":\n"
1893 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1894 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
1895 << " ++NumMCOperands;\n"
1899 case MatchableInfo::ResOperand::RegOperand: {
1900 std::string Reg, Name;
1901 if (OpInfo.Register == 0) {
1905 Reg = getQualifiedName(OpInfo.Register);
1906 Name = "reg" + OpInfo.Register->getName();
1908 Signature += "__" + Name;
1909 Name = "CVT_" + Name;
1910 bool IsNewConverter = false;
1911 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1913 // Add the operand entry to the instruction kind conversion row.
1914 ConversionRow.push_back(ID);
1915 ConversionRow.push_back(0);
1917 if (!IsNewConverter)
1919 CvtOS << " case " << Name << ":\n"
1920 << " Inst.addOperand(MCOperand::CreateReg(" << Reg << "));\n"
1923 OpOS << " case " << Name << ":\n"
1924 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1925 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
1926 << " ++NumMCOperands;\n"
1932 // If there were no operands, add to the signature to that effect
1933 if (Signature == "Convert")
1934 Signature += "_NoOperands";
1936 II.ConversionFnKind = Signature;
1938 // Save the signature. If we already have it, don't add a new row
1940 if (!InstructionConversionKinds.insert(Signature))
1943 // Add the row to the table.
1944 ConversionTable.push_back(ConversionRow);
1947 // Finish up the converter driver function.
1948 CvtOS << " }\n }\n}\n\n";
1950 // Finish up the operand number lookup function.
1951 OpOS << " }\n }\n}\n\n";
1953 OS << "namespace {\n";
1955 // Output the operand conversion kind enum.
1956 OS << "enum OperatorConversionKind {\n";
1957 for (unsigned i = 0, e = OperandConversionKinds.size(); i != e; ++i)
1958 OS << " " << OperandConversionKinds[i] << ",\n";
1959 OS << " CVT_NUM_CONVERTERS\n";
1962 // Output the instruction conversion kind enum.
1963 OS << "enum InstructionConversionKind {\n";
1964 for (SetVector<std::string>::const_iterator
1965 i = InstructionConversionKinds.begin(),
1966 e = InstructionConversionKinds.end(); i != e; ++i)
1967 OS << " " << *i << ",\n";
1968 OS << " CVT_NUM_SIGNATURES\n";
1972 OS << "} // end anonymous namespace\n\n";
1974 // Output the conversion table.
1975 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
1976 << MaxRowLength << "] = {\n";
1978 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
1979 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
1980 OS << " // " << InstructionConversionKinds[Row] << "\n";
1982 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
1983 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
1984 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
1985 OS << "CVT_Done },\n";
1990 // Spit out the conversion driver function.
1993 // Spit out the operand number lookup function.
1997 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1998 static void emitMatchClassEnumeration(CodeGenTarget &Target,
1999 std::vector<ClassInfo*> &Infos,
2001 OS << "namespace {\n\n";
2003 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2004 << "/// instruction matching.\n";
2005 OS << "enum MatchClassKind {\n";
2006 OS << " InvalidMatchClass = 0,\n";
2007 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2008 ie = Infos.end(); it != ie; ++it) {
2009 ClassInfo &CI = **it;
2010 OS << " " << CI.Name << ", // ";
2011 if (CI.Kind == ClassInfo::Token) {
2012 OS << "'" << CI.ValueName << "'\n";
2013 } else if (CI.isRegisterClass()) {
2014 if (!CI.ValueName.empty())
2015 OS << "register class '" << CI.ValueName << "'\n";
2017 OS << "derived register class\n";
2019 OS << "user defined class '" << CI.ValueName << "'\n";
2022 OS << " NumMatchClassKinds\n";
2028 /// emitValidateOperandClass - Emit the function to validate an operand class.
2029 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2031 OS << "static unsigned validateOperandClass(MCParsedAsmOperand *GOp, "
2032 << "MatchClassKind Kind) {\n";
2033 OS << " " << Info.Target.getName() << "Operand &Operand = *("
2034 << Info.Target.getName() << "Operand*)GOp;\n";
2036 // The InvalidMatchClass is not to match any operand.
2037 OS << " if (Kind == InvalidMatchClass)\n";
2038 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2040 // Check for Token operands first.
2041 // FIXME: Use a more specific diagnostic type.
2042 OS << " if (Operand.isToken())\n";
2043 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2044 << " MCTargetAsmParser::Match_Success :\n"
2045 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2047 // Check the user classes. We don't care what order since we're only
2048 // actually matching against one of them.
2049 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
2050 ie = Info.Classes.end(); it != ie; ++it) {
2051 ClassInfo &CI = **it;
2053 if (!CI.isUserClass())
2056 OS << " // '" << CI.ClassName << "' class\n";
2057 OS << " if (Kind == " << CI.Name << ") {\n";
2058 OS << " if (Operand." << CI.PredicateMethod << "())\n";
2059 OS << " return MCTargetAsmParser::Match_Success;\n";
2060 if (!CI.DiagnosticType.empty())
2061 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2062 << CI.DiagnosticType << ";\n";
2066 // Check for register operands, including sub-classes.
2067 OS << " if (Operand.isReg()) {\n";
2068 OS << " MatchClassKind OpKind;\n";
2069 OS << " switch (Operand.getReg()) {\n";
2070 OS << " default: OpKind = InvalidMatchClass; break;\n";
2071 for (AsmMatcherInfo::RegisterClassesTy::iterator
2072 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
2074 OS << " case " << Info.Target.getName() << "::"
2075 << it->first->getName() << ": OpKind = " << it->second->Name
2078 OS << " return isSubclass(OpKind, Kind) ? "
2079 << "MCTargetAsmParser::Match_Success :\n "
2080 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
2082 // Generic fallthrough match failure case for operands that don't have
2083 // specialized diagnostic types.
2084 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2088 /// emitIsSubclass - Emit the subclass predicate function.
2089 static void emitIsSubclass(CodeGenTarget &Target,
2090 std::vector<ClassInfo*> &Infos,
2092 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2093 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2094 OS << " if (A == B)\n";
2095 OS << " return true;\n\n";
2098 raw_string_ostream SS(OStr);
2100 SS << " switch (A) {\n";
2101 SS << " default:\n";
2102 SS << " return false;\n";
2103 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2104 ie = Infos.end(); it != ie; ++it) {
2105 ClassInfo &A = **it;
2107 std::vector<StringRef> SuperClasses;
2108 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2109 ie = Infos.end(); it != ie; ++it) {
2110 ClassInfo &B = **it;
2112 if (&A != &B && A.isSubsetOf(B))
2113 SuperClasses.push_back(B.Name);
2116 if (SuperClasses.empty())
2120 SS << "\n case " << A.Name << ":\n";
2122 if (SuperClasses.size() == 1) {
2123 SS << " return B == " << SuperClasses.back().str() << ";\n";
2127 if (!SuperClasses.empty()) {
2128 SS << " switch (B) {\n";
2129 SS << " default: return false;\n";
2130 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
2131 SS << " case " << SuperClasses[i].str() << ": return true;\n";
2134 // No case statement to emit
2135 SS << " return false;\n";
2140 // If there were case statements emitted into the string stream, write them
2141 // to the output stream, otherwise write the default.
2145 OS << " return false;\n";
2150 /// emitMatchTokenString - Emit the function to match a token string to the
2151 /// appropriate match class value.
2152 static void emitMatchTokenString(CodeGenTarget &Target,
2153 std::vector<ClassInfo*> &Infos,
2155 // Construct the match list.
2156 std::vector<StringMatcher::StringPair> Matches;
2157 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2158 ie = Infos.end(); it != ie; ++it) {
2159 ClassInfo &CI = **it;
2161 if (CI.Kind == ClassInfo::Token)
2162 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
2163 "return " + CI.Name + ";"));
2166 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2168 StringMatcher("Name", Matches, OS).Emit();
2170 OS << " return InvalidMatchClass;\n";
2174 /// emitMatchRegisterName - Emit the function to match a string to the target
2175 /// specific register enum.
2176 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2178 // Construct the match list.
2179 std::vector<StringMatcher::StringPair> Matches;
2180 const std::vector<CodeGenRegister*> &Regs =
2181 Target.getRegBank().getRegisters();
2182 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2183 const CodeGenRegister *Reg = Regs[i];
2184 if (Reg->TheDef->getValueAsString("AsmName").empty())
2187 Matches.push_back(StringMatcher::StringPair(
2188 Reg->TheDef->getValueAsString("AsmName"),
2189 "return " + utostr(Reg->EnumValue) + ";"));
2192 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2194 StringMatcher("Name", Matches, OS).Emit();
2196 OS << " return 0;\n";
2200 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
2202 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
2204 OS << "// Flags for subtarget features that participate in "
2205 << "instruction matching.\n";
2206 OS << "enum SubtargetFeatureFlag {\n";
2207 for (std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator
2208 it = Info.SubtargetFeatures.begin(),
2209 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2210 SubtargetFeatureInfo &SFI = *it->second;
2211 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
2213 OS << " Feature_None = 0\n";
2217 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2218 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2219 // Get the set of diagnostic types from all of the operand classes.
2220 std::set<StringRef> Types;
2221 for (std::map<Record*, ClassInfo*>::const_iterator
2222 I = Info.AsmOperandClasses.begin(),
2223 E = Info.AsmOperandClasses.end(); I != E; ++I) {
2224 if (!I->second->DiagnosticType.empty())
2225 Types.insert(I->second->DiagnosticType);
2228 if (Types.empty()) return;
2230 // Now emit the enum entries.
2231 for (std::set<StringRef>::const_iterator I = Types.begin(), E = Types.end();
2233 OS << " Match_" << *I << ",\n";
2234 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2237 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2238 /// user-level name for a subtarget feature.
2239 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2240 OS << "// User-level names for subtarget features that participate in\n"
2241 << "// instruction matching.\n"
2242 << "static const char *getSubtargetFeatureName(unsigned Val) {\n";
2243 if (!Info.SubtargetFeatures.empty()) {
2244 OS << " switch(Val) {\n";
2245 typedef std::map<Record*, SubtargetFeatureInfo*, LessRecordByID> RecFeatMap;
2246 for (RecFeatMap::const_iterator it = Info.SubtargetFeatures.begin(),
2247 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2248 SubtargetFeatureInfo &SFI = *it->second;
2249 // FIXME: Totally just a placeholder name to get the algorithm working.
2250 OS << " case " << SFI.getEnumName() << ": return \""
2251 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2253 OS << " default: return \"(unknown)\";\n";
2256 // Nothing to emit, so skip the switch
2257 OS << " return \"(unknown)\";\n";
2262 /// emitComputeAvailableFeatures - Emit the function to compute the list of
2263 /// available features given a subtarget.
2264 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
2266 std::string ClassName =
2267 Info.AsmParser->getValueAsString("AsmParserClassName");
2269 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
2270 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
2271 OS << " unsigned Features = 0;\n";
2272 for (std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator
2273 it = Info.SubtargetFeatures.begin(),
2274 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2275 SubtargetFeatureInfo &SFI = *it->second;
2278 std::string CondStorage =
2279 SFI.TheDef->getValueAsString("AssemblerCondString");
2280 StringRef Conds = CondStorage;
2281 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2288 StringRef Cond = Comma.first;
2289 if (Cond[0] == '!') {
2291 Cond = Cond.substr(1);
2294 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2301 if (Comma.second.empty())
2305 Comma = Comma.second.split(',');
2309 OS << " Features |= " << SFI.getEnumName() << ";\n";
2311 OS << " return Features;\n";
2315 static std::string GetAliasRequiredFeatures(Record *R,
2316 const AsmMatcherInfo &Info) {
2317 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2319 unsigned NumFeatures = 0;
2320 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2321 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2324 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2325 "' is not marked as an AssemblerPredicate!");
2330 Result += F->getEnumName();
2334 if (NumFeatures > 1)
2335 Result = '(' + Result + ')';
2339 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2340 std::vector<Record*> &Aliases,
2341 unsigned Indent = 0,
2342 StringRef AsmParserVariantName = StringRef()){
2343 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2344 // iteration order of the map is stable.
2345 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2347 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2348 Record *R = Aliases[i];
2349 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2350 std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2351 if (AsmVariantName != AsmParserVariantName)
2353 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2355 if (AliasesFromMnemonic.empty())
2358 // Process each alias a "from" mnemonic at a time, building the code executed
2359 // by the string remapper.
2360 std::vector<StringMatcher::StringPair> Cases;
2361 for (std::map<std::string, std::vector<Record*> >::iterator
2362 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2364 const std::vector<Record*> &ToVec = I->second;
2366 // Loop through each alias and emit code that handles each case. If there
2367 // are two instructions without predicates, emit an error. If there is one,
2369 std::string MatchCode;
2370 int AliasWithNoPredicate = -1;
2372 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2373 Record *R = ToVec[i];
2374 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2376 // If this unconditionally matches, remember it for later and diagnose
2378 if (FeatureMask.empty()) {
2379 if (AliasWithNoPredicate != -1) {
2380 // We can't have two aliases from the same mnemonic with no predicate.
2381 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2382 "two MnemonicAliases with the same 'from' mnemonic!");
2383 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2386 AliasWithNoPredicate = i;
2389 if (R->getValueAsString("ToMnemonic") == I->first)
2390 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2392 if (!MatchCode.empty())
2393 MatchCode += "else ";
2394 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2395 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
2398 if (AliasWithNoPredicate != -1) {
2399 Record *R = ToVec[AliasWithNoPredicate];
2400 if (!MatchCode.empty())
2401 MatchCode += "else\n ";
2402 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2405 MatchCode += "return;";
2407 Cases.push_back(std::make_pair(I->first, MatchCode));
2409 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2412 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2413 /// emit a function for them and return true, otherwise return false.
2414 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2415 CodeGenTarget &Target) {
2416 // Ignore aliases when match-prefix is set.
2417 if (!MatchPrefix.empty())
2420 std::vector<Record*> Aliases =
2421 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2422 if (Aliases.empty()) return false;
2424 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2425 "unsigned Features, unsigned VariantID) {\n";
2426 OS << " switch (VariantID) {\n";
2427 unsigned VariantCount = Target.getAsmParserVariantCount();
2428 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2429 Record *AsmVariant = Target.getAsmParserVariant(VC);
2430 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2431 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2432 OS << " case " << AsmParserVariantNo << ":\n";
2433 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2434 AsmParserVariantName);
2439 // Emit aliases that apply to all variants.
2440 emitMnemonicAliasVariant(OS, Info, Aliases);
2447 static const char *getMinimalTypeForRange(uint64_t Range) {
2448 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2456 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2457 const AsmMatcherInfo &Info, StringRef ClassName,
2458 StringToOffsetTable &StringTable,
2459 unsigned MaxMnemonicIndex) {
2460 unsigned MaxMask = 0;
2461 for (std::vector<OperandMatchEntry>::const_iterator it =
2462 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2464 MaxMask |= it->OperandMask;
2467 // Emit the static custom operand parsing table;
2468 OS << "namespace {\n";
2469 OS << " struct OperandMatchEntry {\n";
2470 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2471 << " RequiredFeatures;\n";
2472 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2474 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2476 OS << " " << getMinimalTypeForRange(MaxMask)
2477 << " OperandMask;\n\n";
2478 OS << " StringRef getMnemonic() const {\n";
2479 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2480 OS << " MnemonicTable[Mnemonic]);\n";
2484 OS << " // Predicate for searching for an opcode.\n";
2485 OS << " struct LessOpcodeOperand {\n";
2486 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2487 OS << " return LHS.getMnemonic() < RHS;\n";
2489 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2490 OS << " return LHS < RHS.getMnemonic();\n";
2492 OS << " bool operator()(const OperandMatchEntry &LHS,";
2493 OS << " const OperandMatchEntry &RHS) {\n";
2494 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2498 OS << "} // end anonymous namespace.\n\n";
2500 OS << "static const OperandMatchEntry OperandMatchTable["
2501 << Info.OperandMatchInfo.size() << "] = {\n";
2503 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2504 for (std::vector<OperandMatchEntry>::const_iterator it =
2505 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2507 const OperandMatchEntry &OMI = *it;
2508 const MatchableInfo &II = *OMI.MI;
2512 // Write the required features mask.
2513 if (!II.RequiredFeatures.empty()) {
2514 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2516 OS << II.RequiredFeatures[i]->getEnumName();
2521 // Store a pascal-style length byte in the mnemonic.
2522 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2523 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2524 << " /* " << II.Mnemonic << " */, ";
2528 OS << ", " << OMI.OperandMask;
2530 bool printComma = false;
2531 for (int i = 0, e = 31; i !=e; ++i)
2532 if (OMI.OperandMask & (1 << i)) {
2544 // Emit the operand class switch to call the correct custom parser for
2545 // the found operand class.
2546 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2547 << Target.getName() << ClassName << "::\n"
2548 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2549 << " &Operands,\n unsigned MCK) {\n\n"
2550 << " switch(MCK) {\n";
2552 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2553 ie = Info.Classes.end(); it != ie; ++it) {
2554 ClassInfo *CI = *it;
2555 if (CI->ParserMethod.empty())
2557 OS << " case " << CI->Name << ":\n"
2558 << " return " << CI->ParserMethod << "(Operands);\n";
2561 OS << " default:\n";
2562 OS << " return MatchOperand_NoMatch;\n";
2564 OS << " return MatchOperand_NoMatch;\n";
2567 // Emit the static custom operand parser. This code is very similar with
2568 // the other matcher. Also use MatchResultTy here just in case we go for
2569 // a better error handling.
2570 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2571 << Target.getName() << ClassName << "::\n"
2572 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2573 << " &Operands,\n StringRef Mnemonic) {\n";
2575 // Emit code to get the available features.
2576 OS << " // Get the current feature set.\n";
2577 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2579 OS << " // Get the next operand index.\n";
2580 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2582 // Emit code to search the table.
2583 OS << " // Search the table.\n";
2584 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2585 OS << " MnemonicRange =\n";
2586 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2587 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2588 << " LessOpcodeOperand());\n\n";
2590 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2591 OS << " return MatchOperand_NoMatch;\n\n";
2593 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2594 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2596 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2597 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2599 // Emit check that the required features are available.
2600 OS << " // check if the available features match\n";
2601 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2602 << "!= it->RequiredFeatures) {\n";
2603 OS << " continue;\n";
2606 // Emit check to ensure the operand number matches.
2607 OS << " // check if the operand in question has a custom parser.\n";
2608 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2609 OS << " continue;\n\n";
2611 // Emit call to the custom parser method
2612 OS << " // call custom parse method to handle the operand\n";
2613 OS << " OperandMatchResultTy Result = ";
2614 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2615 OS << " if (Result != MatchOperand_NoMatch)\n";
2616 OS << " return Result;\n";
2619 OS << " // Okay, we had no match.\n";
2620 OS << " return MatchOperand_NoMatch;\n";
2624 void AsmMatcherEmitter::run(raw_ostream &OS) {
2625 CodeGenTarget Target(Records);
2626 Record *AsmParser = Target.getAsmParser();
2627 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2629 // Compute the information on the instructions to match.
2630 AsmMatcherInfo Info(AsmParser, Target, Records);
2633 // Sort the instruction table using the partial order on classes. We use
2634 // stable_sort to ensure that ambiguous instructions are still
2635 // deterministically ordered.
2636 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2637 less_ptr<MatchableInfo>());
2639 DEBUG_WITH_TYPE("instruction_info", {
2640 for (std::vector<MatchableInfo*>::iterator
2641 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2646 // Check for ambiguous matchables.
2647 DEBUG_WITH_TYPE("ambiguous_instrs", {
2648 unsigned NumAmbiguous = 0;
2649 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2650 for (unsigned j = i + 1; j != e; ++j) {
2651 MatchableInfo &A = *Info.Matchables[i];
2652 MatchableInfo &B = *Info.Matchables[j];
2654 if (A.couldMatchAmbiguouslyWith(B)) {
2655 errs() << "warning: ambiguous matchables:\n";
2657 errs() << "\nis incomparable with:\n";
2665 errs() << "warning: " << NumAmbiguous
2666 << " ambiguous matchables!\n";
2669 // Compute the information on the custom operand parsing.
2670 Info.buildOperandMatchInfo();
2672 // Write the output.
2674 // Information for the class declaration.
2675 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2676 OS << "#undef GET_ASSEMBLER_HEADER\n";
2677 OS << " // This should be included into the middle of the declaration of\n";
2678 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2679 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2680 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2681 << "unsigned Opcode,\n"
2682 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2684 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
2685 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands);\n";
2686 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n";
2687 OS << " unsigned MatchInstructionImpl(\n";
2689 OS << "const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"
2690 << " MCInst &Inst,\n"
2691 << " unsigned &ErrorInfo,"
2692 << " bool matchingInlineAsm,\n"
2693 << " unsigned VariantID = 0);\n";
2695 if (Info.OperandMatchInfo.size()) {
2696 OS << "\n enum OperandMatchResultTy {\n";
2697 OS << " MatchOperand_Success, // operand matched successfully\n";
2698 OS << " MatchOperand_NoMatch, // operand did not match\n";
2699 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2701 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2702 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2703 OS << " StringRef Mnemonic);\n";
2705 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2706 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2707 OS << " unsigned MCK);\n\n";
2710 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2712 // Emit the operand match diagnostic enum names.
2713 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2714 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2715 emitOperandDiagnosticTypes(Info, OS);
2716 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2719 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2720 OS << "#undef GET_REGISTER_MATCHER\n\n";
2722 // Emit the subtarget feature enumeration.
2723 emitSubtargetFeatureFlagEnumeration(Info, OS);
2725 // Emit the function to match a register name to number.
2726 // This should be omitted for Mips target
2727 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2728 emitMatchRegisterName(Target, AsmParser, OS);
2730 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2732 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2733 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
2735 // Generate the helper function to get the names for subtarget features.
2736 emitGetSubtargetFeatureName(Info, OS);
2738 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2740 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2741 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2743 // Generate the function that remaps for mnemonic aliases.
2744 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
2746 // Generate the convertToMCInst function to convert operands into an MCInst.
2747 // Also, generate the convertToMapAndConstraints function for MS-style inline
2748 // assembly. The latter doesn't actually generate a MCInst.
2749 emitConvertFuncs(Target, ClassName, Info.Matchables, OS);
2751 // Emit the enumeration for classes which participate in matching.
2752 emitMatchClassEnumeration(Target, Info.Classes, OS);
2754 // Emit the routine to match token strings to their match class.
2755 emitMatchTokenString(Target, Info.Classes, OS);
2757 // Emit the subclass predicate routine.
2758 emitIsSubclass(Target, Info.Classes, OS);
2760 // Emit the routine to validate an operand against a match class.
2761 emitValidateOperandClass(Info, OS);
2763 // Emit the available features compute function.
2764 emitComputeAvailableFeatures(Info, OS);
2767 StringToOffsetTable StringTable;
2769 size_t MaxNumOperands = 0;
2770 unsigned MaxMnemonicIndex = 0;
2771 bool HasDeprecation = false;
2772 for (std::vector<MatchableInfo*>::const_iterator it =
2773 Info.Matchables.begin(), ie = Info.Matchables.end();
2775 MatchableInfo &II = **it;
2776 MaxNumOperands = std::max(MaxNumOperands, II.AsmOperands.size());
2777 HasDeprecation |= II.HasDeprecation;
2779 // Store a pascal-style length byte in the mnemonic.
2780 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2781 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2782 StringTable.GetOrAddStringOffset(LenMnemonic, false));
2785 OS << "static const char *const MnemonicTable =\n";
2786 StringTable.EmitString(OS);
2789 // Emit the static match table; unused classes get initalized to 0 which is
2790 // guaranteed to be InvalidMatchClass.
2792 // FIXME: We can reduce the size of this table very easily. First, we change
2793 // it so that store the kinds in separate bit-fields for each index, which
2794 // only needs to be the max width used for classes at that index (we also need
2795 // to reject based on this during classification). If we then make sure to
2796 // order the match kinds appropriately (putting mnemonics last), then we
2797 // should only end up using a few bits for each class, especially the ones
2798 // following the mnemonic.
2799 OS << "namespace {\n";
2800 OS << " struct MatchEntry {\n";
2801 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2803 OS << " uint16_t Opcode;\n";
2804 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2806 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2807 << " RequiredFeatures;\n";
2808 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2809 << " Classes[" << MaxNumOperands << "];\n";
2810 OS << " StringRef getMnemonic() const {\n";
2811 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2812 OS << " MnemonicTable[Mnemonic]);\n";
2816 OS << " // Predicate for searching for an opcode.\n";
2817 OS << " struct LessOpcode {\n";
2818 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2819 OS << " return LHS.getMnemonic() < RHS;\n";
2821 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2822 OS << " return LHS < RHS.getMnemonic();\n";
2824 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2825 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2829 OS << "} // end anonymous namespace.\n\n";
2831 unsigned VariantCount = Target.getAsmParserVariantCount();
2832 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2833 Record *AsmVariant = Target.getAsmParserVariant(VC);
2834 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2836 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
2838 for (std::vector<MatchableInfo*>::const_iterator it =
2839 Info.Matchables.begin(), ie = Info.Matchables.end();
2841 MatchableInfo &II = **it;
2842 if (II.AsmVariantID != AsmVariantNo)
2845 // Store a pascal-style length byte in the mnemonic.
2846 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2847 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2848 << " /* " << II.Mnemonic << " */, "
2849 << Target.getName() << "::"
2850 << II.getResultInst()->TheDef->getName() << ", "
2851 << II.ConversionFnKind << ", ";
2853 // Write the required features mask.
2854 if (!II.RequiredFeatures.empty()) {
2855 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2857 OS << II.RequiredFeatures[i]->getEnumName();
2863 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2864 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2867 OS << Op.Class->Name;
2875 // A method to determine if a mnemonic is in the list.
2876 OS << "bool " << Target.getName() << ClassName << "::\n"
2877 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
2878 OS << " // Find the appropriate table for this asm variant.\n";
2879 OS << " const MatchEntry *Start, *End;\n";
2880 OS << " switch (VariantID) {\n";
2881 OS << " default: // unreachable\n";
2882 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2883 Record *AsmVariant = Target.getAsmParserVariant(VC);
2884 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2885 OS << " case " << AsmVariantNo << ": Start = MatchTable" << VC
2886 << "; End = array_endof(MatchTable" << VC << "); break;\n";
2889 OS << " // Search the table.\n";
2890 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2891 OS << " std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
2892 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2895 // Finally, build the match function.
2897 << Target.getName() << ClassName << "::\n"
2898 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2900 OS << " MCInst &Inst,\n"
2901 << "unsigned &ErrorInfo, bool matchingInlineAsm, unsigned VariantID) {\n";
2903 OS << " // Eliminate obvious mismatches.\n";
2904 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2905 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2906 OS << " return Match_InvalidOperand;\n";
2909 // Emit code to get the available features.
2910 OS << " // Get the current feature set.\n";
2911 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2913 OS << " // Get the instruction mnemonic, which is the first token.\n";
2914 OS << " StringRef Mnemonic = ((" << Target.getName()
2915 << "Operand*)Operands[0])->getToken();\n\n";
2917 if (HasMnemonicAliases) {
2918 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2919 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
2922 // Emit code to compute the class list for this operand vector.
2923 OS << " // Some state to try to produce better error messages.\n";
2924 OS << " bool HadMatchOtherThanFeatures = false;\n";
2925 OS << " bool HadMatchOtherThanPredicate = false;\n";
2926 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2927 OS << " unsigned MissingFeatures = ~0U;\n";
2928 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2929 OS << " // wrong for all instances of the instruction.\n";
2930 OS << " ErrorInfo = ~0U;\n";
2932 // Emit code to search the table.
2933 OS << " // Find the appropriate table for this asm variant.\n";
2934 OS << " const MatchEntry *Start, *End;\n";
2935 OS << " switch (VariantID) {\n";
2936 OS << " default: // unreachable\n";
2937 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2938 Record *AsmVariant = Target.getAsmParserVariant(VC);
2939 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2940 OS << " case " << AsmVariantNo << ": Start = MatchTable" << VC
2941 << "; End = array_endof(MatchTable" << VC << "); break;\n";
2944 OS << " // Search the table.\n";
2945 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2946 OS << " std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
2948 OS << " // Return a more specific error code if no mnemonics match.\n";
2949 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2950 OS << " return Match_MnemonicFail;\n\n";
2952 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2953 << "*ie = MnemonicRange.second;\n";
2954 OS << " it != ie; ++it) {\n";
2956 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2957 OS << " assert(Mnemonic == it->getMnemonic());\n";
2959 // Emit check that the subclasses match.
2960 OS << " bool OperandsValid = true;\n";
2961 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2962 OS << " if (i + 1 >= Operands.size()) {\n";
2963 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2964 OS << " if (!OperandsValid) ErrorInfo = i + 1;\n";
2967 OS << " unsigned Diag = validateOperandClass(Operands[i+1],\n";
2969 OS << "(MatchClassKind)it->Classes[i]);\n";
2970 OS << " if (Diag == Match_Success)\n";
2971 OS << " continue;\n";
2972 OS << " // If the generic handler indicates an invalid operand\n";
2973 OS << " // failure, check for a special case.\n";
2974 OS << " if (Diag == Match_InvalidOperand) {\n";
2975 OS << " Diag = validateTargetOperandClass(Operands[i+1],\n";
2977 OS << "(MatchClassKind)it->Classes[i]);\n";
2978 OS << " if (Diag == Match_Success)\n";
2979 OS << " continue;\n";
2981 OS << " // If this operand is broken for all of the instances of this\n";
2982 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2983 OS << " // If we already had a match that only failed due to a\n";
2984 OS << " // target predicate, that diagnostic is preferred.\n";
2985 OS << " if (!HadMatchOtherThanPredicate &&\n";
2986 OS << " (it == MnemonicRange.first || ErrorInfo <= i+1)) {\n";
2987 OS << " ErrorInfo = i+1;\n";
2988 OS << " // InvalidOperand is the default. Prefer specificity.\n";
2989 OS << " if (Diag != Match_InvalidOperand)\n";
2990 OS << " RetCode = Diag;\n";
2992 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2993 OS << " OperandsValid = false;\n";
2997 OS << " if (!OperandsValid) continue;\n";
2999 // Emit check that the required features are available.
3000 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3001 << "!= it->RequiredFeatures) {\n";
3002 OS << " HadMatchOtherThanFeatures = true;\n";
3003 OS << " unsigned NewMissingFeatures = it->RequiredFeatures & "
3004 "~AvailableFeatures;\n";
3005 OS << " if (CountPopulation_32(NewMissingFeatures) <=\n"
3006 " CountPopulation_32(MissingFeatures))\n";
3007 OS << " MissingFeatures = NewMissingFeatures;\n";
3008 OS << " continue;\n";
3011 OS << " if (matchingInlineAsm) {\n";
3012 OS << " Inst.setOpcode(it->Opcode);\n";
3013 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3014 OS << " return Match_Success;\n";
3016 OS << " // We have selected a definite instruction, convert the parsed\n"
3017 << " // operands into the appropriate MCInst.\n";
3018 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3021 // Verify the instruction with the target-specific match predicate function.
3022 OS << " // We have a potential match. Check the target predicate to\n"
3023 << " // handle any context sensitive constraints.\n"
3024 << " unsigned MatchResult;\n"
3025 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3026 << " Match_Success) {\n"
3027 << " Inst.clear();\n"
3028 << " RetCode = MatchResult;\n"
3029 << " HadMatchOtherThanPredicate = true;\n"
3033 // Call the post-processing function, if used.
3034 std::string InsnCleanupFn =
3035 AsmParser->getValueAsString("AsmParserInstCleanup");
3036 if (!InsnCleanupFn.empty())
3037 OS << " " << InsnCleanupFn << "(Inst);\n";
3039 if (HasDeprecation) {
3040 OS << " std::string Info;\n";
3041 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, STI, Info)) {\n";
3042 OS << " SMLoc Loc = ((" << Target.getName() << "Operand*)Operands[0])->getStartLoc();\n";
3043 OS << " Parser.Warning(Loc, Info, None);\n";
3047 OS << " return Match_Success;\n";
3050 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3051 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3052 OS << " return RetCode;\n\n";
3053 OS << " // Missing feature matches return which features were missing\n";
3054 OS << " ErrorInfo = MissingFeatures;\n";
3055 OS << " return Match_MissingFeature;\n";
3058 if (Info.OperandMatchInfo.size())
3059 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3062 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3067 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3068 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3069 AsmMatcherEmitter(RK).run(OS);
3072 } // End llvm namespace