1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This tablegen backend emits a target specifier matcher for converting parsed
10 // assembly operands in the MCInst structures. It also emits a matcher for
11 // custom operand parsing.
13 // Converting assembly operands into MCInst structures
14 // ---------------------------------------------------
16 // The input to the target specific matcher is a list of literal tokens and
17 // operands. The target specific parser should generally eliminate any syntax
18 // which is not relevant for matching; for example, comma tokens should have
19 // already been consumed and eliminated by the parser. Most instructions will
20 // end up with a single literal token (the instruction name) and some number of
23 // Some example inputs, for X86:
24 // 'addl' (immediate ...) (register ...)
25 // 'add' (immediate ...) (memory ...)
28 // The assembly matcher is responsible for converting this input into a precise
29 // machine instruction (i.e., an instruction with a well defined encoding). This
30 // mapping has several properties which complicate matching:
32 // - It may be ambiguous; many architectures can legally encode particular
33 // variants of an instruction in different ways (for example, using a smaller
34 // encoding for small immediates). Such ambiguities should never be
35 // arbitrarily resolved by the assembler, the assembler is always responsible
36 // for choosing the "best" available instruction.
38 // - It may depend on the subtarget or the assembler context. Instructions
39 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
40 // an SSE instruction in a file being assembled for i486) should be accepted
41 // and rejected by the assembler front end. However, if the proper encoding
42 // for an instruction is dependent on the assembler context then the matcher
43 // is responsible for selecting the correct machine instruction for the
46 // The core matching algorithm attempts to exploit the regularity in most
47 // instruction sets to quickly determine the set of possibly matching
48 // instructions, and the simplify the generated code. Additionally, this helps
49 // to ensure that the ambiguities are intentionally resolved by the user.
51 // The matching is divided into two distinct phases:
53 // 1. Classification: Each operand is mapped to the unique set which (a)
54 // contains it, and (b) is the largest such subset for which a single
55 // instruction could match all members.
57 // For register classes, we can generate these subgroups automatically. For
58 // arbitrary operands, we expect the user to define the classes and their
59 // relations to one another (for example, 8-bit signed immediates as a
60 // subset of 32-bit immediates).
62 // By partitioning the operands in this way, we guarantee that for any
63 // tuple of classes, any single instruction must match either all or none
64 // of the sets of operands which could classify to that tuple.
66 // In addition, the subset relation amongst classes induces a partial order
67 // on such tuples, which we use to resolve ambiguities.
69 // 2. The input can now be treated as a tuple of classes (static tokens are
70 // simple singleton sets). Each such tuple should generally map to a single
71 // instruction (we currently ignore cases where this isn't true, whee!!!),
72 // which we can emit a simple matcher for.
74 // Custom Operand Parsing
75 // ----------------------
77 // Some targets need a custom way to parse operands, some specific instructions
78 // can contain arguments that can represent processor flags and other kinds of
79 // identifiers that need to be mapped to specific values in the final encoded
80 // instructions. The target specific custom operand parsing works in the
83 // 1. A operand match table is built, each entry contains a mnemonic, an
84 // operand class, a mask for all operand positions for that same
85 // class/mnemonic and target features to be checked while trying to match.
87 // 2. The operand matcher will try every possible entry with the same
88 // mnemonic and will check if the target feature for this mnemonic also
89 // matches. After that, if the operand to be matched has its index
90 // present in the mask, a successful match occurs. Otherwise, fallback
91 // to the regular operand parsing.
93 // 3. For a match success, each operand class that has a 'ParserMethod'
94 // becomes part of a switch from where the custom method is called.
96 //===----------------------------------------------------------------------===//
98 #include "CodeGenInstruction.h"
99 #include "CodeGenTarget.h"
100 #include "SubtargetFeatureInfo.h"
102 #include "llvm/ADT/CachedHashString.h"
103 #include "llvm/ADT/PointerUnion.h"
104 #include "llvm/ADT/STLExtras.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallVector.h"
107 #include "llvm/ADT/StringExtras.h"
108 #include "llvm/Config/llvm-config.h"
109 #include "llvm/Support/CommandLine.h"
110 #include "llvm/Support/Debug.h"
111 #include "llvm/Support/ErrorHandling.h"
112 #include "llvm/TableGen/Error.h"
113 #include "llvm/TableGen/Record.h"
114 #include "llvm/TableGen/StringMatcher.h"
115 #include "llvm/TableGen/StringToOffsetTable.h"
116 #include "llvm/TableGen/TableGenBackend.h"
119 #include <forward_list>
123 using namespace llvm;
125 #define DEBUG_TYPE "asm-matcher-emitter"
127 cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
129 static cl::opt<std::string>
130 MatchPrefix("match-prefix", cl::init(""),
131 cl::desc("Only match instructions with the given prefix"),
132 cl::cat(AsmMatcherEmitterCat));
135 class AsmMatcherInfo;
137 // Register sets are used as keys in some second-order sets TableGen creates
138 // when generating its data structures. This means that the order of two
139 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
140 // can even affect compiler output (at least seen in diagnostics produced when
141 // all matches fail). So we use a type that sorts them consistently.
142 typedef std::set<Record*, LessRecordByID> RegisterSet;
144 class AsmMatcherEmitter {
145 RecordKeeper &Records;
147 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
149 void run(raw_ostream &o);
152 /// ClassInfo - Helper class for storing the information about a particular
153 /// class of operands which can be matched.
156 /// Invalid kind, for use as a sentinel value.
159 /// The class for a particular token.
162 /// The (first) register class, subsequent register classes are
163 /// RegisterClass0+1, and so on.
166 /// The (first) user defined class, subsequent user defined classes are
167 /// UserClass0+1, and so on.
171 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
172 /// N) for the Nth user defined class.
175 /// SuperClasses - The super classes of this class. Note that for simplicities
176 /// sake user operands only record their immediate super class, while register
177 /// operands include all superclasses.
178 std::vector<ClassInfo*> SuperClasses;
180 /// Name - The full class name, suitable for use in an enum.
183 /// ClassName - The unadorned generic name for this class (e.g., Token).
184 std::string ClassName;
186 /// ValueName - The name of the value this class represents; for a token this
187 /// is the literal token string, for an operand it is the TableGen class (or
188 /// empty if this is a derived class).
189 std::string ValueName;
191 /// PredicateMethod - The name of the operand method to test whether the
192 /// operand matches this class; this is not valid for Token or register kinds.
193 std::string PredicateMethod;
195 /// RenderMethod - The name of the operand method to add this operand to an
196 /// MCInst; this is not valid for Token or register kinds.
197 std::string RenderMethod;
199 /// ParserMethod - The name of the operand method to do a target specific
200 /// parsing on the operand.
201 std::string ParserMethod;
203 /// For register classes: the records for all the registers in this class.
204 RegisterSet Registers;
206 /// For custom match classes: the diagnostic kind for when the predicate fails.
207 std::string DiagnosticType;
209 /// For custom match classes: the diagnostic string for when the predicate fails.
210 std::string DiagnosticString;
212 /// Is this operand optional and not always required.
215 /// DefaultMethod - The name of the method that returns the default operand
216 /// for optional operand
217 std::string DefaultMethod;
220 /// isRegisterClass() - Check if this is a register class.
221 bool isRegisterClass() const {
222 return Kind >= RegisterClass0 && Kind < UserClass0;
225 /// isUserClass() - Check if this is a user defined class.
226 bool isUserClass() const {
227 return Kind >= UserClass0;
230 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
231 /// are related if they are in the same class hierarchy.
232 bool isRelatedTo(const ClassInfo &RHS) const {
233 // Tokens are only related to tokens.
234 if (Kind == Token || RHS.Kind == Token)
235 return Kind == Token && RHS.Kind == Token;
237 // Registers classes are only related to registers classes, and only if
238 // their intersection is non-empty.
239 if (isRegisterClass() || RHS.isRegisterClass()) {
240 if (!isRegisterClass() || !RHS.isRegisterClass())
244 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
245 std::set_intersection(Registers.begin(), Registers.end(),
246 RHS.Registers.begin(), RHS.Registers.end(),
247 II, LessRecordByID());
252 // Otherwise we have two users operands; they are related if they are in the
253 // same class hierarchy.
255 // FIXME: This is an oversimplification, they should only be related if they
256 // intersect, however we don't have that information.
257 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
258 const ClassInfo *Root = this;
259 while (!Root->SuperClasses.empty())
260 Root = Root->SuperClasses.front();
262 const ClassInfo *RHSRoot = &RHS;
263 while (!RHSRoot->SuperClasses.empty())
264 RHSRoot = RHSRoot->SuperClasses.front();
266 return Root == RHSRoot;
269 /// isSubsetOf - Test whether this class is a subset of \p RHS.
270 bool isSubsetOf(const ClassInfo &RHS) const {
271 // This is a subset of RHS if it is the same class...
275 // ... or if any of its super classes are a subset of RHS.
276 SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
278 SmallPtrSet<const ClassInfo *, 16> Visited;
279 while (!Worklist.empty()) {
280 auto *CI = Worklist.pop_back_val();
283 for (auto *Super : CI->SuperClasses)
284 if (Visited.insert(Super).second)
285 Worklist.push_back(Super);
291 int getTreeDepth() const {
293 const ClassInfo *Root = this;
294 while (!Root->SuperClasses.empty()) {
296 Root = Root->SuperClasses.front();
301 const ClassInfo *findRoot() const {
302 const ClassInfo *Root = this;
303 while (!Root->SuperClasses.empty())
304 Root = Root->SuperClasses.front();
308 /// Compare two classes. This does not produce a total ordering, but does
309 /// guarantee that subclasses are sorted before their parents, and that the
310 /// ordering is transitive.
311 bool operator<(const ClassInfo &RHS) const {
315 // First, enforce the ordering between the three different types of class.
316 // Tokens sort before registers, which sort before user classes.
318 if (RHS.Kind != Token)
320 assert(RHS.Kind == Token);
321 } else if (isRegisterClass()) {
322 if (RHS.Kind == Token)
324 else if (RHS.isUserClass())
326 assert(RHS.isRegisterClass());
327 } else if (isUserClass()) {
328 if (!RHS.isUserClass())
330 assert(RHS.isUserClass());
332 llvm_unreachable("Unknown ClassInfoKind");
335 if (Kind == Token || isUserClass()) {
336 // Related tokens and user classes get sorted by depth in the inheritence
337 // tree (so that subclasses are before their parents).
338 if (isRelatedTo(RHS)) {
339 if (getTreeDepth() > RHS.getTreeDepth())
341 if (getTreeDepth() < RHS.getTreeDepth())
344 // Unrelated tokens and user classes are ordered by the name of their
345 // root nodes, so that there is a consistent ordering between
346 // unconnected trees.
347 return findRoot()->ValueName < RHS.findRoot()->ValueName;
349 } else if (isRegisterClass()) {
350 // For register sets, sort by number of registers. This guarantees that
351 // a set will always sort before all of it's strict supersets.
352 if (Registers.size() != RHS.Registers.size())
353 return Registers.size() < RHS.Registers.size();
355 llvm_unreachable("Unknown ClassInfoKind");
358 // FIXME: We should be able to just return false here, as we only need a
359 // partial order (we use stable sorts, so this is deterministic) and the
360 // name of a class shouldn't be significant. However, some of the backends
361 // accidentally rely on this behaviour, so it will have to stay like this
362 // until they are fixed.
363 return ValueName < RHS.ValueName;
367 class AsmVariantInfo {
369 StringRef RegisterPrefix;
370 StringRef TokenizingCharacters;
371 StringRef SeparatorCharacters;
372 StringRef BreakCharacters;
377 /// MatchableInfo - Helper class for storing the necessary information for an
378 /// instruction or alias which is capable of being matched.
379 struct MatchableInfo {
381 /// Token - This is the token that the operand came from.
384 /// The unique class instance this operand should match.
387 /// The operand name this is, if anything.
390 /// The operand name this is, before renaming for tied operands.
391 StringRef OrigSrcOpName;
393 /// The suboperand index within SrcOpName, or -1 for the entire operand.
396 /// Whether the token is "isolated", i.e., it is preceded and followed
398 bool IsIsolatedToken;
400 /// Register record if this token is singleton register.
401 Record *SingletonReg;
403 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
404 : Token(T), Class(nullptr), SubOpIdx(-1),
405 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
408 /// ResOperand - This represents a single operand in the result instruction
409 /// generated by the match. In cases (like addressing modes) where a single
410 /// assembler operand expands to multiple MCOperands, this represents the
411 /// single assembler operand, not the MCOperand.
414 /// RenderAsmOperand - This represents an operand result that is
415 /// generated by calling the render method on the assembly operand. The
416 /// corresponding AsmOperand is specified by AsmOperandNum.
419 /// TiedOperand - This represents a result operand that is a duplicate of
420 /// a previous result operand.
423 /// ImmOperand - This represents an immediate value that is dumped into
427 /// RegOperand - This represents a fixed register that is dumped in.
431 /// Tuple containing the index of the (earlier) result operand that should
432 /// be copied from, as well as the indices of the corresponding (parsed)
433 /// operands in the asm string.
434 struct TiedOperandsTuple {
436 unsigned SrcOpnd1Idx;
437 unsigned SrcOpnd2Idx;
441 /// This is the operand # in the AsmOperands list that this should be
443 unsigned AsmOperandNum;
445 /// Description of tied operands.
446 TiedOperandsTuple TiedOperands;
448 /// ImmVal - This is the immediate value added to the instruction.
451 /// Register - This is the register record.
455 /// MINumOperands - The number of MCInst operands populated by this
457 unsigned MINumOperands;
459 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
461 X.Kind = RenderAsmOperand;
462 X.AsmOperandNum = AsmOpNum;
463 X.MINumOperands = NumOperands;
467 static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
468 unsigned SrcOperand2) {
470 X.Kind = TiedOperand;
471 X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
476 static ResOperand getImmOp(int64_t Val) {
484 static ResOperand getRegOp(Record *Reg) {
493 /// AsmVariantID - Target's assembly syntax variant no.
496 /// AsmString - The assembly string for this instruction (with variants
497 /// removed), e.g. "movsx $src, $dst".
498 std::string AsmString;
500 /// TheDef - This is the definition of the instruction or InstAlias that this
501 /// matchable came from.
502 Record *const TheDef;
504 /// DefRec - This is the definition that it came from.
505 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
507 const CodeGenInstruction *getResultInst() const {
508 if (DefRec.is<const CodeGenInstruction*>())
509 return DefRec.get<const CodeGenInstruction*>();
510 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
513 /// ResOperands - This is the operand list that should be built for the result
515 SmallVector<ResOperand, 8> ResOperands;
517 /// Mnemonic - This is the first token of the matched instruction, its
521 /// AsmOperands - The textual operands that this instruction matches,
522 /// annotated with a class and where in the OperandList they were defined.
523 /// This directly corresponds to the tokenized AsmString after the mnemonic is
525 SmallVector<AsmOperand, 8> AsmOperands;
527 /// Predicates - The required subtarget features to match this instruction.
528 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
530 /// ConversionFnKind - The enum value which is passed to the generated
531 /// convertToMCInst to convert parsed operands into an MCInst for this
533 std::string ConversionFnKind;
535 /// If this instruction is deprecated in some form.
538 /// If this is an alias, this is use to determine whether or not to using
539 /// the conversion function defined by the instruction's AsmMatchConverter
540 /// or to use the function generated by the alias.
541 bool UseInstAsmMatchConverter;
543 MatchableInfo(const CodeGenInstruction &CGI)
544 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
545 UseInstAsmMatchConverter(true) {
548 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
549 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
550 DefRec(Alias.release()),
551 UseInstAsmMatchConverter(
552 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
555 // Could remove this and the dtor if PointerUnion supported unique_ptr
556 // elements with a dynamic failure/assertion (like the one below) in the case
557 // where it was copied while being in an owning state.
558 MatchableInfo(const MatchableInfo &RHS)
559 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
560 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
561 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
562 RequiredFeatures(RHS.RequiredFeatures),
563 ConversionFnKind(RHS.ConversionFnKind),
564 HasDeprecation(RHS.HasDeprecation),
565 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
566 assert(!DefRec.is<const CodeGenInstAlias *>());
570 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
573 // Two-operand aliases clone from the main matchable, but mark the second
574 // operand as a tied operand of the first for purposes of the assembler.
575 void formTwoOperandAlias(StringRef Constraint);
577 void initialize(const AsmMatcherInfo &Info,
578 SmallPtrSetImpl<Record*> &SingletonRegisters,
579 AsmVariantInfo const &Variant,
580 bool HasMnemonicFirst);
582 /// validate - Return true if this matchable is a valid thing to match against
583 /// and perform a bunch of validity checking.
584 bool validate(StringRef CommentDelimiter, bool IsAlias) const;
586 /// findAsmOperand - Find the AsmOperand with the specified name and
587 /// suboperand index.
588 int findAsmOperand(StringRef N, int SubOpIdx) const {
589 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
590 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
592 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
595 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
596 /// This does not check the suboperand index.
597 int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
599 llvm::find_if(llvm::drop_begin(AsmOperands, LastIdx + 1),
600 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
601 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
604 int findAsmOperandOriginallyNamed(StringRef N) const {
607 [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
608 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
611 void buildInstructionResultOperands();
612 void buildAliasResultOperands(bool AliasConstraintsAreChecked);
614 /// operator< - Compare two matchables.
615 bool operator<(const MatchableInfo &RHS) const {
616 // The primary comparator is the instruction mnemonic.
617 if (int Cmp = Mnemonic.compare_insensitive(RHS.Mnemonic))
620 if (AsmOperands.size() != RHS.AsmOperands.size())
621 return AsmOperands.size() < RHS.AsmOperands.size();
623 // Compare lexicographically by operand. The matcher validates that other
624 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
625 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
626 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
628 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
632 // Give matches that require more features higher precedence. This is useful
633 // because we cannot define AssemblerPredicates with the negation of
634 // processor features. For example, ARM v6 "nop" may be either a HINT or
635 // MOV. With v6, we want to match HINT. The assembler has no way to
636 // predicate MOV under "NoV6", but HINT will always match first because it
637 // requires V6 while MOV does not.
638 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
639 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
641 // For X86 AVX/AVX512 instructions, we prefer vex encoding because the
642 // vex encoding size is smaller. Since X86InstrSSE.td is included ahead
643 // of X86InstrAVX512.td, the AVX instruction ID is less than AVX512 ID.
644 // We use the ID to sort AVX instruction before AVX512 instruction in
646 if (TheDef->isSubClassOf("Instruction") &&
647 TheDef->getValueAsBit("HasPositionOrder"))
648 return TheDef->getID() < RHS.TheDef->getID();
653 /// couldMatchAmbiguouslyWith - Check whether this matchable could
654 /// ambiguously match the same set of operands as \p RHS (without being a
655 /// strictly superior match).
656 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
657 // The primary comparator is the instruction mnemonic.
658 if (Mnemonic != RHS.Mnemonic)
661 // Different variants can't conflict.
662 if (AsmVariantID != RHS.AsmVariantID)
665 // The number of operands is unambiguous.
666 if (AsmOperands.size() != RHS.AsmOperands.size())
669 // Otherwise, make sure the ordering of the two instructions is unambiguous
670 // by checking that either (a) a token or operand kind discriminates them,
671 // or (b) the ordering among equivalent kinds is consistent.
673 // Tokens and operand kinds are unambiguous (assuming a correct target
675 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
676 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
677 AsmOperands[i].Class->Kind == ClassInfo::Token)
678 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
679 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
682 // Otherwise, this operand could commute if all operands are equivalent, or
683 // there is a pair of operands that compare less than and a pair that
684 // compare greater than.
685 bool HasLT = false, HasGT = false;
686 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
687 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
689 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
693 return HasLT == HasGT;
699 void tokenizeAsmString(AsmMatcherInfo const &Info,
700 AsmVariantInfo const &Variant);
701 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
704 struct OperandMatchEntry {
705 unsigned OperandMask;
706 const MatchableInfo* MI;
709 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
712 X.OperandMask = opMask;
719 class AsmMatcherInfo {
722 RecordKeeper &Records;
724 /// The tablegen AsmParser record.
727 /// Target - The target information.
728 CodeGenTarget &Target;
730 /// The classes which are needed for matching.
731 std::forward_list<ClassInfo> Classes;
733 /// The information on the matchables to match.
734 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
736 /// Info for custom matching operands by user defined methods.
737 std::vector<OperandMatchEntry> OperandMatchInfo;
739 /// Map of Register records to their class information.
740 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
741 RegisterClassesTy RegisterClasses;
743 /// Map of Predicate records to their subtarget information.
744 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
746 /// Map of AsmOperandClass records to their class information.
747 std::map<Record*, ClassInfo*> AsmOperandClasses;
749 /// Map of RegisterClass records to their class information.
750 std::map<Record*, ClassInfo*> RegisterClassClasses;
753 /// Map of token to class information which has already been constructed.
754 std::map<std::string, ClassInfo*> TokenClasses;
757 /// getTokenClass - Lookup or create the class for the given token.
758 ClassInfo *getTokenClass(StringRef Token);
760 /// getOperandClass - Lookup or create the class for the given operand.
761 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
763 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
765 /// buildRegisterClasses - Build the ClassInfo* instances for register
767 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
769 /// buildOperandClasses - Build the ClassInfo* instances for user defined
771 void buildOperandClasses();
773 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
775 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
776 MatchableInfo::AsmOperand &Op);
779 AsmMatcherInfo(Record *AsmParser,
780 CodeGenTarget &Target,
781 RecordKeeper &Records);
783 /// Construct the various tables used during matching.
786 /// buildOperandMatchInfo - Build the necessary information to handle user
787 /// defined operand parsing methods.
788 void buildOperandMatchInfo();
790 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
792 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
793 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
794 const auto &I = SubtargetFeatures.find(Def);
795 return I == SubtargetFeatures.end() ? nullptr : &I->second;
798 RecordKeeper &getRecords() const {
802 bool hasOptionalOperands() const {
803 return any_of(Classes,
804 [](const ClassInfo &Class) { return Class.IsOptional; });
808 } // end anonymous namespace
810 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
811 LLVM_DUMP_METHOD void MatchableInfo::dump() const {
812 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
814 errs() << " variant: " << AsmVariantID << "\n";
816 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
817 const AsmOperand &Op = AsmOperands[i];
818 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
819 errs() << '\"' << Op.Token << "\"\n";
824 static std::pair<StringRef, StringRef>
825 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
826 // Split via the '='.
827 std::pair<StringRef, StringRef> Ops = S.split('=');
828 if (Ops.second == "")
829 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
830 // Trim whitespace and the leading '$' on the operand names.
831 size_t start = Ops.first.find_first_of('$');
832 if (start == std::string::npos)
833 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
834 Ops.first = Ops.first.slice(start + 1, std::string::npos);
835 size_t end = Ops.first.find_last_of(" \t");
836 Ops.first = Ops.first.slice(0, end);
837 // Now the second operand.
838 start = Ops.second.find_first_of('$');
839 if (start == std::string::npos)
840 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
841 Ops.second = Ops.second.slice(start + 1, std::string::npos);
842 end = Ops.second.find_last_of(" \t");
843 Ops.first = Ops.first.slice(0, end);
847 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
848 // Figure out which operands are aliased and mark them as tied.
849 std::pair<StringRef, StringRef> Ops =
850 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
852 // Find the AsmOperands that refer to the operands we're aliasing.
853 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
854 int DstAsmOperand = findAsmOperandNamed(Ops.second);
855 if (SrcAsmOperand == -1)
856 PrintFatalError(TheDef->getLoc(),
857 "unknown source two-operand alias operand '" + Ops.first +
859 if (DstAsmOperand == -1)
860 PrintFatalError(TheDef->getLoc(),
861 "unknown destination two-operand alias operand '" +
864 // Find the ResOperand that refers to the operand we're aliasing away
865 // and update it to refer to the combined operand instead.
866 for (ResOperand &Op : ResOperands) {
867 if (Op.Kind == ResOperand::RenderAsmOperand &&
868 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
869 Op.AsmOperandNum = DstAsmOperand;
873 // Remove the AsmOperand for the alias operand.
874 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
875 // Adjust the ResOperand references to any AsmOperands that followed
876 // the one we just deleted.
877 for (ResOperand &Op : ResOperands) {
880 // Nothing to do for operands that don't reference AsmOperands.
882 case ResOperand::RenderAsmOperand:
883 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
890 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
891 /// if present, from specified token.
893 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
894 const AsmMatcherInfo &Info,
895 StringRef RegisterPrefix) {
896 StringRef Tok = Op.Token;
898 // If this token is not an isolated token, i.e., it isn't separated from
899 // other tokens (e.g. with whitespace), don't interpret it as a register name.
900 if (!Op.IsIsolatedToken)
903 if (RegisterPrefix.empty()) {
904 std::string LoweredTok = Tok.lower();
905 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
906 Op.SingletonReg = Reg->TheDef;
910 if (!Tok.startswith(RegisterPrefix))
913 StringRef RegName = Tok.substr(RegisterPrefix.size());
914 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
915 Op.SingletonReg = Reg->TheDef;
917 // If there is no register prefix (i.e. "%" in "%eax"), then this may
918 // be some random non-register token, just ignore it.
921 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
922 SmallPtrSetImpl<Record*> &SingletonRegisters,
923 AsmVariantInfo const &Variant,
924 bool HasMnemonicFirst) {
925 AsmVariantID = Variant.AsmVariantNo;
927 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
928 Variant.AsmVariantNo);
930 tokenizeAsmString(Info, Variant);
932 // The first token of the instruction is the mnemonic, which must be a
933 // simple string, not a $foo variable or a singleton register.
934 if (AsmOperands.empty())
935 PrintFatalError(TheDef->getLoc(),
936 "Instruction '" + TheDef->getName() + "' has no tokens");
938 assert(!AsmOperands[0].Token.empty());
939 if (HasMnemonicFirst) {
940 Mnemonic = AsmOperands[0].Token;
941 if (Mnemonic[0] == '$')
942 PrintFatalError(TheDef->getLoc(),
943 "Invalid instruction mnemonic '" + Mnemonic + "'!");
945 // Remove the first operand, it is tracked in the mnemonic field.
946 AsmOperands.erase(AsmOperands.begin());
947 } else if (AsmOperands[0].Token[0] != '$')
948 Mnemonic = AsmOperands[0].Token;
950 // Compute the require features.
951 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
952 if (const SubtargetFeatureInfo *Feature =
953 Info.getSubtargetFeature(Predicate))
954 RequiredFeatures.push_back(Feature);
956 // Collect singleton registers, if used.
957 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
958 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
959 if (Record *Reg = Op.SingletonReg)
960 SingletonRegisters.insert(Reg);
963 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
965 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
968 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
971 /// Append an AsmOperand for the given substring of AsmString.
972 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
973 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
976 /// tokenizeAsmString - Tokenize a simplified assembly string.
977 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
978 AsmVariantInfo const &Variant) {
979 StringRef String = AsmString;
982 bool IsIsolatedToken = true;
983 for (size_t i = 0, e = String.size(); i != e; ++i) {
984 char Char = String[i];
985 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
987 addAsmOperand(String.slice(Prev, i), false);
989 IsIsolatedToken = false;
994 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
996 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
998 IsIsolatedToken = false;
1000 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1002 IsIsolatedToken = true;
1005 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
1007 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1011 IsIsolatedToken = true;
1018 addAsmOperand(String.slice(Prev, i), false);
1020 IsIsolatedToken = false;
1023 assert(i != String.size() && "Invalid quoted character");
1024 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1026 IsIsolatedToken = false;
1031 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1033 IsIsolatedToken = false;
1036 // If this isn't "${", start new identifier looking like "$xxx"
1037 if (i + 1 == String.size() || String[i + 1] != '{') {
1042 size_t EndPos = String.find('}', i);
1043 assert(EndPos != StringRef::npos &&
1044 "Missing brace in operand reference!");
1045 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
1048 IsIsolatedToken = false;
1057 if (InTok && Prev != String.size())
1058 addAsmOperand(String.substr(Prev), IsIsolatedToken);
1061 bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
1062 // Reject matchables with no .s string.
1063 if (AsmString.empty())
1064 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
1066 // Reject any matchables with a newline in them, they should be marked
1067 // isCodeGenOnly if they are pseudo instructions.
1068 if (AsmString.find('\n') != std::string::npos)
1069 PrintFatalError(TheDef->getLoc(),
1070 "multiline instruction is not valid for the asmparser, "
1071 "mark it isCodeGenOnly");
1073 // Remove comments from the asm string. We know that the asmstring only
1075 if (!CommentDelimiter.empty() &&
1076 StringRef(AsmString).contains(CommentDelimiter))
1077 PrintFatalError(TheDef->getLoc(),
1078 "asmstring for instruction has comment character in it, "
1079 "mark it isCodeGenOnly");
1081 // Reject matchables with operand modifiers, these aren't something we can
1082 // handle, the target should be refactored to use operands instead of
1085 // Also, check for instructions which reference the operand multiple times,
1086 // if they don't define a custom AsmMatcher: this implies a constraint that
1087 // the built-in matching code would not honor.
1088 std::set<std::string> OperandNames;
1089 for (const AsmOperand &Op : AsmOperands) {
1090 StringRef Tok = Op.Token;
1091 if (Tok[0] == '$' && Tok.contains(':'))
1092 PrintFatalError(TheDef->getLoc(),
1093 "matchable with operand modifier '" + Tok +
1094 "' not supported by asm matcher. Mark isCodeGenOnly!");
1095 // Verify that any operand is only mentioned once.
1096 // We reject aliases and ignore instructions for now.
1097 if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
1098 Tok[0] == '$' && !OperandNames.insert(std::string(Tok)).second) {
1100 errs() << "warning: '" << TheDef->getName() << "': "
1101 << "ignoring instruction with tied operand '"
1111 static std::string getEnumNameForToken(StringRef Str) {
1114 for (char C : Str) {
1116 case '*': Res += "_STAR_"; break;
1117 case '%': Res += "_PCT_"; break;
1118 case ':': Res += "_COLON_"; break;
1119 case '!': Res += "_EXCLAIM_"; break;
1120 case '.': Res += "_DOT_"; break;
1121 case '<': Res += "_LT_"; break;
1122 case '>': Res += "_GT_"; break;
1123 case '-': Res += "_MINUS_"; break;
1124 case '#': Res += "_HASH_"; break;
1129 Res += "_" + utostr((unsigned)C) + "_";
1136 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
1137 ClassInfo *&Entry = TokenClasses[std::string(Token)];
1140 Classes.emplace_front();
1141 Entry = &Classes.front();
1142 Entry->Kind = ClassInfo::Token;
1143 Entry->ClassName = "Token";
1144 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1145 Entry->ValueName = std::string(Token);
1146 Entry->PredicateMethod = "<invalid>";
1147 Entry->RenderMethod = "<invalid>";
1148 Entry->ParserMethod = "";
1149 Entry->DiagnosticType = "";
1150 Entry->IsOptional = false;
1151 Entry->DefaultMethod = "<invalid>";
1158 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1160 Record *Rec = OI.Rec;
1162 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1163 return getOperandClass(Rec, SubOpIdx);
1167 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1168 if (Rec->isSubClassOf("RegisterOperand")) {
1169 // RegisterOperand may have an associated ParserMatchClass. If it does,
1170 // use it, else just fall back to the underlying register class.
1171 const RecordVal *R = Rec->getValue("ParserMatchClass");
1172 if (!R || !R->getValue())
1173 PrintFatalError(Rec->getLoc(),
1174 "Record `" + Rec->getName() +
1175 "' does not have a ParserMatchClass!\n");
1177 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1178 Record *MatchClass = DI->getDef();
1179 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1183 // No custom match class. Just use the register class.
1184 Record *ClassRec = Rec->getValueAsDef("RegClass");
1186 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1187 "' has no associated register class!\n");
1188 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1190 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1193 if (Rec->isSubClassOf("RegisterClass")) {
1194 if (ClassInfo *CI = RegisterClassClasses[Rec])
1196 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1199 if (!Rec->isSubClassOf("Operand"))
1200 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1201 "' does not derive from class Operand!\n");
1202 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1203 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1206 PrintFatalError(Rec->getLoc(), "operand has no match class!");
1209 struct LessRegisterSet {
1210 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1211 // std::set<T> defines its own compariso "operator<", but it
1212 // performs a lexicographical comparison by T's innate comparison
1213 // for some reason. We don't want non-deterministic pointer
1214 // comparisons so use this instead.
1215 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1216 RHS.begin(), RHS.end(),
1221 void AsmMatcherInfo::
1222 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
1223 const auto &Registers = Target.getRegBank().getRegisters();
1224 auto &RegClassList = Target.getRegBank().getRegClasses();
1226 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1228 // The register sets used for matching.
1229 RegisterSetSet RegisterSets;
1231 // Gather the defined sets.
1232 for (const CodeGenRegisterClass &RC : RegClassList)
1233 RegisterSets.insert(
1234 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
1236 // Add any required singleton sets.
1237 for (Record *Rec : SingletonRegisters) {
1238 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1241 // Introduce derived sets where necessary (when a register does not determine
1242 // a unique register set class), and build the mapping of registers to the set
1243 // they should classify to.
1244 std::map<Record*, RegisterSet> RegisterMap;
1245 for (const CodeGenRegister &CGR : Registers) {
1246 // Compute the intersection of all sets containing this register.
1247 RegisterSet ContainingSet;
1249 for (const RegisterSet &RS : RegisterSets) {
1250 if (!RS.count(CGR.TheDef))
1253 if (ContainingSet.empty()) {
1259 std::swap(Tmp, ContainingSet);
1260 std::insert_iterator<RegisterSet> II(ContainingSet,
1261 ContainingSet.begin());
1262 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
1266 if (!ContainingSet.empty()) {
1267 RegisterSets.insert(ContainingSet);
1268 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1272 // Construct the register classes.
1273 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1275 for (const RegisterSet &RS : RegisterSets) {
1276 Classes.emplace_front();
1277 ClassInfo *CI = &Classes.front();
1278 CI->Kind = ClassInfo::RegisterClass0 + Index;
1279 CI->ClassName = "Reg" + utostr(Index);
1280 CI->Name = "MCK_Reg" + utostr(Index);
1282 CI->PredicateMethod = ""; // unused
1283 CI->RenderMethod = "addRegOperands";
1285 // FIXME: diagnostic type.
1286 CI->DiagnosticType = "";
1287 CI->IsOptional = false;
1288 CI->DefaultMethod = ""; // unused
1289 RegisterSetClasses.insert(std::make_pair(RS, CI));
1293 // Find the superclasses; we could compute only the subgroup lattice edges,
1294 // but there isn't really a point.
1295 for (const RegisterSet &RS : RegisterSets) {
1296 ClassInfo *CI = RegisterSetClasses[RS];
1297 for (const RegisterSet &RS2 : RegisterSets)
1299 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
1301 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
1304 // Name the register classes which correspond to a user defined RegisterClass.
1305 for (const CodeGenRegisterClass &RC : RegClassList) {
1306 // Def will be NULL for non-user defined register classes.
1307 Record *Def = RC.getDef();
1310 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1311 RC.getOrder().end())];
1312 if (CI->ValueName.empty()) {
1313 CI->ClassName = RC.getName();
1314 CI->Name = "MCK_" + RC.getName();
1315 CI->ValueName = RC.getName();
1317 CI->ValueName = CI->ValueName + "," + RC.getName();
1319 Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1320 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1321 CI->DiagnosticType = std::string(SI->getValue());
1323 Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1324 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1325 CI->DiagnosticString = std::string(SI->getValue());
1327 // If we have a diagnostic string but the diagnostic type is not specified
1328 // explicitly, create an anonymous diagnostic type.
1329 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1330 CI->DiagnosticType = RC.getName();
1332 RegisterClassClasses.insert(std::make_pair(Def, CI));
1335 // Populate the map for individual registers.
1336 for (auto &It : RegisterMap)
1337 RegisterClasses[It.first] = RegisterSetClasses[It.second];
1339 // Name the register classes which correspond to singleton registers.
1340 for (Record *Rec : SingletonRegisters) {
1341 ClassInfo *CI = RegisterClasses[Rec];
1342 assert(CI && "Missing singleton register class info!");
1344 if (CI->ValueName.empty()) {
1345 CI->ClassName = std::string(Rec->getName());
1346 CI->Name = "MCK_" + Rec->getName().str();
1347 CI->ValueName = std::string(Rec->getName());
1349 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
1353 void AsmMatcherInfo::buildOperandClasses() {
1354 std::vector<Record*> AsmOperands =
1355 Records.getAllDerivedDefinitions("AsmOperandClass");
1357 // Pre-populate AsmOperandClasses map.
1358 for (Record *Rec : AsmOperands) {
1359 Classes.emplace_front();
1360 AsmOperandClasses[Rec] = &Classes.front();
1364 for (Record *Rec : AsmOperands) {
1365 ClassInfo *CI = AsmOperandClasses[Rec];
1366 CI->Kind = ClassInfo::UserClass0 + Index;
1368 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
1369 for (Init *I : Supers->getValues()) {
1370 DefInit *DI = dyn_cast<DefInit>(I);
1372 PrintError(Rec->getLoc(), "Invalid super class reference!");
1376 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1378 PrintError(Rec->getLoc(), "Invalid super class reference!");
1380 CI->SuperClasses.push_back(SC);
1382 CI->ClassName = std::string(Rec->getValueAsString("Name"));
1383 CI->Name = "MCK_" + CI->ClassName;
1384 CI->ValueName = std::string(Rec->getName());
1386 // Get or construct the predicate method name.
1387 Init *PMName = Rec->getValueInit("PredicateMethod");
1388 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1389 CI->PredicateMethod = std::string(SI->getValue());
1391 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1392 CI->PredicateMethod = "is" + CI->ClassName;
1395 // Get or construct the render method name.
1396 Init *RMName = Rec->getValueInit("RenderMethod");
1397 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1398 CI->RenderMethod = std::string(SI->getValue());
1400 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1401 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1404 // Get the parse method name or leave it as empty.
1405 Init *PRMName = Rec->getValueInit("ParserMethod");
1406 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1407 CI->ParserMethod = std::string(SI->getValue());
1409 // Get the diagnostic type and string or leave them as empty.
1410 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
1411 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1412 CI->DiagnosticType = std::string(SI->getValue());
1413 Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1414 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1415 CI->DiagnosticString = std::string(SI->getValue());
1416 // If we have a DiagnosticString, we need a DiagnosticType for use within
1418 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1419 CI->DiagnosticType = CI->ClassName;
1421 Init *IsOptional = Rec->getValueInit("IsOptional");
1422 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1423 CI->IsOptional = BI->getValue();
1425 // Get or construct the default method name.
1426 Init *DMName = Rec->getValueInit("DefaultMethod");
1427 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1428 CI->DefaultMethod = std::string(SI->getValue());
1430 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1431 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1438 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1439 CodeGenTarget &target,
1440 RecordKeeper &records)
1441 : Records(records), AsmParser(asmParser), Target(target) {
1444 /// buildOperandMatchInfo - Build the necessary information to handle user
1445 /// defined operand parsing methods.
1446 void AsmMatcherInfo::buildOperandMatchInfo() {
1448 /// Map containing a mask with all operands indices that can be found for
1449 /// that class inside a instruction.
1450 typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
1451 OpClassMaskTy OpClassMask;
1453 bool CallCustomParserForAllOperands =
1454 AsmParser->getValueAsBit("CallCustomParserForAllOperands");
1455 for (const auto &MI : Matchables) {
1456 OpClassMask.clear();
1458 // Keep track of all operands of this instructions which belong to the
1460 unsigned NumOptionalOps = 0;
1461 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1462 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
1463 if (CallCustomParserForAllOperands || !Op.Class->ParserMethod.empty()) {
1464 unsigned &OperandMask = OpClassMask[Op.Class];
1465 OperandMask |= maskTrailingOnes<unsigned>(NumOptionalOps + 1)
1466 << (i - NumOptionalOps);
1468 if (Op.Class->IsOptional)
1472 // Generate operand match info for each mnemonic/operand class pair.
1473 for (const auto &OCM : OpClassMask) {
1474 unsigned OpMask = OCM.second;
1475 ClassInfo *CI = OCM.first;
1476 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1482 void AsmMatcherInfo::buildInfo() {
1483 // Build information about all of the AssemblerPredicates.
1484 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1485 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1486 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1487 SubtargetFeaturePairs.end());
1489 for (const auto &Pair : SubtargetFeatures)
1490 LLVM_DEBUG(Pair.second.dump());
1493 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1494 bool ReportMultipleNearMisses =
1495 AsmParser->getValueAsBit("ReportMultipleNearMisses");
1497 // Parse the instructions; we need to do this first so that we can gather the
1498 // singleton register classes.
1499 SmallPtrSet<Record*, 16> SingletonRegisters;
1500 unsigned VariantCount = Target.getAsmParserVariantCount();
1501 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1502 Record *AsmVariant = Target.getAsmParserVariant(VC);
1503 StringRef CommentDelimiter =
1504 AsmVariant->getValueAsString("CommentDelimiter");
1505 AsmVariantInfo Variant;
1506 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1507 Variant.TokenizingCharacters =
1508 AsmVariant->getValueAsString("TokenizingCharacters");
1509 Variant.SeparatorCharacters =
1510 AsmVariant->getValueAsString("SeparatorCharacters");
1511 Variant.BreakCharacters =
1512 AsmVariant->getValueAsString("BreakCharacters");
1513 Variant.Name = AsmVariant->getValueAsString("Name");
1514 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1516 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
1518 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1519 // filter the set of instructions we consider.
1520 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
1523 // Ignore "codegen only" instructions.
1524 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
1527 // Ignore instructions for different instructions
1528 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
1529 if (!V.empty() && V != Variant.Name)
1532 auto II = std::make_unique<MatchableInfo>(*CGI);
1534 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1536 // Ignore instructions which shouldn't be matched and diagnose invalid
1537 // instruction definitions with an error.
1538 if (!II->validate(CommentDelimiter, false))
1541 Matchables.push_back(std::move(II));
1544 // Parse all of the InstAlias definitions and stick them in the list of
1546 std::vector<Record*> AllInstAliases =
1547 Records.getAllDerivedDefinitions("InstAlias");
1548 for (Record *InstAlias : AllInstAliases) {
1549 auto Alias = std::make_unique<CodeGenInstAlias>(InstAlias, Target);
1551 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1552 // filter the set of instruction aliases we consider, based on the target
1554 if (!StringRef(Alias->ResultInst->TheDef->getName())
1555 .startswith( MatchPrefix))
1558 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
1559 if (!V.empty() && V != Variant.Name)
1562 auto II = std::make_unique<MatchableInfo>(std::move(Alias));
1564 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1566 // Validate the alias definitions.
1567 II->validate(CommentDelimiter, true);
1569 Matchables.push_back(std::move(II));
1573 // Build info for the register classes.
1574 buildRegisterClasses(SingletonRegisters);
1576 // Build info for the user defined assembly operand classes.
1577 buildOperandClasses();
1579 // Build the information about matchables, now that we have fully formed
1581 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
1582 for (auto &II : Matchables) {
1583 // Parse the tokens after the mnemonic.
1584 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1585 // don't precompute the loop bound.
1586 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1587 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1588 StringRef Token = Op.Token;
1590 // Check for singleton registers.
1591 if (Record *RegRecord = Op.SingletonReg) {
1592 Op.Class = RegisterClasses[RegRecord];
1593 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1594 "Unexpected class for singleton register");
1598 // Check for simple tokens.
1599 if (Token[0] != '$') {
1600 Op.Class = getTokenClass(Token);
1604 if (Token.size() > 1 && isdigit(Token[1])) {
1605 Op.Class = getTokenClass(Token);
1609 // Otherwise this is an operand reference.
1610 StringRef OperandName;
1611 if (Token[1] == '{')
1612 OperandName = Token.substr(2, Token.size() - 3);
1614 OperandName = Token.substr(1);
1616 if (II->DefRec.is<const CodeGenInstruction*>())
1617 buildInstructionOperandReference(II.get(), OperandName, i);
1619 buildAliasOperandReference(II.get(), OperandName, Op);
1622 if (II->DefRec.is<const CodeGenInstruction*>()) {
1623 II->buildInstructionResultOperands();
1624 // If the instruction has a two-operand alias, build up the
1625 // matchable here. We'll add them in bulk at the end to avoid
1626 // confusing this loop.
1627 StringRef Constraint =
1628 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1629 if (Constraint != "") {
1630 // Start by making a copy of the original matchable.
1631 auto AliasII = std::make_unique<MatchableInfo>(*II);
1633 // Adjust it to be a two-operand alias.
1634 AliasII->formTwoOperandAlias(Constraint);
1636 // Add the alias to the matchables list.
1637 NewMatchables.push_back(std::move(AliasII));
1640 // FIXME: The tied operands checking is not yet integrated with the
1641 // framework for reporting multiple near misses. To prevent invalid
1642 // formats from being matched with an alias if a tied-operands check
1643 // would otherwise have disallowed it, we just disallow such constructs
1644 // in TableGen completely.
1645 II->buildAliasResultOperands(!ReportMultipleNearMisses);
1647 if (!NewMatchables.empty())
1648 Matchables.insert(Matchables.end(),
1649 std::make_move_iterator(NewMatchables.begin()),
1650 std::make_move_iterator(NewMatchables.end()));
1652 // Process token alias definitions and set up the associated superclass
1654 std::vector<Record*> AllTokenAliases =
1655 Records.getAllDerivedDefinitions("TokenAlias");
1656 for (Record *Rec : AllTokenAliases) {
1657 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1658 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1659 if (FromClass == ToClass)
1660 PrintFatalError(Rec->getLoc(),
1661 "error: Destination value identical to source value.");
1662 FromClass->SuperClasses.push_back(ToClass);
1665 // Reorder classes so that classes precede super classes.
1668 #ifdef EXPENSIVE_CHECKS
1669 // Verify that the table is sorted and operator < works transitively.
1670 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1671 for (auto J = I; J != E; ++J) {
1673 assert(I == J || !J->isSubsetOf(*I));
1679 /// buildInstructionOperandReference - The specified operand is a reference to a
1680 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1681 void AsmMatcherInfo::
1682 buildInstructionOperandReference(MatchableInfo *II,
1683 StringRef OperandName,
1684 unsigned AsmOpIdx) {
1685 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1686 const CGIOperandList &Operands = CGI.Operands;
1687 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1689 // Map this token to an operand.
1691 if (!Operands.hasOperandNamed(OperandName, Idx))
1692 PrintFatalError(II->TheDef->getLoc(),
1693 "error: unable to find operand: '" + OperandName + "'");
1695 // If the instruction operand has multiple suboperands, but the parser
1696 // match class for the asm operand is still the default "ImmAsmOperand",
1697 // then handle each suboperand separately.
1698 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1699 Record *Rec = Operands[Idx].Rec;
1700 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1701 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1702 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1703 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1704 StringRef Token = Op->Token; // save this in case Op gets moved
1705 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1706 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
1707 NewAsmOp.SubOpIdx = SI;
1708 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1710 // Replace Op with first suboperand.
1711 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1716 // Set up the operand class.
1717 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1718 Op->OrigSrcOpName = OperandName;
1720 // If the named operand is tied, canonicalize it to the untied operand.
1721 // For example, something like:
1722 // (outs GPR:$dst), (ins GPR:$src)
1723 // with an asmstring of
1725 // we want to canonicalize to:
1727 // so that we know how to provide the $dst operand when filling in the result.
1729 if (Operands[Idx].MINumOperands == 1)
1730 OITied = Operands[Idx].getTiedRegister();
1732 // The tied operand index is an MIOperand index, find the operand that
1734 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1735 OperandName = Operands[Idx.first].Name;
1736 Op->SubOpIdx = Idx.second;
1739 Op->SrcOpName = OperandName;
1742 /// buildAliasOperandReference - When parsing an operand reference out of the
1743 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1744 /// operand reference is by looking it up in the result pattern definition.
1745 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1746 StringRef OperandName,
1747 MatchableInfo::AsmOperand &Op) {
1748 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1750 // Set up the operand class.
1751 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1752 if (CGA.ResultOperands[i].isRecord() &&
1753 CGA.ResultOperands[i].getName() == OperandName) {
1754 // It's safe to go with the first one we find, because CodeGenInstAlias
1755 // validates that all operands with the same name have the same record.
1756 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1757 // Use the match class from the Alias definition, not the
1758 // destination instruction, as we may have an immediate that's
1759 // being munged by the match class.
1760 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1762 Op.SrcOpName = OperandName;
1763 Op.OrigSrcOpName = OperandName;
1767 PrintFatalError(II->TheDef->getLoc(),
1768 "error: unable to find operand: '" + OperandName + "'");
1771 void MatchableInfo::buildInstructionResultOperands() {
1772 const CodeGenInstruction *ResultInst = getResultInst();
1774 // Loop over all operands of the result instruction, determining how to
1776 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
1777 // If this is a tied operand, just copy from the previously handled operand.
1779 if (OpInfo.MINumOperands == 1)
1780 TiedOp = OpInfo.getTiedRegister();
1782 int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1783 if (TiedSrcOperand != -1 &&
1784 ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1785 ResOperands.push_back(ResOperand::getTiedOp(
1786 TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1788 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
1792 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1793 if (OpInfo.Name.empty() || SrcOperand == -1) {
1794 // This may happen for operands that are tied to a suboperand of a
1795 // complex operand. Simply use a dummy value here; nobody should
1796 // use this operand slot.
1797 // FIXME: The long term goal is for the MCOperand list to not contain
1798 // tied operands at all.
1799 ResOperands.push_back(ResOperand::getImmOp(0));
1803 // Check if the one AsmOperand populates the entire operand.
1804 unsigned NumOperands = OpInfo.MINumOperands;
1805 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1806 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1810 // Add a separate ResOperand for each suboperand.
1811 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1812 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1813 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1814 "unexpected AsmOperands for suboperands");
1815 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1820 void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
1821 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1822 const CodeGenInstruction *ResultInst = getResultInst();
1824 // Map of: $reg -> #lastref
1825 // where $reg is the name of the operand in the asm string
1826 // where #lastref is the last processed index where $reg was referenced in
1828 SmallDenseMap<StringRef, int> OperandRefs;
1830 // Loop over all operands of the result instruction, determining how to
1832 unsigned AliasOpNo = 0;
1833 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1834 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1835 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1837 // If this is a tied operand, just copy from the previously handled operand.
1839 if (OpInfo->MINumOperands == 1)
1840 TiedOp = OpInfo->getTiedRegister();
1842 unsigned SrcOp1 = 0;
1843 unsigned SrcOp2 = 0;
1845 // If an operand has been specified twice in the asm string,
1846 // add the two source operand's indices to the TiedOp so that
1847 // at runtime the 'tied' constraint is checked.
1848 if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1849 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1851 // Find the next operand (similarly named operand) in the string.
1852 StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1853 auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1854 SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1856 // Not updating the record in OperandRefs will cause TableGen
1857 // to fail with an error at the end of this function.
1858 if (AliasConstraintsAreChecked)
1859 Insert.first->second = SrcOp2;
1861 // In case it only has one reference in the asm string,
1862 // it doesn't need to be checked for tied constraints.
1863 SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1866 // If the alias operand is of a different operand class, we only want
1867 // to benefit from the tied-operands check and just match the operand
1868 // as a normal, but not copy the original (TiedOp) to the result
1869 // instruction. We do this by passing -1 as the tied operand to copy.
1870 if (ResultInst->Operands[i].Rec->getName() !=
1871 ResultInst->Operands[TiedOp].Rec->getName()) {
1872 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1873 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1874 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1875 SrcOp2 = findAsmOperand(Name, SubIdx);
1876 ResOperands.push_back(
1877 ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1879 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1884 // Handle all the suboperands for this operand.
1885 const std::string &OpName = OpInfo->Name;
1886 for ( ; AliasOpNo < LastOpNo &&
1887 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1888 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1890 // Find out what operand from the asmparser that this MCInst operand
1892 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1893 case CodeGenInstAlias::ResultOperand::K_Record: {
1894 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1895 int SrcOperand = findAsmOperand(Name, SubIdx);
1896 if (SrcOperand == -1)
1897 PrintFatalError(TheDef->getLoc(), "Instruction '" +
1898 TheDef->getName() + "' has operand '" + OpName +
1899 "' that doesn't appear in asm string!");
1901 // Add it to the operand references. If it is added a second time, the
1902 // record won't be updated and it will fail later on.
1903 OperandRefs.try_emplace(Name, SrcOperand);
1905 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1906 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1910 case CodeGenInstAlias::ResultOperand::K_Imm: {
1911 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1912 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1915 case CodeGenInstAlias::ResultOperand::K_Reg: {
1916 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1917 ResOperands.push_back(ResOperand::getRegOp(Reg));
1924 // Check that operands are not repeated more times than is supported.
1925 for (auto &T : OperandRefs) {
1926 if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1927 PrintFatalError(TheDef->getLoc(),
1928 "Operand '" + T.first + "' can never be matched");
1933 getConverterOperandID(const std::string &Name,
1934 SmallSetVector<CachedHashString, 16> &Table,
1936 IsNew = Table.insert(CachedHashString(Name));
1938 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
1940 assert(ID < Table.size());
1946 emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1947 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1948 bool HasMnemonicFirst, bool HasOptionalOperands,
1950 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1951 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
1952 std::vector<std::vector<uint8_t> > ConversionTable;
1953 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1955 // TargetOperandClass - This is the target's operand class, like X86Operand.
1956 std::string TargetOperandClass = Target.getName().str() + "Operand";
1958 // Write the convert function to a separate stream, so we can drop it after
1959 // the enum. We'll build up the conversion handlers for the individual
1960 // operand types opportunistically as we encounter them.
1961 std::string ConvertFnBody;
1962 raw_string_ostream CvtOS(ConvertFnBody);
1963 // Start the unified conversion function.
1964 if (HasOptionalOperands) {
1965 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1966 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1967 << "unsigned Opcode,\n"
1968 << " const OperandVector &Operands,\n"
1969 << " const SmallBitVector &OptionalOperandsMask) {\n";
1971 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1972 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1973 << "unsigned Opcode,\n"
1974 << " const OperandVector &Operands) {\n";
1976 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1977 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1978 if (HasOptionalOperands) {
1979 size_t MaxNumOperands = 0;
1980 for (const auto &MI : Infos) {
1981 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1983 CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1985 CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1987 CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1989 CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
1990 CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1993 CvtOS << " unsigned OpIdx;\n";
1994 CvtOS << " Inst.setOpcode(Opcode);\n";
1995 CvtOS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
1996 if (HasOptionalOperands) {
1997 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
1999 CvtOS << " OpIdx = *(p + 1);\n";
2001 CvtOS << " switch (*p) {\n";
2002 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
2003 CvtOS << " case CVT_Reg:\n";
2004 CvtOS << " static_cast<" << TargetOperandClass
2005 << " &>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
2006 CvtOS << " break;\n";
2007 CvtOS << " case CVT_Tied: {\n";
2008 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
2009 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
2010 CvtOS << " \"Tied operand not found\");\n";
2011 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
2012 CvtOS << " if (TiedResOpnd != (uint8_t)-1)\n";
2013 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
2014 CvtOS << " break;\n";
2017 std::string OperandFnBody;
2018 raw_string_ostream OpOS(OperandFnBody);
2019 // Start the operand number lookup function.
2020 OpOS << "void " << Target.getName() << ClassName << "::\n"
2021 << "convertToMapAndConstraints(unsigned Kind,\n";
2023 OpOS << "const OperandVector &Operands) {\n"
2024 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
2025 << " unsigned NumMCOperands = 0;\n"
2026 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2027 << " for (const uint8_t *p = Converter; *p; p += 2) {\n"
2028 << " switch (*p) {\n"
2029 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2030 << " case CVT_Reg:\n"
2031 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2032 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
2033 << " ++NumMCOperands;\n"
2035 << " case CVT_Tied:\n"
2036 << " ++NumMCOperands;\n"
2039 // Pre-populate the operand conversion kinds with the standard always
2040 // available entries.
2041 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2042 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2043 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
2044 enum { CVT_Done, CVT_Reg, CVT_Tied };
2046 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2047 std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
2048 TiedOperandsEnumMap;
2050 for (auto &II : Infos) {
2051 // Check if we have a custom match function.
2052 StringRef AsmMatchConverter =
2053 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
2054 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
2055 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
2056 II->ConversionFnKind = Signature;
2058 // Check if we have already generated this signature.
2059 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2062 // Remember this converter for the kind enum.
2063 unsigned KindID = OperandConversionKinds.size();
2064 OperandConversionKinds.insert(
2065 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
2067 // Add the converter row for this instruction.
2068 ConversionTable.emplace_back();
2069 ConversionTable.back().push_back(KindID);
2070 ConversionTable.back().push_back(CVT_Done);
2072 // Add the handler to the conversion driver function.
2073 CvtOS << " case CVT_"
2074 << getEnumNameForToken(AsmMatchConverter) << ":\n"
2075 << " " << AsmMatchConverter << "(Inst, Operands);\n"
2078 // FIXME: Handle the operand number lookup for custom match functions.
2082 // Build the conversion function signature.
2083 std::string Signature = "Convert";
2085 std::vector<uint8_t> ConversionRow;
2087 // Compute the convert enum and the case body.
2088 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
2090 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2091 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
2093 // Generate code to populate each result operand.
2094 switch (OpInfo.Kind) {
2095 case MatchableInfo::ResOperand::RenderAsmOperand: {
2096 // This comes from something we parsed.
2097 const MatchableInfo::AsmOperand &Op =
2098 II->AsmOperands[OpInfo.AsmOperandNum];
2100 // Registers are always converted the same, don't duplicate the
2101 // conversion function based on them.
2104 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2106 Signature += utostr(OpInfo.MINumOperands);
2107 Signature += "_" + itostr(OpInfo.AsmOperandNum);
2109 // Add the conversion kind, if necessary, and get the associated ID
2110 // the index of its entry in the vector).
2111 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
2112 Op.Class->RenderMethod);
2113 if (Op.Class->IsOptional) {
2114 // For optional operands we must also care about DefaultMethod
2115 assert(HasOptionalOperands);
2116 Name += "_" + Op.Class->DefaultMethod;
2118 Name = getEnumNameForToken(Name);
2120 bool IsNewConverter = false;
2121 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2124 // Add the operand entry to the instruction kind conversion row.
2125 ConversionRow.push_back(ID);
2126 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
2128 if (!IsNewConverter)
2131 // This is a new operand kind. Add a handler for it to the
2132 // converter driver.
2133 CvtOS << " case " << Name << ":\n";
2134 if (Op.Class->IsOptional) {
2135 // If optional operand is not present in actual instruction then we
2136 // should call its DefaultMethod before RenderMethod
2137 assert(HasOptionalOperands);
2138 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2139 << " " << Op.Class->DefaultMethod << "()"
2140 << "->" << Op.Class->RenderMethod << "(Inst, "
2141 << OpInfo.MINumOperands << ");\n"
2143 << " static_cast<" << TargetOperandClass
2144 << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2145 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2148 CvtOS << " static_cast<" << TargetOperandClass
2149 << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2150 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2152 CvtOS << " break;\n";
2154 // Add a handler for the operand number lookup.
2155 OpOS << " case " << Name << ":\n"
2156 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2158 if (Op.Class->isRegisterClass())
2159 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2161 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2162 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
2166 case MatchableInfo::ResOperand::TiedOperand: {
2167 // If this operand is tied to a previous one, just copy the MCInst
2168 // operand from the earlier one.We can only tie single MCOperand values.
2169 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
2170 uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
2172 OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2174 OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
2175 assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
2176 "Tied operand precedes its target!");
2177 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2178 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2179 Signature += "__" + TiedTupleName;
2180 ConversionRow.push_back(CVT_Tied);
2181 ConversionRow.push_back(TiedOp);
2182 ConversionRow.push_back(SrcOp1);
2183 ConversionRow.push_back(SrcOp2);
2185 // Also create an 'enum' for this combination of tied operands.
2186 auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
2187 TiedOperandsEnumMap.emplace(Key, TiedTupleName);
2190 case MatchableInfo::ResOperand::ImmOperand: {
2191 int64_t Val = OpInfo.ImmVal;
2192 std::string Ty = "imm_" + itostr(Val);
2193 Ty = getEnumNameForToken(Ty);
2194 Signature += "__" + Ty;
2196 std::string Name = "CVT_" + Ty;
2197 bool IsNewConverter = false;
2198 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2200 // Add the operand entry to the instruction kind conversion row.
2201 ConversionRow.push_back(ID);
2202 ConversionRow.push_back(0);
2204 if (!IsNewConverter)
2207 CvtOS << " case " << Name << ":\n"
2208 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
2211 OpOS << " case " << Name << ":\n"
2212 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2213 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
2214 << " ++NumMCOperands;\n"
2218 case MatchableInfo::ResOperand::RegOperand: {
2219 std::string Reg, Name;
2220 if (!OpInfo.Register) {
2224 Reg = getQualifiedName(OpInfo.Register);
2225 Name = "reg" + OpInfo.Register->getName().str();
2227 Signature += "__" + Name;
2228 Name = "CVT_" + Name;
2229 bool IsNewConverter = false;
2230 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2232 // Add the operand entry to the instruction kind conversion row.
2233 ConversionRow.push_back(ID);
2234 ConversionRow.push_back(0);
2236 if (!IsNewConverter)
2238 CvtOS << " case " << Name << ":\n"
2239 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
2242 OpOS << " case " << Name << ":\n"
2243 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2244 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
2245 << " ++NumMCOperands;\n"
2251 // If there were no operands, add to the signature to that effect
2252 if (Signature == "Convert")
2253 Signature += "_NoOperands";
2255 II->ConversionFnKind = Signature;
2257 // Save the signature. If we already have it, don't add a new row
2259 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2262 // Add the row to the table.
2263 ConversionTable.push_back(std::move(ConversionRow));
2266 // Finish up the converter driver function.
2267 CvtOS << " }\n }\n}\n\n";
2269 // Finish up the operand number lookup function.
2270 OpOS << " }\n }\n}\n\n";
2272 // Output a static table for tied operands.
2273 if (TiedOperandsEnumMap.size()) {
2274 // The number of tied operand combinations will be small in practice,
2275 // but just add the assert to be sure.
2276 assert(TiedOperandsEnumMap.size() <= 254 &&
2277 "Too many tied-operand combinations to reference with "
2278 "an 8bit offset from the conversion table, where index "
2279 "'255' is reserved as operand not to be copied.");
2282 for (auto &KV : TiedOperandsEnumMap) {
2283 OS << " " << KV.second << ",\n";
2287 OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
2288 for (auto &KV : TiedOperandsEnumMap) {
2289 OS << " /* " << KV.second << " */ { "
2290 << utostr(std::get<0>(KV.first)) << ", "
2291 << utostr(std::get<1>(KV.first)) << ", "
2292 << utostr(std::get<2>(KV.first)) << " },\n";
2296 OS << "static const uint8_t TiedAsmOperandTable[][3] = "
2297 "{ /* empty */ {0, 0, 0} };\n\n";
2299 OS << "namespace {\n";
2301 // Output the operand conversion kind enum.
2302 OS << "enum OperatorConversionKind {\n";
2303 for (const auto &Converter : OperandConversionKinds)
2304 OS << " " << Converter << ",\n";
2305 OS << " CVT_NUM_CONVERTERS\n";
2308 // Output the instruction conversion kind enum.
2309 OS << "enum InstructionConversionKind {\n";
2310 for (const auto &Signature : InstructionConversionKinds)
2311 OS << " " << Signature << ",\n";
2312 OS << " CVT_NUM_SIGNATURES\n";
2315 OS << "} // end anonymous namespace\n\n";
2317 // Output the conversion table.
2318 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2319 << MaxRowLength << "] = {\n";
2321 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2322 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2323 OS << " // " << InstructionConversionKinds[Row] << "\n";
2325 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2326 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2327 if (OperandConversionKinds[ConversionTable[Row][i]] !=
2328 CachedHashString("CVT_Tied")) {
2329 OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2333 // For a tied operand, emit a reference to the TiedAsmOperandTable
2334 // that contains the operand to copy, and the parsed operands to
2335 // check for their tied constraints.
2336 auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
2337 (uint8_t)ConversionTable[Row][i + 2],
2338 (uint8_t)ConversionTable[Row][i + 3]);
2339 auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2340 assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2341 "No record for tied operand pair");
2342 OS << TiedOpndEnum->second << ", ";
2345 OS << "CVT_Done },\n";
2350 // Spit out the conversion driver function.
2353 // Spit out the operand number lookup function.
2356 return ConversionTable.size();
2359 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2360 static void emitMatchClassEnumeration(CodeGenTarget &Target,
2361 std::forward_list<ClassInfo> &Infos,
2363 OS << "namespace {\n\n";
2365 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2366 << "/// instruction matching.\n";
2367 OS << "enum MatchClassKind {\n";
2368 OS << " InvalidMatchClass = 0,\n";
2369 OS << " OptionalMatchClass = 1,\n";
2370 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2371 StringRef LastName = "OptionalMatchClass";
2372 for (const auto &CI : Infos) {
2373 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2374 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2375 } else if (LastKind < ClassInfo::UserClass0 &&
2376 CI.Kind >= ClassInfo::UserClass0) {
2377 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2379 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2382 OS << " " << CI.Name << ", // ";
2383 if (CI.Kind == ClassInfo::Token) {
2384 OS << "'" << CI.ValueName << "'\n";
2385 } else if (CI.isRegisterClass()) {
2386 if (!CI.ValueName.empty())
2387 OS << "register class '" << CI.ValueName << "'\n";
2389 OS << "derived register class\n";
2391 OS << "user defined class '" << CI.ValueName << "'\n";
2394 OS << " NumMatchClassKinds\n";
2397 OS << "} // end anonymous namespace\n\n";
2400 /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2401 /// used when an assembly operand does not match the expected operand class.
2402 static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2403 // If the target does not use DiagnosticString for any operands, don't emit
2404 // an unused function.
2405 if (llvm::all_of(Info.Classes, [](const ClassInfo &CI) {
2406 return CI.DiagnosticString.empty();
2410 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2411 << "AsmParser::" << Info.Target.getName()
2412 << "MatchResultTy MatchResult) {\n";
2413 OS << " switch (MatchResult) {\n";
2415 for (const auto &CI: Info.Classes) {
2416 if (!CI.DiagnosticString.empty()) {
2417 assert(!CI.DiagnosticType.empty() &&
2418 "DiagnosticString set without DiagnosticType");
2419 OS << " case " << Info.Target.getName()
2420 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2421 OS << " return \"" << CI.DiagnosticString << "\";\n";
2425 OS << " default:\n";
2426 OS << " return nullptr;\n";
2432 static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2433 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2434 "RegisterClass) {\n";
2435 if (none_of(Info.Classes, [](const ClassInfo &CI) {
2436 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2438 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2440 OS << " switch (RegisterClass) {\n";
2441 for (const auto &CI: Info.Classes) {
2442 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2443 OS << " case " << CI.Name << ":\n";
2444 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2445 << CI.DiagnosticType << ";\n";
2449 OS << " default:\n";
2450 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2457 /// emitValidateOperandClass - Emit the function to validate an operand class.
2458 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2460 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2461 << "MatchClassKind Kind) {\n";
2462 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2463 << Info.Target.getName() << "Operand &)GOp;\n";
2465 // The InvalidMatchClass is not to match any operand.
2466 OS << " if (Kind == InvalidMatchClass)\n";
2467 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2469 // Check for Token operands first.
2470 // FIXME: Use a more specific diagnostic type.
2471 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
2472 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2473 << " MCTargetAsmParser::Match_Success :\n"
2474 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2476 // Check the user classes. We don't care what order since we're only
2477 // actually matching against one of them.
2478 OS << " switch (Kind) {\n"
2479 " default: break;\n";
2480 for (const auto &CI : Info.Classes) {
2481 if (!CI.isUserClass())
2484 OS << " // '" << CI.ClassName << "' class\n";
2485 OS << " case " << CI.Name << ": {\n";
2486 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2488 OS << " if (DP.isMatch())\n";
2489 OS << " return MCTargetAsmParser::Match_Success;\n";
2490 if (!CI.DiagnosticType.empty()) {
2491 OS << " if (DP.isNearMatch())\n";
2492 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2493 << CI.DiagnosticType << ";\n";
2500 OS << " } // end switch (Kind)\n\n";
2502 // Check for register operands, including sub-classes.
2503 OS << " if (Operand.isReg()) {\n";
2504 OS << " MatchClassKind OpKind;\n";
2505 OS << " switch (Operand.getReg()) {\n";
2506 OS << " default: OpKind = InvalidMatchClass; break;\n";
2507 for (const auto &RC : Info.RegisterClasses)
2508 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
2509 << RC.first->getName() << ": OpKind = " << RC.second->Name
2512 OS << " return isSubclass(OpKind, Kind) ? "
2513 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2514 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2516 // Expected operand is a register, but actual is not.
2517 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2518 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
2520 // Generic fallthrough match failure case for operands that don't have
2521 // specialized diagnostic types.
2522 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2526 /// emitIsSubclass - Emit the subclass predicate function.
2527 static void emitIsSubclass(CodeGenTarget &Target,
2528 std::forward_list<ClassInfo> &Infos,
2530 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2531 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2532 OS << " if (A == B)\n";
2533 OS << " return true;\n\n";
2535 bool EmittedSwitch = false;
2536 for (const auto &A : Infos) {
2537 std::vector<StringRef> SuperClasses;
2539 SuperClasses.push_back("OptionalMatchClass");
2540 for (const auto &B : Infos) {
2541 if (&A != &B && A.isSubsetOf(B))
2542 SuperClasses.push_back(B.Name);
2545 if (SuperClasses.empty())
2548 // If this is the first SuperClass, emit the switch header.
2549 if (!EmittedSwitch) {
2550 OS << " switch (A) {\n";
2551 OS << " default:\n";
2552 OS << " return false;\n";
2553 EmittedSwitch = true;
2556 OS << "\n case " << A.Name << ":\n";
2558 if (SuperClasses.size() == 1) {
2559 OS << " return B == " << SuperClasses.back() << ";\n";
2563 if (!SuperClasses.empty()) {
2564 OS << " switch (B) {\n";
2565 OS << " default: return false;\n";
2566 for (StringRef SC : SuperClasses)
2567 OS << " case " << SC << ": return true;\n";
2570 // No case statement to emit
2571 OS << " return false;\n";
2575 // If there were case statements emitted into the string stream write the
2580 OS << " return false;\n";
2585 /// emitMatchTokenString - Emit the function to match a token string to the
2586 /// appropriate match class value.
2587 static void emitMatchTokenString(CodeGenTarget &Target,
2588 std::forward_list<ClassInfo> &Infos,
2590 // Construct the match list.
2591 std::vector<StringMatcher::StringPair> Matches;
2592 for (const auto &CI : Infos) {
2593 if (CI.Kind == ClassInfo::Token)
2594 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
2597 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2599 StringMatcher("Name", Matches, OS).Emit();
2601 OS << " return InvalidMatchClass;\n";
2605 /// emitMatchRegisterName - Emit the function to match a string to the target
2606 /// specific register enum.
2607 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2609 // Construct the match list.
2610 std::vector<StringMatcher::StringPair> Matches;
2611 const auto &Regs = Target.getRegBank().getRegisters();
2612 for (const CodeGenRegister &Reg : Regs) {
2613 if (Reg.TheDef->getValueAsString("AsmName").empty())
2616 Matches.emplace_back(std::string(Reg.TheDef->getValueAsString("AsmName")),
2617 "return " + utostr(Reg.EnumValue) + ";");
2620 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2622 bool IgnoreDuplicates =
2623 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2624 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2626 OS << " return 0;\n";
2630 /// Emit the function to match a string to the target
2631 /// specific register enum.
2632 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2634 // Construct the match list.
2635 std::vector<StringMatcher::StringPair> Matches;
2636 const auto &Regs = Target.getRegBank().getRegisters();
2637 for (const CodeGenRegister &Reg : Regs) {
2639 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2641 for (auto AltName : AltNames) {
2642 AltName = StringRef(AltName).trim();
2644 // don't handle empty alternative names
2645 if (AltName.empty())
2648 Matches.emplace_back(std::string(AltName),
2649 "return " + utostr(Reg.EnumValue) + ";");
2653 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2655 bool IgnoreDuplicates =
2656 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2657 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2659 OS << " return 0;\n";
2663 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2664 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2665 // Get the set of diagnostic types from all of the operand classes.
2666 std::set<StringRef> Types;
2667 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2668 if (!OpClassEntry.second->DiagnosticType.empty())
2669 Types.insert(OpClassEntry.second->DiagnosticType);
2671 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2672 if (!OpClassEntry.second->DiagnosticType.empty())
2673 Types.insert(OpClassEntry.second->DiagnosticType);
2676 if (Types.empty()) return;
2678 // Now emit the enum entries.
2679 for (StringRef Type : Types)
2680 OS << " Match_" << Type << ",\n";
2681 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2684 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2685 /// user-level name for a subtarget feature.
2686 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2687 OS << "// User-level names for subtarget features that participate in\n"
2688 << "// instruction matching.\n"
2689 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2690 if (!Info.SubtargetFeatures.empty()) {
2691 OS << " switch(Val) {\n";
2692 for (const auto &SF : Info.SubtargetFeatures) {
2693 const SubtargetFeatureInfo &SFI = SF.second;
2694 // FIXME: Totally just a placeholder name to get the algorithm working.
2695 OS << " case " << SFI.getEnumBitName() << ": return \""
2696 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2698 OS << " default: return \"(unknown)\";\n";
2701 // Nothing to emit, so skip the switch
2702 OS << " return \"(unknown)\";\n";
2707 static std::string GetAliasRequiredFeatures(Record *R,
2708 const AsmMatcherInfo &Info) {
2709 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2712 if (ReqFeatures.empty())
2715 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2716 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2719 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2720 "' is not marked as an AssemblerPredicate!");
2725 Result += "Features.test(" + F->getEnumBitName() + ')';
2731 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2732 std::vector<Record*> &Aliases,
2733 unsigned Indent = 0,
2734 StringRef AsmParserVariantName = StringRef()){
2735 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2736 // iteration order of the map is stable.
2737 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2739 for (Record *R : Aliases) {
2740 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2741 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
2742 if (AsmVariantName != AsmParserVariantName)
2744 AliasesFromMnemonic[R->getValueAsString("FromMnemonic").lower()]
2747 if (AliasesFromMnemonic.empty())
2750 // Process each alias a "from" mnemonic at a time, building the code executed
2751 // by the string remapper.
2752 std::vector<StringMatcher::StringPair> Cases;
2753 for (const auto &AliasEntry : AliasesFromMnemonic) {
2754 const std::vector<Record*> &ToVec = AliasEntry.second;
2756 // Loop through each alias and emit code that handles each case. If there
2757 // are two instructions without predicates, emit an error. If there is one,
2759 std::string MatchCode;
2760 int AliasWithNoPredicate = -1;
2762 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2763 Record *R = ToVec[i];
2764 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2766 // If this unconditionally matches, remember it for later and diagnose
2768 if (FeatureMask.empty()) {
2769 if (AliasWithNoPredicate != -1 &&
2770 R->getValueAsString("ToMnemonic") !=
2771 ToVec[AliasWithNoPredicate]->getValueAsString("ToMnemonic")) {
2772 // We can't have two different aliases from the same mnemonic with no
2775 ToVec[AliasWithNoPredicate]->getLoc(),
2776 "two different MnemonicAliases with the same 'from' mnemonic!");
2777 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2780 AliasWithNoPredicate = i;
2783 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
2784 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2786 if (!MatchCode.empty())
2787 MatchCode += "else ";
2788 MatchCode += "if (" + FeatureMask + ")\n";
2789 MatchCode += " Mnemonic = \"";
2790 MatchCode += R->getValueAsString("ToMnemonic").lower();
2791 MatchCode += "\";\n";
2794 if (AliasWithNoPredicate != -1) {
2795 Record *R = ToVec[AliasWithNoPredicate];
2796 if (!MatchCode.empty())
2797 MatchCode += "else\n ";
2798 MatchCode += "Mnemonic = \"";
2799 MatchCode += R->getValueAsString("ToMnemonic").lower();
2800 MatchCode += "\";\n";
2803 MatchCode += "return;";
2805 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
2807 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2810 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2811 /// emit a function for them and return true, otherwise return false.
2812 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2813 CodeGenTarget &Target) {
2814 // Ignore aliases when match-prefix is set.
2815 if (!MatchPrefix.empty())
2818 std::vector<Record*> Aliases =
2819 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2820 if (Aliases.empty()) return false;
2822 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2823 "const FeatureBitset &Features, unsigned VariantID) {\n";
2824 OS << " switch (VariantID) {\n";
2825 unsigned VariantCount = Target.getAsmParserVariantCount();
2826 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2827 Record *AsmVariant = Target.getAsmParserVariant(VC);
2828 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2829 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
2830 OS << " case " << AsmParserVariantNo << ":\n";
2831 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2832 AsmParserVariantName);
2837 // Emit aliases that apply to all variants.
2838 emitMnemonicAliasVariant(OS, Info, Aliases);
2846 emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2847 const AsmMatcherInfo &Info, StringRef ClassName,
2848 StringToOffsetTable &StringTable,
2849 unsigned MaxMnemonicIndex, unsigned MaxFeaturesIndex,
2850 bool HasMnemonicFirst, const Record &AsmParser) {
2851 unsigned MaxMask = 0;
2852 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2853 MaxMask |= OMI.OperandMask;
2856 // Emit the static custom operand parsing table;
2857 OS << "namespace {\n";
2858 OS << " struct OperandMatchEntry {\n";
2859 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2861 OS << " " << getMinimalTypeForRange(MaxMask)
2862 << " OperandMask;\n";
2863 OS << " " << getMinimalTypeForRange(std::distance(
2864 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
2865 OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
2866 << " RequiredFeaturesIdx;\n\n";
2867 OS << " StringRef getMnemonic() const {\n";
2868 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2869 OS << " MnemonicTable[Mnemonic]);\n";
2873 OS << " // Predicate for searching for an opcode.\n";
2874 OS << " struct LessOpcodeOperand {\n";
2875 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2876 OS << " return LHS.getMnemonic() < RHS;\n";
2878 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2879 OS << " return LHS < RHS.getMnemonic();\n";
2881 OS << " bool operator()(const OperandMatchEntry &LHS,";
2882 OS << " const OperandMatchEntry &RHS) {\n";
2883 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2887 OS << "} // end anonymous namespace\n\n";
2889 OS << "static const OperandMatchEntry OperandMatchTable["
2890 << Info.OperandMatchInfo.size() << "] = {\n";
2892 OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
2893 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2894 const MatchableInfo &II = *OMI.MI;
2898 // Store a pascal-style length byte in the mnemonic.
2899 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
2900 OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2901 << " /* " << II.Mnemonic << " */, ";
2903 OS << OMI.OperandMask;
2906 for (int i = 0, e = 31; i !=e; ++i)
2907 if (OMI.OperandMask & (1 << i))
2913 // Write the required features mask.
2915 if (II.RequiredFeatures.empty())
2918 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
2919 OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
2925 // Emit the operand class switch to call the correct custom parser for
2926 // the found operand class.
2927 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2928 << "tryCustomParseOperand(OperandVector"
2929 << " &Operands,\n unsigned MCK) {\n\n"
2930 << " switch(MCK) {\n";
2932 for (const auto &CI : Info.Classes) {
2933 if (CI.ParserMethod.empty())
2935 OS << " case " << CI.Name << ":\n"
2936 << " return " << CI.ParserMethod << "(Operands);\n";
2939 OS << " default:\n";
2940 OS << " return MatchOperand_NoMatch;\n";
2942 OS << " return MatchOperand_NoMatch;\n";
2945 // Emit the static custom operand parser. This code is very similar with
2946 // the other matcher. Also use MatchResultTy here just in case we go for
2947 // a better error handling.
2948 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2949 << "MatchOperandParserImpl(OperandVector"
2950 << " &Operands,\n StringRef Mnemonic,\n"
2951 << " bool ParseForAllFeatures) {\n";
2953 // Emit code to get the available features.
2954 OS << " // Get the current feature set.\n";
2955 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
2957 OS << " // Get the next operand index.\n";
2958 OS << " unsigned NextOpNum = Operands.size()"
2959 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
2961 // Emit code to search the table.
2962 OS << " // Search the table.\n";
2963 if (HasMnemonicFirst) {
2964 OS << " auto MnemonicRange =\n";
2965 OS << " std::equal_range(std::begin(OperandMatchTable), "
2966 "std::end(OperandMatchTable),\n";
2967 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2969 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2970 " std::end(OperandMatchTable));\n";
2971 OS << " if (!Mnemonic.empty())\n";
2972 OS << " MnemonicRange =\n";
2973 OS << " std::equal_range(std::begin(OperandMatchTable), "
2974 "std::end(OperandMatchTable),\n";
2975 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2978 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2979 OS << " return MatchOperand_NoMatch;\n\n";
2981 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2982 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2984 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2985 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2987 // Emit check that the required features are available.
2988 OS << " // check if the available features match\n";
2989 OS << " const FeatureBitset &RequiredFeatures = "
2990 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
2991 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
2992 "RequiredFeatures) != RequiredFeatures)\n";
2993 OS << " continue;\n\n";
2995 // Emit check to ensure the operand number matches.
2996 OS << " // check if the operand in question has a custom parser.\n";
2997 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2998 OS << " continue;\n\n";
3000 // Emit call to the custom parser method
3001 StringRef ParserName = AsmParser.getValueAsString("OperandParserMethod");
3002 if (ParserName.empty())
3003 ParserName = "tryCustomParseOperand";
3004 OS << " // call custom parse method to handle the operand\n";
3005 OS << " OperandMatchResultTy Result = " << ParserName
3006 << "(Operands, it->Class);\n";
3007 OS << " if (Result != MatchOperand_NoMatch)\n";
3008 OS << " return Result;\n";
3011 OS << " // Okay, we had no match.\n";
3012 OS << " return MatchOperand_NoMatch;\n";
3016 static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
3017 AsmMatcherInfo &Info,
3019 std::string AsmParserName =
3020 std::string(Info.AsmParser->getValueAsString("AsmParserClassName"));
3021 OS << "static bool ";
3022 OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3023 << AsmParserName << "&AsmParser,\n";
3024 OS << " unsigned Kind,\n";
3025 OS << " const OperandVector &Operands,\n";
3026 OS << " uint64_t &ErrorInfo) {\n";
3027 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3028 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3029 OS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
3030 OS << " switch (*p) {\n";
3031 OS << " case CVT_Tied: {\n";
3032 OS << " unsigned OpIdx = *(p + 1);\n";
3033 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3034 OS << " std::begin(TiedAsmOperandTable)) &&\n";
3035 OS << " \"Tied operand not found\");\n";
3036 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3037 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3038 OS << " if (OpndNum1 != OpndNum2) {\n";
3039 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3040 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
3041 OS << " if (!AsmParser.areEqualRegs(*SrcOp1, *SrcOp2)) {\n";
3042 OS << " ErrorInfo = OpndNum2;\n";
3043 OS << " return false;\n";
3048 OS << " default:\n";
3052 OS << " return true;\n";
3056 static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3057 unsigned VariantCount) {
3058 OS << "static std::string " << Target.getName()
3059 << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3060 << " unsigned VariantID) {\n";
3062 OS << " return \"\";";
3064 OS << " const unsigned MaxEditDist = 2;\n";
3065 OS << " std::vector<StringRef> Candidates;\n";
3066 OS << " StringRef Prev = \"\";\n\n";
3068 OS << " // Find the appropriate table for this asm variant.\n";
3069 OS << " const MatchEntry *Start, *End;\n";
3070 OS << " switch (VariantID) {\n";
3071 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3072 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3073 Record *AsmVariant = Target.getAsmParserVariant(VC);
3074 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3075 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3076 << "); End = std::end(MatchTable" << VC << "); break;\n";
3079 OS << " for (auto I = Start; I < End; I++) {\n";
3080 OS << " // Ignore unsupported instructions.\n";
3081 OS << " const FeatureBitset &RequiredFeatures = "
3082 "FeatureBitsets[I->RequiredFeaturesIdx];\n";
3083 OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
3084 OS << " continue;\n";
3086 OS << " StringRef T = I->getMnemonic();\n";
3087 OS << " // Avoid recomputing the edit distance for the same string.\n";
3088 OS << " if (T.equals(Prev))\n";
3089 OS << " continue;\n";
3091 OS << " Prev = T;\n";
3092 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3093 OS << " if (Dist <= MaxEditDist)\n";
3094 OS << " Candidates.push_back(T);\n";
3097 OS << " if (Candidates.empty())\n";
3098 OS << " return \"\";\n";
3100 OS << " std::string Res = \", did you mean: \";\n";
3101 OS << " unsigned i = 0;\n";
3102 OS << " for (; i < Candidates.size() - 1; i++)\n";
3103 OS << " Res += Candidates[i].str() + \", \";\n";
3104 OS << " return Res + Candidates[i].str() + \"?\";\n";
3110 static void emitMnemonicChecker(raw_ostream &OS,
3111 CodeGenTarget &Target,
3112 unsigned VariantCount,
3113 bool HasMnemonicFirst,
3114 bool HasMnemonicAliases) {
3115 OS << "static bool " << Target.getName()
3116 << "CheckMnemonic(StringRef Mnemonic,\n";
3118 << "const FeatureBitset &AvailableFeatures,\n";
3120 << "unsigned VariantID) {\n";
3122 if (!VariantCount) {
3123 OS << " return false;\n";
3125 if (HasMnemonicAliases) {
3126 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
3127 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);";
3130 OS << " // Find the appropriate table for this asm variant.\n";
3131 OS << " const MatchEntry *Start, *End;\n";
3132 OS << " switch (VariantID) {\n";
3133 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3134 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3135 Record *AsmVariant = Target.getAsmParserVariant(VC);
3136 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3137 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3138 << "); End = std::end(MatchTable" << VC << "); break;\n";
3142 OS << " // Search the table.\n";
3143 if (HasMnemonicFirst) {
3144 OS << " auto MnemonicRange = "
3145 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3147 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3148 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3149 OS << " if (!Mnemonic.empty())\n";
3150 OS << " MnemonicRange = "
3151 << "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3154 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3155 OS << " return false;\n\n";
3157 OS << " for (const MatchEntry *it = MnemonicRange.first, "
3158 << "*ie = MnemonicRange.second;\n";
3159 OS << " it != ie; ++it) {\n";
3160 OS << " const FeatureBitset &RequiredFeatures =\n";
3161 OS << " FeatureBitsets[it->RequiredFeaturesIdx];\n";
3162 OS << " if ((AvailableFeatures & RequiredFeatures) == ";
3163 OS << "RequiredFeatures)\n";
3164 OS << " return true;\n";
3166 OS << " return false;\n";
3172 // Emit a function mapping match classes to strings, for debugging.
3173 static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3175 OS << "#ifndef NDEBUG\n";
3176 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3177 OS << " switch (Kind) {\n";
3179 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3180 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3181 for (const auto &CI : Infos) {
3182 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3184 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3187 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3189 OS << "#endif // NDEBUG\n";
3193 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
3194 std::string Name = "AMFBS";
3195 for (const auto &Feature : FeatureBitset)
3196 Name += ("_" + Feature->getName()).str();
3200 void AsmMatcherEmitter::run(raw_ostream &OS) {
3201 CodeGenTarget Target(Records);
3202 Record *AsmParser = Target.getAsmParser();
3203 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
3205 // Compute the information on the instructions to match.
3206 AsmMatcherInfo Info(AsmParser, Target, Records);
3209 // Sort the instruction table using the partial order on classes. We use
3210 // stable_sort to ensure that ambiguous instructions are still
3211 // deterministically ordered.
3214 [](const std::unique_ptr<MatchableInfo> &a,
3215 const std::unique_ptr<MatchableInfo> &b) { return *a < *b; });
3217 #ifdef EXPENSIVE_CHECKS
3218 // Verify that the table is sorted and operator < works transitively.
3219 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3221 for (auto J = I; J != E; ++J) {
3222 assert(!(**J < **I));
3227 DEBUG_WITH_TYPE("instruction_info", {
3228 for (const auto &MI : Info.Matchables)
3232 // Check for ambiguous matchables.
3233 DEBUG_WITH_TYPE("ambiguous_instrs", {
3234 unsigned NumAmbiguous = 0;
3235 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3237 for (auto J = std::next(I); J != E; ++J) {
3238 const MatchableInfo &A = **I;
3239 const MatchableInfo &B = **J;
3241 if (A.couldMatchAmbiguouslyWith(B)) {
3242 errs() << "warning: ambiguous matchables:\n";
3244 errs() << "\nis incomparable with:\n";
3252 errs() << "warning: " << NumAmbiguous
3253 << " ambiguous matchables!\n";
3256 // Compute the information on the custom operand parsing.
3257 Info.buildOperandMatchInfo();
3259 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
3260 bool HasOptionalOperands = Info.hasOptionalOperands();
3261 bool ReportMultipleNearMisses =
3262 AsmParser->getValueAsBit("ReportMultipleNearMisses");
3264 // Write the output.
3266 // Information for the class declaration.
3267 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3268 OS << "#undef GET_ASSEMBLER_HEADER\n";
3269 OS << " // This should be included into the middle of the declaration of\n";
3270 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
3271 OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset &FB) const;\n";
3272 if (HasOptionalOperands) {
3273 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3274 << "unsigned Opcode,\n"
3275 << " const OperandVector &Operands,\n"
3276 << " const SmallBitVector &OptionalOperandsMask);\n";
3278 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3279 << "unsigned Opcode,\n"
3280 << " const OperandVector &Operands);\n";
3282 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
3283 OS << " const OperandVector &Operands) override;\n";
3284 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3285 << " MCInst &Inst,\n";
3286 if (ReportMultipleNearMisses)
3287 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3289 OS << " uint64_t &ErrorInfo,\n"
3290 << " FeatureBitset &MissingFeatures,\n";
3291 OS << " bool matchingInlineAsm,\n"
3292 << " unsigned VariantID = 0);\n";
3293 if (!ReportMultipleNearMisses)
3294 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3295 << " MCInst &Inst,\n"
3296 << " uint64_t &ErrorInfo,\n"
3297 << " bool matchingInlineAsm,\n"
3298 << " unsigned VariantID = 0) {\n"
3299 << " FeatureBitset MissingFeatures;\n"
3300 << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
3301 << " matchingInlineAsm, VariantID);\n"
3305 if (!Info.OperandMatchInfo.empty()) {
3306 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
3307 OS << " OperandVector &Operands,\n";
3308 OS << " StringRef Mnemonic,\n";
3309 OS << " bool ParseForAllFeatures = false);\n";
3311 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
3312 OS << " OperandVector &Operands,\n";
3313 OS << " unsigned MCK);\n\n";
3316 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3318 // Emit the operand match diagnostic enum names.
3319 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3320 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3321 emitOperandDiagnosticTypes(Info, OS);
3322 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3324 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3325 OS << "#undef GET_REGISTER_MATCHER\n\n";
3327 // Emit the subtarget feature enumeration.
3328 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
3329 Info.SubtargetFeatures, OS);
3331 // Emit the function to match a register name to number.
3332 // This should be omitted for Mips target
3333 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3334 emitMatchRegisterName(Target, AsmParser, OS);
3336 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3337 emitMatchRegisterAltName(Target, AsmParser, OS);
3339 OS << "#endif // GET_REGISTER_MATCHER\n\n";
3341 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3342 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
3344 // Generate the helper function to get the names for subtarget features.
3345 emitGetSubtargetFeatureName(Info, OS);
3347 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3349 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3350 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3352 // Generate the function that remaps for mnemonic aliases.
3353 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
3355 // Generate the convertToMCInst function to convert operands into an MCInst.
3356 // Also, generate the convertToMapAndConstraints function for MS-style inline
3357 // assembly. The latter doesn't actually generate a MCInst.
3358 unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
3360 HasOptionalOperands, OS);
3362 // Emit the enumeration for classes which participate in matching.
3363 emitMatchClassEnumeration(Target, Info.Classes, OS);
3365 // Emit a function to get the user-visible string to describe an operand
3366 // match failure in diagnostics.
3367 emitOperandMatchErrorDiagStrings(Info, OS);
3369 // Emit a function to map register classes to operand match failure codes.
3370 emitRegisterMatchErrorFunc(Info, OS);
3372 // Emit the routine to match token strings to their match class.
3373 emitMatchTokenString(Target, Info.Classes, OS);
3375 // Emit the subclass predicate routine.
3376 emitIsSubclass(Target, Info.Classes, OS);
3378 // Emit the routine to validate an operand against a match class.
3379 emitValidateOperandClass(Info, OS);
3381 emitMatchClassKindNames(Info.Classes, OS);
3383 // Emit the available features compute function.
3384 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
3385 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3386 Info.SubtargetFeatures, OS);
3388 if (!ReportMultipleNearMisses)
3389 emitAsmTiedOperandConstraints(Target, Info, OS);
3391 StringToOffsetTable StringTable;
3393 size_t MaxNumOperands = 0;
3394 unsigned MaxMnemonicIndex = 0;
3395 bool HasDeprecation = false;
3396 for (const auto &MI : Info.Matchables) {
3397 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3398 HasDeprecation |= MI->HasDeprecation;
3400 // Store a pascal-style length byte in the mnemonic.
3401 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3402 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3403 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3406 OS << "static const char MnemonicTable[] =\n";
3407 StringTable.EmitString(OS);
3410 std::vector<std::vector<Record *>> FeatureBitsets;
3411 for (const auto &MI : Info.Matchables) {
3412 if (MI->RequiredFeatures.empty())
3414 FeatureBitsets.emplace_back();
3415 for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
3416 FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
3419 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
3420 const std::vector<Record *> &B) {
3421 if (A.size() < B.size())
3423 if (A.size() > B.size())
3425 for (auto Pair : zip(A, B)) {
3426 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3428 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3433 FeatureBitsets.erase(
3434 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3435 FeatureBitsets.end());
3436 OS << "// Feature bitsets.\n"
3437 << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
3438 << " AMFBS_None,\n";
3439 for (const auto &FeatureBitset : FeatureBitsets) {
3440 if (FeatureBitset.empty())
3442 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3445 << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
3446 << " {}, // AMFBS_None\n";
3447 for (const auto &FeatureBitset : FeatureBitsets) {
3448 if (FeatureBitset.empty())
3451 for (const auto &Feature : FeatureBitset) {
3452 const auto &I = Info.SubtargetFeatures.find(Feature);
3453 assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
3454 OS << I->second.getEnumBitName() << ", ";
3460 // Emit the static match table; unused classes get initialized to 0 which is
3461 // guaranteed to be InvalidMatchClass.
3463 // FIXME: We can reduce the size of this table very easily. First, we change
3464 // it so that store the kinds in separate bit-fields for each index, which
3465 // only needs to be the max width used for classes at that index (we also need
3466 // to reject based on this during classification). If we then make sure to
3467 // order the match kinds appropriately (putting mnemonics last), then we
3468 // should only end up using a few bits for each class, especially the ones
3469 // following the mnemonic.
3470 OS << "namespace {\n";
3471 OS << " struct MatchEntry {\n";
3472 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3474 OS << " uint16_t Opcode;\n";
3475 OS << " " << getMinimalTypeForRange(NumConverters)
3477 OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
3478 << " RequiredFeaturesIdx;\n";
3479 OS << " " << getMinimalTypeForRange(
3480 std::distance(Info.Classes.begin(), Info.Classes.end()))
3481 << " Classes[" << MaxNumOperands << "];\n";
3482 OS << " StringRef getMnemonic() const {\n";
3483 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3484 OS << " MnemonicTable[Mnemonic]);\n";
3488 OS << " // Predicate for searching for an opcode.\n";
3489 OS << " struct LessOpcode {\n";
3490 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3491 OS << " return LHS.getMnemonic() < RHS;\n";
3493 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3494 OS << " return LHS < RHS.getMnemonic();\n";
3496 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3497 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
3501 OS << "} // end anonymous namespace\n\n";
3503 unsigned VariantCount = Target.getAsmParserVariantCount();
3504 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3505 Record *AsmVariant = Target.getAsmParserVariant(VC);
3506 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3508 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
3510 for (const auto &MI : Info.Matchables) {
3511 if (MI->AsmVariantID != AsmVariantNo)
3514 // Store a pascal-style length byte in the mnemonic.
3515 std::string LenMnemonic =
3516 char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3517 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
3518 << " /* " << MI->Mnemonic << " */, "
3519 << Target.getInstNamespace() << "::"
3520 << MI->getResultInst()->TheDef->getName() << ", "
3521 << MI->ConversionFnKind << ", ";
3523 // Write the required features mask.
3525 if (MI->RequiredFeatures.empty())
3528 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
3529 OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
3533 for (const MatchableInfo::AsmOperand &Op : MI->AsmOperands)
3534 OS << LS << Op.Class->Name;
3541 OS << "#include \"llvm/Support/Debug.h\"\n";
3542 OS << "#include \"llvm/Support/Format.h\"\n\n";
3544 // Finally, build the match function.
3545 OS << "unsigned " << Target.getName() << ClassName << "::\n"
3546 << "MatchInstructionImpl(const OperandVector &Operands,\n";
3547 OS << " MCInst &Inst,\n";
3548 if (ReportMultipleNearMisses)
3549 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3551 OS << " uint64_t &ErrorInfo,\n"
3552 << " FeatureBitset &MissingFeatures,\n";
3553 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
3555 if (!ReportMultipleNearMisses) {
3556 OS << " // Eliminate obvious mismatches.\n";
3557 OS << " if (Operands.size() > "
3558 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3559 OS << " ErrorInfo = "
3560 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3561 OS << " return Match_InvalidOperand;\n";
3565 // Emit code to get the available features.
3566 OS << " // Get the current feature set.\n";
3567 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
3569 OS << " // Get the instruction mnemonic, which is the first token.\n";
3570 if (HasMnemonicFirst) {
3571 OS << " StringRef Mnemonic = ((" << Target.getName()
3572 << "Operand &)*Operands[0]).getToken();\n\n";
3574 OS << " StringRef Mnemonic;\n";
3575 OS << " if (Operands[0]->isToken())\n";
3576 OS << " Mnemonic = ((" << Target.getName()
3577 << "Operand &)*Operands[0]).getToken();\n\n";
3580 if (HasMnemonicAliases) {
3581 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
3582 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3585 // Emit code to compute the class list for this operand vector.
3586 if (!ReportMultipleNearMisses) {
3587 OS << " // Some state to try to produce better error messages.\n";
3588 OS << " bool HadMatchOtherThanFeatures = false;\n";
3589 OS << " bool HadMatchOtherThanPredicate = false;\n";
3590 OS << " unsigned RetCode = Match_InvalidOperand;\n";
3591 OS << " MissingFeatures.set();\n";
3592 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3593 OS << " // wrong for all instances of the instruction.\n";
3594 OS << " ErrorInfo = ~0ULL;\n";
3597 if (HasOptionalOperands) {
3598 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3601 // Emit code to search the table.
3602 OS << " // Find the appropriate table for this asm variant.\n";
3603 OS << " const MatchEntry *Start, *End;\n";
3604 OS << " switch (VariantID) {\n";
3605 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3606 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3607 Record *AsmVariant = Target.getAsmParserVariant(VC);
3608 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3609 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3610 << "); End = std::end(MatchTable" << VC << "); break;\n";
3614 OS << " // Search the table.\n";
3615 if (HasMnemonicFirst) {
3616 OS << " auto MnemonicRange = "
3617 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3619 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3620 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3621 OS << " if (!Mnemonic.empty())\n";
3622 OS << " MnemonicRange = "
3623 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3626 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3627 << " std::distance(MnemonicRange.first, MnemonicRange.second) <<\n"
3628 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3630 OS << " // Return a more specific error code if no mnemonics match.\n";
3631 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3632 OS << " return Match_MnemonicFail;\n\n";
3634 OS << " for (const MatchEntry *it = MnemonicRange.first, "
3635 << "*ie = MnemonicRange.second;\n";
3636 OS << " it != ie; ++it) {\n";
3637 OS << " const FeatureBitset &RequiredFeatures = "
3638 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
3639 OS << " bool HasRequiredFeatures =\n";
3640 OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
3641 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3642 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3644 if (ReportMultipleNearMisses) {
3645 OS << " // Some state to record ways in which this instruction did not match.\n";
3646 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3647 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3648 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3649 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
3650 OS << " bool MultipleInvalidOperands = false;\n";
3653 if (HasMnemonicFirst) {
3654 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3655 OS << " assert(Mnemonic == it->getMnemonic());\n";
3658 // Emit check that the subclasses match.
3659 if (!ReportMultipleNearMisses)
3660 OS << " bool OperandsValid = true;\n";
3661 if (HasOptionalOperands) {
3662 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3664 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3665 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3666 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3667 OS << " auto Formal = "
3668 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3669 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3670 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3671 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3672 OS << " if (ActualIdx < Operands.size())\n";
3673 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3674 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3676 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
3677 OS << " if (ActualIdx >= Operands.size()) {\n";
3678 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand "
3679 "index out of range\\n\");\n";
3680 if (ReportMultipleNearMisses) {
3681 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3682 "isSubclass(Formal, OptionalMatchClass);\n";
3683 OS << " if (!ThisOperandValid) {\n";
3684 OS << " if (!OperandNearMiss) {\n";
3685 OS << " // Record info about match failure for later use.\n";
3686 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
3687 OS << " OperandNearMiss =\n";
3688 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
3689 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
3690 OS << " // If more than one operand is invalid, give up on this match entry.\n";
3691 OS << " DEBUG_WITH_TYPE(\n";
3692 OS << " \"asm-matcher\",\n";
3693 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
3694 OS << " MultipleInvalidOperands = true;\n";
3697 OS << " } else {\n";
3698 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal "
3699 "operand not required\\n\");\n";
3701 OS << " continue;\n";
3703 OS << " if (Formal == InvalidMatchClass) {\n";
3704 if (HasOptionalOperands) {
3705 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3710 OS << " if (isSubclass(Formal, OptionalMatchClass)) {\n";
3711 if (HasOptionalOperands) {
3712 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3714 OS << " continue;\n";
3716 OS << " OperandsValid = false;\n";
3717 OS << " ErrorInfo = ActualIdx;\n";
3721 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3722 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
3723 OS << " if (Diag == Match_Success) {\n";
3724 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3725 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
3726 OS << " ++ActualIdx;\n";
3727 OS << " continue;\n";
3729 OS << " // If the generic handler indicates an invalid operand\n";
3730 OS << " // failure, check for a special case.\n";
3731 OS << " if (Diag != Match_Success) {\n";
3732 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3733 OS << " if (TargetDiag == Match_Success) {\n";
3734 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3735 OS << " dbgs() << \"match success using target matcher\\n\");\n";
3736 OS << " ++ActualIdx;\n";
3737 OS << " continue;\n";
3739 OS << " // If the target matcher returned a specific error code use\n";
3740 OS << " // that, else use the one from the generic matcher.\n";
3741 OS << " if (TargetDiag != Match_InvalidOperand && "
3742 "HasRequiredFeatures)\n";
3743 OS << " Diag = TargetDiag;\n";
3745 OS << " // If current formal operand wasn't matched and it is optional\n"
3746 << " // then try to match next formal operand\n";
3747 OS << " if (Diag == Match_InvalidOperand "
3748 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3749 if (HasOptionalOperands) {
3750 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3752 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
3753 OS << " continue;\n";
3756 if (ReportMultipleNearMisses) {
3757 OS << " if (!OperandNearMiss) {\n";
3758 OS << " // If this is the first invalid operand we have seen, record some\n";
3759 OS << " // information about it.\n";
3760 OS << " DEBUG_WITH_TYPE(\n";
3761 OS << " \"asm-matcher\",\n";
3763 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3764 OS << " << Diag << \"\\n\");\n";
3765 OS << " OperandNearMiss =\n";
3766 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3767 OS << " ++ActualIdx;\n";
3768 OS << " } else {\n";
3769 OS << " // If more than one operand is invalid, give up on this match entry.\n";
3770 OS << " DEBUG_WITH_TYPE(\n";
3771 OS << " \"asm-matcher\",\n";
3772 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
3773 OS << " MultipleInvalidOperands = true;\n";
3778 OS << " // If this operand is broken for all of the instances of this\n";
3779 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3780 OS << " // If we already had a match that only failed due to a\n";
3781 OS << " // target predicate, that diagnostic is preferred.\n";
3782 OS << " if (!HadMatchOtherThanPredicate &&\n";
3783 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3784 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3785 "!= Match_InvalidOperand))\n";
3786 OS << " RetCode = Diag;\n";
3787 OS << " ErrorInfo = ActualIdx;\n";
3789 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3790 OS << " OperandsValid = false;\n";
3795 if (ReportMultipleNearMisses)
3796 OS << " if (MultipleInvalidOperands) {\n";
3798 OS << " if (!OperandsValid) {\n";
3799 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3800 OS << " \"operand mismatches, ignoring \"\n";
3801 OS << " \"this opcode\\n\");\n";
3802 OS << " continue;\n";
3805 // Emit check that the required features are available.
3806 OS << " if (!HasRequiredFeatures) {\n";
3807 if (!ReportMultipleNearMisses)
3808 OS << " HadMatchOtherThanFeatures = true;\n";
3809 OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
3810 "~AvailableFeatures;\n";
3811 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
3812 OS << " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
3813 OS << " if (NewMissingFeatures[I])\n";
3814 OS << " dbgs() << ' ' << I;\n";
3815 OS << " dbgs() << \"\\n\");\n";
3816 if (ReportMultipleNearMisses) {
3817 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3819 OS << " if (NewMissingFeatures.count() <=\n"
3820 " MissingFeatures.count())\n";
3821 OS << " MissingFeatures = NewMissingFeatures;\n";
3822 OS << " continue;\n";
3826 OS << " Inst.clear();\n\n";
3827 OS << " Inst.setOpcode(it->Opcode);\n";
3828 // Verify the instruction with the target-specific match predicate function.
3829 OS << " // We have a potential match but have not rendered the operands.\n"
3830 << " // Check the target predicate to handle any context sensitive\n"
3831 " // constraints.\n"
3832 << " // For example, Ties that are referenced multiple times must be\n"
3833 " // checked here to ensure the input is the same for each match\n"
3834 " // constraints. If we leave it any later the ties will have been\n"
3835 " // canonicalized\n"
3836 << " unsigned MatchResult;\n"
3837 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3838 "Operands)) != Match_Success) {\n"
3839 << " Inst.clear();\n";
3840 OS << " DEBUG_WITH_TYPE(\n";
3841 OS << " \"asm-matcher\",\n";
3842 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3843 OS << " << MatchResult << \"\\n\");\n";
3844 if (ReportMultipleNearMisses) {
3845 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3847 OS << " RetCode = MatchResult;\n"
3848 << " HadMatchOtherThanPredicate = true;\n"
3853 if (ReportMultipleNearMisses) {
3854 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3855 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3856 OS << " if (OperandNearMiss) {\n";
3857 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3858 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
3859 OS << " DEBUG_WITH_TYPE(\n";
3860 OS << " \"asm-matcher\",\n";
3862 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
3863 OS << " NearMisses->push_back(OperandNearMiss);\n";
3864 OS << " } else {\n";
3865 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3866 OS << " \"types of mismatch, so not \"\n";
3867 OS << " \"reporting near-miss\\n\");\n";
3869 OS << " continue;\n";
3873 OS << " if (matchingInlineAsm) {\n";
3874 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3875 if (!ReportMultipleNearMisses) {
3876 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3877 "Operands, ErrorInfo))\n";
3878 OS << " return Match_InvalidTiedOperand;\n";
3881 OS << " return Match_Success;\n";
3883 OS << " // We have selected a definite instruction, convert the parsed\n"
3884 << " // operands into the appropriate MCInst.\n";
3885 if (HasOptionalOperands) {
3886 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3887 << " OptionalOperandsMask);\n";
3889 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3893 // Verify the instruction with the target-specific match predicate function.
3894 OS << " // We have a potential match. Check the target predicate to\n"
3895 << " // handle any context sensitive constraints.\n"
3896 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3897 << " Match_Success) {\n"
3898 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3899 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3900 << " << MatchResult << \"\\n\");\n"
3901 << " Inst.clear();\n";
3902 if (ReportMultipleNearMisses) {
3903 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3905 OS << " RetCode = MatchResult;\n"
3906 << " HadMatchOtherThanPredicate = true;\n"
3911 if (ReportMultipleNearMisses) {
3912 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3913 OS << " (int)(bool)FeaturesNearMiss +\n";
3914 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3915 OS << " (int)(bool)LatePredicateNearMiss);\n";
3916 OS << " if (NumNearMisses == 1) {\n";
3917 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3918 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
3919 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3920 OS << " \"mismatch, so reporting a \"\n";
3921 OS << " \"near-miss\\n\");\n";
3922 OS << " if (NearMisses && FeaturesNearMiss)\n";
3923 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3924 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3925 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3926 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3927 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3929 OS << " continue;\n";
3930 OS << " } else if (NumNearMisses > 1) {\n";
3931 OS << " // This instruction missed in more than one way, so ignore it.\n";
3932 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3933 OS << " \"types of mismatch, so not \"\n";
3934 OS << " \"reporting near-miss\\n\");\n";
3935 OS << " continue;\n";
3939 // Call the post-processing function, if used.
3940 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
3941 if (!InsnCleanupFn.empty())
3942 OS << " " << InsnCleanupFn << "(Inst);\n";
3944 if (HasDeprecation) {
3945 OS << " std::string Info;\n";
3946 OS << " if (!getParser().getTargetParser().getTargetOptions().MCNoDeprecatedWarn &&\n";
3947 OS << " MII.getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
3948 OS << " SMLoc Loc = ((" << Target.getName()
3949 << "Operand &)*Operands[0]).getStartLoc();\n";
3950 OS << " getParser().Warning(Loc, Info, std::nullopt);\n";
3954 if (!ReportMultipleNearMisses) {
3955 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3956 "Operands, ErrorInfo))\n";
3957 OS << " return Match_InvalidTiedOperand;\n";
3961 OS << " DEBUG_WITH_TYPE(\n";
3962 OS << " \"asm-matcher\",\n";
3963 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
3964 OS << " return Match_Success;\n";
3967 if (ReportMultipleNearMisses) {
3968 OS << " // No instruction variants matched exactly.\n";
3969 OS << " return Match_NearMisses;\n";
3971 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3972 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3973 OS << " return RetCode;\n\n";
3974 OS << " ErrorInfo = 0;\n";
3975 OS << " return Match_MissingFeature;\n";
3979 if (!Info.OperandMatchInfo.empty())
3980 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3981 MaxMnemonicIndex, FeatureBitsets.size(),
3982 HasMnemonicFirst, *AsmParser);
3984 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3986 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3987 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3989 emitMnemonicSpellChecker(OS, Target, VariantCount);
3991 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
3993 OS << "\n#ifdef GET_MNEMONIC_CHECKER\n";
3994 OS << "#undef GET_MNEMONIC_CHECKER\n\n";
3996 emitMnemonicChecker(OS, Target, VariantCount,
3997 HasMnemonicFirst, HasMnemonicAliases);
3999 OS << "#endif // GET_MNEMONIC_CHECKER\n\n";
4004 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
4005 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
4006 AsmMatcherEmitter(RK).run(OS);
4009 } // end namespace llvm