llvm-project
4134 строки · 157.5 Кб
1//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
12//
13// Converting assembly operands into MCInst structures
14// ---------------------------------------------------
15//
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
21// operands.
22//
23// Some example inputs, for X86:
24// 'addl' (immediate ...) (register ...)
25// 'add' (immediate ...) (memory ...)
26// 'call' '*' %epc
27//
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:
31//
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.
37//
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
44// current mode.
45//
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.
50//
51// The matching is divided into two distinct phases:
52//
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.
56//
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).
61//
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.
65//
66// In addition, the subset relation amongst classes induces a partial order
67// on such tuples, which we use to resolve ambiguities.
68//
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.
73//
74// Custom Operand Parsing
75// ----------------------
76//
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
81// following way:
82//
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.
86//
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.
92//
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.
95//
96//===----------------------------------------------------------------------===//
97
98#include "Common/CodeGenInstAlias.h"
99#include "Common/CodeGenInstruction.h"
100#include "Common/CodeGenRegisters.h"
101#include "Common/CodeGenTarget.h"
102#include "Common/SubtargetFeatureInfo.h"
103#include "Common/Types.h"
104#include "llvm/ADT/CachedHashString.h"
105#include "llvm/ADT/PointerUnion.h"
106#include "llvm/ADT/STLExtras.h"
107#include "llvm/ADT/SmallPtrSet.h"
108#include "llvm/ADT/SmallVector.h"
109#include "llvm/ADT/StringExtras.h"
110#include "llvm/Support/CommandLine.h"
111#include "llvm/Support/Debug.h"
112#include "llvm/Support/ErrorHandling.h"
113#include "llvm/TableGen/Error.h"
114#include "llvm/TableGen/Record.h"
115#include "llvm/TableGen/StringMatcher.h"
116#include "llvm/TableGen/StringToOffsetTable.h"
117#include "llvm/TableGen/TableGenBackend.h"
118#include <cassert>
119#include <cctype>
120#include <forward_list>
121#include <map>
122#include <set>
123
124using namespace llvm;
125
126#define DEBUG_TYPE "asm-matcher-emitter"
127
128cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
129
130static cl::opt<std::string>
131MatchPrefix("match-prefix", cl::init(""),
132cl::desc("Only match instructions with the given prefix"),
133cl::cat(AsmMatcherEmitterCat));
134
135namespace {
136class AsmMatcherInfo;
137
138// Register sets are used as keys in some second-order sets TableGen creates
139// when generating its data structures. This means that the order of two
140// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
141// can even affect compiler output (at least seen in diagnostics produced when
142// all matches fail). So we use a type that sorts them consistently.
143typedef std::set<Record *, LessRecordByID> RegisterSet;
144
145class AsmMatcherEmitter {
146RecordKeeper &Records;
147
148public:
149AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
150
151void run(raw_ostream &o);
152};
153
154/// ClassInfo - Helper class for storing the information about a particular
155/// class of operands which can be matched.
156struct ClassInfo {
157enum ClassInfoKind {
158/// Invalid kind, for use as a sentinel value.
159Invalid = 0,
160
161/// The class for a particular token.
162Token,
163
164/// The (first) register class, subsequent register classes are
165/// RegisterClass0+1, and so on.
166RegisterClass0,
167
168/// The (first) user defined class, subsequent user defined classes are
169/// UserClass0+1, and so on.
170UserClass0 = 1 << 16
171};
172
173/// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
174/// N) for the Nth user defined class.
175unsigned Kind;
176
177/// SuperClasses - The super classes of this class. Note that for simplicities
178/// sake user operands only record their immediate super class, while register
179/// operands include all superclasses.
180std::vector<ClassInfo *> SuperClasses;
181
182/// Name - The full class name, suitable for use in an enum.
183std::string Name;
184
185/// ClassName - The unadorned generic name for this class (e.g., Token).
186std::string ClassName;
187
188/// ValueName - The name of the value this class represents; for a token this
189/// is the literal token string, for an operand it is the TableGen class (or
190/// empty if this is a derived class).
191std::string ValueName;
192
193/// PredicateMethod - The name of the operand method to test whether the
194/// operand matches this class; this is not valid for Token or register kinds.
195std::string PredicateMethod;
196
197/// RenderMethod - The name of the operand method to add this operand to an
198/// MCInst; this is not valid for Token or register kinds.
199std::string RenderMethod;
200
201/// ParserMethod - The name of the operand method to do a target specific
202/// parsing on the operand.
203std::string ParserMethod;
204
205/// For register classes: the records for all the registers in this class.
206RegisterSet Registers;
207
208/// For custom match classes: the diagnostic kind for when the predicate
209/// fails.
210std::string DiagnosticType;
211
212/// For custom match classes: the diagnostic string for when the predicate
213/// fails.
214std::string DiagnosticString;
215
216/// Is this operand optional and not always required.
217bool IsOptional;
218
219/// DefaultMethod - The name of the method that returns the default operand
220/// for optional operand
221std::string DefaultMethod;
222
223public:
224/// isRegisterClass() - Check if this is a register class.
225bool isRegisterClass() const {
226return Kind >= RegisterClass0 && Kind < UserClass0;
227}
228
229/// isUserClass() - Check if this is a user defined class.
230bool isUserClass() const { return Kind >= UserClass0; }
231
232/// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
233/// are related if they are in the same class hierarchy.
234bool isRelatedTo(const ClassInfo &RHS) const {
235// Tokens are only related to tokens.
236if (Kind == Token || RHS.Kind == Token)
237return Kind == Token && RHS.Kind == Token;
238
239// Registers classes are only related to registers classes, and only if
240// their intersection is non-empty.
241if (isRegisterClass() || RHS.isRegisterClass()) {
242if (!isRegisterClass() || !RHS.isRegisterClass())
243return false;
244
245std::vector<Record *> Tmp;
246std::set_intersection(Registers.begin(), Registers.end(),
247RHS.Registers.begin(), RHS.Registers.end(),
248std::back_inserter(Tmp), LessRecordByID());
249
250return !Tmp.empty();
251}
252
253// Otherwise we have two users operands; they are related if they are in the
254// same class hierarchy.
255//
256// FIXME: This is an oversimplification, they should only be related if they
257// intersect, however we don't have that information.
258assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
259const ClassInfo *Root = this;
260while (!Root->SuperClasses.empty())
261Root = Root->SuperClasses.front();
262
263const ClassInfo *RHSRoot = &RHS;
264while (!RHSRoot->SuperClasses.empty())
265RHSRoot = RHSRoot->SuperClasses.front();
266
267return Root == RHSRoot;
268}
269
270/// isSubsetOf - Test whether this class is a subset of \p RHS.
271bool isSubsetOf(const ClassInfo &RHS) const {
272// This is a subset of RHS if it is the same class...
273if (this == &RHS)
274return true;
275
276// ... or if any of its super classes are a subset of RHS.
277SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
278SuperClasses.end());
279SmallPtrSet<const ClassInfo *, 16> Visited;
280while (!Worklist.empty()) {
281auto *CI = Worklist.pop_back_val();
282if (CI == &RHS)
283return true;
284for (auto *Super : CI->SuperClasses)
285if (Visited.insert(Super).second)
286Worklist.push_back(Super);
287}
288
289return false;
290}
291
292int getTreeDepth() const {
293int Depth = 0;
294const ClassInfo *Root = this;
295while (!Root->SuperClasses.empty()) {
296Depth++;
297Root = Root->SuperClasses.front();
298}
299return Depth;
300}
301
302const ClassInfo *findRoot() const {
303const ClassInfo *Root = this;
304while (!Root->SuperClasses.empty())
305Root = Root->SuperClasses.front();
306return Root;
307}
308
309/// Compare two classes. This does not produce a total ordering, but does
310/// guarantee that subclasses are sorted before their parents, and that the
311/// ordering is transitive.
312bool operator<(const ClassInfo &RHS) const {
313if (this == &RHS)
314return false;
315
316// First, enforce the ordering between the three different types of class.
317// Tokens sort before registers, which sort before user classes.
318if (Kind == Token) {
319if (RHS.Kind != Token)
320return true;
321assert(RHS.Kind == Token);
322} else if (isRegisterClass()) {
323if (RHS.Kind == Token)
324return false;
325else if (RHS.isUserClass())
326return true;
327assert(RHS.isRegisterClass());
328} else if (isUserClass()) {
329if (!RHS.isUserClass())
330return false;
331assert(RHS.isUserClass());
332} else {
333llvm_unreachable("Unknown ClassInfoKind");
334}
335
336if (Kind == Token || isUserClass()) {
337// Related tokens and user classes get sorted by depth in the inheritence
338// tree (so that subclasses are before their parents).
339if (isRelatedTo(RHS)) {
340if (getTreeDepth() > RHS.getTreeDepth())
341return true;
342if (getTreeDepth() < RHS.getTreeDepth())
343return false;
344} else {
345// Unrelated tokens and user classes are ordered by the name of their
346// root nodes, so that there is a consistent ordering between
347// unconnected trees.
348return findRoot()->ValueName < RHS.findRoot()->ValueName;
349}
350} else if (isRegisterClass()) {
351// For register sets, sort by number of registers. This guarantees that
352// a set will always sort before all of it's strict supersets.
353if (Registers.size() != RHS.Registers.size())
354return Registers.size() < RHS.Registers.size();
355} else {
356llvm_unreachable("Unknown ClassInfoKind");
357}
358
359// FIXME: We should be able to just return false here, as we only need a
360// partial order (we use stable sorts, so this is deterministic) and the
361// name of a class shouldn't be significant. However, some of the backends
362// accidentally rely on this behaviour, so it will have to stay like this
363// until they are fixed.
364return ValueName < RHS.ValueName;
365}
366};
367
368class AsmVariantInfo {
369public:
370StringRef RegisterPrefix;
371StringRef TokenizingCharacters;
372StringRef SeparatorCharacters;
373StringRef BreakCharacters;
374StringRef Name;
375int AsmVariantNo;
376};
377
378bool getPreferSmallerInstructions(CodeGenTarget const &Target) {
379return Target.getAsmParser()->getValueAsBit("PreferSmallerInstructions");
380}
381
382/// MatchableInfo - Helper class for storing the necessary information for an
383/// instruction or alias which is capable of being matched.
384struct MatchableInfo {
385struct AsmOperand {
386/// Token - This is the token that the operand came from.
387StringRef Token;
388
389/// The unique class instance this operand should match.
390ClassInfo *Class;
391
392/// The operand name this is, if anything.
393StringRef SrcOpName;
394
395/// The operand name this is, before renaming for tied operands.
396StringRef OrigSrcOpName;
397
398/// The suboperand index within SrcOpName, or -1 for the entire operand.
399int SubOpIdx;
400
401/// Whether the token is "isolated", i.e., it is preceded and followed
402/// by separators.
403bool IsIsolatedToken;
404
405/// Register record if this token is singleton register.
406Record *SingletonReg;
407
408explicit AsmOperand(bool IsIsolatedToken, StringRef T)
409: Token(T), Class(nullptr), SubOpIdx(-1),
410IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
411};
412
413/// ResOperand - This represents a single operand in the result instruction
414/// generated by the match. In cases (like addressing modes) where a single
415/// assembler operand expands to multiple MCOperands, this represents the
416/// single assembler operand, not the MCOperand.
417struct ResOperand {
418enum {
419/// RenderAsmOperand - This represents an operand result that is
420/// generated by calling the render method on the assembly operand. The
421/// corresponding AsmOperand is specified by AsmOperandNum.
422RenderAsmOperand,
423
424/// TiedOperand - This represents a result operand that is a duplicate of
425/// a previous result operand.
426TiedOperand,
427
428/// ImmOperand - This represents an immediate value that is dumped into
429/// the operand.
430ImmOperand,
431
432/// RegOperand - This represents a fixed register that is dumped in.
433RegOperand
434} Kind;
435
436/// Tuple containing the index of the (earlier) result operand that should
437/// be copied from, as well as the indices of the corresponding (parsed)
438/// operands in the asm string.
439struct TiedOperandsTuple {
440unsigned ResOpnd;
441unsigned SrcOpnd1Idx;
442unsigned SrcOpnd2Idx;
443};
444
445union {
446/// This is the operand # in the AsmOperands list that this should be
447/// copied from.
448unsigned AsmOperandNum;
449
450/// Description of tied operands.
451TiedOperandsTuple TiedOperands;
452
453/// ImmVal - This is the immediate value added to the instruction.
454int64_t ImmVal;
455
456/// Register - This is the register record.
457Record *Register;
458};
459
460/// MINumOperands - The number of MCInst operands populated by this
461/// operand.
462unsigned MINumOperands;
463
464static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
465ResOperand X;
466X.Kind = RenderAsmOperand;
467X.AsmOperandNum = AsmOpNum;
468X.MINumOperands = NumOperands;
469return X;
470}
471
472static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
473unsigned SrcOperand2) {
474ResOperand X;
475X.Kind = TiedOperand;
476X.TiedOperands = {TiedOperandNum, SrcOperand1, SrcOperand2};
477X.MINumOperands = 1;
478return X;
479}
480
481static ResOperand getImmOp(int64_t Val) {
482ResOperand X;
483X.Kind = ImmOperand;
484X.ImmVal = Val;
485X.MINumOperands = 1;
486return X;
487}
488
489static ResOperand getRegOp(Record *Reg) {
490ResOperand X;
491X.Kind = RegOperand;
492X.Register = Reg;
493X.MINumOperands = 1;
494return X;
495}
496};
497
498/// AsmVariantID - Target's assembly syntax variant no.
499int AsmVariantID;
500
501/// AsmString - The assembly string for this instruction (with variants
502/// removed), e.g. "movsx $src, $dst".
503std::string AsmString;
504
505/// TheDef - This is the definition of the instruction or InstAlias that this
506/// matchable came from.
507Record *const TheDef;
508
509// ResInstSize - The size of the resulting instruction for this matchable.
510unsigned ResInstSize;
511
512/// DefRec - This is the definition that it came from.
513PointerUnion<const CodeGenInstruction *, const CodeGenInstAlias *> DefRec;
514
515const CodeGenInstruction *getResultInst() const {
516if (isa<const CodeGenInstruction *>(DefRec))
517return cast<const CodeGenInstruction *>(DefRec);
518return cast<const CodeGenInstAlias *>(DefRec)->ResultInst;
519}
520
521/// ResOperands - This is the operand list that should be built for the result
522/// MCInst.
523SmallVector<ResOperand, 8> ResOperands;
524
525/// Mnemonic - This is the first token of the matched instruction, its
526/// mnemonic.
527StringRef Mnemonic;
528
529/// AsmOperands - The textual operands that this instruction matches,
530/// annotated with a class and where in the OperandList they were defined.
531/// This directly corresponds to the tokenized AsmString after the mnemonic is
532/// removed.
533SmallVector<AsmOperand, 8> AsmOperands;
534
535/// Predicates - The required subtarget features to match this instruction.
536SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
537
538/// ConversionFnKind - The enum value which is passed to the generated
539/// convertToMCInst to convert parsed operands into an MCInst for this
540/// function.
541std::string ConversionFnKind;
542
543/// If this instruction is deprecated in some form.
544bool HasDeprecation = false;
545
546/// If this is an alias, this is use to determine whether or not to using
547/// the conversion function defined by the instruction's AsmMatchConverter
548/// or to use the function generated by the alias.
549bool UseInstAsmMatchConverter;
550
551MatchableInfo(const CodeGenInstruction &CGI)
552: AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef),
553ResInstSize(TheDef->getValueAsInt("Size")), DefRec(&CGI),
554UseInstAsmMatchConverter(true) {}
555
556MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
557: AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
558ResInstSize(Alias->ResultInst->TheDef->getValueAsInt("Size")),
559DefRec(Alias.release()), UseInstAsmMatchConverter(TheDef->getValueAsBit(
560"UseInstAsmMatchConverter")) {}
561
562// Could remove this and the dtor if PointerUnion supported unique_ptr
563// elements with a dynamic failure/assertion (like the one below) in the case
564// where it was copied while being in an owning state.
565MatchableInfo(const MatchableInfo &RHS)
566: AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
567TheDef(RHS.TheDef), ResInstSize(RHS.ResInstSize), DefRec(RHS.DefRec),
568ResOperands(RHS.ResOperands), Mnemonic(RHS.Mnemonic),
569AsmOperands(RHS.AsmOperands), RequiredFeatures(RHS.RequiredFeatures),
570ConversionFnKind(RHS.ConversionFnKind),
571HasDeprecation(RHS.HasDeprecation),
572UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
573assert(!isa<const CodeGenInstAlias *>(DefRec));
574}
575
576~MatchableInfo() {
577delete dyn_cast_if_present<const CodeGenInstAlias *>(DefRec);
578}
579
580// Two-operand aliases clone from the main matchable, but mark the second
581// operand as a tied operand of the first for purposes of the assembler.
582void formTwoOperandAlias(StringRef Constraint);
583
584void initialize(const AsmMatcherInfo &Info,
585SmallPtrSetImpl<Record *> &SingletonRegisters,
586AsmVariantInfo const &Variant, bool HasMnemonicFirst);
587
588/// validate - Return true if this matchable is a valid thing to match against
589/// and perform a bunch of validity checking.
590bool validate(StringRef CommentDelimiter, bool IsAlias) const;
591
592/// findAsmOperand - Find the AsmOperand with the specified name and
593/// suboperand index.
594int findAsmOperand(StringRef N, int SubOpIdx) const {
595auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
596return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
597});
598return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
599}
600
601/// findAsmOperandNamed - Find the first AsmOperand with the specified name.
602/// This does not check the suboperand index.
603int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
604auto I =
605llvm::find_if(llvm::drop_begin(AsmOperands, LastIdx + 1),
606[&](const AsmOperand &Op) { return Op.SrcOpName == N; });
607return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
608}
609
610int findAsmOperandOriginallyNamed(StringRef N) const {
611auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
612return Op.OrigSrcOpName == N;
613});
614return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
615}
616
617void buildInstructionResultOperands();
618void buildAliasResultOperands(bool AliasConstraintsAreChecked);
619
620/// shouldBeMatchedBefore - Compare two matchables for ordering.
621bool shouldBeMatchedBefore(const MatchableInfo &RHS,
622bool PreferSmallerInstructions) const {
623// The primary comparator is the instruction mnemonic.
624if (int Cmp = Mnemonic.compare_insensitive(RHS.Mnemonic))
625return Cmp == -1;
626
627// (Optionally) Order by the resultant instuctions size.
628// eg. for ARM thumb instructions smaller encodings should be preferred.
629if (PreferSmallerInstructions && ResInstSize != RHS.ResInstSize)
630return ResInstSize < RHS.ResInstSize;
631
632if (AsmOperands.size() != RHS.AsmOperands.size())
633return AsmOperands.size() < RHS.AsmOperands.size();
634
635// Compare lexicographically by operand. The matcher validates that other
636// orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
637for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
638if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
639return true;
640if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
641return false;
642}
643
644// For X86 AVX/AVX512 instructions, we prefer vex encoding because the
645// vex encoding size is smaller. Since X86InstrSSE.td is included ahead
646// of X86InstrAVX512.td, the AVX instruction ID is less than AVX512 ID.
647// We use the ID to sort AVX instruction before AVX512 instruction in
648// matching table. As well as InstAlias.
649if (getResultInst()->TheDef->isSubClassOf("Instruction") &&
650getResultInst()->TheDef->getValueAsBit("HasPositionOrder") &&
651RHS.getResultInst()->TheDef->isSubClassOf("Instruction") &&
652RHS.getResultInst()->TheDef->getValueAsBit("HasPositionOrder"))
653return getResultInst()->TheDef->getID() <
654RHS.getResultInst()->TheDef->getID();
655
656// Give matches that require more features higher precedence. This is useful
657// because we cannot define AssemblerPredicates with the negation of
658// processor features. For example, ARM v6 "nop" may be either a HINT or
659// MOV. With v6, we want to match HINT. The assembler has no way to
660// predicate MOV under "NoV6", but HINT will always match first because it
661// requires V6 while MOV does not.
662if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
663return RequiredFeatures.size() > RHS.RequiredFeatures.size();
664
665return false;
666}
667
668/// couldMatchAmbiguouslyWith - Check whether this matchable could
669/// ambiguously match the same set of operands as \p RHS (without being a
670/// strictly superior match).
671bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS,
672bool PreferSmallerInstructions) const {
673// The primary comparator is the instruction mnemonic.
674if (Mnemonic != RHS.Mnemonic)
675return false;
676
677// Different variants can't conflict.
678if (AsmVariantID != RHS.AsmVariantID)
679return false;
680
681// The size of instruction is unambiguous.
682if (PreferSmallerInstructions && ResInstSize != RHS.ResInstSize)
683return false;
684
685// The number of operands is unambiguous.
686if (AsmOperands.size() != RHS.AsmOperands.size())
687return false;
688
689// Otherwise, make sure the ordering of the two instructions is unambiguous
690// by checking that either (a) a token or operand kind discriminates them,
691// or (b) the ordering among equivalent kinds is consistent.
692
693// Tokens and operand kinds are unambiguous (assuming a correct target
694// specific parser).
695for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
696if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
697AsmOperands[i].Class->Kind == ClassInfo::Token)
698if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
699*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
700return false;
701
702// Otherwise, this operand could commute if all operands are equivalent, or
703// there is a pair of operands that compare less than and a pair that
704// compare greater than.
705bool HasLT = false, HasGT = false;
706for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
707if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
708HasLT = true;
709if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
710HasGT = true;
711}
712
713return HasLT == HasGT;
714}
715
716void dump() const;
717
718private:
719void tokenizeAsmString(AsmMatcherInfo const &Info,
720AsmVariantInfo const &Variant);
721void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
722};
723
724struct OperandMatchEntry {
725unsigned OperandMask;
726const MatchableInfo *MI;
727ClassInfo *CI;
728
729static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
730unsigned opMask) {
731OperandMatchEntry X;
732X.OperandMask = opMask;
733X.CI = ci;
734X.MI = mi;
735return X;
736}
737};
738
739class AsmMatcherInfo {
740public:
741/// Tracked Records
742RecordKeeper &Records;
743
744/// The tablegen AsmParser record.
745Record *AsmParser;
746
747/// Target - The target information.
748CodeGenTarget &Target;
749
750/// The classes which are needed for matching.
751std::forward_list<ClassInfo> Classes;
752
753/// The information on the matchables to match.
754std::vector<std::unique_ptr<MatchableInfo>> Matchables;
755
756/// Info for custom matching operands by user defined methods.
757std::vector<OperandMatchEntry> OperandMatchInfo;
758
759/// Map of Register records to their class information.
760typedef std::map<Record *, ClassInfo *, LessRecordByID> RegisterClassesTy;
761RegisterClassesTy RegisterClasses;
762
763/// Map of Predicate records to their subtarget information.
764std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
765
766/// Map of AsmOperandClass records to their class information.
767std::map<Record *, ClassInfo *> AsmOperandClasses;
768
769/// Map of RegisterClass records to their class information.
770std::map<Record *, ClassInfo *> RegisterClassClasses;
771
772private:
773/// Map of token to class information which has already been constructed.
774std::map<std::string, ClassInfo *> TokenClasses;
775
776private:
777/// getTokenClass - Lookup or create the class for the given token.
778ClassInfo *getTokenClass(StringRef Token);
779
780/// getOperandClass - Lookup or create the class for the given operand.
781ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
782int SubOpIdx);
783ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
784
785/// buildRegisterClasses - Build the ClassInfo* instances for register
786/// classes.
787void buildRegisterClasses(SmallPtrSetImpl<Record *> &SingletonRegisters);
788
789/// buildOperandClasses - Build the ClassInfo* instances for user defined
790/// operand classes.
791void buildOperandClasses();
792
793void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
794unsigned AsmOpIdx);
795void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
796MatchableInfo::AsmOperand &Op);
797
798public:
799AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target,
800RecordKeeper &Records);
801
802/// Construct the various tables used during matching.
803void buildInfo();
804
805/// buildOperandMatchInfo - Build the necessary information to handle user
806/// defined operand parsing methods.
807void buildOperandMatchInfo();
808
809/// getSubtargetFeature - Lookup or create the subtarget feature info for the
810/// given operand.
811const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
812assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
813const auto &I = SubtargetFeatures.find(Def);
814return I == SubtargetFeatures.end() ? nullptr : &I->second;
815}
816
817RecordKeeper &getRecords() const { return Records; }
818
819bool hasOptionalOperands() const {
820return any_of(Classes,
821[](const ClassInfo &Class) { return Class.IsOptional; });
822}
823};
824
825} // end anonymous namespace
826
827#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
828LLVM_DUMP_METHOD void MatchableInfo::dump() const {
829errs() << TheDef->getName() << " -- "
830<< "flattened:\"" << AsmString << "\"\n";
831
832errs() << " variant: " << AsmVariantID << "\n";
833
834for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
835const AsmOperand &Op = AsmOperands[i];
836errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
837errs() << '\"' << Op.Token << "\"\n";
838}
839}
840#endif
841
842static std::pair<StringRef, StringRef>
843parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
844// Split via the '='.
845std::pair<StringRef, StringRef> Ops = S.split('=');
846if (Ops.second == "")
847PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
848// Trim whitespace and the leading '$' on the operand names.
849size_t start = Ops.first.find_first_of('$');
850if (start == std::string::npos)
851PrintFatalError(Loc, "expected '$' prefix on asm operand name");
852Ops.first = Ops.first.slice(start + 1, std::string::npos);
853size_t end = Ops.first.find_last_of(" \t");
854Ops.first = Ops.first.slice(0, end);
855// Now the second operand.
856start = Ops.second.find_first_of('$');
857if (start == std::string::npos)
858PrintFatalError(Loc, "expected '$' prefix on asm operand name");
859Ops.second = Ops.second.slice(start + 1, std::string::npos);
860end = Ops.second.find_last_of(" \t");
861Ops.first = Ops.first.slice(0, end);
862return Ops;
863}
864
865void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
866// Figure out which operands are aliased and mark them as tied.
867std::pair<StringRef, StringRef> Ops =
868parseTwoOperandConstraint(Constraint, TheDef->getLoc());
869
870// Find the AsmOperands that refer to the operands we're aliasing.
871int SrcAsmOperand = findAsmOperandNamed(Ops.first);
872int DstAsmOperand = findAsmOperandNamed(Ops.second);
873if (SrcAsmOperand == -1)
874PrintFatalError(TheDef->getLoc(),
875"unknown source two-operand alias operand '" + Ops.first +
876"'.");
877if (DstAsmOperand == -1)
878PrintFatalError(TheDef->getLoc(),
879"unknown destination two-operand alias operand '" +
880Ops.second + "'.");
881
882// Find the ResOperand that refers to the operand we're aliasing away
883// and update it to refer to the combined operand instead.
884for (ResOperand &Op : ResOperands) {
885if (Op.Kind == ResOperand::RenderAsmOperand &&
886Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
887Op.AsmOperandNum = DstAsmOperand;
888break;
889}
890}
891// Remove the AsmOperand for the alias operand.
892AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
893// Adjust the ResOperand references to any AsmOperands that followed
894// the one we just deleted.
895for (ResOperand &Op : ResOperands) {
896switch (Op.Kind) {
897default:
898// Nothing to do for operands that don't reference AsmOperands.
899break;
900case ResOperand::RenderAsmOperand:
901if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
902--Op.AsmOperandNum;
903break;
904}
905}
906}
907
908/// extractSingletonRegisterForAsmOperand - Extract singleton register,
909/// if present, from specified token.
910static void extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
911const AsmMatcherInfo &Info,
912StringRef RegisterPrefix) {
913StringRef Tok = Op.Token;
914
915// If this token is not an isolated token, i.e., it isn't separated from
916// other tokens (e.g. with whitespace), don't interpret it as a register name.
917if (!Op.IsIsolatedToken)
918return;
919
920if (RegisterPrefix.empty()) {
921std::string LoweredTok = Tok.lower();
922if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
923Op.SingletonReg = Reg->TheDef;
924return;
925}
926
927if (!Tok.starts_with(RegisterPrefix))
928return;
929
930StringRef RegName = Tok.substr(RegisterPrefix.size());
931if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
932Op.SingletonReg = Reg->TheDef;
933
934// If there is no register prefix (i.e. "%" in "%eax"), then this may
935// be some random non-register token, just ignore it.
936}
937
938void MatchableInfo::initialize(const AsmMatcherInfo &Info,
939SmallPtrSetImpl<Record *> &SingletonRegisters,
940AsmVariantInfo const &Variant,
941bool HasMnemonicFirst) {
942AsmVariantID = Variant.AsmVariantNo;
943AsmString = CodeGenInstruction::FlattenAsmStringVariants(
944AsmString, Variant.AsmVariantNo);
945
946tokenizeAsmString(Info, Variant);
947
948// The first token of the instruction is the mnemonic, which must be a
949// simple string, not a $foo variable or a singleton register.
950if (AsmOperands.empty())
951PrintFatalError(TheDef->getLoc(),
952"Instruction '" + TheDef->getName() + "' has no tokens");
953
954assert(!AsmOperands[0].Token.empty());
955if (HasMnemonicFirst) {
956Mnemonic = AsmOperands[0].Token;
957if (Mnemonic[0] == '$')
958PrintFatalError(TheDef->getLoc(),
959"Invalid instruction mnemonic '" + Mnemonic + "'!");
960
961// Remove the first operand, it is tracked in the mnemonic field.
962AsmOperands.erase(AsmOperands.begin());
963} else if (AsmOperands[0].Token[0] != '$')
964Mnemonic = AsmOperands[0].Token;
965
966// Compute the require features.
967for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
968if (const SubtargetFeatureInfo *Feature =
969Info.getSubtargetFeature(Predicate))
970RequiredFeatures.push_back(Feature);
971
972// Collect singleton registers, if used.
973for (MatchableInfo::AsmOperand &Op : AsmOperands) {
974extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
975if (Record *Reg = Op.SingletonReg)
976SingletonRegisters.insert(Reg);
977}
978
979const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
980if (!DepMask)
981DepMask = TheDef->getValue("ComplexDeprecationPredicate");
982
983HasDeprecation =
984DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
985}
986
987/// Append an AsmOperand for the given substring of AsmString.
988void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
989AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
990}
991
992/// tokenizeAsmString - Tokenize a simplified assembly string.
993void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
994AsmVariantInfo const &Variant) {
995StringRef String = AsmString;
996size_t Prev = 0;
997bool InTok = false;
998bool IsIsolatedToken = true;
999for (size_t i = 0, e = String.size(); i != e; ++i) {
1000char Char = String[i];
1001if (Variant.BreakCharacters.contains(Char)) {
1002if (InTok) {
1003addAsmOperand(String.slice(Prev, i), false);
1004Prev = i;
1005IsIsolatedToken = false;
1006}
1007InTok = true;
1008continue;
1009}
1010if (Variant.TokenizingCharacters.contains(Char)) {
1011if (InTok) {
1012addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1013InTok = false;
1014IsIsolatedToken = false;
1015}
1016addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1017Prev = i + 1;
1018IsIsolatedToken = true;
1019continue;
1020}
1021if (Variant.SeparatorCharacters.contains(Char)) {
1022if (InTok) {
1023addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1024InTok = false;
1025}
1026Prev = i + 1;
1027IsIsolatedToken = true;
1028continue;
1029}
1030
1031switch (Char) {
1032case '\\':
1033if (InTok) {
1034addAsmOperand(String.slice(Prev, i), false);
1035InTok = false;
1036IsIsolatedToken = false;
1037}
1038++i;
1039assert(i != String.size() && "Invalid quoted character");
1040addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1041Prev = i + 1;
1042IsIsolatedToken = false;
1043break;
1044
1045case '$': {
1046if (InTok) {
1047addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
1048InTok = false;
1049IsIsolatedToken = false;
1050}
1051
1052// If this isn't "${", start new identifier looking like "$xxx"
1053if (i + 1 == String.size() || String[i + 1] != '{') {
1054Prev = i;
1055break;
1056}
1057
1058size_t EndPos = String.find('}', i);
1059assert(EndPos != StringRef::npos &&
1060"Missing brace in operand reference!");
1061addAsmOperand(String.slice(i, EndPos + 1), IsIsolatedToken);
1062Prev = EndPos + 1;
1063i = EndPos;
1064IsIsolatedToken = false;
1065break;
1066}
1067
1068default:
1069InTok = true;
1070break;
1071}
1072}
1073if (InTok && Prev != String.size())
1074addAsmOperand(String.substr(Prev), IsIsolatedToken);
1075}
1076
1077bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
1078// Reject matchables with no .s string.
1079if (AsmString.empty())
1080PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
1081
1082// Reject any matchables with a newline in them, they should be marked
1083// isCodeGenOnly if they are pseudo instructions.
1084if (AsmString.find('\n') != std::string::npos)
1085PrintFatalError(TheDef->getLoc(),
1086"multiline instruction is not valid for the asmparser, "
1087"mark it isCodeGenOnly");
1088
1089// Remove comments from the asm string. We know that the asmstring only
1090// has one line.
1091if (!CommentDelimiter.empty() &&
1092StringRef(AsmString).contains(CommentDelimiter))
1093PrintFatalError(TheDef->getLoc(),
1094"asmstring for instruction has comment character in it, "
1095"mark it isCodeGenOnly");
1096
1097// Reject matchables with operand modifiers, these aren't something we can
1098// handle, the target should be refactored to use operands instead of
1099// modifiers.
1100//
1101// Also, check for instructions which reference the operand multiple times,
1102// if they don't define a custom AsmMatcher: this implies a constraint that
1103// the built-in matching code would not honor.
1104std::set<std::string> OperandNames;
1105for (const AsmOperand &Op : AsmOperands) {
1106StringRef Tok = Op.Token;
1107if (Tok[0] == '$' && Tok.contains(':'))
1108PrintFatalError(
1109TheDef->getLoc(),
1110"matchable with operand modifier '" + Tok +
1111"' not supported by asm matcher. Mark isCodeGenOnly!");
1112// Verify that any operand is only mentioned once.
1113// We reject aliases and ignore instructions for now.
1114if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
1115Tok[0] == '$' && !OperandNames.insert(std::string(Tok)).second) {
1116LLVM_DEBUG({
1117errs() << "warning: '" << TheDef->getName() << "': "
1118<< "ignoring instruction with tied operand '" << Tok << "'\n";
1119});
1120return false;
1121}
1122}
1123
1124return true;
1125}
1126
1127static std::string getEnumNameForToken(StringRef Str) {
1128std::string Res;
1129
1130for (char C : Str) {
1131switch (C) {
1132case '*':
1133Res += "_STAR_";
1134break;
1135case '%':
1136Res += "_PCT_";
1137break;
1138case ':':
1139Res += "_COLON_";
1140break;
1141case '!':
1142Res += "_EXCLAIM_";
1143break;
1144case '.':
1145Res += "_DOT_";
1146break;
1147case '<':
1148Res += "_LT_";
1149break;
1150case '>':
1151Res += "_GT_";
1152break;
1153case '-':
1154Res += "_MINUS_";
1155break;
1156case '#':
1157Res += "_HASH_";
1158break;
1159default:
1160if (isAlnum(C))
1161Res += C;
1162else
1163Res += "_" + utostr((unsigned)C) + "_";
1164}
1165}
1166
1167return Res;
1168}
1169
1170ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
1171ClassInfo *&Entry = TokenClasses[std::string(Token)];
1172
1173if (!Entry) {
1174Classes.emplace_front();
1175Entry = &Classes.front();
1176Entry->Kind = ClassInfo::Token;
1177Entry->ClassName = "Token";
1178Entry->Name = "MCK_" + getEnumNameForToken(Token);
1179Entry->ValueName = std::string(Token);
1180Entry->PredicateMethod = "<invalid>";
1181Entry->RenderMethod = "<invalid>";
1182Entry->ParserMethod = "";
1183Entry->DiagnosticType = "";
1184Entry->IsOptional = false;
1185Entry->DefaultMethod = "<invalid>";
1186}
1187
1188return Entry;
1189}
1190
1191ClassInfo *
1192AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1193int SubOpIdx) {
1194Record *Rec = OI.Rec;
1195if (SubOpIdx != -1)
1196Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1197return getOperandClass(Rec, SubOpIdx);
1198}
1199
1200ClassInfo *AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1201if (Rec->isSubClassOf("RegisterOperand")) {
1202// RegisterOperand may have an associated ParserMatchClass. If it does,
1203// use it, else just fall back to the underlying register class.
1204const RecordVal *R = Rec->getValue("ParserMatchClass");
1205if (!R || !R->getValue())
1206PrintFatalError(Rec->getLoc(),
1207"Record `" + Rec->getName() +
1208"' does not have a ParserMatchClass!\n");
1209
1210if (DefInit *DI = dyn_cast<DefInit>(R->getValue())) {
1211Record *MatchClass = DI->getDef();
1212if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1213return CI;
1214}
1215
1216// No custom match class. Just use the register class.
1217Record *ClassRec = Rec->getValueAsDef("RegClass");
1218if (!ClassRec)
1219PrintFatalError(Rec->getLoc(),
1220"RegisterOperand `" + Rec->getName() +
1221"' has no associated register class!\n");
1222if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1223return CI;
1224PrintFatalError(Rec->getLoc(), "register class has no class info!");
1225}
1226
1227if (Rec->isSubClassOf("RegisterClass")) {
1228if (ClassInfo *CI = RegisterClassClasses[Rec])
1229return CI;
1230PrintFatalError(Rec->getLoc(), "register class has no class info!");
1231}
1232
1233if (!Rec->isSubClassOf("Operand"))
1234PrintFatalError(Rec->getLoc(),
1235"Operand `" + Rec->getName() +
1236"' does not derive from class Operand!\n");
1237Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1238if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1239return CI;
1240
1241PrintFatalError(Rec->getLoc(), "operand has no match class!");
1242}
1243
1244struct LessRegisterSet {
1245bool operator()(const RegisterSet &LHS, const RegisterSet &RHS) const {
1246// std::set<T> defines its own compariso "operator<", but it
1247// performs a lexicographical comparison by T's innate comparison
1248// for some reason. We don't want non-deterministic pointer
1249// comparisons so use this instead.
1250return std::lexicographical_compare(LHS.begin(), LHS.end(), RHS.begin(),
1251RHS.end(), LessRecordByID());
1252}
1253};
1254
1255void AsmMatcherInfo::buildRegisterClasses(
1256SmallPtrSetImpl<Record *> &SingletonRegisters) {
1257const auto &Registers = Target.getRegBank().getRegisters();
1258auto &RegClassList = Target.getRegBank().getRegClasses();
1259
1260typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1261
1262// The register sets used for matching.
1263RegisterSetSet RegisterSets;
1264
1265// Gather the defined sets.
1266for (const CodeGenRegisterClass &RC : RegClassList)
1267RegisterSets.insert(
1268RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
1269
1270// Add any required singleton sets.
1271for (Record *Rec : SingletonRegisters) {
1272RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1273}
1274
1275// Introduce derived sets where necessary (when a register does not determine
1276// a unique register set class), and build the mapping of registers to the set
1277// they should classify to.
1278std::map<Record *, RegisterSet> RegisterMap;
1279for (const CodeGenRegister &CGR : Registers) {
1280// Compute the intersection of all sets containing this register.
1281RegisterSet ContainingSet;
1282
1283for (const RegisterSet &RS : RegisterSets) {
1284if (!RS.count(CGR.TheDef))
1285continue;
1286
1287if (ContainingSet.empty()) {
1288ContainingSet = RS;
1289continue;
1290}
1291
1292RegisterSet Tmp;
1293std::set_intersection(ContainingSet.begin(), ContainingSet.end(),
1294RS.begin(), RS.end(),
1295std::inserter(Tmp, Tmp.begin()), LessRecordByID());
1296ContainingSet = std::move(Tmp);
1297}
1298
1299if (!ContainingSet.empty()) {
1300RegisterSets.insert(ContainingSet);
1301RegisterMap.insert(std::pair(CGR.TheDef, ContainingSet));
1302}
1303}
1304
1305// Construct the register classes.
1306std::map<RegisterSet, ClassInfo *, LessRegisterSet> RegisterSetClasses;
1307unsigned Index = 0;
1308for (const RegisterSet &RS : RegisterSets) {
1309Classes.emplace_front();
1310ClassInfo *CI = &Classes.front();
1311CI->Kind = ClassInfo::RegisterClass0 + Index;
1312CI->ClassName = "Reg" + utostr(Index);
1313CI->Name = "MCK_Reg" + utostr(Index);
1314CI->ValueName = "";
1315CI->PredicateMethod = ""; // unused
1316CI->RenderMethod = "addRegOperands";
1317CI->Registers = RS;
1318// FIXME: diagnostic type.
1319CI->DiagnosticType = "";
1320CI->IsOptional = false;
1321CI->DefaultMethod = ""; // unused
1322RegisterSetClasses.insert(std::pair(RS, CI));
1323++Index;
1324}
1325
1326// Find the superclasses; we could compute only the subgroup lattice edges,
1327// but there isn't really a point.
1328for (const RegisterSet &RS : RegisterSets) {
1329ClassInfo *CI = RegisterSetClasses[RS];
1330for (const RegisterSet &RS2 : RegisterSets)
1331if (RS != RS2 && std::includes(RS2.begin(), RS2.end(), RS.begin(),
1332RS.end(), LessRecordByID()))
1333CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
1334}
1335
1336// Name the register classes which correspond to a user defined RegisterClass.
1337for (const CodeGenRegisterClass &RC : RegClassList) {
1338// Def will be NULL for non-user defined register classes.
1339Record *Def = RC.getDef();
1340if (!Def)
1341continue;
1342ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1343RC.getOrder().end())];
1344if (CI->ValueName.empty()) {
1345CI->ClassName = RC.getName();
1346CI->Name = "MCK_" + RC.getName();
1347CI->ValueName = RC.getName();
1348} else
1349CI->ValueName = CI->ValueName + "," + RC.getName();
1350
1351Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1352if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1353CI->DiagnosticType = std::string(SI->getValue());
1354
1355Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1356if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1357CI->DiagnosticString = std::string(SI->getValue());
1358
1359// If we have a diagnostic string but the diagnostic type is not specified
1360// explicitly, create an anonymous diagnostic type.
1361if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1362CI->DiagnosticType = RC.getName();
1363
1364RegisterClassClasses.insert(std::pair(Def, CI));
1365}
1366
1367// Populate the map for individual registers.
1368for (auto &It : RegisterMap)
1369RegisterClasses[It.first] = RegisterSetClasses[It.second];
1370
1371// Name the register classes which correspond to singleton registers.
1372for (Record *Rec : SingletonRegisters) {
1373ClassInfo *CI = RegisterClasses[Rec];
1374assert(CI && "Missing singleton register class info!");
1375
1376if (CI->ValueName.empty()) {
1377CI->ClassName = std::string(Rec->getName());
1378CI->Name = "MCK_" + Rec->getName().str();
1379CI->ValueName = std::string(Rec->getName());
1380} else
1381CI->ValueName = CI->ValueName + "," + Rec->getName().str();
1382}
1383}
1384
1385void AsmMatcherInfo::buildOperandClasses() {
1386std::vector<Record *> AsmOperands =
1387Records.getAllDerivedDefinitions("AsmOperandClass");
1388
1389// Pre-populate AsmOperandClasses map.
1390for (Record *Rec : AsmOperands) {
1391Classes.emplace_front();
1392AsmOperandClasses[Rec] = &Classes.front();
1393}
1394
1395unsigned Index = 0;
1396for (Record *Rec : AsmOperands) {
1397ClassInfo *CI = AsmOperandClasses[Rec];
1398CI->Kind = ClassInfo::UserClass0 + Index;
1399
1400ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
1401for (Init *I : Supers->getValues()) {
1402DefInit *DI = dyn_cast<DefInit>(I);
1403if (!DI) {
1404PrintError(Rec->getLoc(), "Invalid super class reference!");
1405continue;
1406}
1407
1408ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1409if (!SC)
1410PrintError(Rec->getLoc(), "Invalid super class reference!");
1411else
1412CI->SuperClasses.push_back(SC);
1413}
1414CI->ClassName = std::string(Rec->getValueAsString("Name"));
1415CI->Name = "MCK_" + CI->ClassName;
1416CI->ValueName = std::string(Rec->getName());
1417
1418// Get or construct the predicate method name.
1419Init *PMName = Rec->getValueInit("PredicateMethod");
1420if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1421CI->PredicateMethod = std::string(SI->getValue());
1422} else {
1423assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1424CI->PredicateMethod = "is" + CI->ClassName;
1425}
1426
1427// Get or construct the render method name.
1428Init *RMName = Rec->getValueInit("RenderMethod");
1429if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1430CI->RenderMethod = std::string(SI->getValue());
1431} else {
1432assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1433CI->RenderMethod = "add" + CI->ClassName + "Operands";
1434}
1435
1436// Get the parse method name or leave it as empty.
1437Init *PRMName = Rec->getValueInit("ParserMethod");
1438if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1439CI->ParserMethod = std::string(SI->getValue());
1440
1441// Get the diagnostic type and string or leave them as empty.
1442Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
1443if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1444CI->DiagnosticType = std::string(SI->getValue());
1445Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1446if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1447CI->DiagnosticString = std::string(SI->getValue());
1448// If we have a DiagnosticString, we need a DiagnosticType for use within
1449// the matcher.
1450if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1451CI->DiagnosticType = CI->ClassName;
1452
1453Init *IsOptional = Rec->getValueInit("IsOptional");
1454if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1455CI->IsOptional = BI->getValue();
1456
1457// Get or construct the default method name.
1458Init *DMName = Rec->getValueInit("DefaultMethod");
1459if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1460CI->DefaultMethod = std::string(SI->getValue());
1461} else {
1462assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1463CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1464}
1465
1466++Index;
1467}
1468}
1469
1470AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target,
1471RecordKeeper &records)
1472: Records(records), AsmParser(asmParser), Target(target) {}
1473
1474/// buildOperandMatchInfo - Build the necessary information to handle user
1475/// defined operand parsing methods.
1476void AsmMatcherInfo::buildOperandMatchInfo() {
1477
1478/// Map containing a mask with all operands indices that can be found for
1479/// that class inside a instruction.
1480typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
1481OpClassMaskTy OpClassMask;
1482
1483bool CallCustomParserForAllOperands =
1484AsmParser->getValueAsBit("CallCustomParserForAllOperands");
1485for (const auto &MI : Matchables) {
1486OpClassMask.clear();
1487
1488// Keep track of all operands of this instructions which belong to the
1489// same class.
1490unsigned NumOptionalOps = 0;
1491for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1492const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
1493if (CallCustomParserForAllOperands || !Op.Class->ParserMethod.empty()) {
1494unsigned &OperandMask = OpClassMask[Op.Class];
1495OperandMask |= maskTrailingOnes<unsigned>(NumOptionalOps + 1)
1496<< (i - NumOptionalOps);
1497}
1498if (Op.Class->IsOptional)
1499++NumOptionalOps;
1500}
1501
1502// Generate operand match info for each mnemonic/operand class pair.
1503for (const auto &OCM : OpClassMask) {
1504unsigned OpMask = OCM.second;
1505ClassInfo *CI = OCM.first;
1506OperandMatchInfo.push_back(
1507OperandMatchEntry::create(MI.get(), CI, OpMask));
1508}
1509}
1510}
1511
1512void AsmMatcherInfo::buildInfo() {
1513// Build information about all of the AssemblerPredicates.
1514const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1515&SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1516SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1517SubtargetFeaturePairs.end());
1518#ifndef NDEBUG
1519for (const auto &Pair : SubtargetFeatures)
1520LLVM_DEBUG(Pair.second.dump());
1521#endif // NDEBUG
1522
1523bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1524bool ReportMultipleNearMisses =
1525AsmParser->getValueAsBit("ReportMultipleNearMisses");
1526
1527// Parse the instructions; we need to do this first so that we can gather the
1528// singleton register classes.
1529SmallPtrSet<Record *, 16> SingletonRegisters;
1530unsigned VariantCount = Target.getAsmParserVariantCount();
1531for (unsigned VC = 0; VC != VariantCount; ++VC) {
1532Record *AsmVariant = Target.getAsmParserVariant(VC);
1533StringRef CommentDelimiter =
1534AsmVariant->getValueAsString("CommentDelimiter");
1535AsmVariantInfo Variant;
1536Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1537Variant.TokenizingCharacters =
1538AsmVariant->getValueAsString("TokenizingCharacters");
1539Variant.SeparatorCharacters =
1540AsmVariant->getValueAsString("SeparatorCharacters");
1541Variant.BreakCharacters = AsmVariant->getValueAsString("BreakCharacters");
1542Variant.Name = AsmVariant->getValueAsString("Name");
1543Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1544
1545for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
1546
1547// If the tblgen -match-prefix option is specified (for tblgen hackers),
1548// filter the set of instructions we consider.
1549if (!StringRef(CGI->TheDef->getName()).starts_with(MatchPrefix))
1550continue;
1551
1552// Ignore "codegen only" instructions.
1553if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
1554continue;
1555
1556// Ignore instructions for different instructions
1557StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
1558if (!V.empty() && V != Variant.Name)
1559continue;
1560
1561auto II = std::make_unique<MatchableInfo>(*CGI);
1562
1563II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1564
1565// Ignore instructions which shouldn't be matched and diagnose invalid
1566// instruction definitions with an error.
1567if (!II->validate(CommentDelimiter, false))
1568continue;
1569
1570Matchables.push_back(std::move(II));
1571}
1572
1573// Parse all of the InstAlias definitions and stick them in the list of
1574// matchables.
1575std::vector<Record *> AllInstAliases =
1576Records.getAllDerivedDefinitions("InstAlias");
1577for (Record *InstAlias : AllInstAliases) {
1578auto Alias = std::make_unique<CodeGenInstAlias>(InstAlias, Target);
1579
1580// If the tblgen -match-prefix option is specified (for tblgen hackers),
1581// filter the set of instruction aliases we consider, based on the target
1582// instruction.
1583if (!StringRef(Alias->ResultInst->TheDef->getName())
1584.starts_with(MatchPrefix))
1585continue;
1586
1587StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
1588if (!V.empty() && V != Variant.Name)
1589continue;
1590
1591auto II = std::make_unique<MatchableInfo>(std::move(Alias));
1592
1593II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1594
1595// Validate the alias definitions.
1596II->validate(CommentDelimiter, true);
1597
1598Matchables.push_back(std::move(II));
1599}
1600}
1601
1602// Build info for the register classes.
1603buildRegisterClasses(SingletonRegisters);
1604
1605// Build info for the user defined assembly operand classes.
1606buildOperandClasses();
1607
1608// Build the information about matchables, now that we have fully formed
1609// classes.
1610std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
1611for (auto &II : Matchables) {
1612// Parse the tokens after the mnemonic.
1613// Note: buildInstructionOperandReference may insert new AsmOperands, so
1614// don't precompute the loop bound.
1615for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1616MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1617StringRef Token = Op.Token;
1618
1619// Check for singleton registers.
1620if (Record *RegRecord = Op.SingletonReg) {
1621Op.Class = RegisterClasses[RegRecord];
1622assert(Op.Class && Op.Class->Registers.size() == 1 &&
1623"Unexpected class for singleton register");
1624continue;
1625}
1626
1627// Check for simple tokens.
1628if (Token[0] != '$') {
1629Op.Class = getTokenClass(Token);
1630continue;
1631}
1632
1633if (Token.size() > 1 && isdigit(Token[1])) {
1634Op.Class = getTokenClass(Token);
1635continue;
1636}
1637
1638// Otherwise this is an operand reference.
1639StringRef OperandName;
1640if (Token[1] == '{')
1641OperandName = Token.substr(2, Token.size() - 3);
1642else
1643OperandName = Token.substr(1);
1644
1645if (isa<const CodeGenInstruction *>(II->DefRec))
1646buildInstructionOperandReference(II.get(), OperandName, i);
1647else
1648buildAliasOperandReference(II.get(), OperandName, Op);
1649}
1650
1651if (isa<const CodeGenInstruction *>(II->DefRec)) {
1652II->buildInstructionResultOperands();
1653// If the instruction has a two-operand alias, build up the
1654// matchable here. We'll add them in bulk at the end to avoid
1655// confusing this loop.
1656StringRef Constraint =
1657II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1658if (Constraint != "") {
1659// Start by making a copy of the original matchable.
1660auto AliasII = std::make_unique<MatchableInfo>(*II);
1661
1662// Adjust it to be a two-operand alias.
1663AliasII->formTwoOperandAlias(Constraint);
1664
1665// Add the alias to the matchables list.
1666NewMatchables.push_back(std::move(AliasII));
1667}
1668} else
1669// FIXME: The tied operands checking is not yet integrated with the
1670// framework for reporting multiple near misses. To prevent invalid
1671// formats from being matched with an alias if a tied-operands check
1672// would otherwise have disallowed it, we just disallow such constructs
1673// in TableGen completely.
1674II->buildAliasResultOperands(!ReportMultipleNearMisses);
1675}
1676if (!NewMatchables.empty())
1677Matchables.insert(Matchables.end(),
1678std::make_move_iterator(NewMatchables.begin()),
1679std::make_move_iterator(NewMatchables.end()));
1680
1681// Process token alias definitions and set up the associated superclass
1682// information.
1683std::vector<Record *> AllTokenAliases =
1684Records.getAllDerivedDefinitions("TokenAlias");
1685for (Record *Rec : AllTokenAliases) {
1686ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1687ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1688if (FromClass == ToClass)
1689PrintFatalError(Rec->getLoc(),
1690"error: Destination value identical to source value.");
1691FromClass->SuperClasses.push_back(ToClass);
1692}
1693
1694// Reorder classes so that classes precede super classes.
1695Classes.sort();
1696
1697#ifdef EXPENSIVE_CHECKS
1698// Verify that the table is sorted and operator < works transitively.
1699for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1700for (auto J = I; J != E; ++J) {
1701assert(!(*J < *I));
1702assert(I == J || !J->isSubsetOf(*I));
1703}
1704}
1705#endif
1706}
1707
1708/// buildInstructionOperandReference - The specified operand is a reference to a
1709/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1710void AsmMatcherInfo::buildInstructionOperandReference(MatchableInfo *II,
1711StringRef OperandName,
1712unsigned AsmOpIdx) {
1713const CodeGenInstruction &CGI = *cast<const CodeGenInstruction *>(II->DefRec);
1714const CGIOperandList &Operands = CGI.Operands;
1715MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1716
1717// Map this token to an operand.
1718unsigned Idx;
1719if (!Operands.hasOperandNamed(OperandName, Idx))
1720PrintFatalError(II->TheDef->getLoc(),
1721"error: unable to find operand: '" + OperandName + "'");
1722
1723// If the instruction operand has multiple suboperands, but the parser
1724// match class for the asm operand is still the default "ImmAsmOperand",
1725// then handle each suboperand separately.
1726if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1727Record *Rec = Operands[Idx].Rec;
1728assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1729Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1730if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1731// Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1732StringRef Token = Op->Token; // save this in case Op gets moved
1733for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1734MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
1735NewAsmOp.SubOpIdx = SI;
1736II->AsmOperands.insert(II->AsmOperands.begin() + AsmOpIdx + SI,
1737NewAsmOp);
1738}
1739// Replace Op with first suboperand.
1740Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1741Op->SubOpIdx = 0;
1742}
1743}
1744
1745// Set up the operand class.
1746Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1747Op->OrigSrcOpName = OperandName;
1748
1749// If the named operand is tied, canonicalize it to the untied operand.
1750// For example, something like:
1751// (outs GPR:$dst), (ins GPR:$src)
1752// with an asmstring of
1753// "inc $src"
1754// we want to canonicalize to:
1755// "inc $dst"
1756// so that we know how to provide the $dst operand when filling in the result.
1757int OITied = -1;
1758if (Operands[Idx].MINumOperands == 1)
1759OITied = Operands[Idx].getTiedRegister();
1760if (OITied != -1) {
1761// The tied operand index is an MIOperand index, find the operand that
1762// contains it.
1763std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1764OperandName = Operands[Idx.first].Name;
1765Op->SubOpIdx = Idx.second;
1766}
1767
1768Op->SrcOpName = OperandName;
1769}
1770
1771/// buildAliasOperandReference - When parsing an operand reference out of the
1772/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1773/// operand reference is by looking it up in the result pattern definition.
1774void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1775StringRef OperandName,
1776MatchableInfo::AsmOperand &Op) {
1777const CodeGenInstAlias &CGA = *cast<const CodeGenInstAlias *>(II->DefRec);
1778
1779// Set up the operand class.
1780for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1781if (CGA.ResultOperands[i].isRecord() &&
1782CGA.ResultOperands[i].getName() == OperandName) {
1783// It's safe to go with the first one we find, because CodeGenInstAlias
1784// validates that all operands with the same name have the same record.
1785Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1786// Use the match class from the Alias definition, not the
1787// destination instruction, as we may have an immediate that's
1788// being munged by the match class.
1789Op.Class =
1790getOperandClass(CGA.ResultOperands[i].getRecord(), Op.SubOpIdx);
1791Op.SrcOpName = OperandName;
1792Op.OrigSrcOpName = OperandName;
1793return;
1794}
1795
1796PrintFatalError(II->TheDef->getLoc(),
1797"error: unable to find operand: '" + OperandName + "'");
1798}
1799
1800void MatchableInfo::buildInstructionResultOperands() {
1801const CodeGenInstruction *ResultInst = getResultInst();
1802
1803// Loop over all operands of the result instruction, determining how to
1804// populate them.
1805for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
1806// If this is a tied operand, just copy from the previously handled operand.
1807int TiedOp = -1;
1808if (OpInfo.MINumOperands == 1)
1809TiedOp = OpInfo.getTiedRegister();
1810if (TiedOp != -1) {
1811int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1812if (TiedSrcOperand != -1 &&
1813ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1814ResOperands.push_back(ResOperand::getTiedOp(
1815TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1816else
1817ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
1818continue;
1819}
1820
1821int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1822if (OpInfo.Name.empty() || SrcOperand == -1) {
1823// This may happen for operands that are tied to a suboperand of a
1824// complex operand. Simply use a dummy value here; nobody should
1825// use this operand slot.
1826// FIXME: The long term goal is for the MCOperand list to not contain
1827// tied operands at all.
1828ResOperands.push_back(ResOperand::getImmOp(0));
1829continue;
1830}
1831
1832// Check if the one AsmOperand populates the entire operand.
1833unsigned NumOperands = OpInfo.MINumOperands;
1834if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1835ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1836continue;
1837}
1838
1839// Add a separate ResOperand for each suboperand.
1840for (unsigned AI = 0; AI < NumOperands; ++AI) {
1841assert(AsmOperands[SrcOperand + AI].SubOpIdx == (int)AI &&
1842AsmOperands[SrcOperand + AI].SrcOpName == OpInfo.Name &&
1843"unexpected AsmOperands for suboperands");
1844ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1845}
1846}
1847}
1848
1849void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
1850const CodeGenInstAlias &CGA = *cast<const CodeGenInstAlias *>(DefRec);
1851const CodeGenInstruction *ResultInst = getResultInst();
1852
1853// Map of: $reg -> #lastref
1854// where $reg is the name of the operand in the asm string
1855// where #lastref is the last processed index where $reg was referenced in
1856// the asm string.
1857SmallDenseMap<StringRef, int> OperandRefs;
1858
1859// Loop over all operands of the result instruction, determining how to
1860// populate them.
1861unsigned AliasOpNo = 0;
1862unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1863for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1864const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1865
1866// If this is a tied operand, just copy from the previously handled operand.
1867int TiedOp = -1;
1868if (OpInfo->MINumOperands == 1)
1869TiedOp = OpInfo->getTiedRegister();
1870if (TiedOp != -1) {
1871unsigned SrcOp1 = 0;
1872unsigned SrcOp2 = 0;
1873
1874// If an operand has been specified twice in the asm string,
1875// add the two source operand's indices to the TiedOp so that
1876// at runtime the 'tied' constraint is checked.
1877if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1878SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1879
1880// Find the next operand (similarly named operand) in the string.
1881StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1882auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1883SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1884
1885// Not updating the record in OperandRefs will cause TableGen
1886// to fail with an error at the end of this function.
1887if (AliasConstraintsAreChecked)
1888Insert.first->second = SrcOp2;
1889
1890// In case it only has one reference in the asm string,
1891// it doesn't need to be checked for tied constraints.
1892SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1893}
1894
1895// If the alias operand is of a different operand class, we only want
1896// to benefit from the tied-operands check and just match the operand
1897// as a normal, but not copy the original (TiedOp) to the result
1898// instruction. We do this by passing -1 as the tied operand to copy.
1899if (ResultInst->Operands[i].Rec->getName() !=
1900ResultInst->Operands[TiedOp].Rec->getName()) {
1901SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1902int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1903StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1904SrcOp2 = findAsmOperand(Name, SubIdx);
1905ResOperands.push_back(
1906ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1907} else {
1908ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1909continue;
1910}
1911}
1912
1913// Handle all the suboperands for this operand.
1914const std::string &OpName = OpInfo->Name;
1915for (; AliasOpNo < LastOpNo &&
1916CGA.ResultInstOperandIndex[AliasOpNo].first == i;
1917++AliasOpNo) {
1918int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1919
1920// Find out what operand from the asmparser that this MCInst operand
1921// comes from.
1922switch (CGA.ResultOperands[AliasOpNo].Kind) {
1923case CodeGenInstAlias::ResultOperand::K_Record: {
1924StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1925int SrcOperand = findAsmOperand(Name, SubIdx);
1926if (SrcOperand == -1)
1927PrintFatalError(TheDef->getLoc(),
1928"Instruction '" + TheDef->getName() +
1929"' has operand '" + OpName +
1930"' that doesn't appear in asm string!");
1931
1932// Add it to the operand references. If it is added a second time, the
1933// record won't be updated and it will fail later on.
1934OperandRefs.try_emplace(Name, SrcOperand);
1935
1936unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1937ResOperands.push_back(
1938ResOperand::getRenderedOp(SrcOperand, NumOperands));
1939break;
1940}
1941case CodeGenInstAlias::ResultOperand::K_Imm: {
1942int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1943ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1944break;
1945}
1946case CodeGenInstAlias::ResultOperand::K_Reg: {
1947Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1948ResOperands.push_back(ResOperand::getRegOp(Reg));
1949break;
1950}
1951}
1952}
1953}
1954
1955// Check that operands are not repeated more times than is supported.
1956for (auto &T : OperandRefs) {
1957if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1958PrintFatalError(TheDef->getLoc(),
1959"Operand '" + T.first + "' can never be matched");
1960}
1961}
1962
1963static unsigned
1964getConverterOperandID(const std::string &Name,
1965SmallSetVector<CachedHashString, 16> &Table,
1966bool &IsNew) {
1967IsNew = Table.insert(CachedHashString(Name));
1968
1969unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
1970
1971assert(ID < Table.size());
1972
1973return ID;
1974}
1975
1976static unsigned
1977emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1978std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1979bool HasMnemonicFirst, bool HasOptionalOperands,
1980raw_ostream &OS) {
1981SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1982SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
1983std::vector<std::vector<uint8_t>> ConversionTable;
1984size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1985
1986// TargetOperandClass - This is the target's operand class, like X86Operand.
1987std::string TargetOperandClass = Target.getName().str() + "Operand";
1988
1989// Write the convert function to a separate stream, so we can drop it after
1990// the enum. We'll build up the conversion handlers for the individual
1991// operand types opportunistically as we encounter them.
1992std::string ConvertFnBody;
1993raw_string_ostream CvtOS(ConvertFnBody);
1994// Start the unified conversion function.
1995if (HasOptionalOperands) {
1996CvtOS << "void " << Target.getName() << ClassName << "::\n"
1997<< "convertToMCInst(unsigned Kind, MCInst &Inst, "
1998<< "unsigned Opcode,\n"
1999<< " const OperandVector &Operands,\n"
2000<< " const SmallBitVector &OptionalOperandsMask,\n"
2001<< " ArrayRef<unsigned> DefaultsOffset) {\n";
2002} else {
2003CvtOS << "void " << Target.getName() << ClassName << "::\n"
2004<< "convertToMCInst(unsigned Kind, MCInst &Inst, "
2005<< "unsigned Opcode,\n"
2006<< " const OperandVector &Operands) {\n";
2007}
2008CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
2009CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
2010CvtOS << " Inst.setOpcode(Opcode);\n";
2011CvtOS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
2012if (HasOptionalOperands) {
2013// When optional operands are involved, formal and actual operand indices
2014// may differ. Map the former to the latter by subtracting the number of
2015// absent optional operands.
2016// FIXME: This is not an operand index in the CVT_Tied case
2017CvtOS << " unsigned OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
2018} else {
2019CvtOS << " unsigned OpIdx = *(p + 1);\n";
2020}
2021CvtOS << " switch (*p) {\n";
2022CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
2023CvtOS << " case CVT_Reg:\n";
2024CvtOS << " static_cast<" << TargetOperandClass
2025<< " &>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
2026CvtOS << " break;\n";
2027CvtOS << " case CVT_Tied: {\n";
2028CvtOS << " assert(*(p + 1) < (size_t)(std::end(TiedAsmOperandTable) -\n";
2029CvtOS
2030<< " std::begin(TiedAsmOperandTable)) &&\n";
2031CvtOS << " \"Tied operand not found\");\n";
2032CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[*(p + 1)][0];\n";
2033CvtOS << " if (TiedResOpnd != (uint8_t)-1)\n";
2034CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
2035CvtOS << " break;\n";
2036CvtOS << " }\n";
2037
2038std::string OperandFnBody;
2039raw_string_ostream OpOS(OperandFnBody);
2040// Start the operand number lookup function.
2041OpOS << "void " << Target.getName() << ClassName << "::\n"
2042<< "convertToMapAndConstraints(unsigned Kind,\n";
2043OpOS.indent(27);
2044OpOS << "const OperandVector &Operands) {\n"
2045<< " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
2046<< " unsigned NumMCOperands = 0;\n"
2047<< " const uint8_t *Converter = ConversionTable[Kind];\n"
2048<< " for (const uint8_t *p = Converter; *p; p += 2) {\n"
2049<< " switch (*p) {\n"
2050<< " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2051<< " case CVT_Reg:\n"
2052<< " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2053<< " Operands[*(p + 1)]->setConstraint(\"r\");\n"
2054<< " ++NumMCOperands;\n"
2055<< " break;\n"
2056<< " case CVT_Tied:\n"
2057<< " ++NumMCOperands;\n"
2058<< " break;\n";
2059
2060// Pre-populate the operand conversion kinds with the standard always
2061// available entries.
2062OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2063OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2064OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
2065enum { CVT_Done, CVT_Reg, CVT_Tied };
2066
2067// Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2068std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
2069TiedOperandsEnumMap;
2070
2071for (auto &II : Infos) {
2072// Check if we have a custom match function.
2073StringRef AsmMatchConverter =
2074II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
2075if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
2076std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
2077II->ConversionFnKind = Signature;
2078
2079// Check if we have already generated this signature.
2080if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2081continue;
2082
2083// Remember this converter for the kind enum.
2084unsigned KindID = OperandConversionKinds.size();
2085OperandConversionKinds.insert(
2086CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
2087
2088// Add the converter row for this instruction.
2089ConversionTable.emplace_back();
2090ConversionTable.back().push_back(KindID);
2091ConversionTable.back().push_back(CVT_Done);
2092
2093// Add the handler to the conversion driver function.
2094CvtOS << " case CVT_" << getEnumNameForToken(AsmMatchConverter)
2095<< ":\n"
2096<< " " << AsmMatchConverter << "(Inst, Operands);\n"
2097<< " break;\n";
2098
2099// FIXME: Handle the operand number lookup for custom match functions.
2100continue;
2101}
2102
2103// Build the conversion function signature.
2104std::string Signature = "Convert";
2105
2106std::vector<uint8_t> ConversionRow;
2107
2108// Compute the convert enum and the case body.
2109MaxRowLength = std::max(MaxRowLength, II->ResOperands.size() * 2 + 1);
2110
2111for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2112const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
2113
2114// Generate code to populate each result operand.
2115switch (OpInfo.Kind) {
2116case MatchableInfo::ResOperand::RenderAsmOperand: {
2117// This comes from something we parsed.
2118const MatchableInfo::AsmOperand &Op =
2119II->AsmOperands[OpInfo.AsmOperandNum];
2120
2121// Registers are always converted the same, don't duplicate the
2122// conversion function based on them.
2123Signature += "__";
2124std::string Class;
2125Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2126Signature += Class;
2127Signature += utostr(OpInfo.MINumOperands);
2128Signature += "_" + itostr(OpInfo.AsmOperandNum);
2129
2130// Add the conversion kind, if necessary, and get the associated ID
2131// the index of its entry in the vector).
2132std::string Name =
2133"CVT_" +
2134(Op.Class->isRegisterClass() ? "Reg" : Op.Class->RenderMethod);
2135if (Op.Class->IsOptional) {
2136// For optional operands we must also care about DefaultMethod
2137assert(HasOptionalOperands);
2138Name += "_" + Op.Class->DefaultMethod;
2139}
2140Name = getEnumNameForToken(Name);
2141
2142bool IsNewConverter = false;
2143unsigned ID =
2144getConverterOperandID(Name, OperandConversionKinds, IsNewConverter);
2145
2146// Add the operand entry to the instruction kind conversion row.
2147ConversionRow.push_back(ID);
2148ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
2149
2150if (!IsNewConverter)
2151break;
2152
2153// This is a new operand kind. Add a handler for it to the
2154// converter driver.
2155CvtOS << " case " << Name << ":\n";
2156if (Op.Class->IsOptional) {
2157// If optional operand is not present in actual instruction then we
2158// should call its DefaultMethod before RenderMethod
2159assert(HasOptionalOperands);
2160CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2161<< " " << Op.Class->DefaultMethod << "()"
2162<< "->" << Op.Class->RenderMethod << "(Inst, "
2163<< OpInfo.MINumOperands << ");\n"
2164<< " } else {\n"
2165<< " static_cast<" << TargetOperandClass
2166<< " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2167<< "(Inst, " << OpInfo.MINumOperands << ");\n"
2168<< " }\n";
2169} else {
2170CvtOS << " static_cast<" << TargetOperandClass
2171<< " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
2172<< "(Inst, " << OpInfo.MINumOperands << ");\n";
2173}
2174CvtOS << " break;\n";
2175
2176// Add a handler for the operand number lookup.
2177OpOS << " case " << Name << ":\n"
2178<< " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2179
2180if (Op.Class->isRegisterClass())
2181OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2182else
2183OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2184OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
2185<< " break;\n";
2186break;
2187}
2188case MatchableInfo::ResOperand::TiedOperand: {
2189// If this operand is tied to a previous one, just copy the MCInst
2190// operand from the earlier one.We can only tie single MCOperand values.
2191assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
2192uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
2193uint8_t SrcOp1 = OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2194uint8_t SrcOp2 = OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
2195assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
2196"Tied operand precedes its target!");
2197auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2198utostr(SrcOp1) + '_' + utostr(SrcOp2);
2199Signature += "__" + TiedTupleName;
2200ConversionRow.push_back(CVT_Tied);
2201ConversionRow.push_back(TiedOp);
2202ConversionRow.push_back(SrcOp1);
2203ConversionRow.push_back(SrcOp2);
2204
2205// Also create an 'enum' for this combination of tied operands.
2206auto Key = std::tuple(TiedOp, SrcOp1, SrcOp2);
2207TiedOperandsEnumMap.emplace(Key, TiedTupleName);
2208break;
2209}
2210case MatchableInfo::ResOperand::ImmOperand: {
2211int64_t Val = OpInfo.ImmVal;
2212std::string Ty = "imm_" + itostr(Val);
2213Ty = getEnumNameForToken(Ty);
2214Signature += "__" + Ty;
2215
2216std::string Name = "CVT_" + Ty;
2217bool IsNewConverter = false;
2218unsigned ID =
2219getConverterOperandID(Name, OperandConversionKinds, IsNewConverter);
2220// Add the operand entry to the instruction kind conversion row.
2221ConversionRow.push_back(ID);
2222ConversionRow.push_back(0);
2223
2224if (!IsNewConverter)
2225break;
2226
2227CvtOS << " case " << Name << ":\n"
2228<< " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
2229<< " break;\n";
2230
2231OpOS << " case " << Name << ":\n"
2232<< " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2233<< " Operands[*(p + 1)]->setConstraint(\"\");\n"
2234<< " ++NumMCOperands;\n"
2235<< " break;\n";
2236break;
2237}
2238case MatchableInfo::ResOperand::RegOperand: {
2239std::string Reg, Name;
2240if (!OpInfo.Register) {
2241Name = "reg0";
2242Reg = "0";
2243} else {
2244Reg = getQualifiedName(OpInfo.Register);
2245Name = "reg" + OpInfo.Register->getName().str();
2246}
2247Signature += "__" + Name;
2248Name = "CVT_" + Name;
2249bool IsNewConverter = false;
2250unsigned ID =
2251getConverterOperandID(Name, OperandConversionKinds, IsNewConverter);
2252// Add the operand entry to the instruction kind conversion row.
2253ConversionRow.push_back(ID);
2254ConversionRow.push_back(0);
2255
2256if (!IsNewConverter)
2257break;
2258CvtOS << " case " << Name << ":\n"
2259<< " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
2260<< " break;\n";
2261
2262OpOS << " case " << Name << ":\n"
2263<< " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2264<< " Operands[*(p + 1)]->setConstraint(\"m\");\n"
2265<< " ++NumMCOperands;\n"
2266<< " break;\n";
2267}
2268}
2269}
2270
2271// If there were no operands, add to the signature to that effect
2272if (Signature == "Convert")
2273Signature += "_NoOperands";
2274
2275II->ConversionFnKind = Signature;
2276
2277// Save the signature. If we already have it, don't add a new row
2278// to the table.
2279if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2280continue;
2281
2282// Add the row to the table.
2283ConversionTable.push_back(std::move(ConversionRow));
2284}
2285
2286// Finish up the converter driver function.
2287CvtOS << " }\n }\n}\n\n";
2288
2289// Finish up the operand number lookup function.
2290OpOS << " }\n }\n}\n\n";
2291
2292// Output a static table for tied operands.
2293if (TiedOperandsEnumMap.size()) {
2294// The number of tied operand combinations will be small in practice,
2295// but just add the assert to be sure.
2296assert(TiedOperandsEnumMap.size() <= 254 &&
2297"Too many tied-operand combinations to reference with "
2298"an 8bit offset from the conversion table, where index "
2299"'255' is reserved as operand not to be copied.");
2300
2301OS << "enum {\n";
2302for (auto &KV : TiedOperandsEnumMap) {
2303OS << " " << KV.second << ",\n";
2304}
2305OS << "};\n\n";
2306
2307OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
2308for (auto &KV : TiedOperandsEnumMap) {
2309OS << " /* " << KV.second << " */ { " << utostr(std::get<0>(KV.first))
2310<< ", " << utostr(std::get<1>(KV.first)) << ", "
2311<< utostr(std::get<2>(KV.first)) << " },\n";
2312}
2313OS << "};\n\n";
2314} else
2315OS << "static const uint8_t TiedAsmOperandTable[][3] = "
2316"{ /* empty */ {0, 0, 0} };\n\n";
2317
2318OS << "namespace {\n";
2319
2320// Output the operand conversion kind enum.
2321OS << "enum OperatorConversionKind {\n";
2322for (const auto &Converter : OperandConversionKinds)
2323OS << " " << Converter << ",\n";
2324OS << " CVT_NUM_CONVERTERS\n";
2325OS << "};\n\n";
2326
2327// Output the instruction conversion kind enum.
2328OS << "enum InstructionConversionKind {\n";
2329for (const auto &Signature : InstructionConversionKinds)
2330OS << " " << Signature << ",\n";
2331OS << " CVT_NUM_SIGNATURES\n";
2332OS << "};\n\n";
2333
2334OS << "} // end anonymous namespace\n\n";
2335
2336// Output the conversion table.
2337OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2338<< MaxRowLength << "] = {\n";
2339
2340for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2341assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2342OS << " // " << InstructionConversionKinds[Row] << "\n";
2343OS << " { ";
2344for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2345OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2346if (OperandConversionKinds[ConversionTable[Row][i]] !=
2347CachedHashString("CVT_Tied")) {
2348OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2349continue;
2350}
2351
2352// For a tied operand, emit a reference to the TiedAsmOperandTable
2353// that contains the operand to copy, and the parsed operands to
2354// check for their tied constraints.
2355auto Key = std::tuple((uint8_t)ConversionTable[Row][i + 1],
2356(uint8_t)ConversionTable[Row][i + 2],
2357(uint8_t)ConversionTable[Row][i + 3]);
2358auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2359assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2360"No record for tied operand pair");
2361OS << TiedOpndEnum->second << ", ";
2362i += 2;
2363}
2364OS << "CVT_Done },\n";
2365}
2366
2367OS << "};\n\n";
2368
2369// Spit out the conversion driver function.
2370OS << ConvertFnBody;
2371
2372// Spit out the operand number lookup function.
2373OS << OperandFnBody;
2374
2375return ConversionTable.size();
2376}
2377
2378/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2379static void emitMatchClassEnumeration(CodeGenTarget &Target,
2380std::forward_list<ClassInfo> &Infos,
2381raw_ostream &OS) {
2382OS << "namespace {\n\n";
2383
2384OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2385<< "/// instruction matching.\n";
2386OS << "enum MatchClassKind {\n";
2387OS << " InvalidMatchClass = 0,\n";
2388OS << " OptionalMatchClass = 1,\n";
2389ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2390StringRef LastName = "OptionalMatchClass";
2391for (const auto &CI : Infos) {
2392if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2393OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2394} else if (LastKind < ClassInfo::UserClass0 &&
2395CI.Kind >= ClassInfo::UserClass0) {
2396OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2397}
2398LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2399LastName = CI.Name;
2400
2401OS << " " << CI.Name << ", // ";
2402if (CI.Kind == ClassInfo::Token) {
2403OS << "'" << CI.ValueName << "'\n";
2404} else if (CI.isRegisterClass()) {
2405if (!CI.ValueName.empty())
2406OS << "register class '" << CI.ValueName << "'\n";
2407else
2408OS << "derived register class\n";
2409} else {
2410OS << "user defined class '" << CI.ValueName << "'\n";
2411}
2412}
2413OS << " NumMatchClassKinds\n";
2414OS << "};\n\n";
2415
2416OS << "} // end anonymous namespace\n\n";
2417}
2418
2419/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2420/// used when an assembly operand does not match the expected operand class.
2421static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info,
2422raw_ostream &OS) {
2423// If the target does not use DiagnosticString for any operands, don't emit
2424// an unused function.
2425if (llvm::all_of(Info.Classes, [](const ClassInfo &CI) {
2426return CI.DiagnosticString.empty();
2427}))
2428return;
2429
2430OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2431<< "AsmParser::" << Info.Target.getName()
2432<< "MatchResultTy MatchResult) {\n";
2433OS << " switch (MatchResult) {\n";
2434
2435for (const auto &CI : Info.Classes) {
2436if (!CI.DiagnosticString.empty()) {
2437assert(!CI.DiagnosticType.empty() &&
2438"DiagnosticString set without DiagnosticType");
2439OS << " case " << Info.Target.getName() << "AsmParser::Match_"
2440<< CI.DiagnosticType << ":\n";
2441OS << " return \"" << CI.DiagnosticString << "\";\n";
2442}
2443}
2444
2445OS << " default:\n";
2446OS << " return nullptr;\n";
2447
2448OS << " }\n";
2449OS << "}\n\n";
2450}
2451
2452static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2453OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2454"RegisterClass) {\n";
2455if (none_of(Info.Classes, [](const ClassInfo &CI) {
2456return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2457})) {
2458OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2459} else {
2460OS << " switch (RegisterClass) {\n";
2461for (const auto &CI : Info.Classes) {
2462if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2463OS << " case " << CI.Name << ":\n";
2464OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2465<< CI.DiagnosticType << ";\n";
2466}
2467}
2468
2469OS << " default:\n";
2470OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2471
2472OS << " }\n";
2473}
2474OS << "}\n\n";
2475}
2476
2477/// emitValidateOperandClass - Emit the function to validate an operand class.
2478static void emitValidateOperandClass(AsmMatcherInfo &Info, raw_ostream &OS) {
2479OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2480<< "MatchClassKind Kind) {\n";
2481OS << " " << Info.Target.getName() << "Operand &Operand = ("
2482<< Info.Target.getName() << "Operand &)GOp;\n";
2483
2484// The InvalidMatchClass is not to match any operand.
2485OS << " if (Kind == InvalidMatchClass)\n";
2486OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2487
2488// Check for Token operands first.
2489// FIXME: Use a more specific diagnostic type.
2490OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
2491OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2492<< " MCTargetAsmParser::Match_Success :\n"
2493<< " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2494
2495// Check the user classes. We don't care what order since we're only
2496// actually matching against one of them.
2497OS << " switch (Kind) {\n"
2498" default: break;\n";
2499for (const auto &CI : Info.Classes) {
2500if (!CI.isUserClass())
2501continue;
2502
2503OS << " // '" << CI.ClassName << "' class\n";
2504OS << " case " << CI.Name << ": {\n";
2505OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2506<< "());\n";
2507OS << " if (DP.isMatch())\n";
2508OS << " return MCTargetAsmParser::Match_Success;\n";
2509if (!CI.DiagnosticType.empty()) {
2510OS << " if (DP.isNearMatch())\n";
2511OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2512<< CI.DiagnosticType << ";\n";
2513OS << " break;\n";
2514} else
2515OS << " break;\n";
2516OS << " }\n";
2517}
2518OS << " } // end switch (Kind)\n\n";
2519
2520// Check for register operands, including sub-classes.
2521OS << " if (Operand.isReg()) {\n";
2522OS << " MatchClassKind OpKind;\n";
2523OS << " switch (Operand.getReg().id()) {\n";
2524OS << " default: OpKind = InvalidMatchClass; break;\n";
2525for (const auto &RC : Info.RegisterClasses)
2526OS << " case " << RC.first->getValueAsString("Namespace")
2527<< "::" << RC.first->getName() << ": OpKind = " << RC.second->Name
2528<< "; break;\n";
2529OS << " }\n";
2530OS << " return isSubclass(OpKind, Kind) ? "
2531<< "(unsigned)MCTargetAsmParser::Match_Success :\n "
2532<< " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2533
2534// Expected operand is a register, but actual is not.
2535OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2536OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
2537
2538// Generic fallthrough match failure case for operands that don't have
2539// specialized diagnostic types.
2540OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2541OS << "}\n\n";
2542}
2543
2544/// emitIsSubclass - Emit the subclass predicate function.
2545static void emitIsSubclass(CodeGenTarget &Target,
2546std::forward_list<ClassInfo> &Infos,
2547raw_ostream &OS) {
2548OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2549OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2550OS << " if (A == B)\n";
2551OS << " return true;\n\n";
2552
2553bool EmittedSwitch = false;
2554for (const auto &A : Infos) {
2555std::vector<StringRef> SuperClasses;
2556if (A.IsOptional)
2557SuperClasses.push_back("OptionalMatchClass");
2558for (const auto &B : Infos) {
2559if (&A != &B && A.isSubsetOf(B))
2560SuperClasses.push_back(B.Name);
2561}
2562
2563if (SuperClasses.empty())
2564continue;
2565
2566// If this is the first SuperClass, emit the switch header.
2567if (!EmittedSwitch) {
2568OS << " switch (A) {\n";
2569OS << " default:\n";
2570OS << " return false;\n";
2571EmittedSwitch = true;
2572}
2573
2574OS << "\n case " << A.Name << ":\n";
2575
2576if (SuperClasses.size() == 1) {
2577OS << " return B == " << SuperClasses.back() << ";\n";
2578continue;
2579}
2580
2581if (!SuperClasses.empty()) {
2582OS << " switch (B) {\n";
2583OS << " default: return false;\n";
2584for (StringRef SC : SuperClasses)
2585OS << " case " << SC << ": return true;\n";
2586OS << " }\n";
2587} else {
2588// No case statement to emit
2589OS << " return false;\n";
2590}
2591}
2592
2593// If there were case statements emitted into the string stream write the
2594// default.
2595if (EmittedSwitch)
2596OS << " }\n";
2597else
2598OS << " return false;\n";
2599
2600OS << "}\n\n";
2601}
2602
2603/// emitMatchTokenString - Emit the function to match a token string to the
2604/// appropriate match class value.
2605static void emitMatchTokenString(CodeGenTarget &Target,
2606std::forward_list<ClassInfo> &Infos,
2607raw_ostream &OS) {
2608// Construct the match list.
2609std::vector<StringMatcher::StringPair> Matches;
2610for (const auto &CI : Infos) {
2611if (CI.Kind == ClassInfo::Token)
2612Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
2613}
2614
2615OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2616
2617StringMatcher("Name", Matches, OS).Emit();
2618
2619OS << " return InvalidMatchClass;\n";
2620OS << "}\n\n";
2621}
2622
2623/// emitMatchRegisterName - Emit the function to match a string to the target
2624/// specific register enum.
2625static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2626raw_ostream &OS) {
2627// Construct the match list.
2628std::vector<StringMatcher::StringPair> Matches;
2629const auto &Regs = Target.getRegBank().getRegisters();
2630std::string Namespace =
2631Regs.front().TheDef->getValueAsString("Namespace").str();
2632for (const CodeGenRegister &Reg : Regs) {
2633StringRef AsmName = Reg.TheDef->getValueAsString("AsmName");
2634if (AsmName.empty())
2635continue;
2636
2637Matches.emplace_back(AsmName.str(), "return " + Namespace +
2638"::" + Reg.getName().str() + ';');
2639}
2640
2641OS << "static MCRegister MatchRegisterName(StringRef Name) {\n";
2642
2643bool IgnoreDuplicates =
2644AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2645StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2646
2647OS << " return " << Namespace << "::NoRegister;\n";
2648OS << "}\n\n";
2649}
2650
2651/// Emit the function to match a string to the target
2652/// specific register enum.
2653static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2654raw_ostream &OS) {
2655// Construct the match list.
2656std::vector<StringMatcher::StringPair> Matches;
2657const auto &Regs = Target.getRegBank().getRegisters();
2658std::string Namespace =
2659Regs.front().TheDef->getValueAsString("Namespace").str();
2660for (const CodeGenRegister &Reg : Regs) {
2661
2662auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2663
2664for (auto AltName : AltNames) {
2665AltName = StringRef(AltName).trim();
2666
2667// don't handle empty alternative names
2668if (AltName.empty())
2669continue;
2670
2671Matches.emplace_back(AltName.str(), "return " + Namespace +
2672"::" + Reg.getName().str() + ';');
2673}
2674}
2675
2676OS << "static MCRegister MatchRegisterAltName(StringRef Name) {\n";
2677
2678bool IgnoreDuplicates =
2679AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2680StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2681
2682OS << " return " << Namespace << "::NoRegister;\n";
2683OS << "}\n\n";
2684}
2685
2686/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2687static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2688// Get the set of diagnostic types from all of the operand classes.
2689std::set<StringRef> Types;
2690for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2691if (!OpClassEntry.second->DiagnosticType.empty())
2692Types.insert(OpClassEntry.second->DiagnosticType);
2693}
2694for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2695if (!OpClassEntry.second->DiagnosticType.empty())
2696Types.insert(OpClassEntry.second->DiagnosticType);
2697}
2698
2699if (Types.empty())
2700return;
2701
2702// Now emit the enum entries.
2703for (StringRef Type : Types)
2704OS << " Match_" << Type << ",\n";
2705OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2706}
2707
2708/// emitGetSubtargetFeatureName - Emit the helper function to get the
2709/// user-level name for a subtarget feature.
2710static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2711OS << "// User-level names for subtarget features that participate in\n"
2712<< "// instruction matching.\n"
2713<< "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2714if (!Info.SubtargetFeatures.empty()) {
2715OS << " switch(Val) {\n";
2716for (const auto &SF : Info.SubtargetFeatures) {
2717const SubtargetFeatureInfo &SFI = SF.second;
2718// FIXME: Totally just a placeholder name to get the algorithm working.
2719OS << " case " << SFI.getEnumBitName() << ": return \""
2720<< SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2721}
2722OS << " default: return \"(unknown)\";\n";
2723OS << " }\n";
2724} else {
2725// Nothing to emit, so skip the switch
2726OS << " return \"(unknown)\";\n";
2727}
2728OS << "}\n\n";
2729}
2730
2731static std::string GetAliasRequiredFeatures(Record *R,
2732const AsmMatcherInfo &Info) {
2733std::vector<Record *> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2734std::string Result;
2735
2736if (ReqFeatures.empty())
2737return Result;
2738
2739for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2740const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2741
2742if (!F)
2743PrintFatalError(R->getLoc(),
2744"Predicate '" + ReqFeatures[i]->getName() +
2745"' is not marked as an AssemblerPredicate!");
2746
2747if (i)
2748Result += " && ";
2749
2750Result += "Features.test(" + F->getEnumBitName() + ')';
2751}
2752
2753return Result;
2754}
2755
2756static void
2757emitMnemonicAliasVariant(raw_ostream &OS, const AsmMatcherInfo &Info,
2758std::vector<Record *> &Aliases, unsigned Indent = 0,
2759StringRef AsmParserVariantName = StringRef()) {
2760// Keep track of all the aliases from a mnemonic. Use an std::map so that the
2761// iteration order of the map is stable.
2762std::map<std::string, std::vector<Record *>> AliasesFromMnemonic;
2763
2764for (Record *R : Aliases) {
2765// FIXME: Allow AssemblerVariantName to be a comma separated list.
2766StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
2767if (AsmVariantName != AsmParserVariantName)
2768continue;
2769AliasesFromMnemonic[R->getValueAsString("FromMnemonic").lower()].push_back(
2770R);
2771}
2772if (AliasesFromMnemonic.empty())
2773return;
2774
2775// Process each alias a "from" mnemonic at a time, building the code executed
2776// by the string remapper.
2777std::vector<StringMatcher::StringPair> Cases;
2778for (const auto &AliasEntry : AliasesFromMnemonic) {
2779const std::vector<Record *> &ToVec = AliasEntry.second;
2780
2781// Loop through each alias and emit code that handles each case. If there
2782// are two instructions without predicates, emit an error. If there is one,
2783// emit it last.
2784std::string MatchCode;
2785int AliasWithNoPredicate = -1;
2786
2787for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2788Record *R = ToVec[i];
2789std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2790
2791// If this unconditionally matches, remember it for later and diagnose
2792// duplicates.
2793if (FeatureMask.empty()) {
2794if (AliasWithNoPredicate != -1 &&
2795R->getValueAsString("ToMnemonic") !=
2796ToVec[AliasWithNoPredicate]->getValueAsString("ToMnemonic")) {
2797// We can't have two different aliases from the same mnemonic with no
2798// predicate.
2799PrintError(
2800ToVec[AliasWithNoPredicate]->getLoc(),
2801"two different MnemonicAliases with the same 'from' mnemonic!");
2802PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2803}
2804
2805AliasWithNoPredicate = i;
2806continue;
2807}
2808if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
2809PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2810
2811if (!MatchCode.empty())
2812MatchCode += "else ";
2813MatchCode += "if (" + FeatureMask + ")\n";
2814MatchCode += " Mnemonic = \"";
2815MatchCode += R->getValueAsString("ToMnemonic").lower();
2816MatchCode += "\";\n";
2817}
2818
2819if (AliasWithNoPredicate != -1) {
2820Record *R = ToVec[AliasWithNoPredicate];
2821if (!MatchCode.empty())
2822MatchCode += "else\n ";
2823MatchCode += "Mnemonic = \"";
2824MatchCode += R->getValueAsString("ToMnemonic").lower();
2825MatchCode += "\";\n";
2826}
2827
2828MatchCode += "return;";
2829
2830Cases.push_back(std::pair(AliasEntry.first, MatchCode));
2831}
2832StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2833}
2834
2835/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2836/// emit a function for them and return true, otherwise return false.
2837static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2838CodeGenTarget &Target) {
2839// Ignore aliases when match-prefix is set.
2840if (!MatchPrefix.empty())
2841return false;
2842
2843std::vector<Record *> Aliases =
2844Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2845if (Aliases.empty())
2846return false;
2847
2848OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2849"const FeatureBitset &Features, unsigned VariantID) {\n";
2850OS << " switch (VariantID) {\n";
2851unsigned VariantCount = Target.getAsmParserVariantCount();
2852for (unsigned VC = 0; VC != VariantCount; ++VC) {
2853Record *AsmVariant = Target.getAsmParserVariant(VC);
2854int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2855StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
2856OS << " case " << AsmParserVariantNo << ":\n";
2857emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2858AsmParserVariantName);
2859OS << " break;\n";
2860}
2861OS << " }\n";
2862
2863// Emit aliases that apply to all variants.
2864emitMnemonicAliasVariant(OS, Info, Aliases);
2865
2866OS << "}\n\n";
2867
2868return true;
2869}
2870
2871static void
2872emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2873const AsmMatcherInfo &Info, StringRef ClassName,
2874StringToOffsetTable &StringTable,
2875unsigned MaxMnemonicIndex, unsigned MaxFeaturesIndex,
2876bool HasMnemonicFirst, const Record &AsmParser) {
2877unsigned MaxMask = 0;
2878for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2879MaxMask |= OMI.OperandMask;
2880}
2881
2882// Emit the static custom operand parsing table;
2883OS << "namespace {\n";
2884OS << " struct OperandMatchEntry {\n";
2885OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) << " Mnemonic;\n";
2886OS << " " << getMinimalTypeForRange(MaxMask) << " OperandMask;\n";
2887OS << " "
2888<< getMinimalTypeForRange(
2889std::distance(Info.Classes.begin(), Info.Classes.end()) +
28902 /* Include 'InvalidMatchClass' and 'OptionalMatchClass' */)
2891<< " Class;\n";
2892OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
2893<< " RequiredFeaturesIdx;\n\n";
2894OS << " StringRef getMnemonic() const {\n";
2895OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2896OS << " MnemonicTable[Mnemonic]);\n";
2897OS << " }\n";
2898OS << " };\n\n";
2899
2900OS << " // Predicate for searching for an opcode.\n";
2901OS << " struct LessOpcodeOperand {\n";
2902OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2903OS << " return LHS.getMnemonic() < RHS;\n";
2904OS << " }\n";
2905OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2906OS << " return LHS < RHS.getMnemonic();\n";
2907OS << " }\n";
2908OS << " bool operator()(const OperandMatchEntry &LHS,";
2909OS << " const OperandMatchEntry &RHS) {\n";
2910OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2911OS << " }\n";
2912OS << " };\n";
2913
2914OS << "} // end anonymous namespace\n\n";
2915
2916OS << "static const OperandMatchEntry OperandMatchTable["
2917<< Info.OperandMatchInfo.size() << "] = {\n";
2918
2919OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
2920for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2921const MatchableInfo &II = *OMI.MI;
2922
2923OS << " { ";
2924
2925// Store a pascal-style length byte in the mnemonic.
2926std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
2927OS << StringTable.GetOrAddStringOffset(LenMnemonic, false) << " /* "
2928<< II.Mnemonic << " */, ";
2929
2930OS << OMI.OperandMask;
2931OS << " /* ";
2932ListSeparator LS;
2933for (int i = 0, e = 31; i != e; ++i)
2934if (OMI.OperandMask & (1 << i))
2935OS << LS << i;
2936OS << " */, ";
2937
2938OS << OMI.CI->Name;
2939
2940// Write the required features mask.
2941OS << ", AMFBS";
2942if (II.RequiredFeatures.empty())
2943OS << "_None";
2944else
2945for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
2946OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
2947
2948OS << " },\n";
2949}
2950OS << "};\n\n";
2951
2952// Emit the operand class switch to call the correct custom parser for
2953// the found operand class.
2954OS << "ParseStatus " << Target.getName() << ClassName << "::\n"
2955<< "tryCustomParseOperand(OperandVector"
2956<< " &Operands,\n unsigned MCK) {\n\n"
2957<< " switch(MCK) {\n";
2958
2959for (const auto &CI : Info.Classes) {
2960if (CI.ParserMethod.empty())
2961continue;
2962OS << " case " << CI.Name << ":\n"
2963<< " return " << CI.ParserMethod << "(Operands);\n";
2964}
2965
2966OS << " default:\n";
2967OS << " return ParseStatus::NoMatch;\n";
2968OS << " }\n";
2969OS << " return ParseStatus::NoMatch;\n";
2970OS << "}\n\n";
2971
2972// Emit the static custom operand parser. This code is very similar with
2973// the other matcher. Also use MatchResultTy here just in case we go for
2974// a better error handling.
2975OS << "ParseStatus " << Target.getName() << ClassName << "::\n"
2976<< "MatchOperandParserImpl(OperandVector"
2977<< " &Operands,\n StringRef Mnemonic,\n"
2978<< " bool ParseForAllFeatures) {\n";
2979
2980// Emit code to get the available features.
2981OS << " // Get the current feature set.\n";
2982OS << " const FeatureBitset &AvailableFeatures = "
2983"getAvailableFeatures();\n\n";
2984
2985OS << " // Get the next operand index.\n";
2986OS << " unsigned NextOpNum = Operands.size()"
2987<< (HasMnemonicFirst ? " - 1" : "") << ";\n";
2988
2989// Emit code to search the table.
2990OS << " // Search the table.\n";
2991if (HasMnemonicFirst) {
2992OS << " auto MnemonicRange =\n";
2993OS << " std::equal_range(std::begin(OperandMatchTable), "
2994"std::end(OperandMatchTable),\n";
2995OS << " Mnemonic, LessOpcodeOperand());\n\n";
2996} else {
2997OS << " auto MnemonicRange = std::pair(std::begin(OperandMatchTable),"
2998" std::end(OperandMatchTable));\n";
2999OS << " if (!Mnemonic.empty())\n";
3000OS << " MnemonicRange =\n";
3001OS << " std::equal_range(std::begin(OperandMatchTable), "
3002"std::end(OperandMatchTable),\n";
3003OS << " Mnemonic, LessOpcodeOperand());\n\n";
3004}
3005
3006OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3007OS << " return ParseStatus::NoMatch;\n\n";
3008
3009OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
3010<< " *ie = MnemonicRange.second; it != ie; ++it) {\n";
3011
3012OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3013OS << " assert(Mnemonic == it->getMnemonic());\n\n";
3014
3015// Emit check that the required features are available.
3016OS << " // check if the available features match\n";
3017OS << " const FeatureBitset &RequiredFeatures = "
3018"FeatureBitsets[it->RequiredFeaturesIdx];\n";
3019OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
3020"RequiredFeatures) != RequiredFeatures)\n";
3021OS << " continue;\n\n";
3022
3023// Emit check to ensure the operand number matches.
3024OS << " // check if the operand in question has a custom parser.\n";
3025OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
3026OS << " continue;\n\n";
3027
3028// Emit call to the custom parser method
3029StringRef ParserName = AsmParser.getValueAsString("OperandParserMethod");
3030if (ParserName.empty())
3031ParserName = "tryCustomParseOperand";
3032OS << " // call custom parse method to handle the operand\n";
3033OS << " ParseStatus Result = " << ParserName << "(Operands, it->Class);\n";
3034OS << " if (!Result.isNoMatch())\n";
3035OS << " return Result;\n";
3036OS << " }\n\n";
3037
3038OS << " // Okay, we had no match.\n";
3039OS << " return ParseStatus::NoMatch;\n";
3040OS << "}\n\n";
3041}
3042
3043static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
3044AsmMatcherInfo &Info, raw_ostream &OS,
3045bool HasOptionalOperands) {
3046std::string AsmParserName =
3047std::string(Info.AsmParser->getValueAsString("AsmParserClassName"));
3048OS << "static bool ";
3049OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3050<< AsmParserName << "&AsmParser,\n";
3051OS << " unsigned Kind, const OperandVector "
3052"&Operands,\n";
3053if (HasOptionalOperands)
3054OS << " ArrayRef<unsigned> DefaultsOffset,\n";
3055OS << " uint64_t &ErrorInfo) {\n";
3056OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3057OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3058OS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
3059OS << " switch (*p) {\n";
3060OS << " case CVT_Tied: {\n";
3061OS << " unsigned OpIdx = *(p + 1);\n";
3062OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3063OS << " std::begin(TiedAsmOperandTable)) &&\n";
3064OS << " \"Tied operand not found\");\n";
3065OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3066OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3067if (HasOptionalOperands) {
3068// When optional operands are involved, formal and actual operand indices
3069// may differ. Map the former to the latter by subtracting the number of
3070// absent optional operands.
3071OS << " OpndNum1 = OpndNum1 - DefaultsOffset[OpndNum1];\n";
3072OS << " OpndNum2 = OpndNum2 - DefaultsOffset[OpndNum2];\n";
3073}
3074OS << " if (OpndNum1 != OpndNum2) {\n";
3075OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3076OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
3077OS << " if (!AsmParser.areEqualRegs(*SrcOp1, *SrcOp2)) {\n";
3078OS << " ErrorInfo = OpndNum2;\n";
3079OS << " return false;\n";
3080OS << " }\n";
3081OS << " }\n";
3082OS << " break;\n";
3083OS << " }\n";
3084OS << " default:\n";
3085OS << " break;\n";
3086OS << " }\n";
3087OS << " }\n";
3088OS << " return true;\n";
3089OS << "}\n\n";
3090}
3091
3092static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3093unsigned VariantCount) {
3094OS << "static std::string " << Target.getName()
3095<< "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3096<< " unsigned VariantID) {\n";
3097if (!VariantCount)
3098OS << " return \"\";";
3099else {
3100OS << " const unsigned MaxEditDist = 2;\n";
3101OS << " std::vector<StringRef> Candidates;\n";
3102OS << " StringRef Prev = \"\";\n\n";
3103
3104OS << " // Find the appropriate table for this asm variant.\n";
3105OS << " const MatchEntry *Start, *End;\n";
3106OS << " switch (VariantID) {\n";
3107OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3108for (unsigned VC = 0; VC != VariantCount; ++VC) {
3109Record *AsmVariant = Target.getAsmParserVariant(VC);
3110int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3111OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3112<< "); End = std::end(MatchTable" << VC << "); break;\n";
3113}
3114OS << " }\n\n";
3115OS << " for (auto I = Start; I < End; I++) {\n";
3116OS << " // Ignore unsupported instructions.\n";
3117OS << " const FeatureBitset &RequiredFeatures = "
3118"FeatureBitsets[I->RequiredFeaturesIdx];\n";
3119OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
3120OS << " continue;\n";
3121OS << "\n";
3122OS << " StringRef T = I->getMnemonic();\n";
3123OS << " // Avoid recomputing the edit distance for the same string.\n";
3124OS << " if (T == Prev)\n";
3125OS << " continue;\n";
3126OS << "\n";
3127OS << " Prev = T;\n";
3128OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3129OS << " if (Dist <= MaxEditDist)\n";
3130OS << " Candidates.push_back(T);\n";
3131OS << " }\n";
3132OS << "\n";
3133OS << " if (Candidates.empty())\n";
3134OS << " return \"\";\n";
3135OS << "\n";
3136OS << " std::string Res = \", did you mean: \";\n";
3137OS << " unsigned i = 0;\n";
3138OS << " for (; i < Candidates.size() - 1; i++)\n";
3139OS << " Res += Candidates[i].str() + \", \";\n";
3140OS << " return Res + Candidates[i].str() + \"?\";\n";
3141}
3142OS << "}\n";
3143OS << "\n";
3144}
3145
3146static void emitMnemonicChecker(raw_ostream &OS, CodeGenTarget &Target,
3147unsigned VariantCount, bool HasMnemonicFirst,
3148bool HasMnemonicAliases) {
3149OS << "static bool " << Target.getName()
3150<< "CheckMnemonic(StringRef Mnemonic,\n";
3151OS << " "
3152<< "const FeatureBitset &AvailableFeatures,\n";
3153OS << " "
3154<< "unsigned VariantID) {\n";
3155
3156if (!VariantCount) {
3157OS << " return false;\n";
3158} else {
3159if (HasMnemonicAliases) {
3160OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
3161OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);";
3162OS << "\n\n";
3163}
3164OS << " // Find the appropriate table for this asm variant.\n";
3165OS << " const MatchEntry *Start, *End;\n";
3166OS << " switch (VariantID) {\n";
3167OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3168for (unsigned VC = 0; VC != VariantCount; ++VC) {
3169Record *AsmVariant = Target.getAsmParserVariant(VC);
3170int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3171OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3172<< "); End = std::end(MatchTable" << VC << "); break;\n";
3173}
3174OS << " }\n\n";
3175
3176OS << " // Search the table.\n";
3177if (HasMnemonicFirst) {
3178OS << " auto MnemonicRange = "
3179"std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3180} else {
3181OS << " auto MnemonicRange = std::pair(Start, End);\n";
3182OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3183OS << " if (!Mnemonic.empty())\n";
3184OS << " MnemonicRange = "
3185<< "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3186}
3187
3188OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3189OS << " return false;\n\n";
3190
3191OS << " for (const MatchEntry *it = MnemonicRange.first, "
3192<< "*ie = MnemonicRange.second;\n";
3193OS << " it != ie; ++it) {\n";
3194OS << " const FeatureBitset &RequiredFeatures =\n";
3195OS << " FeatureBitsets[it->RequiredFeaturesIdx];\n";
3196OS << " if ((AvailableFeatures & RequiredFeatures) == ";
3197OS << "RequiredFeatures)\n";
3198OS << " return true;\n";
3199OS << " }\n";
3200OS << " return false;\n";
3201}
3202OS << "}\n";
3203OS << "\n";
3204}
3205
3206// Emit a function mapping match classes to strings, for debugging.
3207static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3208raw_ostream &OS) {
3209OS << "#ifndef NDEBUG\n";
3210OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3211OS << " switch (Kind) {\n";
3212
3213OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3214OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3215for (const auto &CI : Infos) {
3216OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3217}
3218OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3219
3220OS << " }\n";
3221OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3222OS << "}\n\n";
3223OS << "#endif // NDEBUG\n";
3224}
3225
3226static std::string
3227getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
3228std::string Name = "AMFBS";
3229for (const auto &Feature : FeatureBitset)
3230Name += ("_" + Feature->getName()).str();
3231return Name;
3232}
3233
3234void AsmMatcherEmitter::run(raw_ostream &OS) {
3235CodeGenTarget Target(Records);
3236Record *AsmParser = Target.getAsmParser();
3237StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
3238
3239emitSourceFileHeader("Assembly Matcher Source Fragment", OS, Records);
3240
3241// Compute the information on the instructions to match.
3242AsmMatcherInfo Info(AsmParser, Target, Records);
3243Info.buildInfo();
3244
3245bool PreferSmallerInstructions = getPreferSmallerInstructions(Target);
3246// Sort the instruction table using the partial order on classes. We use
3247// stable_sort to ensure that ambiguous instructions are still
3248// deterministically ordered.
3249llvm::stable_sort(
3250Info.Matchables,
3251[PreferSmallerInstructions](const std::unique_ptr<MatchableInfo> &A,
3252const std::unique_ptr<MatchableInfo> &B) {
3253return A->shouldBeMatchedBefore(*B, PreferSmallerInstructions);
3254});
3255
3256#ifdef EXPENSIVE_CHECKS
3257// Verify that the table is sorted and operator < works transitively.
3258for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3259++I) {
3260for (auto J = I; J != E; ++J) {
3261assert(!(*J)->shouldBeMatchedBefore(**I, PreferSmallerInstructions));
3262}
3263}
3264#endif
3265
3266DEBUG_WITH_TYPE("instruction_info", {
3267for (const auto &MI : Info.Matchables)
3268MI->dump();
3269});
3270
3271// Check for ambiguous matchables.
3272DEBUG_WITH_TYPE("ambiguous_instrs", {
3273unsigned NumAmbiguous = 0;
3274for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3275++I) {
3276for (auto J = std::next(I); J != E; ++J) {
3277const MatchableInfo &A = **I;
3278const MatchableInfo &B = **J;
3279
3280if (A.couldMatchAmbiguouslyWith(B, PreferSmallerInstructions)) {
3281errs() << "warning: ambiguous matchables:\n";
3282A.dump();
3283errs() << "\nis incomparable with:\n";
3284B.dump();
3285errs() << "\n\n";
3286++NumAmbiguous;
3287}
3288}
3289}
3290if (NumAmbiguous)
3291errs() << "warning: " << NumAmbiguous << " ambiguous matchables!\n";
3292});
3293
3294// Compute the information on the custom operand parsing.
3295Info.buildOperandMatchInfo();
3296
3297bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
3298bool HasOptionalOperands = Info.hasOptionalOperands();
3299bool ReportMultipleNearMisses =
3300AsmParser->getValueAsBit("ReportMultipleNearMisses");
3301
3302// Write the output.
3303
3304// Information for the class declaration.
3305OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3306OS << "#undef GET_ASSEMBLER_HEADER\n";
3307OS << " // This should be included into the middle of the declaration of\n";
3308OS << " // your subclasses implementation of MCTargetAsmParser.\n";
3309OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset &FB) "
3310"const;\n";
3311if (HasOptionalOperands) {
3312OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3313<< "unsigned Opcode,\n"
3314<< " const OperandVector &Operands,\n"
3315<< " const SmallBitVector "
3316"&OptionalOperandsMask,\n"
3317<< " ArrayRef<unsigned> DefaultsOffset);\n";
3318} else {
3319OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3320<< "unsigned Opcode,\n"
3321<< " const OperandVector &Operands);\n";
3322}
3323OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
3324OS << " const OperandVector &Operands) override;\n";
3325OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3326<< " MCInst &Inst,\n";
3327if (ReportMultipleNearMisses)
3328OS << " SmallVectorImpl<NearMissInfo> "
3329"*NearMisses,\n";
3330else
3331OS << " uint64_t &ErrorInfo,\n"
3332<< " FeatureBitset &MissingFeatures,\n";
3333OS << " bool matchingInlineAsm,\n"
3334<< " unsigned VariantID = 0);\n";
3335if (!ReportMultipleNearMisses)
3336OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3337<< " MCInst &Inst,\n"
3338<< " uint64_t &ErrorInfo,\n"
3339<< " bool matchingInlineAsm,\n"
3340<< " unsigned VariantID = 0) {\n"
3341<< " FeatureBitset MissingFeatures;\n"
3342<< " return MatchInstructionImpl(Operands, Inst, ErrorInfo, "
3343"MissingFeatures,\n"
3344<< " matchingInlineAsm, VariantID);\n"
3345<< " }\n\n";
3346
3347if (!Info.OperandMatchInfo.empty()) {
3348OS << " ParseStatus MatchOperandParserImpl(\n";
3349OS << " OperandVector &Operands,\n";
3350OS << " StringRef Mnemonic,\n";
3351OS << " bool ParseForAllFeatures = false);\n";
3352
3353OS << " ParseStatus tryCustomParseOperand(\n";
3354OS << " OperandVector &Operands,\n";
3355OS << " unsigned MCK);\n\n";
3356}
3357
3358OS << "#endif // GET_ASSEMBLER_HEADER\n\n";
3359
3360// Emit the operand match diagnostic enum names.
3361OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3362OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3363emitOperandDiagnosticTypes(Info, OS);
3364OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3365
3366OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3367OS << "#undef GET_REGISTER_MATCHER\n\n";
3368
3369// Emit the subtarget feature enumeration.
3370SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
3371Info.SubtargetFeatures, OS);
3372
3373// Emit the function to match a register name to number.
3374// This should be omitted for Mips target
3375if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3376emitMatchRegisterName(Target, AsmParser, OS);
3377
3378if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3379emitMatchRegisterAltName(Target, AsmParser, OS);
3380
3381OS << "#endif // GET_REGISTER_MATCHER\n\n";
3382
3383OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3384OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
3385
3386// Generate the helper function to get the names for subtarget features.
3387emitGetSubtargetFeatureName(Info, OS);
3388
3389OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3390
3391OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3392OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3393
3394// Generate the function that remaps for mnemonic aliases.
3395bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
3396
3397// Generate the convertToMCInst function to convert operands into an MCInst.
3398// Also, generate the convertToMapAndConstraints function for MS-style inline
3399// assembly. The latter doesn't actually generate a MCInst.
3400unsigned NumConverters =
3401emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
3402HasOptionalOperands, OS);
3403
3404// Emit the enumeration for classes which participate in matching.
3405emitMatchClassEnumeration(Target, Info.Classes, OS);
3406
3407// Emit a function to get the user-visible string to describe an operand
3408// match failure in diagnostics.
3409emitOperandMatchErrorDiagStrings(Info, OS);
3410
3411// Emit a function to map register classes to operand match failure codes.
3412emitRegisterMatchErrorFunc(Info, OS);
3413
3414// Emit the routine to match token strings to their match class.
3415emitMatchTokenString(Target, Info.Classes, OS);
3416
3417// Emit the subclass predicate routine.
3418emitIsSubclass(Target, Info.Classes, OS);
3419
3420// Emit the routine to validate an operand against a match class.
3421emitValidateOperandClass(Info, OS);
3422
3423emitMatchClassKindNames(Info.Classes, OS);
3424
3425// Emit the available features compute function.
3426SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
3427Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3428Info.SubtargetFeatures, OS);
3429
3430if (!ReportMultipleNearMisses)
3431emitAsmTiedOperandConstraints(Target, Info, OS, HasOptionalOperands);
3432
3433StringToOffsetTable StringTable;
3434
3435size_t MaxNumOperands = 0;
3436unsigned MaxMnemonicIndex = 0;
3437bool HasDeprecation = false;
3438for (const auto &MI : Info.Matchables) {
3439MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3440HasDeprecation |= MI->HasDeprecation;
3441
3442// Store a pascal-style length byte in the mnemonic.
3443std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3444MaxMnemonicIndex = std::max(
3445MaxMnemonicIndex, StringTable.GetOrAddStringOffset(LenMnemonic, false));
3446}
3447
3448OS << "static const char MnemonicTable[] =\n";
3449StringTable.EmitString(OS);
3450OS << ";\n\n";
3451
3452std::vector<std::vector<Record *>> FeatureBitsets;
3453for (const auto &MI : Info.Matchables) {
3454if (MI->RequiredFeatures.empty())
3455continue;
3456FeatureBitsets.emplace_back();
3457for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
3458FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
3459}
3460
3461llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
3462const std::vector<Record *> &B) {
3463if (A.size() < B.size())
3464return true;
3465if (A.size() > B.size())
3466return false;
3467for (auto Pair : zip(A, B)) {
3468if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3469return true;
3470if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3471return false;
3472}
3473return false;
3474});
3475FeatureBitsets.erase(llvm::unique(FeatureBitsets), FeatureBitsets.end());
3476OS << "// Feature bitsets.\n"
3477<< "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
3478<< " AMFBS_None,\n";
3479for (const auto &FeatureBitset : FeatureBitsets) {
3480if (FeatureBitset.empty())
3481continue;
3482OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3483}
3484OS << "};\n\n"
3485<< "static constexpr FeatureBitset FeatureBitsets[] = {\n"
3486<< " {}, // AMFBS_None\n";
3487for (const auto &FeatureBitset : FeatureBitsets) {
3488if (FeatureBitset.empty())
3489continue;
3490OS << " {";
3491for (const auto &Feature : FeatureBitset) {
3492const auto &I = Info.SubtargetFeatures.find(Feature);
3493assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
3494OS << I->second.getEnumBitName() << ", ";
3495}
3496OS << "},\n";
3497}
3498OS << "};\n\n";
3499
3500// Emit the static match table; unused classes get initialized to 0 which is
3501// guaranteed to be InvalidMatchClass.
3502//
3503// FIXME: We can reduce the size of this table very easily. First, we change
3504// it so that store the kinds in separate bit-fields for each index, which
3505// only needs to be the max width used for classes at that index (we also need
3506// to reject based on this during classification). If we then make sure to
3507// order the match kinds appropriately (putting mnemonics last), then we
3508// should only end up using a few bits for each class, especially the ones
3509// following the mnemonic.
3510OS << "namespace {\n";
3511OS << " struct MatchEntry {\n";
3512OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) << " Mnemonic;\n";
3513OS << " uint16_t Opcode;\n";
3514OS << " " << getMinimalTypeForRange(NumConverters) << " ConvertFn;\n";
3515OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
3516<< " RequiredFeaturesIdx;\n";
3517OS << " "
3518<< getMinimalTypeForRange(
3519std::distance(Info.Classes.begin(), Info.Classes.end()) +
35202 /* Include 'InvalidMatchClass' and 'OptionalMatchClass' */)
3521<< " Classes[" << MaxNumOperands << "];\n";
3522OS << " StringRef getMnemonic() const {\n";
3523OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3524OS << " MnemonicTable[Mnemonic]);\n";
3525OS << " }\n";
3526OS << " };\n\n";
3527
3528OS << " // Predicate for searching for an opcode.\n";
3529OS << " struct LessOpcode {\n";
3530OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3531OS << " return LHS.getMnemonic() < RHS;\n";
3532OS << " }\n";
3533OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3534OS << " return LHS < RHS.getMnemonic();\n";
3535OS << " }\n";
3536OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3537OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
3538OS << " }\n";
3539OS << " };\n";
3540
3541OS << "} // end anonymous namespace\n\n";
3542
3543unsigned VariantCount = Target.getAsmParserVariantCount();
3544for (unsigned VC = 0; VC != VariantCount; ++VC) {
3545Record *AsmVariant = Target.getAsmParserVariant(VC);
3546int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3547
3548OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
3549
3550for (const auto &MI : Info.Matchables) {
3551if (MI->AsmVariantID != AsmVariantNo)
3552continue;
3553
3554// Store a pascal-style length byte in the mnemonic.
3555std::string LenMnemonic =
3556char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
3557OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
3558<< " /* " << MI->Mnemonic << " */, " << Target.getInstNamespace()
3559<< "::" << MI->getResultInst()->TheDef->getName() << ", "
3560<< MI->ConversionFnKind << ", ";
3561
3562// Write the required features mask.
3563OS << "AMFBS";
3564if (MI->RequiredFeatures.empty())
3565OS << "_None";
3566else
3567for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
3568OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
3569
3570OS << ", { ";
3571ListSeparator LS;
3572for (const MatchableInfo::AsmOperand &Op : MI->AsmOperands)
3573OS << LS << Op.Class->Name;
3574OS << " }, },\n";
3575}
3576
3577OS << "};\n\n";
3578}
3579
3580OS << "#include \"llvm/Support/Debug.h\"\n";
3581OS << "#include \"llvm/Support/Format.h\"\n\n";
3582
3583// Finally, build the match function.
3584OS << "unsigned " << Target.getName() << ClassName << "::\n"
3585<< "MatchInstructionImpl(const OperandVector &Operands,\n";
3586OS << " MCInst &Inst,\n";
3587if (ReportMultipleNearMisses)
3588OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3589else
3590OS << " uint64_t &ErrorInfo,\n"
3591<< " FeatureBitset &MissingFeatures,\n";
3592OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
3593
3594if (!ReportMultipleNearMisses) {
3595OS << " // Eliminate obvious mismatches.\n";
3596OS << " if (Operands.size() > " << (MaxNumOperands + HasMnemonicFirst)
3597<< ") {\n";
3598OS << " ErrorInfo = " << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3599OS << " return Match_InvalidOperand;\n";
3600OS << " }\n\n";
3601}
3602
3603// Emit code to get the available features.
3604OS << " // Get the current feature set.\n";
3605OS << " const FeatureBitset &AvailableFeatures = "
3606"getAvailableFeatures();\n\n";
3607
3608OS << " // Get the instruction mnemonic, which is the first token.\n";
3609if (HasMnemonicFirst) {
3610OS << " StringRef Mnemonic = ((" << Target.getName()
3611<< "Operand &)*Operands[0]).getToken();\n\n";
3612} else {
3613OS << " StringRef Mnemonic;\n";
3614OS << " if (Operands[0]->isToken())\n";
3615OS << " Mnemonic = ((" << Target.getName()
3616<< "Operand &)*Operands[0]).getToken();\n\n";
3617}
3618
3619if (HasMnemonicAliases) {
3620OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
3621OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3622}
3623
3624// Emit code to compute the class list for this operand vector.
3625if (!ReportMultipleNearMisses) {
3626OS << " // Some state to try to produce better error messages.\n";
3627OS << " bool HadMatchOtherThanFeatures = false;\n";
3628OS << " bool HadMatchOtherThanPredicate = false;\n";
3629OS << " unsigned RetCode = Match_InvalidOperand;\n";
3630OS << " MissingFeatures.set();\n";
3631OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3632OS << " // wrong for all instances of the instruction.\n";
3633OS << " ErrorInfo = ~0ULL;\n";
3634}
3635
3636if (HasOptionalOperands) {
3637OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3638}
3639
3640// Emit code to search the table.
3641OS << " // Find the appropriate table for this asm variant.\n";
3642OS << " const MatchEntry *Start, *End;\n";
3643OS << " switch (VariantID) {\n";
3644OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3645for (unsigned VC = 0; VC != VariantCount; ++VC) {
3646Record *AsmVariant = Target.getAsmParserVariant(VC);
3647int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3648OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3649<< "); End = std::end(MatchTable" << VC << "); break;\n";
3650}
3651OS << " }\n";
3652
3653OS << " // Search the table.\n";
3654if (HasMnemonicFirst) {
3655OS << " auto MnemonicRange = "
3656"std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3657} else {
3658OS << " auto MnemonicRange = std::pair(Start, End);\n";
3659OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3660OS << " if (!Mnemonic.empty())\n";
3661OS << " MnemonicRange = "
3662"std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3663}
3664
3665OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" "
3666"<<\n"
3667<< " std::distance(MnemonicRange.first, MnemonicRange.second) <<\n"
3668<< " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3669
3670OS << " // Return a more specific error code if no mnemonics match.\n";
3671OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3672OS << " return Match_MnemonicFail;\n\n";
3673
3674OS << " for (const MatchEntry *it = MnemonicRange.first, "
3675<< "*ie = MnemonicRange.second;\n";
3676OS << " it != ie; ++it) {\n";
3677OS << " const FeatureBitset &RequiredFeatures = "
3678"FeatureBitsets[it->RequiredFeaturesIdx];\n";
3679OS << " bool HasRequiredFeatures =\n";
3680OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
3681OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match "
3682"opcode \"\n";
3683OS << " << MII.getName(it->Opcode) "
3684"<< \"\\n\");\n";
3685
3686if (ReportMultipleNearMisses) {
3687OS << " // Some state to record ways in which this instruction did not "
3688"match.\n";
3689OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3690OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3691OS << " NearMissInfo EarlyPredicateNearMiss = "
3692"NearMissInfo::getSuccess();\n";
3693OS << " NearMissInfo LatePredicateNearMiss = "
3694"NearMissInfo::getSuccess();\n";
3695OS << " bool MultipleInvalidOperands = false;\n";
3696}
3697
3698if (HasMnemonicFirst) {
3699OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3700OS << " assert(Mnemonic == it->getMnemonic());\n";
3701}
3702
3703// Emit check that the subclasses match.
3704if (!ReportMultipleNearMisses)
3705OS << " bool OperandsValid = true;\n";
3706if (HasOptionalOperands) {
3707OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3708}
3709OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3710<< ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3711<< "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3712OS << " auto Formal = "
3713<< "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3714OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3715OS << " dbgs() << \" Matching formal operand class \" "
3716"<< getMatchClassName(Formal)\n";
3717OS << " << \" against actual operand at index \" "
3718"<< ActualIdx);\n";
3719OS << " if (ActualIdx < Operands.size())\n";
3720OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3721OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << "
3722"\"): \");\n";
3723OS << " else\n";
3724OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
3725OS << " if (ActualIdx >= Operands.size()) {\n";
3726OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand "
3727"index out of range\\n\");\n";
3728if (ReportMultipleNearMisses) {
3729OS << " bool ThisOperandValid = (Formal == "
3730<< "InvalidMatchClass) || "
3731"isSubclass(Formal, OptionalMatchClass);\n";
3732OS << " if (!ThisOperandValid) {\n";
3733OS << " if (!OperandNearMiss) {\n";
3734OS << " // Record info about match failure for later use.\n";
3735OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording "
3736"too-few-operands near miss\\n\");\n";
3737OS << " OperandNearMiss =\n";
3738OS << " NearMissInfo::getTooFewOperands(Formal, "
3739"it->Opcode);\n";
3740OS << " } else if (OperandNearMiss.getKind() != "
3741"NearMissInfo::NearMissTooFewOperands) {\n";
3742OS << " // If more than one operand is invalid, give up on this "
3743"match entry.\n";
3744OS << " DEBUG_WITH_TYPE(\n";
3745OS << " \"asm-matcher\",\n";
3746OS << " dbgs() << \"second invalid operand, giving up on "
3747"this opcode\\n\");\n";
3748OS << " MultipleInvalidOperands = true;\n";
3749OS << " break;\n";
3750OS << " }\n";
3751OS << " } else {\n";
3752OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal "
3753"operand not required\\n\");\n";
3754OS << " if (isSubclass(Formal, OptionalMatchClass)) {\n";
3755OS << " OptionalOperandsMask.set(FormalIdx);\n";
3756OS << " }\n";
3757OS << " }\n";
3758OS << " continue;\n";
3759} else {
3760OS << " if (Formal == InvalidMatchClass) {\n";
3761if (HasOptionalOperands) {
3762OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3763<< ");\n";
3764}
3765OS << " break;\n";
3766OS << " }\n";
3767OS << " if (isSubclass(Formal, OptionalMatchClass)) {\n";
3768if (HasOptionalOperands) {
3769OS << " OptionalOperandsMask.set(FormalIdx);\n";
3770}
3771OS << " continue;\n";
3772OS << " }\n";
3773OS << " OperandsValid = false;\n";
3774OS << " ErrorInfo = ActualIdx;\n";
3775OS << " break;\n";
3776}
3777OS << " }\n";
3778OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3779OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
3780OS << " if (Diag == Match_Success) {\n";
3781OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3782OS << " dbgs() << \"match success using generic "
3783"matcher\\n\");\n";
3784OS << " ++ActualIdx;\n";
3785OS << " continue;\n";
3786OS << " }\n";
3787OS << " // If the generic handler indicates an invalid operand\n";
3788OS << " // failure, check for a special case.\n";
3789OS << " if (Diag != Match_Success) {\n";
3790OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, "
3791"Formal);\n";
3792OS << " if (TargetDiag == Match_Success) {\n";
3793OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3794OS << " dbgs() << \"match success using target "
3795"matcher\\n\");\n";
3796OS << " ++ActualIdx;\n";
3797OS << " continue;\n";
3798OS << " }\n";
3799OS << " // If the target matcher returned a specific error code use\n";
3800OS << " // that, else use the one from the generic matcher.\n";
3801OS << " if (TargetDiag != Match_InvalidOperand && "
3802"HasRequiredFeatures)\n";
3803OS << " Diag = TargetDiag;\n";
3804OS << " }\n";
3805OS << " // If current formal operand wasn't matched and it is optional\n"
3806<< " // then try to match next formal operand\n";
3807OS << " if (Diag == Match_InvalidOperand "
3808<< "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3809if (HasOptionalOperands) {
3810OS << " OptionalOperandsMask.set(FormalIdx);\n";
3811}
3812OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring "
3813"optional operand\\n\");\n";
3814OS << " continue;\n";
3815OS << " }\n";
3816
3817if (ReportMultipleNearMisses) {
3818OS << " if (!OperandNearMiss) {\n";
3819OS << " // If this is the first invalid operand we have seen, "
3820"record some\n";
3821OS << " // information about it.\n";
3822OS << " DEBUG_WITH_TYPE(\n";
3823OS << " \"asm-matcher\",\n";
3824OS << " dbgs()\n";
3825OS << " << \"operand match failed, recording near-miss with "
3826"diag code \"\n";
3827OS << " << Diag << \"\\n\");\n";
3828OS << " OperandNearMiss =\n";
3829OS << " NearMissInfo::getMissedOperand(Diag, Formal, "
3830"it->Opcode, ActualIdx);\n";
3831OS << " ++ActualIdx;\n";
3832OS << " } else {\n";
3833OS << " // If more than one operand is invalid, give up on this "
3834"match entry.\n";
3835OS << " DEBUG_WITH_TYPE(\n";
3836OS << " \"asm-matcher\",\n";
3837OS << " dbgs() << \"second operand mismatch, skipping this "
3838"opcode\\n\");\n";
3839OS << " MultipleInvalidOperands = true;\n";
3840OS << " break;\n";
3841OS << " }\n";
3842OS << " }\n\n";
3843} else {
3844OS << " // If this operand is broken for all of the instances of "
3845"this\n";
3846OS << " // mnemonic, keep track of it so we can report loc info.\n";
3847OS << " // If we already had a match that only failed due to a\n";
3848OS << " // target predicate, that diagnostic is preferred.\n";
3849OS << " if (!HadMatchOtherThanPredicate &&\n";
3850OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) "
3851"{\n";
3852OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3853"!= Match_InvalidOperand))\n";
3854OS << " RetCode = Diag;\n";
3855OS << " ErrorInfo = ActualIdx;\n";
3856OS << " }\n";
3857OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3858OS << " OperandsValid = false;\n";
3859OS << " break;\n";
3860OS << " }\n\n";
3861}
3862
3863if (ReportMultipleNearMisses)
3864OS << " if (MultipleInvalidOperands) {\n";
3865else
3866OS << " if (!OperandsValid) {\n";
3867OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: "
3868"multiple \"\n";
3869OS << " \"operand mismatches, "
3870"ignoring \"\n";
3871OS << " \"this opcode\\n\");\n";
3872OS << " continue;\n";
3873OS << " }\n";
3874
3875// Emit check that the required features are available.
3876OS << " if (!HasRequiredFeatures) {\n";
3877if (!ReportMultipleNearMisses)
3878OS << " HadMatchOtherThanFeatures = true;\n";
3879OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
3880"~AvailableFeatures;\n";
3881OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target "
3882"features:\";\n";
3883OS << " for (unsigned I = 0, E = "
3884"NewMissingFeatures.size(); I != E; ++I)\n";
3885OS << " if (NewMissingFeatures[I])\n";
3886OS << " dbgs() << ' ' << I;\n";
3887OS << " dbgs() << \"\\n\");\n";
3888if (ReportMultipleNearMisses) {
3889OS << " FeaturesNearMiss = "
3890"NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3891} else {
3892OS << " if (NewMissingFeatures.count() <=\n"
3893" MissingFeatures.count())\n";
3894OS << " MissingFeatures = NewMissingFeatures;\n";
3895OS << " continue;\n";
3896}
3897OS << " }\n";
3898OS << "\n";
3899OS << " Inst.clear();\n\n";
3900OS << " Inst.setOpcode(it->Opcode);\n";
3901// Verify the instruction with the target-specific match predicate function.
3902OS << " // We have a potential match but have not rendered the operands.\n"
3903<< " // Check the target predicate to handle any context sensitive\n"
3904" // constraints.\n"
3905<< " // For example, Ties that are referenced multiple times must be\n"
3906" // checked here to ensure the input is the same for each match\n"
3907" // constraints. If we leave it any later the ties will have been\n"
3908" // canonicalized\n"
3909<< " unsigned MatchResult;\n"
3910<< " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3911"Operands)) != Match_Success) {\n"
3912<< " Inst.clear();\n";
3913OS << " DEBUG_WITH_TYPE(\n";
3914OS << " \"asm-matcher\",\n";
3915OS << " dbgs() << \"Early target match predicate failed with diag "
3916"code \"\n";
3917OS << " << MatchResult << \"\\n\");\n";
3918if (ReportMultipleNearMisses) {
3919OS << " EarlyPredicateNearMiss = "
3920"NearMissInfo::getMissedPredicate(MatchResult);\n";
3921} else {
3922OS << " RetCode = MatchResult;\n"
3923<< " HadMatchOtherThanPredicate = true;\n"
3924<< " continue;\n";
3925}
3926OS << " }\n\n";
3927
3928if (ReportMultipleNearMisses) {
3929OS << " // If we did not successfully match the operands, then we can't "
3930"convert to\n";
3931OS << " // an MCInst, so bail out on this instruction variant now.\n";
3932OS << " if (OperandNearMiss) {\n";
3933OS << " // If the operand mismatch was the only problem, reprrt it as "
3934"a near-miss.\n";
3935OS << " if (NearMisses && !FeaturesNearMiss && "
3936"!EarlyPredicateNearMiss) {\n";
3937OS << " DEBUG_WITH_TYPE(\n";
3938OS << " \"asm-matcher\",\n";
3939OS << " dbgs()\n";
3940OS << " << \"Opcode result: one mismatched operand, adding "
3941"near-miss\\n\");\n";
3942OS << " NearMisses->push_back(OperandNearMiss);\n";
3943OS << " } else {\n";
3944OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: "
3945"multiple \"\n";
3946OS << " \"types of "
3947"mismatch, so not \"\n";
3948OS << " \"reporting "
3949"near-miss\\n\");\n";
3950OS << " }\n";
3951OS << " continue;\n";
3952OS << " }\n\n";
3953}
3954
3955// When converting parsed operands to MCInst we need to know whether optional
3956// operands were parsed or not so that we can choose the correct converter
3957// function. We also need to know this when checking tied operand constraints.
3958// DefaultsOffset is an array of deltas between the formal (MCInst) and the
3959// actual (parsed operand array) operand indices. When all optional operands
3960// are present, all elements of the array are zeros. If some of the optional
3961// operands are absent, the array might look like '0, 0, 1, 1, 1, 2, 2, 3',
3962// where each increment in value reflects the absence of an optional operand.
3963if (HasOptionalOperands) {
3964OS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
3965<< "] = { 0 };\n";
3966OS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
3967<< ");\n";
3968OS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
3969<< "; ++i) {\n";
3970OS << " DefaultsOffset[i + 1] = NumDefaults;\n";
3971OS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
3972OS << " }\n\n";
3973}
3974
3975OS << " if (matchingInlineAsm) {\n";
3976OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3977if (!ReportMultipleNearMisses) {
3978if (HasOptionalOperands) {
3979OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3980"Operands,\n";
3981OS << " DefaultsOffset, "
3982"ErrorInfo))\n";
3983} else {
3984OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3985"Operands,\n";
3986OS << " ErrorInfo))\n";
3987}
3988OS << " return Match_InvalidTiedOperand;\n";
3989OS << "\n";
3990}
3991OS << " return Match_Success;\n";
3992OS << " }\n\n";
3993OS << " // We have selected a definite instruction, convert the parsed\n"
3994<< " // operands into the appropriate MCInst.\n";
3995if (HasOptionalOperands) {
3996OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3997<< " OptionalOperandsMask, DefaultsOffset);\n";
3998} else {
3999OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
4000}
4001OS << "\n";
4002
4003// Verify the instruction with the target-specific match predicate function.
4004OS << " // We have a potential match. Check the target predicate to\n"
4005<< " // handle any context sensitive constraints.\n"
4006<< " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
4007<< " Match_Success) {\n"
4008<< " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
4009<< " dbgs() << \"Target match predicate failed with "
4010"diag code \"\n"
4011<< " << MatchResult << \"\\n\");\n"
4012<< " Inst.clear();\n";
4013if (ReportMultipleNearMisses) {
4014OS << " LatePredicateNearMiss = "
4015"NearMissInfo::getMissedPredicate(MatchResult);\n";
4016} else {
4017OS << " RetCode = MatchResult;\n"
4018<< " HadMatchOtherThanPredicate = true;\n"
4019<< " continue;\n";
4020}
4021OS << " }\n\n";
4022
4023if (ReportMultipleNearMisses) {
4024OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
4025OS << " (int)(bool)FeaturesNearMiss +\n";
4026OS << " (int)(bool)EarlyPredicateNearMiss +\n";
4027OS << " (int)(bool)LatePredicateNearMiss);\n";
4028OS << " if (NumNearMisses == 1) {\n";
4029OS << " // We had exactly one type of near-miss, so add that to the "
4030"list.\n";
4031OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled "
4032"earlier\");\n";
4033OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: "
4034"found one type of \"\n";
4035OS << " \"mismatch, so "
4036"reporting a \"\n";
4037OS << " \"near-miss\\n\");\n";
4038OS << " if (NearMisses && FeaturesNearMiss)\n";
4039OS << " NearMisses->push_back(FeaturesNearMiss);\n";
4040OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
4041OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
4042OS << " else if (NearMisses && LatePredicateNearMiss)\n";
4043OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
4044OS << "\n";
4045OS << " continue;\n";
4046OS << " } else if (NumNearMisses > 1) {\n";
4047OS << " // This instruction missed in more than one way, so ignore "
4048"it.\n";
4049OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: "
4050"multiple \"\n";
4051OS << " \"types of mismatch, "
4052"so not \"\n";
4053OS << " \"reporting "
4054"near-miss\\n\");\n";
4055OS << " continue;\n";
4056OS << " }\n";
4057}
4058
4059// Call the post-processing function, if used.
4060StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
4061if (!InsnCleanupFn.empty())
4062OS << " " << InsnCleanupFn << "(Inst);\n";
4063
4064if (HasDeprecation) {
4065OS << " std::string Info;\n";
4066OS << " if "
4067"(!getParser().getTargetParser().getTargetOptions()."
4068"MCNoDeprecatedWarn &&\n";
4069OS << " MII.getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
4070OS << " SMLoc Loc = ((" << Target.getName()
4071<< "Operand &)*Operands[0]).getStartLoc();\n";
4072OS << " getParser().Warning(Loc, Info, std::nullopt);\n";
4073OS << " }\n";
4074}
4075
4076if (!ReportMultipleNearMisses) {
4077if (HasOptionalOperands) {
4078OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
4079"Operands,\n";
4080OS << " DefaultsOffset, "
4081"ErrorInfo))\n";
4082} else {
4083OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
4084"Operands,\n";
4085OS << " ErrorInfo))\n";
4086}
4087OS << " return Match_InvalidTiedOperand;\n";
4088OS << "\n";
4089}
4090
4091OS << " DEBUG_WITH_TYPE(\n";
4092OS << " \"asm-matcher\",\n";
4093OS << " dbgs() << \"Opcode result: complete match, selecting this "
4094"opcode\\n\");\n";
4095OS << " return Match_Success;\n";
4096OS << " }\n\n";
4097
4098if (ReportMultipleNearMisses) {
4099OS << " // No instruction variants matched exactly.\n";
4100OS << " return Match_NearMisses;\n";
4101} else {
4102OS << " // Okay, we had no match. Try to return a useful error code.\n";
4103OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
4104OS << " return RetCode;\n\n";
4105OS << " ErrorInfo = 0;\n";
4106OS << " return Match_MissingFeature;\n";
4107}
4108OS << "}\n\n";
4109
4110if (!Info.OperandMatchInfo.empty())
4111emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
4112MaxMnemonicIndex, FeatureBitsets.size(),
4113HasMnemonicFirst, *AsmParser);
4114
4115OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
4116
4117OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
4118OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
4119
4120emitMnemonicSpellChecker(OS, Target, VariantCount);
4121
4122OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
4123
4124OS << "\n#ifdef GET_MNEMONIC_CHECKER\n";
4125OS << "#undef GET_MNEMONIC_CHECKER\n\n";
4126
4127emitMnemonicChecker(OS, Target, VariantCount, HasMnemonicFirst,
4128HasMnemonicAliases);
4129
4130OS << "#endif // GET_MNEMONIC_CHECKER\n\n";
4131}
4132
4133static TableGen::Emitter::OptClass<AsmMatcherEmitter>
4134X("gen-asm-matcher", "Generate assembly instruction matcher");
4135