blob: d279e8c3ae9490c3924db4cc7c12b36661479f4c [file] [log] [blame]
Daniel Dunbar3085b572009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000011// assembly operands in the MCInst structures. It also emits a matcher for
12// custom operand parsing.
13//
14// Converting assembly operands into MCInst structures
15// ---------------------------------------------------
Daniel Dunbar3085b572009-07-11 19:39:44 +000016//
Daniel Dunbare10787e2009-08-07 08:26:05 +000017// The input to the target specific matcher is a list of literal tokens and
18// operands. The target specific parser should generally eliminate any syntax
19// which is not relevant for matching; for example, comma tokens should have
20// already been consumed and eliminated by the parser. Most instructions will
21// end up with a single literal token (the instruction name) and some number of
22// operands.
23//
24// Some example inputs, for X86:
25// 'addl' (immediate ...) (register ...)
26// 'add' (immediate ...) (memory ...)
Jim Grosbach0eccfc22010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbare10787e2009-08-07 08:26:05 +000028//
29// The assembly matcher is responsible for converting this input into a precise
30// machine instruction (i.e., an instruction with a well defined encoding). This
31// mapping has several properties which complicate matching:
32//
33// - It may be ambiguous; many architectures can legally encode particular
34// variants of an instruction in different ways (for example, using a smaller
35// encoding for small immediates). Such ambiguities should never be
36// arbitrarily resolved by the assembler, the assembler is always responsible
37// for choosing the "best" available instruction.
38//
39// - It may depend on the subtarget or the assembler context. Instructions
40// which are invalid for the current mode, but otherwise unambiguous (e.g.,
41// an SSE instruction in a file being assembled for i486) should be accepted
42// and rejected by the assembler front end. However, if the proper encoding
43// for an instruction is dependent on the assembler context then the matcher
44// is responsible for selecting the correct machine instruction for the
45// current mode.
46//
47// The core matching algorithm attempts to exploit the regularity in most
48// instruction sets to quickly determine the set of possibly matching
49// instructions, and the simplify the generated code. Additionally, this helps
50// to ensure that the ambiguities are intentionally resolved by the user.
51//
52// The matching is divided into two distinct phases:
53//
54// 1. Classification: Each operand is mapped to the unique set which (a)
55// contains it, and (b) is the largest such subset for which a single
56// instruction could match all members.
57//
58// For register classes, we can generate these subgroups automatically. For
59// arbitrary operands, we expect the user to define the classes and their
60// relations to one another (for example, 8-bit signed immediates as a
61// subset of 32-bit immediates).
62//
63// By partitioning the operands in this way, we guarantee that for any
64// tuple of classes, any single instruction must match either all or none
65// of the sets of operands which could classify to that tuple.
66//
67// In addition, the subset relation amongst classes induces a partial order
68// on such tuples, which we use to resolve ambiguities.
69//
Daniel Dunbare10787e2009-08-07 08:26:05 +000070// 2. The input can now be treated as a tuple of classes (static tokens are
71// simple singleton sets). Each such tuple should generally map to a single
72// instruction (we currently ignore cases where this isn't true, whee!!!),
73// which we can emit a simple matcher for.
74//
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000075// Custom Operand Parsing
76// ----------------------
77//
78// Some targets need a custom way to parse operands, some specific instructions
79// can contain arguments that can represent processor flags and other kinds of
Craig Topperaae8fb82012-09-18 01:13:36 +000080// identifiers that need to be mapped to specific values in the final encoded
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000081// instructions. The target specific custom operand parsing works in the
82// following way:
83//
84// 1. A operand match table is built, each entry contains a mnemonic, an
85// operand class, a mask for all operand positions for that same
86// class/mnemonic and target features to be checked while trying to match.
87//
88// 2. The operand matcher will try every possible entry with the same
89// mnemonic and will check if the target feature for this mnemonic also
90// matches. After that, if the operand to be matched has its index
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000092// to the regular operand parsing.
93//
94// 3. For a match success, each operand class that has a 'ParserMethod'
95// becomes part of a switch from where the custom method is called.
96//
Daniel Dunbar3085b572009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
Daniel Dunbar3085b572009-07-11 19:39:44 +000099#include "CodeGenTarget.h"
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000100#include "SubtargetFeatureInfo.h"
Daniel Sandersca89f3a2016-11-19 12:21:34 +0000101#include "Types.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000102#include "llvm/ADT/CachedHashString.h"
Chris Lattner4efe13d2010-11-04 02:11:18 +0000103#include "llvm/ADT/PointerUnion.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +0000104#include "llvm/ADT/STLExtras.h"
Chris Lattnerf7a01e92010-11-01 01:47:07 +0000105#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000106#include "llvm/ADT/SmallVector.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000107#include "llvm/ADT/StringExtras.h"
108#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000109#include "llvm/Support/Debug.h"
Craig Topperc4965bc2012-02-05 07:21:30 +0000110#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +0000111#include "llvm/TableGen/Error.h"
112#include "llvm/TableGen/Record.h"
Douglas Gregor12c1cd32012-05-02 17:32:48 +0000113#include "llvm/TableGen/StringMatcher.h"
Craig Topper3e1d5da2013-08-29 05:09:55 +0000114#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000115#include "llvm/TableGen/TableGenBackend.h"
116#include <cassert>
Will Dietz981af002013-10-12 00:55:57 +0000117#include <cctype>
Mehdi Aminib550cb12016-04-18 09:17:29 +0000118#include <forward_list>
Daniel Dunbar71330282009-08-08 05:24:34 +0000119#include <map>
120#include <set>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000121
Daniel Dunbar3085b572009-07-11 19:39:44 +0000122using namespace llvm;
123
Chandler Carruthe96dd892014-04-21 22:55:11 +0000124#define DEBUG_TYPE "asm-matcher-emitter"
125
Daniel Sanders0848b232017-03-27 13:15:13 +0000126cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
127
Daniel Dunbar15b80372009-08-07 20:33:39 +0000128static cl::opt<std::string>
Daniel Sanders0848b232017-03-27 13:15:13 +0000129 MatchPrefix("match-prefix", cl::init(""),
130 cl::desc("Only match instructions with the given prefix"),
131 cl::cat(AsmMatcherEmitterCat));
Daniel Dunbare10787e2009-08-07 08:26:05 +0000132
Daniel Dunbare10787e2009-08-07 08:26:05 +0000133namespace {
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000134class AsmMatcherInfo;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000135
Tim Northoverc74e6912013-09-16 16:43:19 +0000136// Register sets are used as keys in some second-order sets TableGen creates
137// when generating its data structures. This means that the order of two
138// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
139// can even affect compiler output (at least seen in diagnostics produced when
140// all matches fail). So we use a type that sorts them consistently.
141typedef std::set<Record*, LessRecordByID> RegisterSet;
142
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000143class AsmMatcherEmitter {
144 RecordKeeper &Records;
145public:
146 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
147
148 void run(raw_ostream &o);
149};
150
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000151/// ClassInfo - Helper class for storing the information about a particular
152/// class of operands which can be matched.
153struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000154 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000155 /// Invalid kind, for use as a sentinel value.
156 Invalid = 0,
157
158 /// The class for a particular token.
159 Token,
160
161 /// The (first) register class, subsequent register classes are
162 /// RegisterClass0+1, and so on.
163 RegisterClass0,
164
165 /// The (first) user defined class, subsequent user defined classes are
166 /// UserClass0+1, and so on.
167 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000168 };
169
170 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
171 /// N) for the Nth user defined class.
172 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000173
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000174 /// SuperClasses - The super classes of this class. Note that for simplicities
175 /// sake user operands only record their immediate super class, while register
176 /// operands include all superclasses.
177 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000178
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000179 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000180 std::string Name;
181
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000182 /// ClassName - The unadorned generic name for this class (e.g., Token).
183 std::string ClassName;
184
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000185 /// ValueName - The name of the value this class represents; for a token this
186 /// is the literal token string, for an operand it is the TableGen class (or
187 /// empty if this is a derived class).
188 std::string ValueName;
189
190 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000191 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000192 std::string PredicateMethod;
193
194 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000195 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000196 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000197
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000198 /// ParserMethod - The name of the operand method to do a target specific
199 /// parsing on the operand.
200 std::string ParserMethod;
201
Eric Christopher650c8f22014-05-20 17:11:11 +0000202 /// For register classes: the records for all the registers in this class.
Tim Northoverc74e6912013-09-16 16:43:19 +0000203 RegisterSet Registers;
Daniel Dunbar34c87912009-08-11 20:10:07 +0000204
Eric Christopher650c8f22014-05-20 17:11:11 +0000205 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000206 std::string DiagnosticType;
Tom Stellardb9f235e2016-02-05 19:59:33 +0000207
Oliver Stannard41dfac32017-10-03 14:34:57 +0000208 /// For custom match classes: the diagnostic string for when the predicate fails.
209 std::string DiagnosticString;
210
Tom Stellardb9f235e2016-02-05 19:59:33 +0000211 /// Is this operand optional and not always required.
212 bool IsOptional;
213
Sam Kolton5f10a132016-05-06 11:31:17 +0000214 /// DefaultMethod - The name of the method that returns the default operand
215 /// for optional operand
216 std::string DefaultMethod;
217
Daniel Dunbar34c87912009-08-11 20:10:07 +0000218public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000219 /// isRegisterClass() - Check if this is a register class.
220 bool isRegisterClass() const {
221 return Kind >= RegisterClass0 && Kind < UserClass0;
222 }
223
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000224 /// isUserClass() - Check if this is a user defined class.
225 bool isUserClass() const {
226 return Kind >= UserClass0;
227 }
228
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000229 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000230 /// are related if they are in the same class hierarchy.
231 bool isRelatedTo(const ClassInfo &RHS) const {
232 // Tokens are only related to tokens.
233 if (Kind == Token || RHS.Kind == Token)
234 return Kind == Token && RHS.Kind == Token;
235
Daniel Dunbar34c87912009-08-11 20:10:07 +0000236 // Registers classes are only related to registers classes, and only if
237 // their intersection is non-empty.
238 if (isRegisterClass() || RHS.isRegisterClass()) {
239 if (!isRegisterClass() || !RHS.isRegisterClass())
240 return false;
241
Tim Northoverc74e6912013-09-16 16:43:19 +0000242 RegisterSet Tmp;
243 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000244 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000245 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +0000246 II, LessRecordByID());
Daniel Dunbar34c87912009-08-11 20:10:07 +0000247
248 return !Tmp.empty();
249 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000250
251 // Otherwise we have two users operands; they are related if they are in the
252 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000253 //
254 // FIXME: This is an oversimplification, they should only be related if they
255 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000256 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
257 const ClassInfo *Root = this;
258 while (!Root->SuperClasses.empty())
259 Root = Root->SuperClasses.front();
260
Daniel Dunbar34c87912009-08-11 20:10:07 +0000261 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000262 while (!RHSRoot->SuperClasses.empty())
263 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000264
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000265 return Root == RHSRoot;
266 }
267
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000268 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000269 bool isSubsetOf(const ClassInfo &RHS) const {
270 // This is a subset of RHS if it is the same class...
271 if (this == &RHS)
272 return true;
273
274 // ... or if any of its super classes are a subset of RHS.
Craig Topper03ec8012014-11-25 20:11:31 +0000275 for (const ClassInfo *CI : SuperClasses)
276 if (CI->isSubsetOf(RHS))
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000277 return true;
278
279 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000280 }
281
Oliver Stannard7772f022016-01-25 10:20:19 +0000282 int getTreeDepth() const {
283 int Depth = 0;
284 const ClassInfo *Root = this;
285 while (!Root->SuperClasses.empty()) {
286 Depth++;
287 Root = Root->SuperClasses.front();
288 }
289 return Depth;
290 }
291
292 const ClassInfo *findRoot() const {
293 const ClassInfo *Root = this;
294 while (!Root->SuperClasses.empty())
295 Root = Root->SuperClasses.front();
296 return Root;
297 }
298
299 /// Compare two classes. This does not produce a total ordering, but does
300 /// guarantee that subclasses are sorted before their parents, and that the
301 /// ordering is transitive.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000302 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000303 if (this == &RHS)
304 return false;
305
Oliver Stannard7772f022016-01-25 10:20:19 +0000306 // First, enforce the ordering between the three different types of class.
307 // Tokens sort before registers, which sort before user classes.
308 if (Kind == Token) {
309 if (RHS.Kind != Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000310 return true;
Oliver Stannard7772f022016-01-25 10:20:19 +0000311 assert(RHS.Kind == Token);
312 } else if (isRegisterClass()) {
313 if (RHS.Kind == Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000314 return false;
Oliver Stannard7772f022016-01-25 10:20:19 +0000315 else if (RHS.isUserClass())
316 return true;
317 assert(RHS.isRegisterClass());
318 } else if (isUserClass()) {
319 if (!RHS.isUserClass())
320 return false;
321 assert(RHS.isUserClass());
322 } else {
323 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000324 }
Oliver Stannard7772f022016-01-25 10:20:19 +0000325
326 if (Kind == Token || isUserClass()) {
327 // Related tokens and user classes get sorted by depth in the inheritence
328 // tree (so that subclasses are before their parents).
329 if (isRelatedTo(RHS)) {
330 if (getTreeDepth() > RHS.getTreeDepth())
331 return true;
332 if (getTreeDepth() < RHS.getTreeDepth())
333 return false;
334 } else {
335 // Unrelated tokens and user classes are ordered by the name of their
336 // root nodes, so that there is a consistent ordering between
337 // unconnected trees.
338 return findRoot()->ValueName < RHS.findRoot()->ValueName;
339 }
340 } else if (isRegisterClass()) {
341 // For register sets, sort by number of registers. This guarantees that
342 // a set will always sort before all of it's strict supersets.
343 if (Registers.size() != RHS.Registers.size())
344 return Registers.size() < RHS.Registers.size();
345 } else {
346 llvm_unreachable("Unknown ClassInfoKind");
347 }
348
349 // FIXME: We should be able to just return false here, as we only need a
350 // partial order (we use stable sorts, so this is deterministic) and the
351 // name of a class shouldn't be significant. However, some of the backends
352 // accidentally rely on this behaviour, so it will have to stay like this
353 // until they are fixed.
354 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000355 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000356};
357
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000358class AsmVariantInfo {
359public:
Craig Topperbcd3c372017-05-31 21:12:46 +0000360 StringRef RegisterPrefix;
361 StringRef TokenizingCharacters;
362 StringRef SeparatorCharacters;
363 StringRef BreakCharacters;
364 StringRef Name;
Craig Topperc8b5b252015-12-30 06:00:18 +0000365 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000366};
367
Chris Lattnerad776812010-11-01 05:06:45 +0000368/// MatchableInfo - Helper class for storing the necessary information for an
369/// instruction or alias which is capable of being matched.
370struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000371 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000372 /// Token - This is the token that the operand came from.
373 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000374
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000375 /// The unique class instance this operand should match.
376 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000377
Chris Lattner7108dad2010-11-04 01:42:59 +0000378 /// The operand name this is, if anything.
379 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000380
381 /// The suboperand index within SrcOpName, or -1 for the entire operand.
382 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000383
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000384 /// Whether the token is "isolated", i.e., it is preceded and followed
385 /// by separators.
386 bool IsIsolatedToken;
387
Devang Patel6d676e42012-01-07 01:33:34 +0000388 /// Register record if this token is singleton register.
389 Record *SingletonReg;
390
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000391 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
392 : Token(T), Class(nullptr), SubOpIdx(-1),
393 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000394 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000395
Chris Lattner743081d2010-11-04 00:43:46 +0000396 /// ResOperand - This represents a single operand in the result instruction
397 /// generated by the match. In cases (like addressing modes) where a single
398 /// assembler operand expands to multiple MCOperands, this represents the
399 /// single assembler operand, not the MCOperand.
400 struct ResOperand {
401 enum {
402 /// RenderAsmOperand - This represents an operand result that is
403 /// generated by calling the render method on the assembly operand. The
404 /// corresponding AsmOperand is specified by AsmOperandNum.
405 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000406
Chris Lattner743081d2010-11-04 00:43:46 +0000407 /// TiedOperand - This represents a result operand that is a duplicate of
408 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000409 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000410
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000411 /// ImmOperand - This represents an immediate value that is dumped into
412 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000413 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000414
Chris Lattner4869d342010-11-06 19:57:21 +0000415 /// RegOperand - This represents a fixed register that is dumped in.
416 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000417 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000418
Chris Lattner743081d2010-11-04 00:43:46 +0000419 union {
420 /// This is the operand # in the AsmOperands list that this should be
421 /// copied from.
422 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000423
Chris Lattner743081d2010-11-04 00:43:46 +0000424 /// TiedOperandNum - This is the (earlier) result operand that should be
425 /// copied from.
426 unsigned TiedOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000427
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000428 /// ImmVal - This is the immediate value added to the instruction.
429 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000430
Chris Lattner4869d342010-11-06 19:57:21 +0000431 /// Register - This is the register record.
432 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000433 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000434
Bob Wilsonb9b24222011-01-26 19:44:55 +0000435 /// MINumOperands - The number of MCInst operands populated by this
436 /// operand.
437 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000438
Bob Wilsonb9b24222011-01-26 19:44:55 +0000439 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000440 ResOperand X;
441 X.Kind = RenderAsmOperand;
442 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000443 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000444 return X;
445 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000446
Bob Wilsonb9b24222011-01-26 19:44:55 +0000447 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner743081d2010-11-04 00:43:46 +0000448 ResOperand X;
449 X.Kind = TiedOperand;
450 X.TiedOperandNum = TiedOperandNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000451 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000452 return X;
453 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000454
Bob Wilsonb9b24222011-01-26 19:44:55 +0000455 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000456 ResOperand X;
457 X.Kind = ImmOperand;
458 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000459 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000460 return X;
461 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000462
Bob Wilsonb9b24222011-01-26 19:44:55 +0000463 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000464 ResOperand X;
465 X.Kind = RegOperand;
466 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000467 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000468 return X;
469 }
Chris Lattner743081d2010-11-04 00:43:46 +0000470 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000471
Devang Patel9bdc5052012-01-10 17:50:43 +0000472 /// AsmVariantID - Target's assembly syntax variant no.
473 int AsmVariantID;
474
David Blaikieba4e00f2014-12-22 21:26:26 +0000475 /// AsmString - The assembly string for this instruction (with variants
476 /// removed), e.g. "movsx $src, $dst".
477 std::string AsmString;
478
Chris Lattnera7a903e2010-11-02 17:34:28 +0000479 /// TheDef - This is the definition of the instruction or InstAlias that this
480 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000481 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000482
Chris Lattner4efe13d2010-11-04 02:11:18 +0000483 /// DefRec - This is the definition that it came from.
484 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000485
Chris Lattnerfecdad62010-11-06 07:14:44 +0000486 const CodeGenInstruction *getResultInst() const {
487 if (DefRec.is<const CodeGenInstruction*>())
488 return DefRec.get<const CodeGenInstruction*>();
489 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
490 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000491
Chris Lattner743081d2010-11-04 00:43:46 +0000492 /// ResOperands - This is the operand list that should be built for the result
493 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000494 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000495
Chris Lattner28ea9b12010-11-02 17:30:52 +0000496 /// Mnemonic - This is the first token of the matched instruction, its
497 /// mnemonic.
498 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000499
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000500 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000501 /// annotated with a class and where in the OperandList they were defined.
502 /// This directly corresponds to the tokenized AsmString after the mnemonic is
503 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000504 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000505
Daniel Dunbareefe8612010-07-19 05:44:09 +0000506 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000507 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000508
Daniel Dunbar71330282009-08-08 05:24:34 +0000509 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000510 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000511 /// function.
512 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000513
Joey Gouly0e76fa72013-09-12 10:28:05 +0000514 /// If this instruction is deprecated in some form.
515 bool HasDeprecation;
516
Tom Stellard74c87c82015-05-26 15:55:50 +0000517 /// If this is an alias, this is use to determine whether or not to using
518 /// the conversion function defined by the instruction's AsmMatchConverter
519 /// or to use the function generated by the alias.
520 bool UseInstAsmMatchConverter;
521
Chris Lattnerad776812010-11-01 05:06:45 +0000522 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000523 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
524 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000525 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000526
David Blaikieba4e00f2014-12-22 21:26:26 +0000527 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000528 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
529 DefRec(Alias.release()),
530 UseInstAsmMatchConverter(
531 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000532 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000533
David Blaikie6e48a812015-08-01 01:08:30 +0000534 // Could remove this and the dtor if PointerUnion supported unique_ptr
535 // elements with a dynamic failure/assertion (like the one below) in the case
536 // where it was copied while being in an owning state.
537 MatchableInfo(const MatchableInfo &RHS)
538 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
539 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
540 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
541 RequiredFeatures(RHS.RequiredFeatures),
542 ConversionFnKind(RHS.ConversionFnKind),
543 HasDeprecation(RHS.HasDeprecation),
544 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
545 assert(!DefRec.is<const CodeGenInstAlias *>());
546 }
547
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000548 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000549 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000550 }
Craig Topperce274892014-11-28 05:01:21 +0000551
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000552 // Two-operand aliases clone from the main matchable, but mark the second
553 // operand as a tied operand of the first for purposes of the assembler.
554 void formTwoOperandAlias(StringRef Constraint);
555
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000556 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000557 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000558 AsmVariantInfo const &Variant,
559 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000560
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000561 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000562 /// and perform a bunch of validity checking.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000563 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000564
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000565 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000566 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000567 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000568 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
569 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
570 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000571 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000572 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000573
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000574 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000575 /// This does not check the suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000576 int findAsmOperandNamed(StringRef N) const {
David Majnemer562e8292016-08-12 00:18:03 +0000577 auto I = find_if(AsmOperands,
578 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000579 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000580 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000581
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000582 void buildInstructionResultOperands();
583 void buildAliasResultOperands();
Chris Lattner743081d2010-11-04 00:43:46 +0000584
Chris Lattnerad776812010-11-01 05:06:45 +0000585 /// operator< - Compare two matchables.
586 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000587 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000588 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
589 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000590
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000591 if (AsmOperands.size() != RHS.AsmOperands.size())
592 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000593
Daniel Dunbard9631912009-08-09 08:23:23 +0000594 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000595 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000596 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
597 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000598 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000599 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000600 return false;
601 }
602
Andrew Trick818f5ac2012-08-29 03:52:57 +0000603 // Give matches that require more features higher precedence. This is useful
604 // because we cannot define AssemblerPredicates with the negation of
605 // processor features. For example, ARM v6 "nop" may be either a HINT or
606 // MOV. With v6, we want to match HINT. The assembler has no way to
607 // predicate MOV under "NoV6", but HINT will always match first because it
608 // requires V6 while MOV does not.
609 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
610 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
611
Daniel Dunbar3239f022009-08-09 04:00:06 +0000612 return false;
613 }
614
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000615 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000616 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000617 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000618 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000619 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000620 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000621 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000622
Daniel Dunbarf573b562009-08-09 06:05:33 +0000623 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000624 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000625 return false;
626
Daniel Dunbare1974092010-01-23 00:26:16 +0000627 // Otherwise, make sure the ordering of the two instructions is unambiguous
628 // by checking that either (a) a token or operand kind discriminates them,
629 // or (b) the ordering among equivalent kinds is consistent.
630
Daniel Dunbarf573b562009-08-09 06:05:33 +0000631 // Tokens and operand kinds are unambiguous (assuming a correct target
632 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000633 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
634 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
635 AsmOperands[i].Class->Kind == ClassInfo::Token)
636 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
637 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000638 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000639
Daniel Dunbarf573b562009-08-09 06:05:33 +0000640 // Otherwise, this operand could commute if all operands are equivalent, or
641 // there is a pair of operands that compare less than and a pair that
642 // compare greater than.
643 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000644 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
645 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000646 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000647 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000648 HasGT = true;
649 }
650
Craig Topper322b67f2016-01-03 07:33:39 +0000651 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000652 }
653
Craig Topper42bd8192014-11-28 03:53:00 +0000654 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000655
Chris Lattner28ea9b12010-11-02 17:30:52 +0000656private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000657 void tokenizeAsmString(AsmMatcherInfo const &Info,
658 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000659 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000660};
661
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000662struct OperandMatchEntry {
663 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000664 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000665 ClassInfo *CI;
666
Craig Topper42bd8192014-11-28 03:53:00 +0000667 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000668 unsigned opMask) {
669 OperandMatchEntry X;
670 X.OperandMask = opMask;
671 X.CI = ci;
672 X.MI = mi;
673 return X;
674 }
675};
676
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000677class AsmMatcherInfo {
678public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000679 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000680 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000681
Daniel Dunbare4318712009-08-11 20:59:47 +0000682 /// The tablegen AsmParser record.
683 Record *AsmParser;
684
Chris Lattnerb80ab362010-11-01 01:37:30 +0000685 /// Target - The target information.
686 CodeGenTarget &Target;
687
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000688 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000689 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000690
Chris Lattnerad776812010-11-01 05:06:45 +0000691 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000692 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000693
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000694 /// Info for custom matching operands by user defined methods.
695 std::vector<OperandMatchEntry> OperandMatchInfo;
696
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000697 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000698 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
699 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000700
Daniel Dunbareefe8612010-07-19 05:44:09 +0000701 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000702 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000703
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000704 /// Map of AsmOperandClass records to their class information.
705 std::map<Record*, ClassInfo*> AsmOperandClasses;
706
Oliver Stannard29ffd3f2017-10-10 11:00:40 +0000707 /// Map of RegisterClass records to their class information.
708 std::map<Record*, ClassInfo*> RegisterClassClasses;
709
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000710private:
711 /// Map of token to class information which has already been constructed.
712 std::map<std::string, ClassInfo*> TokenClasses;
713
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000714private:
715 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000716 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000717
718 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000719 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000720 int SubOpIdx);
721 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000722
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000723 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000724 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000725 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000726
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000727 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000728 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000729 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000730
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000731 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000732 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000733 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000734 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000735
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000736public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000737 AsmMatcherInfo(Record *AsmParser,
738 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000739 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000740
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000741 /// Construct the various tables used during matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000742 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000743
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000744 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000745 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000746 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000747
Chris Lattner43690072010-10-30 20:15:02 +0000748 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
749 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000750 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000751 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000752 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000753 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000754 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000755
Chris Lattner89dcb682010-12-15 04:48:22 +0000756 RecordKeeper &getRecords() const {
757 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000758 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000759
760 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000761 return find_if(Classes, [](const ClassInfo &Class) {
762 return Class.IsOptional;
763 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000764 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000765};
766
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000767} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000768
Aaron Ballman615eb472017-10-15 14:32:27 +0000769#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000770LLVM_DUMP_METHOD void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000771 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000772
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000773 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000774 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000775 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000776 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000777 }
778}
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000779#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +0000780
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000781static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000782parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000783 // Split via the '='.
784 std::pair<StringRef, StringRef> Ops = S.split('=');
785 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000786 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000787 // Trim whitespace and the leading '$' on the operand names.
788 size_t start = Ops.first.find_first_of('$');
789 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000790 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000791 Ops.first = Ops.first.slice(start + 1, std::string::npos);
792 size_t end = Ops.first.find_last_of(" \t");
793 Ops.first = Ops.first.slice(0, end);
794 // Now the second operand.
795 start = Ops.second.find_first_of('$');
796 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000797 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000798 Ops.second = Ops.second.slice(start + 1, std::string::npos);
799 end = Ops.second.find_last_of(" \t");
800 Ops.first = Ops.first.slice(0, end);
801 return Ops;
802}
803
804void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
805 // Figure out which operands are aliased and mark them as tied.
806 std::pair<StringRef, StringRef> Ops =
807 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
808
809 // Find the AsmOperands that refer to the operands we're aliasing.
810 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
811 int DstAsmOperand = findAsmOperandNamed(Ops.second);
812 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000813 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000814 "unknown source two-operand alias operand '" + Ops.first +
815 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000816 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000817 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000818 "unknown destination two-operand alias operand '" +
819 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000820
821 // Find the ResOperand that refers to the operand we're aliasing away
822 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000823 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000824 if (Op.Kind == ResOperand::RenderAsmOperand &&
825 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
826 Op.AsmOperandNum = DstAsmOperand;
827 break;
828 }
829 }
830 // Remove the AsmOperand for the alias operand.
831 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
832 // Adjust the ResOperand references to any AsmOperands that followed
833 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000834 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000835 switch(Op.Kind) {
836 default:
837 // Nothing to do for operands that don't reference AsmOperands.
838 break;
839 case ResOperand::RenderAsmOperand:
840 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
841 --Op.AsmOperandNum;
842 break;
843 case ResOperand::TiedOperand:
844 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
845 --Op.TiedOperandNum;
846 break;
847 }
848 }
849}
850
Craig Topper22fa45f2015-09-13 18:01:25 +0000851/// extractSingletonRegisterForAsmOperand - Extract singleton register,
852/// if present, from specified token.
853static void
854extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
855 const AsmMatcherInfo &Info,
856 StringRef RegisterPrefix) {
857 StringRef Tok = Op.Token;
858
859 // If this token is not an isolated token, i.e., it isn't separated from
860 // other tokens (e.g. with whitespace), don't interpret it as a register name.
861 if (!Op.IsIsolatedToken)
862 return;
863
864 if (RegisterPrefix.empty()) {
865 std::string LoweredTok = Tok.lower();
866 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
867 Op.SingletonReg = Reg->TheDef;
868 return;
869 }
870
871 if (!Tok.startswith(RegisterPrefix))
872 return;
873
874 StringRef RegName = Tok.substr(RegisterPrefix.size());
875 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
876 Op.SingletonReg = Reg->TheDef;
877
878 // If there is no register prefix (i.e. "%" in "%eax"), then this may
879 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000880}
881
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000882void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000883 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000884 AsmVariantInfo const &Variant,
885 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000886 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000887 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000888 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
889 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000890
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000891 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000892
Craig Topperfd2c6a32015-12-31 08:18:23 +0000893 // The first token of the instruction is the mnemonic, which must be a
894 // simple string, not a $foo variable or a singleton register.
895 if (AsmOperands.empty())
896 PrintFatalError(TheDef->getLoc(),
897 "Instruction '" + TheDef->getName() + "' has no tokens");
898
899 assert(!AsmOperands[0].Token.empty());
900 if (HasMnemonicFirst) {
901 Mnemonic = AsmOperands[0].Token;
902 if (Mnemonic[0] == '$')
903 PrintFatalError(TheDef->getLoc(),
904 "Invalid instruction mnemonic '" + Mnemonic + "'!");
905
906 // Remove the first operand, it is tracked in the mnemonic field.
907 AsmOperands.erase(AsmOperands.begin());
908 } else if (AsmOperands[0].Token[0] != '$')
909 Mnemonic = AsmOperands[0].Token;
910
Chris Lattnerba465f92010-11-01 04:53:48 +0000911 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000912 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000913 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000914 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000915 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000916
Chris Lattnerba465f92010-11-01 04:53:48 +0000917 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000918 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000919 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000920 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000921 SingletonRegisters.insert(Reg);
922 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000923
924 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
925 if (!DepMask)
926 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
927
928 HasDeprecation =
929 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000930}
931
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000932/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000933void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
934 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000935}
936
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000937/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000938void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
939 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000940 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000941 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000942 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000943 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000944 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000945 char Char = String[i];
946 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
947 if (InTok) {
948 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000949 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000950 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000951 }
952 InTok = true;
953 continue;
954 }
Craig Topperbc22e262015-12-31 05:01:45 +0000955 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
956 if (InTok) {
957 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000958 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000959 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000960 }
Craig Topperbc22e262015-12-31 05:01:45 +0000961 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000962 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000963 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000964 continue;
965 }
Craig Topperbc22e262015-12-31 05:01:45 +0000966 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
967 if (InTok) {
968 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000969 InTok = false;
970 }
971 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000972 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000973 continue;
974 }
Craig Topperbc22e262015-12-31 05:01:45 +0000975
976 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000977 case '\\':
978 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +0000979 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000980 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000981 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000982 }
983 ++i;
984 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +0000985 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000986 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000987 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000988 break;
989
990 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +0000991 if (InTok) {
992 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000993 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000994 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000995 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000996
Colin LeMahieu3d905742015-08-10 19:58:06 +0000997 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +0000998 if (i + 1 == String.size() || String[i + 1] != '{') {
999 Prev = i;
1000 break;
1001 }
Chris Lattner28ea9b12010-11-02 17:30:52 +00001002
Craig Topperba614322015-12-30 06:00:15 +00001003 size_t EndPos = String.find('}', i);
1004 assert(EndPos != StringRef::npos &&
1005 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001006 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001007 Prev = EndPos + 1;
1008 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001009 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001010 break;
1011 }
Craig Topperbc22e262015-12-31 05:01:45 +00001012
Chris Lattner28ea9b12010-11-02 17:30:52 +00001013 default:
1014 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001015 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001016 }
1017 }
1018 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001019 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001020}
1021
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001022bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001023 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001024 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001025 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001026
Chris Lattnerad776812010-11-01 05:06:45 +00001027 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001028 // isCodeGenOnly if they are pseudo instructions.
1029 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001030 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001031 "multiline instruction is not valid for the asmparser, "
1032 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001033
Chris Lattner178f4bb2010-11-01 04:44:29 +00001034 // Remove comments from the asm string. We know that the asmstring only
1035 // has one line.
1036 if (!CommentDelimiter.empty() &&
1037 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001038 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001039 "asmstring for instruction has comment character in it, "
1040 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001041
Chris Lattnerad776812010-11-01 05:06:45 +00001042 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001043 // handle, the target should be refactored to use operands instead of
1044 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001045 //
1046 // Also, check for instructions which reference the operand multiple times;
1047 // this implies a constraint we would not honor.
1048 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001049 for (const AsmOperand &Op : AsmOperands) {
1050 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001051 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001052 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001053 "matchable with operand modifier '" + Tok +
1054 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001055
Chris Lattnerad776812010-11-01 05:06:45 +00001056 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001057 // We reject aliases and ignore instructions for now.
Chris Lattner28ea9b12010-11-02 17:30:52 +00001058 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattnerad776812010-11-01 05:06:45 +00001059 if (!Hack)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001060 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001061 "ERROR: matchable with tied operand '" + Tok +
1062 "' can never be matched!");
Chris Lattnerad776812010-11-01 05:06:45 +00001063 // FIXME: Should reject these. The ARM backend hits this with $lane in a
1064 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001065 DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001066 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001067 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001068 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001069 });
1070 return false;
1071 }
1072 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001073
Chris Lattner39bc53b2010-11-01 04:34:44 +00001074 return true;
1075}
1076
Chris Lattner60db0a62010-02-09 00:34:28 +00001077static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001078 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001079
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001080 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1081 switch (*it) {
1082 case '*': Res += "_STAR_"; break;
1083 case '%': Res += "_PCT_"; break;
1084 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001085 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001086 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001087 case '<': Res += "_LT_"; break;
1088 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001089 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001090 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001091 if ((*it >= 'A' && *it <= 'Z') ||
1092 (*it >= 'a' && *it <= 'z') ||
1093 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001094 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001095 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001096 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001097 }
1098 }
1099
1100 return Res;
1101}
1102
Chris Lattner60db0a62010-02-09 00:34:28 +00001103ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001104 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001105
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001106 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001107 Classes.emplace_front();
1108 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001109 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001110 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001111 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1112 Entry->ValueName = Token;
1113 Entry->PredicateMethod = "<invalid>";
1114 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001115 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001116 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001117 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001118 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001119 }
1120
1121 return Entry;
1122}
1123
1124ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001125AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1126 int SubOpIdx) {
1127 Record *Rec = OI.Rec;
1128 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001129 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001130 return getOperandClass(Rec, SubOpIdx);
1131}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001132
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001133ClassInfo *
1134AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001135 if (Rec->isSubClassOf("RegisterOperand")) {
1136 // RegisterOperand may have an associated ParserMatchClass. If it does,
1137 // use it, else just fall back to the underlying register class.
1138 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001139 if (!R || !R->getValue())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001140 PrintFatalError("Record `" + Rec->getName() +
1141 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001142
Sean Silvafb509ed2012-10-10 20:24:43 +00001143 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001144 Record *MatchClass = DI->getDef();
1145 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1146 return CI;
1147 }
1148
1149 // No custom match class. Just use the register class.
1150 Record *ClassRec = Rec->getValueAsDef("RegClass");
1151 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001152 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001153 "' has no associated register class!\n");
1154 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1155 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001156 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001157 }
1158
Bob Wilsonb9b24222011-01-26 19:44:55 +00001159 if (Rec->isSubClassOf("RegisterClass")) {
1160 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001161 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001162 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001163 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001164
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001165 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001166 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001167 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001168 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001169 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1170 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001171
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001172 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001173}
1174
Tim Northoverc74e6912013-09-16 16:43:19 +00001175struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001176 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001177 // std::set<T> defines its own compariso "operator<", but it
1178 // performs a lexicographical comparison by T's innate comparison
1179 // for some reason. We don't want non-deterministic pointer
1180 // comparisons so use this instead.
1181 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1182 RHS.begin(), RHS.end(),
1183 LessRecordByID());
1184 }
1185};
1186
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001187void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001188buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001189 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001190 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001191
Tim Northoverc74e6912013-09-16 16:43:19 +00001192 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1193
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001194 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001195 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001196
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001197 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001198 for (const CodeGenRegisterClass &RC : RegClassList)
1199 RegisterSets.insert(
1200 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001201
1202 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001203 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001204 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001205 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001206
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001207 // Introduce derived sets where necessary (when a register does not determine
1208 // a unique register set class), and build the mapping of registers to the set
1209 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001210 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001211 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001212 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001213 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001214
Craig Topper03ec8012014-11-25 20:11:31 +00001215 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001216 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001217 continue;
1218
1219 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001220 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001221 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001222 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001223
Tim Northoverc74e6912013-09-16 16:43:19 +00001224 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001225 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001226 std::insert_iterator<RegisterSet> II(ContainingSet,
1227 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001228 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001229 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001230 }
1231
1232 if (!ContainingSet.empty()) {
1233 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001234 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001235 }
1236 }
1237
1238 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001239 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001240 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001241 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001242 Classes.emplace_front();
1243 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001244 CI->Kind = ClassInfo::RegisterClass0 + Index;
1245 CI->ClassName = "Reg" + utostr(Index);
1246 CI->Name = "MCK_Reg" + utostr(Index);
1247 CI->ValueName = "";
1248 CI->PredicateMethod = ""; // unused
1249 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001250 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001251 // FIXME: diagnostic type.
1252 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001253 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001254 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001255 RegisterSetClasses.insert(std::make_pair(RS, CI));
1256 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001257 }
1258
1259 // Find the superclasses; we could compute only the subgroup lattice edges,
1260 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001261 for (const RegisterSet &RS : RegisterSets) {
1262 ClassInfo *CI = RegisterSetClasses[RS];
1263 for (const RegisterSet &RS2 : RegisterSets)
1264 if (RS != RS2 &&
1265 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001266 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001267 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001268 }
1269
1270 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001271 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001272 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001273 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001274 if (!Def)
1275 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001276 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1277 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001278 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001279 CI->ClassName = RC.getName();
1280 CI->Name = "MCK_" + RC.getName();
1281 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001282 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001283 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001284
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00001285 Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1286 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1287 CI->DiagnosticType = SI->getValue();
1288
1289 Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1290 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1291 CI->DiagnosticString = SI->getValue();
1292
1293 // If we have a diagnostic string but the diagnostic type is not specified
1294 // explicitly, create an anonymous diagnostic type.
1295 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1296 CI->DiagnosticType = RC.getName();
1297
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001298 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001299 }
1300
1301 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001302 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001303 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001304 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001305
1306 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001307 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001308 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001309 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001310
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001311 if (CI->ValueName.empty()) {
1312 CI->ClassName = Rec->getName();
Matthias Braun4a86d452016-12-04 05:48:16 +00001313 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001314 CI->ValueName = Rec->getName();
1315 } else
Matthias Braun4a86d452016-12-04 05:48:16 +00001316 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001317 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001318}
1319
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001320void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001321 std::vector<Record*> AsmOperands =
1322 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001323
1324 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001325 for (Record *Rec : AsmOperands) {
1326 Classes.emplace_front();
1327 AsmOperandClasses[Rec] = &Classes.front();
1328 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001329
Daniel Dunbar17410a42009-08-10 18:41:10 +00001330 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001331 for (Record *Rec : AsmOperands) {
1332 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001333 CI->Kind = ClassInfo::UserClass0 + Index;
1334
Craig Topper03ec8012014-11-25 20:11:31 +00001335 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001336 for (Init *I : Supers->getValues()) {
1337 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001338 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001339 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001340 continue;
1341 }
1342
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001343 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1344 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001345 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001346 else
1347 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001348 }
Craig Topper03ec8012014-11-25 20:11:31 +00001349 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001350 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001351 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001352
1353 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001354 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001355 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001356 CI->PredicateMethod = SI->getValue();
1357 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001358 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001359 CI->PredicateMethod = "is" + CI->ClassName;
1360 }
1361
1362 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001363 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001364 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001365 CI->RenderMethod = SI->getValue();
1366 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001367 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001368 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1369 }
1370
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001371 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001372 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001373 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001374 CI->ParserMethod = SI->getValue();
1375
Oliver Stannard41dfac32017-10-03 14:34:57 +00001376 // Get the diagnostic type and string or leave them as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001377 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001378 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001379 CI->DiagnosticType = SI->getValue();
Oliver Stannard41dfac32017-10-03 14:34:57 +00001380 Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1381 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1382 CI->DiagnosticString = SI->getValue();
1383 // If we have a DiagnosticString, we need a DiagnosticType for use within
1384 // the matcher.
1385 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1386 CI->DiagnosticType = CI->ClassName;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001387
Tom Stellardb9f235e2016-02-05 19:59:33 +00001388 Init *IsOptional = Rec->getValueInit("IsOptional");
1389 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1390 CI->IsOptional = BI->getValue();
1391
Sam Kolton5f10a132016-05-06 11:31:17 +00001392 // Get or construct the default method name.
1393 Init *DMName = Rec->getValueInit("DefaultMethod");
1394 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1395 CI->DefaultMethod = SI->getValue();
1396 } else {
1397 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1398 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1399 }
1400
Craig Topper03ec8012014-11-25 20:11:31 +00001401 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001402 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001403}
1404
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001405AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1406 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001407 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001408 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001409}
1410
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001411/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001412/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001413void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001414
Jim Grosbach925a6d02012-04-18 23:46:25 +00001415 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001416 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001417 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001418 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001419
Craig Topperf34dad92014-11-28 03:53:02 +00001420 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001421 OpClassMask.clear();
1422
1423 // Keep track of all operands of this instructions which belong to the
1424 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001425 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1426 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001427 if (Op.Class->ParserMethod.empty())
1428 continue;
1429 unsigned &OperandMask = OpClassMask[Op.Class];
1430 OperandMask |= (1 << i);
1431 }
1432
1433 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001434 for (const auto &OCM : OpClassMask) {
1435 unsigned OpMask = OCM.second;
1436 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001437 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1438 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001439 }
1440 }
1441}
1442
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001443void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001444 // Build information about all of the AssemblerPredicates.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001445 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1446 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1447 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1448 SubtargetFeaturePairs.end());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001449#ifndef NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001450 for (const auto &Pair : SubtargetFeatures)
1451 DEBUG(Pair.second.dump());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001452#endif // NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001453 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001454
Craig Topperfd2c6a32015-12-31 08:18:23 +00001455 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1456
Chris Lattner33fc3e02010-10-31 19:10:56 +00001457 // Parse the instructions; we need to do this first so that we can gather the
1458 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001459 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001460 unsigned VariantCount = Target.getAsmParserVariantCount();
1461 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1462 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperbcd3c372017-05-31 21:12:46 +00001463 StringRef CommentDelimiter =
1464 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001465 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001466 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001467 Variant.TokenizingCharacters =
1468 AsmVariant->getValueAsString("TokenizingCharacters");
1469 Variant.SeparatorCharacters =
1470 AsmVariant->getValueAsString("SeparatorCharacters");
1471 Variant.BreakCharacters =
1472 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001473 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001474 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001475
Craig Topper8cc904d2016-01-17 20:38:18 +00001476 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001477
Devang Patel85d684a2012-01-09 19:13:28 +00001478 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1479 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001480 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001481 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001482
Devang Patel85d684a2012-01-09 19:13:28 +00001483 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001484 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001485 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001486
Sam Kolton1b746d12016-09-08 15:50:52 +00001487 // Ignore instructions for different instructions
Craig Topperbcd3c372017-05-31 21:12:46 +00001488 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001489 if (!V.empty() && V != Variant.Name)
1490 continue;
1491
Craig Topper1c8fbd22015-09-06 03:44:50 +00001492 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001493
Craig Topperfd2c6a32015-12-31 08:18:23 +00001494 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001495
Devang Patel85d684a2012-01-09 19:13:28 +00001496 // Ignore instructions which shouldn't be matched and diagnose invalid
1497 // instruction definitions with an error.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001498 if (!II->validate(CommentDelimiter, true))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001499 continue;
1500
1501 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001502 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001503
Devang Patel85d684a2012-01-09 19:13:28 +00001504 // Parse all of the InstAlias definitions and stick them in the list of
1505 // matchables.
1506 std::vector<Record*> AllInstAliases =
1507 Records.getAllDerivedDefinitions("InstAlias");
1508 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001509 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001510 Variant.AsmVariantNo,
1511 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001512
Devang Patel85d684a2012-01-09 19:13:28 +00001513 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1514 // filter the set of instruction aliases we consider, based on the target
1515 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001516 if (!StringRef(Alias->ResultInst->TheDef->getName())
1517 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001518 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001519
Craig Topperbcd3c372017-05-31 21:12:46 +00001520 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001521 if (!V.empty() && V != Variant.Name)
1522 continue;
1523
Craig Topper1c8fbd22015-09-06 03:44:50 +00001524 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001525
Craig Topperfd2c6a32015-12-31 08:18:23 +00001526 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001527
Devang Patel85d684a2012-01-09 19:13:28 +00001528 // Validate the alias definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001529 II->validate(CommentDelimiter, false);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001530
1531 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001532 }
Chris Lattner488c2012010-11-01 04:05:41 +00001533 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001534
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001535 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001536 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001537
1538 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001539 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001540
Chris Lattner4779e3e92010-11-04 00:57:06 +00001541 // Build the information about matchables, now that we have fully formed
1542 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001543 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001544 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001545 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001546 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001547 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001548 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1549 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001550 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001551
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001552 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001553 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001554 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001555 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1556 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001557 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001558 }
1559
Daniel Dunbare10787e2009-08-07 08:26:05 +00001560 // Check for simple tokens.
1561 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001562 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001563 continue;
1564 }
1565
Chris Lattnerd6746d52010-11-06 22:06:03 +00001566 if (Token.size() > 1 && isdigit(Token[1])) {
1567 Op.Class = getTokenClass(Token);
1568 continue;
1569 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001570
Chris Lattner4efe13d2010-11-04 02:11:18 +00001571 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001572 StringRef OperandName;
1573 if (Token[1] == '{')
1574 OperandName = Token.substr(2, Token.size() - 3);
1575 else
1576 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001577
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001578 if (II->DefRec.is<const CodeGenInstruction*>())
1579 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001580 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001581 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001582 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001583
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001584 if (II->DefRec.is<const CodeGenInstruction*>()) {
1585 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001586 // If the instruction has a two-operand alias, build up the
1587 // matchable here. We'll add them in bulk at the end to avoid
1588 // confusing this loop.
Craig Topperbcd3c372017-05-31 21:12:46 +00001589 StringRef Constraint =
1590 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001591 if (Constraint != "") {
1592 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001593 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001594
1595 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001596 AliasII->formTwoOperandAlias(Constraint);
1597
1598 // Add the alias to the matchables list.
1599 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001600 }
1601 } else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001602 II->buildAliasResultOperands();
Daniel Dunbare10787e2009-08-07 08:26:05 +00001603 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001604 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001605 Matchables.insert(Matchables.end(),
1606 std::make_move_iterator(NewMatchables.begin()),
1607 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001608
Jim Grosbachba395922011-12-06 23:43:54 +00001609 // Process token alias definitions and set up the associated superclass
1610 // information.
1611 std::vector<Record*> AllTokenAliases =
1612 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001613 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001614 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1615 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001616 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001617 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001618 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001619 FromClass->SuperClasses.push_back(ToClass);
1620 }
1621
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001622 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001623 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001624
Matthias Brauna8eed312016-12-05 19:44:31 +00001625#ifdef EXPENSIVE_CHECKS
1626 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard7772f022016-01-25 10:20:19 +00001627 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1628 for (auto J = I; J != E; ++J) {
1629 assert(!(*J < *I));
1630 assert(I == J || !J->isSubsetOf(*I));
1631 }
1632 }
Matthias Brauna8eed312016-12-05 19:44:31 +00001633#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +00001634}
1635
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001636/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001637/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1638void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001639buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001640 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001641 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001642 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1643 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001644 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001645
Chris Lattnerfecdad62010-11-06 07:14:44 +00001646 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001647 unsigned Idx;
1648 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001649 PrintFatalError(II->TheDef->getLoc(),
1650 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001651
Bob Wilsonb9b24222011-01-26 19:44:55 +00001652 // If the instruction operand has multiple suboperands, but the parser
1653 // match class for the asm operand is still the default "ImmAsmOperand",
1654 // then handle each suboperand separately.
1655 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1656 Record *Rec = Operands[Idx].Rec;
1657 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1658 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1659 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1660 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1661 StringRef Token = Op->Token; // save this in case Op gets moved
1662 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001663 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001664 NewAsmOp.SubOpIdx = SI;
1665 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1666 }
1667 // Replace Op with first suboperand.
1668 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1669 Op->SubOpIdx = 0;
1670 }
1671 }
1672
Chris Lattner897a1402010-11-04 01:55:23 +00001673 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001674 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattner897a1402010-11-04 01:55:23 +00001675
1676 // If the named operand is tied, canonicalize it to the untied operand.
1677 // For example, something like:
1678 // (outs GPR:$dst), (ins GPR:$src)
1679 // with an asmstring of
1680 // "inc $src"
1681 // we want to canonicalize to:
1682 // "inc $dst"
1683 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001684 int OITied = -1;
1685 if (Operands[Idx].MINumOperands == 1)
1686 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001687 if (OITied != -1) {
1688 // The tied operand index is an MIOperand index, find the operand that
1689 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001690 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1691 OperandName = Operands[Idx.first].Name;
1692 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001693 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001694
Bob Wilsonb9b24222011-01-26 19:44:55 +00001695 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001696}
1697
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001698/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001699/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1700/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001701void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001702 StringRef OperandName,
1703 MatchableInfo::AsmOperand &Op) {
1704 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001705
Chris Lattner4efe13d2010-11-04 02:11:18 +00001706 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001707 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001708 if (CGA.ResultOperands[i].isRecord() &&
1709 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001710 // It's safe to go with the first one we find, because CodeGenInstAlias
1711 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001712 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001713 // Use the match class from the Alias definition, not the
1714 // destination instruction, as we may have an immediate that's
1715 // being munged by the match class.
1716 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001717 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001718 Op.SrcOpName = OperandName;
1719 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001720 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001721
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001722 PrintFatalError(II->TheDef->getLoc(),
1723 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001724}
1725
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001726void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001727 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001728
Chris Lattnerfecdad62010-11-06 07:14:44 +00001729 // Loop over all operands of the result instruction, determining how to
1730 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001731 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001732 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001733 int TiedOp = -1;
1734 if (OpInfo.MINumOperands == 1)
1735 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001736 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001737 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner7108dad2010-11-04 01:42:59 +00001738 continue;
1739 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001740
Bob Wilsonb9b24222011-01-26 19:44:55 +00001741 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001742 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001743 if (OpInfo.Name.empty() || SrcOperand == -1) {
1744 // This may happen for operands that are tied to a suboperand of a
1745 // complex operand. Simply use a dummy value here; nobody should
1746 // use this operand slot.
1747 // FIXME: The long term goal is for the MCOperand list to not contain
1748 // tied operands at all.
1749 ResOperands.push_back(ResOperand::getImmOp(0));
1750 continue;
1751 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001752
Bob Wilsonb9b24222011-01-26 19:44:55 +00001753 // Check if the one AsmOperand populates the entire operand.
1754 unsigned NumOperands = OpInfo.MINumOperands;
1755 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1756 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001757 continue;
1758 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001759
1760 // Add a separate ResOperand for each suboperand.
1761 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1762 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1763 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1764 "unexpected AsmOperands for suboperands");
1765 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1766 }
Chris Lattner743081d2010-11-04 00:43:46 +00001767 }
1768}
1769
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001770void MatchableInfo::buildAliasResultOperands() {
Chris Lattner8188fb22010-11-06 07:31:43 +00001771 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1772 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001773
Chris Lattner8188fb22010-11-06 07:31:43 +00001774 // Loop over all operands of the result instruction, determining how to
1775 // populate them.
1776 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001777 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001778 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001779 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001780
Chris Lattner8188fb22010-11-06 07:31:43 +00001781 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001782 int TiedOp = -1;
1783 if (OpInfo->MINumOperands == 1)
1784 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001785 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001786 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner4869d342010-11-06 19:57:21 +00001787 continue;
1788 }
1789
Bob Wilsonb9b24222011-01-26 19:44:55 +00001790 // Handle all the suboperands for this operand.
1791 const std::string &OpName = OpInfo->Name;
1792 for ( ; AliasOpNo < LastOpNo &&
1793 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1794 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1795
1796 // Find out what operand from the asmparser that this MCInst operand
1797 // comes from.
1798 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001799 case CodeGenInstAlias::ResultOperand::K_Record: {
1800 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001801 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001802 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001803 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001804 TheDef->getName() + "' has operand '" + OpName +
1805 "' that doesn't appear in asm string!");
1806 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1807 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1808 NumOperands));
1809 break;
1810 }
1811 case CodeGenInstAlias::ResultOperand::K_Imm: {
1812 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1813 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1814 break;
1815 }
1816 case CodeGenInstAlias::ResultOperand::K_Reg: {
1817 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1818 ResOperands.push_back(ResOperand::getRegOp(Reg));
1819 break;
1820 }
1821 }
Chris Lattner4869d342010-11-06 19:57:21 +00001822 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001823 }
1824}
Chris Lattner743081d2010-11-04 00:43:46 +00001825
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001826static unsigned
1827getConverterOperandID(const std::string &Name,
1828 SmallSetVector<CachedHashString, 16> &Table,
1829 bool &IsNew) {
1830 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001831
David Majnemer0d955d02016-08-11 22:21:41 +00001832 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001833
1834 assert(ID < Table.size());
1835
1836 return ID;
1837}
1838
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001839static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001840 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Kolton5f10a132016-05-06 11:31:17 +00001841 bool HasMnemonicFirst, bool HasOptionalOperands,
1842 raw_ostream &OS) {
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001843 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1844 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001845 std::vector<std::vector<uint8_t> > ConversionTable;
1846 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001847
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001848 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun4a86d452016-12-04 05:48:16 +00001849 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001850
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001851 // Write the convert function to a separate stream, so we can drop it after
1852 // the enum. We'll build up the conversion handlers for the individual
1853 // operand types opportunistically as we encounter them.
1854 std::string ConvertFnBody;
1855 raw_string_ostream CvtOS(ConvertFnBody);
1856 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001857 if (HasOptionalOperands) {
1858 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1859 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1860 << "unsigned Opcode,\n"
1861 << " const OperandVector &Operands,\n"
1862 << " const SmallBitVector &OptionalOperandsMask) {\n";
1863 } else {
1864 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1865 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1866 << "unsigned Opcode,\n"
1867 << " const OperandVector &Operands) {\n";
1868 }
1869 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1870 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1871 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001872 size_t MaxNumOperands = 0;
1873 for (const auto &MI : Infos) {
1874 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1875 }
1876 CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1877 << "] = { 0 };\n";
1878 CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1879 << ");\n";
1880 CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1881 << "; ++i) {\n";
1882 CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
1883 CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1884 CvtOS << " }\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001885 }
1886 CvtOS << " unsigned OpIdx;\n";
1887 CvtOS << " Inst.setOpcode(Opcode);\n";
1888 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1889 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001890 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001891 } else {
1892 CvtOS << " OpIdx = *(p + 1);\n";
1893 }
1894 CvtOS << " switch (*p) {\n";
1895 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1896 CvtOS << " case CVT_Reg:\n";
1897 CvtOS << " static_cast<" << TargetOperandClass
1898 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1899 CvtOS << " break;\n";
1900 CvtOS << " case CVT_Tied:\n";
1901 CvtOS << " Inst.addOperand(Inst.getOperand(OpIdx));\n";
1902 CvtOS << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001903
Chad Rosier738ea252012-08-30 17:59:25 +00001904 std::string OperandFnBody;
1905 raw_string_ostream OpOS(OperandFnBody);
1906 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001907 OpOS << "void " << Target.getName() << ClassName << "::\n"
1908 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00001909 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00001910 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001911 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001912 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00001913 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1914 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001915 << " switch (*p) {\n"
1916 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1917 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001918 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00001919 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001920 << " ++NumMCOperands;\n"
1921 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001922 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001923 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001924 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001925
1926 // Pre-populate the operand conversion kinds with the standard always
1927 // available entries.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001928 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
1929 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
1930 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001931 enum { CVT_Done, CVT_Reg, CVT_Tied };
1932
Craig Topperf34dad92014-11-28 03:53:02 +00001933 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001934 // Check if we have a custom match function.
Craig Topperbcd3c372017-05-31 21:12:46 +00001935 StringRef AsmMatchConverter =
1936 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00001937 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Craig Topperbcd3c372017-05-31 21:12:46 +00001938 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001939 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001940
1941 // Check if we have already generated this signature.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001942 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001943 continue;
1944
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001945 // Remember this converter for the kind enum.
1946 unsigned KindID = OperandConversionKinds.size();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001947 OperandConversionKinds.insert(
1948 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001949
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001950 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001951 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001952 ConversionTable.back().push_back(KindID);
1953 ConversionTable.back().push_back(CVT_Done);
1954
1955 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00001956 CvtOS << " case CVT_"
1957 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00001958 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001959 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001960
Chad Rosier738ea252012-08-30 17:59:25 +00001961 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001962 continue;
1963 }
1964
Daniel Dunbare10787e2009-08-07 08:26:05 +00001965 // Build the conversion function signature.
1966 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001967
1968 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001969
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00001970 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001971 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001972
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001973 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
1974 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001975
Chris Lattner743081d2010-11-04 00:43:46 +00001976 // Generate code to populate each result operand.
1977 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00001978 case MatchableInfo::ResOperand::RenderAsmOperand: {
1979 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00001980 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001981 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001982
Chris Lattnere032dbf2010-11-02 22:55:03 +00001983 // Registers are always converted the same, don't duplicate the
1984 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00001985 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001986 std::string Class;
1987 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1988 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001989 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00001990 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001991
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001992 // Add the conversion kind, if necessary, and get the associated ID
1993 // the index of its entry in the vector).
1994 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1995 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00001996 if (Op.Class->IsOptional) {
1997 // For optional operands we must also care about DefaultMethod
1998 assert(HasOptionalOperands);
1999 Name += "_" + Op.Class->DefaultMethod;
2000 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00002001 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002002
2003 bool IsNewConverter = false;
2004 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2005 IsNewConverter);
2006
2007 // Add the operand entry to the instruction kind conversion row.
2008 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00002009 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002010
2011 if (!IsNewConverter)
2012 break;
2013
2014 // This is a new operand kind. Add a handler for it to the
2015 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00002016 CvtOS << " case " << Name << ":\n";
2017 if (Op.Class->IsOptional) {
2018 // If optional operand is not present in actual instruction then we
2019 // should call its DefaultMethod before RenderMethod
2020 assert(HasOptionalOperands);
2021 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2022 << " " << Op.Class->DefaultMethod << "()"
2023 << "->" << Op.Class->RenderMethod << "(Inst, "
2024 << OpInfo.MINumOperands << ");\n"
Sam Kolton5f10a132016-05-06 11:31:17 +00002025 << " } else {\n"
2026 << " static_cast<" << TargetOperandClass
2027 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2028 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2029 << " }\n";
2030 } else {
2031 CvtOS << " static_cast<" << TargetOperandClass
2032 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2033 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2034 }
2035 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002036
2037 // Add a handler for the operand number lookup.
2038 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002039 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2040
2041 if (Op.Class->isRegisterClass())
2042 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2043 else
2044 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2045 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002046 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002047 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002048 }
Chris Lattner743081d2010-11-04 00:43:46 +00002049 case MatchableInfo::ResOperand::TiedOperand: {
2050 // If this operand is tied to a previous one, just copy the MCInst
2051 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002052 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner743081d2010-11-04 00:43:46 +00002053 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002054 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner743081d2010-11-04 00:43:46 +00002055 Signature += "__Tie" + utostr(TiedOp);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002056 ConversionRow.push_back(CVT_Tied);
2057 ConversionRow.push_back(TiedOp);
Chris Lattner743081d2010-11-04 00:43:46 +00002058 break;
2059 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002060 case MatchableInfo::ResOperand::ImmOperand: {
2061 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002062 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002063 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002064 Signature += "__" + Ty;
2065
2066 std::string Name = "CVT_" + Ty;
2067 bool IsNewConverter = false;
2068 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2069 IsNewConverter);
2070 // Add the operand entry to the instruction kind conversion row.
2071 ConversionRow.push_back(ID);
2072 ConversionRow.push_back(0);
2073
2074 if (!IsNewConverter)
2075 break;
2076
2077 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002078 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002079 << " break;\n";
2080
Chad Rosier738ea252012-08-30 17:59:25 +00002081 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002082 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2083 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002084 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002085 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002086 break;
2087 }
Chris Lattner4869d342010-11-06 19:57:21 +00002088 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002089 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002090 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002091 Name = "reg0";
2092 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002093 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002094 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun4a86d452016-12-04 05:48:16 +00002095 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilson03912ab2011-01-14 22:58:09 +00002096 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002097 Signature += "__" + Name;
2098 Name = "CVT_" + Name;
2099 bool IsNewConverter = false;
2100 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2101 IsNewConverter);
2102 // Add the operand entry to the instruction kind conversion row.
2103 ConversionRow.push_back(ID);
2104 ConversionRow.push_back(0);
2105
2106 if (!IsNewConverter)
2107 break;
2108 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002109 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002110 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002111
2112 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002113 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2114 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002115 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002116 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002117 }
Chris Lattner743081d2010-11-04 00:43:46 +00002118 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002119 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002120
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002121 // If there were no operands, add to the signature to that effect
2122 if (Signature == "Convert")
2123 Signature += "_NoOperands";
2124
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002125 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002126
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002127 // Save the signature. If we already have it, don't add a new row
2128 // to the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002129 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002130 continue;
2131
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002132 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002133 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002134 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002135
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002136 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002137 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002138
Chad Rosier738ea252012-08-30 17:59:25 +00002139 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002140 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002141
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002142 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002143
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002144 // Output the operand conversion kind enum.
2145 OS << "enum OperatorConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002146 for (const auto &Converter : OperandConversionKinds)
Craig Topper6e526f12016-01-03 07:33:30 +00002147 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002148 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002149 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002150
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002151 // Output the instruction conversion kind enum.
2152 OS << "enum InstructionConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002153 for (const auto &Signature : InstructionConversionKinds)
Craig Topper802d3d32015-08-16 21:27:10 +00002154 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002155 OS << " CVT_NUM_SIGNATURES\n";
2156 OS << "};\n\n";
2157
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002158 OS << "} // end anonymous namespace\n\n";
2159
2160 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002161 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002162 << MaxRowLength << "] = {\n";
2163
2164 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2165 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2166 OS << " // " << InstructionConversionKinds[Row] << "\n";
2167 OS << " { ";
2168 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
2169 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
2170 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2171 OS << "CVT_Done },\n";
2172 }
2173
2174 OS << "};\n\n";
2175
2176 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002177 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002178
Chad Rosier738ea252012-08-30 17:59:25 +00002179 // Spit out the operand number lookup function.
2180 OS << OpOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002181}
2182
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002183/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2184static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002185 std::forward_list<ClassInfo> &Infos,
2186 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002187 OS << "namespace {\n\n";
2188
2189 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2190 << "/// instruction matching.\n";
2191 OS << "enum MatchClassKind {\n";
2192 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002193 OS << " OptionalMatchClass = 1,\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002194 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2195 StringRef LastName = "OptionalMatchClass";
Craig Topperf34dad92014-11-28 03:53:02 +00002196 for (const auto &CI : Infos) {
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002197 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2198 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2199 } else if (LastKind < ClassInfo::UserClass0 &&
2200 CI.Kind >= ClassInfo::UserClass0) {
2201 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2202 }
2203 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2204 LastName = CI.Name;
2205
David Blaikied749e342014-11-28 20:35:57 +00002206 OS << " " << CI.Name << ", // ";
2207 if (CI.Kind == ClassInfo::Token) {
2208 OS << "'" << CI.ValueName << "'\n";
2209 } else if (CI.isRegisterClass()) {
2210 if (!CI.ValueName.empty())
2211 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002212 else
2213 OS << "derived register class\n";
2214 } else {
David Blaikied749e342014-11-28 20:35:57 +00002215 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002216 }
2217 }
2218 OS << " NumMatchClassKinds\n";
2219 OS << "};\n\n";
2220
2221 OS << "}\n\n";
2222}
2223
Oliver Stannard41dfac32017-10-03 14:34:57 +00002224/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2225/// used when an assembly operand does not match the expected operand class.
2226static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2227 // If the target does not use DiagnosticString for any operands, don't emit
2228 // an unused function.
2229 if (std::all_of(
2230 Info.Classes.begin(), Info.Classes.end(),
2231 [](const ClassInfo &CI) { return CI.DiagnosticString.empty(); }))
2232 return;
2233
2234 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2235 << "AsmParser::" << Info.Target.getName()
2236 << "MatchResultTy MatchResult) {\n";
2237 OS << " switch (MatchResult) {\n";
2238
2239 for (const auto &CI: Info.Classes) {
2240 if (!CI.DiagnosticString.empty()) {
2241 assert(!CI.DiagnosticType.empty() &&
2242 "DiagnosticString set without DiagnosticType");
2243 OS << " case " << Info.Target.getName()
2244 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2245 OS << " return \"" << CI.DiagnosticString << "\";\n";
2246 }
2247 }
2248
2249 OS << " default:\n";
2250 OS << " return nullptr;\n";
2251
2252 OS << " }\n";
2253 OS << "}\n\n";
2254}
2255
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002256static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2257 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2258 "RegisterClass) {\n";
Oliver Stannarddab52122017-10-12 09:28:23 +00002259 if (std::none_of(Info.Classes.begin(), Info.Classes.end(),
2260 [](const ClassInfo &CI) {
2261 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2262 })) {
2263 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2264 } else {
2265 OS << " switch (RegisterClass) {\n";
2266 for (const auto &CI: Info.Classes) {
2267 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2268 OS << " case " << CI.Name << ":\n";
2269 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2270 << CI.DiagnosticType << ";\n";
2271 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002272 }
Oliver Stannarddab52122017-10-12 09:28:23 +00002273
2274 OS << " default:\n";
2275 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2276
2277 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002278 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002279 OS << "}\n\n";
2280}
2281
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002282/// emitValidateOperandClass - Emit the function to validate an operand class.
2283static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002284 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002285 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002286 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002287 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2288 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002289
Kevin Enderby1b87c802011-07-15 18:30:43 +00002290 // The InvalidMatchClass is not to match any operand.
2291 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002292 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002293
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002294 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002295 // FIXME: Use a more specific diagnostic type.
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002296 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002297 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2298 << " MCTargetAsmParser::Match_Success :\n"
2299 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002300
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002301 // Check the user classes. We don't care what order since we're only
2302 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002303 OS << " switch (Kind) {\n"
2304 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002305 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002306 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002307 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002308
David Blaikied749e342014-11-28 20:35:57 +00002309 OS << " // '" << CI.ClassName << "' class\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002310 OS << " case " << CI.Name << ":\n";
David Blaikied749e342014-11-28 20:35:57 +00002311 OS << " if (Operand." << CI.PredicateMethod << "())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002312 OS << " return MCTargetAsmParser::Match_Success;\n";
David Blaikied749e342014-11-28 20:35:57 +00002313 if (!CI.DiagnosticType.empty())
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002314 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002315 << CI.DiagnosticType << ";\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002316 else
2317 OS << " break;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002318 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002319 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002320
Owen Anderson8a503f22012-07-16 23:20:09 +00002321 // Check for register operands, including sub-classes.
2322 OS << " if (Operand.isReg()) {\n";
2323 OS << " MatchClassKind OpKind;\n";
2324 OS << " switch (Operand.getReg()) {\n";
2325 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002326 for (const auto &RC : Info.RegisterClasses)
Craig Topper2b347eb2017-07-07 05:19:25 +00002327 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002328 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002329 << "; break;\n";
2330 OS << " }\n";
2331 OS << " return isSubclass(OpKind, Kind) ? "
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002332 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2333 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2334
2335 // Expected operand is a register, but actual is not.
2336 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2337 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
Owen Anderson8a503f22012-07-16 23:20:09 +00002338
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002339 // Generic fallthrough match failure case for operands that don't have
2340 // specialized diagnostic types.
2341 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002342 OS << "}\n\n";
2343}
2344
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002345/// emitIsSubclass - Emit the subclass predicate function.
2346static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002347 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002348 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002349 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002350 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002351 OS << " if (A == B)\n";
2352 OS << " return true;\n\n";
2353
Craig Topper39311c72015-12-30 06:00:22 +00002354 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002355 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002356 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002357 if (A.IsOptional)
2358 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002359 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002360 if (&A != &B && A.isSubsetOf(B))
2361 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002362 }
Jim Grosbachba395922011-12-06 23:43:54 +00002363
2364 if (SuperClasses.empty())
2365 continue;
2366
Craig Topper39311c72015-12-30 06:00:22 +00002367 // If this is the first SuperClass, emit the switch header.
2368 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002369 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002370 OS << " default:\n";
2371 OS << " return false;\n";
2372 EmittedSwitch = true;
2373 }
2374
2375 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002376
2377 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002378 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002379 continue;
2380 }
2381
Aaron Ballmane59e3582013-07-15 16:53:32 +00002382 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002383 OS << " switch (B) {\n";
2384 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002385 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002386 OS << " case " << SC << ": return true;\n";
2387 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002388 } else {
2389 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002390 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002391 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002392 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002393
Craig Topper39311c72015-12-30 06:00:22 +00002394 // If there were case statements emitted into the string stream write the
2395 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002396 if (EmittedSwitch)
2397 OS << " }\n";
2398 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002399 OS << " return false;\n";
2400
Daniel Dunbar2587b612009-08-10 16:05:47 +00002401 OS << "}\n\n";
2402}
2403
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002404/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002405/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002406static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002407 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002408 raw_ostream &OS) {
2409 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002410 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002411 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002412 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002413 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002414 }
2415
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002416 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002417
Chris Lattnerca5a3552010-09-06 02:01:51 +00002418 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002419
2420 OS << " return InvalidMatchClass;\n";
2421 OS << "}\n\n";
2422}
Chris Lattner00e2e742009-08-08 20:02:57 +00002423
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002424/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002425/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002426static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002427 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002428 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002429 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002430 const auto &Regs = Target.getRegBank().getRegisters();
2431 for (const CodeGenRegister &Reg : Regs) {
2432 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002433 continue;
2434
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002435 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2436 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002437 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002438
Chris Lattner60db0a62010-02-09 00:34:28 +00002439 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002440
Chris Lattnerca5a3552010-09-06 02:01:51 +00002441 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002442
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002443 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002444 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002445}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002446
Dylan McKaybff960a2016-02-03 10:30:16 +00002447/// Emit the function to match a string to the target
2448/// specific register enum.
2449static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2450 raw_ostream &OS) {
2451 // Construct the match list.
2452 std::vector<StringMatcher::StringPair> Matches;
2453 const auto &Regs = Target.getRegBank().getRegisters();
2454 for (const CodeGenRegister &Reg : Regs) {
2455
2456 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2457
2458 for (auto AltName : AltNames) {
2459 AltName = StringRef(AltName).trim();
2460
2461 // don't handle empty alternative names
2462 if (AltName.empty())
2463 continue;
2464
2465 Matches.emplace_back(AltName,
2466 "return " + utostr(Reg.EnumValue) + ";");
2467 }
2468 }
2469
2470 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2471
2472 StringMatcher("Name", Matches, OS).Emit();
2473
2474 OS << " return 0;\n";
2475 OS << "}\n\n";
2476}
2477
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002478/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2479static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2480 // Get the set of diagnostic types from all of the operand classes.
2481 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002482 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2483 if (!OpClassEntry.second->DiagnosticType.empty())
2484 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002485 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002486 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2487 if (!OpClassEntry.second->DiagnosticType.empty())
2488 Types.insert(OpClassEntry.second->DiagnosticType);
2489 }
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002490
2491 if (Types.empty()) return;
2492
2493 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002494 for (StringRef Type : Types)
2495 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002496 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2497}
2498
Jim Grosbach5117ef72012-04-24 22:40:08 +00002499/// emitGetSubtargetFeatureName - Emit the helper function to get the
2500/// user-level name for a subtarget feature.
2501static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2502 OS << "// User-level names for subtarget features that participate in\n"
2503 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002504 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002505 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002506 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002507 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002508 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002509 // FIXME: Totally just a placeholder name to get the algorithm working.
2510 OS << " case " << SFI.getEnumName() << ": return \""
2511 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2512 }
2513 OS << " default: return \"(unknown)\";\n";
2514 OS << " }\n";
2515 } else {
2516 // Nothing to emit, so skip the switch
2517 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002518 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002519 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002520}
2521
Chris Lattner43690072010-10-30 20:15:02 +00002522static std::string GetAliasRequiredFeatures(Record *R,
2523 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002524 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002525 std::string Result;
2526 unsigned NumFeatures = 0;
2527 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002528 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002529
Craig Topper24064772014-04-15 07:20:03 +00002530 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002531 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002532 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002533
Chris Lattner517dc952010-11-01 02:09:21 +00002534 if (NumFeatures)
2535 Result += '|';
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002536
Chris Lattner517dc952010-11-01 02:09:21 +00002537 Result += F->getEnumName();
2538 ++NumFeatures;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002539 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002540
Chris Lattner2cb092d2010-10-30 19:23:13 +00002541 if (NumFeatures > 1)
2542 Result = '(' + Result + ')';
2543 return Result;
2544}
2545
Chad Rosier9f7a2212013-04-18 22:35:36 +00002546static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2547 std::vector<Record*> &Aliases,
2548 unsigned Indent = 0,
2549 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002550 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2551 // iteration order of the map is stable.
2552 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002553
Craig Topper6e526f12016-01-03 07:33:30 +00002554 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002555 // FIXME: Allow AssemblerVariantName to be a comma separated list.
Craig Topperbcd3c372017-05-31 21:12:46 +00002556 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002557 if (AsmVariantName != AsmParserVariantName)
2558 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002559 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002560 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002561 if (AliasesFromMnemonic.empty())
2562 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002563
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002564 // Process each alias a "from" mnemonic at a time, building the code executed
2565 // by the string remapper.
2566 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002567 for (const auto &AliasEntry : AliasesFromMnemonic) {
2568 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002569
2570 // Loop through each alias and emit code that handles each case. If there
2571 // are two instructions without predicates, emit an error. If there is one,
2572 // emit it last.
2573 std::string MatchCode;
2574 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002575
Chris Lattner2cb092d2010-10-30 19:23:13 +00002576 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2577 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002578 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002579
Chris Lattner2cb092d2010-10-30 19:23:13 +00002580 // If this unconditionally matches, remember it for later and diagnose
2581 // duplicates.
2582 if (FeatureMask.empty()) {
2583 if (AliasWithNoPredicate != -1) {
2584 // We can't have two aliases from the same mnemonic with no predicate.
2585 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2586 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002587 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002588 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002589
Chris Lattner2cb092d2010-10-30 19:23:13 +00002590 AliasWithNoPredicate = i;
2591 continue;
2592 }
Craig Topper6e526f12016-01-03 07:33:30 +00002593 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002594 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002595
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002596 if (!MatchCode.empty())
2597 MatchCode += "else ";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002598 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Craig Topper2b8419a2017-05-31 19:01:11 +00002599 MatchCode += " Mnemonic = \"";
2600 MatchCode += R->getValueAsString("ToMnemonic");
2601 MatchCode += "\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002602 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002603
Chris Lattner2cb092d2010-10-30 19:23:13 +00002604 if (AliasWithNoPredicate != -1) {
2605 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002606 if (!MatchCode.empty())
2607 MatchCode += "else\n ";
Craig Topper2b8419a2017-05-31 19:01:11 +00002608 MatchCode += "Mnemonic = \"";
2609 MatchCode += R->getValueAsString("ToMnemonic");
2610 MatchCode += "\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002611 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002612
Chris Lattner2cb092d2010-10-30 19:23:13 +00002613 MatchCode += "return;";
2614
Craig Topper6e526f12016-01-03 07:33:30 +00002615 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002616 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002617 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2618}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002619
Chad Rosier9f7a2212013-04-18 22:35:36 +00002620/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2621/// emit a function for them and return true, otherwise return false.
2622static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2623 CodeGenTarget &Target) {
2624 // Ignore aliases when match-prefix is set.
2625 if (!MatchPrefix.empty())
2626 return false;
2627
2628 std::vector<Record*> Aliases =
2629 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2630 if (Aliases.empty()) return false;
2631
2632 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002633 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002634 OS << " switch (VariantID) {\n";
2635 unsigned VariantCount = Target.getAsmParserVariantCount();
2636 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2637 Record *AsmVariant = Target.getAsmParserVariant(VC);
2638 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
Craig Topperbcd3c372017-05-31 21:12:46 +00002639 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002640 OS << " case " << AsmParserVariantNo << ":\n";
2641 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2642 AsmParserVariantName);
2643 OS << " break;\n";
2644 }
2645 OS << " }\n";
2646
2647 // Emit aliases that apply to all variants.
2648 emitMnemonicAliasVariant(OS, Info, Aliases);
2649
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002650 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002651
Chris Lattner477fba4f2010-10-30 18:48:18 +00002652 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002653}
2654
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002655static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002656 const AsmMatcherInfo &Info, StringRef ClassName,
2657 StringToOffsetTable &StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00002658 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002659 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002660 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2661 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002662 }
2663
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002664 // Emit the static custom operand parsing table;
2665 OS << "namespace {\n";
2666 OS << " struct OperandMatchEntry {\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00002667 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002668 << " RequiredFeatures;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002669 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2670 << " Mnemonic;\n";
David Blaikied749e342014-11-28 20:35:57 +00002671 OS << " " << getMinimalTypeForRange(std::distance(
2672 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002673 OS << " " << getMinimalTypeForRange(MaxMask)
2674 << " OperandMask;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002675 OS << " StringRef getMnemonic() const {\n";
2676 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2677 OS << " MnemonicTable[Mnemonic]);\n";
2678 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002679 OS << " };\n\n";
2680
2681 OS << " // Predicate for searching for an opcode.\n";
2682 OS << " struct LessOpcodeOperand {\n";
2683 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002684 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002685 OS << " }\n";
2686 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002687 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002688 OS << " }\n";
2689 OS << " bool operator()(const OperandMatchEntry &LHS,";
2690 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002691 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002692 OS << " }\n";
2693 OS << " };\n";
2694
2695 OS << "} // end anonymous namespace.\n\n";
2696
2697 OS << "static const OperandMatchEntry OperandMatchTable["
2698 << Info.OperandMatchInfo.size() << "] = {\n";
2699
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002700 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002701 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002702 const MatchableInfo &II = *OMI.MI;
2703
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002704 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002705
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002706 // Write the required features mask.
2707 if (!II.RequiredFeatures.empty()) {
2708 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002709 if (i) OS << "|";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002710 OS << II.RequiredFeatures[i]->getEnumName();
2711 }
2712 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002713 OS << "0";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002714
2715 // Store a pascal-style length byte in the mnemonic.
2716 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2717 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2718 << " /* " << II.Mnemonic << " */, ";
2719
2720 OS << OMI.CI->Name;
2721
2722 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002723 OS << " /* ";
2724 bool printComma = false;
2725 for (int i = 0, e = 31; i !=e; ++i)
2726 if (OMI.OperandMask & (1 << i)) {
2727 if (printComma)
2728 OS << ", ";
2729 OS << i;
2730 printComma = true;
2731 }
2732 OS << " */";
2733
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002734 OS << " },\n";
2735 }
2736 OS << "};\n\n";
2737
2738 // Emit the operand class switch to call the correct custom parser for
2739 // the found operand class.
Alex Bradbury58eba092016-11-01 16:32:05 +00002740 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002741 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002742 << " &Operands,\n unsigned MCK) {\n\n"
2743 << " switch(MCK) {\n";
2744
Craig Topperf34dad92014-11-28 03:53:02 +00002745 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002746 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002747 continue;
David Blaikied749e342014-11-28 20:35:57 +00002748 OS << " case " << CI.Name << ":\n"
2749 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002750 }
2751
2752 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002753 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002754 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002755 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002756 OS << "}\n\n";
2757
2758 // Emit the static custom operand parser. This code is very similar with
2759 // the other matcher. Also use MatchResultTy here just in case we go for
2760 // a better error handling.
Alex Bradbury58eba092016-11-01 16:32:05 +00002761 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002762 << "MatchOperandParserImpl(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002763 << " &Operands,\n StringRef Mnemonic) {\n";
2764
2765 // Emit code to get the available features.
2766 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002767 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002768
2769 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002770 OS << " unsigned NextOpNum = Operands.size()"
2771 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002772
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002773 // Emit code to search the table.
2774 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002775 if (HasMnemonicFirst) {
2776 OS << " auto MnemonicRange =\n";
2777 OS << " std::equal_range(std::begin(OperandMatchTable), "
2778 "std::end(OperandMatchTable),\n";
2779 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2780 } else {
2781 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2782 " std::end(OperandMatchTable));\n";
2783 OS << " if (!Mnemonic.empty())\n";
2784 OS << " MnemonicRange =\n";
2785 OS << " std::equal_range(std::begin(OperandMatchTable), "
2786 "std::end(OperandMatchTable),\n";
2787 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2788 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002789
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002790 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002791 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002792
2793 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2794 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2795
2796 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002797 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002798
2799 // Emit check that the required features are available.
2800 OS << " // check if the available features match\n";
2801 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2802 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002803 OS << " continue;\n";
2804 OS << " }\n\n";
2805
2806 // Emit check to ensure the operand number matches.
2807 OS << " // check if the operand in question has a custom parser.\n";
2808 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2809 OS << " continue;\n\n";
2810
2811 // Emit call to the custom parser method
2812 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002813 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002814 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002815 OS << " if (Result != MatchOperand_NoMatch)\n";
2816 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002817 OS << " }\n\n";
2818
Jim Grosbach861e49c2011-02-12 01:34:40 +00002819 OS << " // Okay, we had no match.\n";
2820 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002821 OS << "}\n\n";
2822}
2823
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00002824static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
2825 unsigned VariantCount) {
Craig Topper2a060282017-10-26 06:46:40 +00002826 OS << "static std::string " << Target.getName()
Craig Topper05515562017-10-26 06:46:41 +00002827 << "MnemonicSpellCheck(StringRef S, uint64_t FBS, unsigned VariantID) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00002828 if (!VariantCount)
2829 OS << " return \"\";";
2830 else {
2831 OS << " const unsigned MaxEditDist = 2;\n";
2832 OS << " std::vector<StringRef> Candidates;\n";
Craig Topper05515562017-10-26 06:46:41 +00002833 OS << " StringRef Prev = \"\";\n\n";
2834
2835 OS << " // Find the appropriate table for this asm variant.\n";
2836 OS << " const MatchEntry *Start, *End;\n";
2837 OS << " switch (VariantID) {\n";
2838 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
2839 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2840 Record *AsmVariant = Target.getAsmParserVariant(VC);
2841 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2842 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
2843 << "); End = std::end(MatchTable" << VC << "); break;\n";
2844 }
2845 OS << " }\n\n";
2846 OS << " for (auto I = Start; I < End; I++) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00002847 OS << " // Ignore unsupported instructions.\n";
2848 OS << " if ((FBS & I->RequiredFeatures) != I->RequiredFeatures)\n";
2849 OS << " continue;\n";
2850 OS << "\n";
2851 OS << " StringRef T = I->getMnemonic();\n";
2852 OS << " // Avoid recomputing the edit distance for the same string.\n";
2853 OS << " if (T.equals(Prev))\n";
2854 OS << " continue;\n";
2855 OS << "\n";
2856 OS << " Prev = T;\n";
2857 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
2858 OS << " if (Dist <= MaxEditDist)\n";
2859 OS << " Candidates.push_back(T);\n";
2860 OS << " }\n";
2861 OS << "\n";
2862 OS << " if (Candidates.empty())\n";
2863 OS << " return \"\";\n";
2864 OS << "\n";
2865 OS << " std::string Res = \", did you mean: \";\n";
2866 OS << " unsigned i = 0;\n";
2867 OS << " for( ; i < Candidates.size() - 1; i++)\n";
2868 OS << " Res += Candidates[i].str() + \", \";\n";
2869 OS << " return Res + Candidates[i].str() + \"?\";\n";
2870 }
2871 OS << "}\n";
2872 OS << "\n";
2873}
2874
2875
Oliver Stannard4191b9e2017-10-11 09:17:43 +00002876// Emit a function mapping match classes to strings, for debugging.
2877static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
2878 raw_ostream &OS) {
2879 OS << "#ifndef NDEBUG\n";
2880 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
2881 OS << " switch (Kind) {\n";
2882
2883 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
2884 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
2885 for (const auto &CI : Infos) {
2886 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
2887 }
2888 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
2889
2890 OS << " }\n";
2891 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
2892 OS << "}\n\n";
2893 OS << "#endif // NDEBUG\n";
2894}
2895
Daniel Dunbard0470d72009-08-07 21:01:44 +00002896void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002897 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00002898 Record *AsmParser = Target.getAsmParser();
Craig Topperbcd3c372017-05-31 21:12:46 +00002899 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
Daniel Dunbard0470d72009-08-07 21:01:44 +00002900
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002901 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00002902 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002903 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002904
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00002905 // Sort the instruction table using the partial order on classes. We use
2906 // stable_sort to ensure that ambiguous instructions are still
2907 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002908 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2909 [](const std::unique_ptr<MatchableInfo> &a,
2910 const std::unique_ptr<MatchableInfo> &b){
2911 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002912
Matthias Brauna8eed312016-12-05 19:44:31 +00002913#ifdef EXPENSIVE_CHECKS
2914 // Verify that the table is sorted and operator < works transitively.
2915 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2916 ++I) {
2917 for (auto J = I; J != E; ++J) {
2918 assert(!(**J < **I));
2919 }
2920 }
2921#endif
2922
Daniel Dunbar71330282009-08-08 05:24:34 +00002923 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00002924 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002925 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00002926 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002927
Chris Lattnerad776812010-11-01 05:06:45 +00002928 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002929 DEBUG_WITH_TYPE("ambiguous_instrs", {
2930 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00002931 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2932 ++I) {
2933 for (auto J = std::next(I); J != E; ++J) {
2934 const MatchableInfo &A = **I;
2935 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002936
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002937 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00002938 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002939 A.dump();
2940 errs() << "\nis incomparable with:\n";
2941 B.dump();
2942 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002943 ++NumAmbiguous;
2944 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00002945 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00002946 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002947 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002948 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00002949 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002950 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00002951
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002952 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002953 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002954
Craig Topperfd2c6a32015-12-31 08:18:23 +00002955 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00002956 bool HasOptionalOperands = Info.hasOptionalOperands();
Oliver Stannard65f7bc52017-10-03 09:33:12 +00002957 bool ReportMultipleNearMisses =
2958 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00002959
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002960 // Write the output.
2961
Chris Lattner3e4582a2010-09-06 19:11:01 +00002962 // Information for the class declaration.
2963 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2964 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00002965 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00002966 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002967 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00002968 if (HasOptionalOperands) {
2969 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2970 << "unsigned Opcode,\n"
2971 << " const OperandVector &Operands,\n"
2972 << " const SmallBitVector &OptionalOperandsMask);\n";
2973 } else {
2974 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2975 << "unsigned Opcode,\n"
2976 << " const OperandVector &Operands);\n";
2977 }
Chad Rosier380a74a2012-10-02 00:25:57 +00002978 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00002979 OS << " const OperandVector &Operands) override;\n";
Craig Toppera5754e62015-01-03 08:16:29 +00002980 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00002981 << " MCInst &Inst,\n";
2982 if (ReportMultipleNearMisses)
2983 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
2984 else
2985 OS << " uint64_t &ErrorInfo,\n";
2986 OS << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00002987 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002988
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002989 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00002990 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002991 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002992 OS << " StringRef Mnemonic);\n";
2993
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002994 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002995 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002996 OS << " unsigned MCK);\n\n";
2997 }
2998
Chris Lattner3e4582a2010-09-06 19:11:01 +00002999 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3000
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003001 // Emit the operand match diagnostic enum names.
3002 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3003 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3004 emitOperandDiagnosticTypes(Info, OS);
3005 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3006
Chris Lattner3e4582a2010-09-06 19:11:01 +00003007 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3008 OS << "#undef GET_REGISTER_MATCHER\n\n";
3009
Daniel Dunbareefe8612010-07-19 05:44:09 +00003010 // Emit the subtarget feature enumeration.
Daniel Sanders72db2a32016-11-19 13:05:44 +00003011 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(
3012 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003013
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003014 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00003015 // This should be omitted for Mips target
3016 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3017 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00003018
Dylan McKaybff960a2016-02-03 10:30:16 +00003019 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3020 emitMatchRegisterAltName(Target, AsmParser, OS);
3021
Chris Lattner3e4582a2010-09-06 19:11:01 +00003022 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003023
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003024 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3025 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003026
Jim Grosbach5117ef72012-04-24 22:40:08 +00003027 // Generate the helper function to get the names for subtarget features.
3028 emitGetSubtargetFeatureName(Info, OS);
3029
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003030 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3031
3032 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3033 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3034
Chris Lattner477fba4f2010-10-30 18:48:18 +00003035 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00003036 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003037
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003038 // Generate the convertToMCInst function to convert operands into an MCInst.
3039 // Also, generate the convertToMapAndConstraints function for MS-style inline
3040 // assembly. The latter doesn't actually generate a MCInst.
Sam Kolton5f10a132016-05-06 11:31:17 +00003041 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
3042 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003043
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003044 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003045 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003046
Oliver Stannard41dfac32017-10-03 14:34:57 +00003047 // Emit a function to get the user-visible string to describe an operand
3048 // match failure in diagnostics.
3049 emitOperandMatchErrorDiagStrings(Info, OS);
3050
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003051 // Emit a function to map register classes to operand match failure codes.
3052 emitRegisterMatchErrorFunc(Info, OS);
3053
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003054 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003055 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003056
Daniel Dunbar2587b612009-08-10 16:05:47 +00003057 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003058 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00003059
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003060 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003061 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003062
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003063 emitMatchClassKindNames(Info.Classes, OS);
3064
Daniel Dunbareefe8612010-07-19 05:44:09 +00003065 // Emit the available features compute function.
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003066 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003067 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3068 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003069
Craig Toppere2cfeb32012-09-18 06:10:45 +00003070 StringToOffsetTable StringTable;
3071
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003072 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003073 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00003074 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00003075 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003076 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3077 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003078
3079 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003080 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00003081 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3082 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3083 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003084
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003085 OS << "static const char *const MnemonicTable =\n";
3086 StringTable.EmitString(OS);
3087 OS << ";\n\n";
3088
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00003089 // Emit the static match table; unused classes get initialized to 0 which is
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003090 // guaranteed to be InvalidMatchClass.
3091 //
3092 // FIXME: We can reduce the size of this table very easily. First, we change
3093 // it so that store the kinds in separate bit-fields for each index, which
3094 // only needs to be the max width used for classes at that index (we also need
3095 // to reject based on this during classification). If we then make sure to
3096 // order the match kinds appropriately (putting mnemonics last), then we
3097 // should only end up using a few bits for each class, especially the ones
3098 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003099 OS << "namespace {\n";
3100 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00003101 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3102 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003103 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003104 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3105 << " ConvertFn;\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00003106 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003107 << " RequiredFeatures;\n";
David Blaikied749e342014-11-28 20:35:57 +00003108 OS << " " << getMinimalTypeForRange(
3109 std::distance(Info.Classes.begin(), Info.Classes.end()))
3110 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003111 OS << " StringRef getMnemonic() const {\n";
3112 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3113 OS << " MnemonicTable[Mnemonic]);\n";
3114 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003115 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003116
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003117 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003118 OS << " struct LessOpcode {\n";
3119 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003120 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003121 OS << " }\n";
3122 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003123 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003124 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003125 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003126 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003127 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003128 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003129
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003130 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003131
Craig Topper690d8ea2013-07-24 07:33:14 +00003132 unsigned VariantCount = Target.getAsmParserVariantCount();
3133 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3134 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003135 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003136
Craig Topper690d8ea2013-07-24 07:33:14 +00003137 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003138
Craig Topperf34dad92014-11-28 03:53:02 +00003139 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003140 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003141 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003142
Craig Topper690d8ea2013-07-24 07:33:14 +00003143 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003144 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003145 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003146 << " /* " << MI->Mnemonic << " */, "
Craig Topper2b347eb2017-07-07 05:19:25 +00003147 << Target.getInstNamespace() << "::"
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003148 << MI->getResultInst()->TheDef->getName() << ", "
3149 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003150
3151 // Write the required features mask.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003152 if (!MI->RequiredFeatures.empty()) {
3153 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003154 if (i) OS << "|";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003155 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003156 }
3157 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003158 OS << "0";
Craig Topper690d8ea2013-07-24 07:33:14 +00003159
3160 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003161 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3162 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003163
3164 if (i) OS << ", ";
3165 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003166 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003167 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003168 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003169
Craig Topper690d8ea2013-07-24 07:33:14 +00003170 OS << "};\n\n";
3171 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003172
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003173 OS << "#include \"llvm/Support/Debug.h\"\n";
3174 OS << "#include \"llvm/Support/Format.h\"\n\n";
3175
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003176 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003177 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003178 << "MatchInstructionImpl(const OperandVector &Operands,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003179 OS << " MCInst &Inst,\n";
3180 if (ReportMultipleNearMisses)
3181 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3182 else
3183 OS << " uint64_t &ErrorInfo,\n";
3184 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003185
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003186 if (!ReportMultipleNearMisses) {
3187 OS << " // Eliminate obvious mismatches.\n";
3188 OS << " if (Operands.size() > "
3189 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3190 OS << " ErrorInfo = "
3191 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3192 OS << " return Match_InvalidOperand;\n";
3193 OS << " }\n\n";
3194 }
Chad Rosiereac13a32012-08-30 21:43:05 +00003195
Daniel Dunbareefe8612010-07-19 05:44:09 +00003196 // Emit code to get the available features.
3197 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003198 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003199
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003200 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003201 if (HasMnemonicFirst) {
3202 OS << " StringRef Mnemonic = ((" << Target.getName()
3203 << "Operand&)*Operands[0]).getToken();\n\n";
3204 } else {
3205 OS << " StringRef Mnemonic;\n";
3206 OS << " if (Operands[0]->isToken())\n";
3207 OS << " Mnemonic = ((" << Target.getName()
3208 << "Operand&)*Operands[0]).getToken();\n\n";
3209 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003210
Chris Lattner477fba4f2010-10-30 18:48:18 +00003211 if (HasMnemonicAliases) {
3212 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003213 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003214 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003215
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003216 // Emit code to compute the class list for this operand vector.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003217 if (!ReportMultipleNearMisses) {
3218 OS << " // Some state to try to produce better error messages.\n";
3219 OS << " bool HadMatchOtherThanFeatures = false;\n";
3220 OS << " bool HadMatchOtherThanPredicate = false;\n";
3221 OS << " unsigned RetCode = Match_InvalidOperand;\n";
3222 OS << " uint64_t MissingFeatures = ~0ULL;\n";
3223 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3224 OS << " // wrong for all instances of the instruction.\n";
3225 OS << " ErrorInfo = ~0ULL;\n";
3226 }
3227
Sam Kolton5f10a132016-05-06 11:31:17 +00003228 if (HasOptionalOperands) {
3229 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3230 }
Chris Lattner81301972010-09-06 21:22:45 +00003231
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003232 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003233 OS << " // Find the appropriate table for this asm variant.\n";
3234 OS << " const MatchEntry *Start, *End;\n";
3235 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003236 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003237 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3238 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003239 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003240 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3241 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003242 }
3243 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003244
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003245 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003246 if (HasMnemonicFirst) {
3247 OS << " auto MnemonicRange = "
3248 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3249 } else {
3250 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3251 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3252 OS << " if (!Mnemonic.empty())\n";
3253 OS << " MnemonicRange = "
3254 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3255 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003256
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003257 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3258 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3259 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3260
Chris Lattner628fbec2010-09-06 21:54:15 +00003261 OS << " // Return a more specific error code if no mnemonics match.\n";
3262 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3263 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003264
Chris Lattner81301972010-09-06 21:22:45 +00003265 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003266 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003267 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003268
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003269 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3270 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3271
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003272 if (ReportMultipleNearMisses) {
3273 OS << " // Some state to record ways in which this instruction did not match.\n";
3274 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3275 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3276 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3277 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
3278 OS << " bool MultipleInvalidOperands = false;\n";
3279 }
3280
Craig Topperfd2c6a32015-12-31 08:18:23 +00003281 if (HasMnemonicFirst) {
3282 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3283 OS << " assert(Mnemonic == it->getMnemonic());\n";
3284 }
3285
Daniel Dunbareefe8612010-07-19 05:44:09 +00003286 // Emit check that the subclasses match.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003287 if (!ReportMultipleNearMisses)
3288 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003289 if (HasOptionalOperands) {
3290 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3291 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003292 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3293 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3294 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3295 OS << " auto Formal = "
3296 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003297 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3298 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3299 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3300 OS << " if (ActualIdx < Operands.size())\n";
3301 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3302 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3303 OS << " else\n";
3304 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003305 OS << " if (ActualIdx >= Operands.size()) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003306 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003307 if (ReportMultipleNearMisses) {
3308 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3309 "isSubclass(Formal, OptionalMatchClass);\n";
3310 OS << " if (!ThisOperandValid) {\n";
3311 OS << " if (!OperandNearMiss) {\n";
3312 OS << " // Record info about match failure for later use.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003313 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003314 OS << " OperandNearMiss =\n";
3315 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
3316 OS << " } else {\n";
3317 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003318 OS << " DEBUG_WITH_TYPE(\n";
3319 OS << " \"asm-matcher\",\n";
3320 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003321 OS << " MultipleInvalidOperands = true;\n";
3322 OS << " break;\n";
3323 OS << " }\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003324 OS << " } else {\n";
3325 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003326 OS << " }\n";
3327 OS << " continue;\n";
3328 } else {
3329 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3330 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3331 if (HasOptionalOperands) {
3332 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3333 << ");\n";
3334 }
3335 OS << " break;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003336 }
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003337 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003338 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003339 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003340 OS << " if (Diag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003341 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3342 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003343 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003344 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003345 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003346 OS << " // If the generic handler indicates an invalid operand\n";
3347 OS << " // failure, check for a special case.\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003348 OS << " if (Diag != Match_Success) {\n";
3349 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3350 OS << " if (TargetDiag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003351 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3352 OS << " dbgs() << \"match success using target matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003353 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003354 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003355 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003356 OS << " // If the target matcher returned a specific error code use\n";
3357 OS << " // that, else use the one from the generic matcher.\n";
3358 OS << " if (TargetDiag != Match_InvalidOperand)\n";
3359 OS << " Diag = TargetDiag;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003360 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003361 OS << " // If current formal operand wasn't matched and it is optional\n"
3362 << " // then try to match next formal operand\n";
3363 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003364 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3365 if (HasOptionalOperands) {
3366 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3367 }
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003368 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003369 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003370 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003371
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003372 if (ReportMultipleNearMisses) {
3373 OS << " if (!OperandNearMiss) {\n";
3374 OS << " // If this is the first invalid operand we have seen, record some\n";
3375 OS << " // information about it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003376 OS << " DEBUG_WITH_TYPE(\n";
3377 OS << " \"asm-matcher\",\n";
3378 OS << " dbgs()\n";
3379 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3380 OS << " << Diag << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003381 OS << " OperandNearMiss =\n";
3382 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3383 OS << " ++ActualIdx;\n";
3384 OS << " } else {\n";
3385 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003386 OS << " DEBUG_WITH_TYPE(\n";
3387 OS << " \"asm-matcher\",\n";
3388 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003389 OS << " MultipleInvalidOperands = true;\n";
3390 OS << " break;\n";
3391 OS << " }\n";
3392 OS << " }\n\n";
3393 } else {
3394 OS << " // If this operand is broken for all of the instances of this\n";
3395 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3396 OS << " // If we already had a match that only failed due to a\n";
3397 OS << " // target predicate, that diagnostic is preferred.\n";
3398 OS << " if (!HadMatchOtherThanPredicate &&\n";
3399 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3400 OS << " ErrorInfo = ActualIdx;\n";
3401 OS << " // InvalidOperand is the default. Prefer specificity.\n";
3402 OS << " if (Diag != Match_InvalidOperand)\n";
3403 OS << " RetCode = Diag;\n";
3404 OS << " }\n";
3405 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3406 OS << " OperandsValid = false;\n";
3407 OS << " break;\n";
3408 OS << " }\n\n";
3409 }
3410
3411 if (ReportMultipleNearMisses)
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003412 OS << " if (MultipleInvalidOperands) {\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003413 else
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003414 OS << " if (!OperandsValid) {\n";
3415 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3416 OS << " \"operand mismatches, ignoring \"\n";
3417 OS << " \"this opcode\\n\");\n";
3418 OS << " continue;\n";
3419 OS << " }\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003420
3421 // Emit check that the required features are available.
3422 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3423 << "!= it->RequiredFeatures) {\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003424 if (!ReportMultipleNearMisses)
3425 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003426 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003427 "~AvailableFeatures;\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003428 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features: \"\n";
3429 OS << " << format_hex(NewMissingFeatures, 18)\n";
3430 OS << " << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003431 if (ReportMultipleNearMisses) {
3432 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3433 } else {
3434 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3435 " countPopulation(MissingFeatures))\n";
3436 OS << " MissingFeatures = NewMissingFeatures;\n";
3437 OS << " continue;\n";
3438 }
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003439 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003440 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003441 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003442 OS << " Inst.setOpcode(it->Opcode);\n";
3443 // Verify the instruction with the target-specific match predicate function.
3444 OS << " // We have a potential match but have not rendered the operands.\n"
3445 << " // Check the target predicate to handle any context sensitive\n"
3446 " // constraints.\n"
3447 << " // For example, Ties that are referenced multiple times must be\n"
3448 " // checked here to ensure the input is the same for each match\n"
3449 " // constraints. If we leave it any later the ties will have been\n"
3450 " // canonicalized\n"
3451 << " unsigned MatchResult;\n"
3452 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3453 "Operands)) != Match_Success) {\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003454 << " Inst.clear();\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003455 OS << " DEBUG_WITH_TYPE(\n";
3456 OS << " \"asm-matcher\",\n";
3457 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3458 OS << " << MatchResult << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003459 if (ReportMultipleNearMisses) {
3460 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3461 } else {
3462 OS << " RetCode = MatchResult;\n"
3463 << " HadMatchOtherThanPredicate = true;\n"
3464 << " continue;\n";
3465 }
3466 OS << " }\n\n";
3467
3468 if (ReportMultipleNearMisses) {
3469 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3470 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3471 OS << " if (OperandNearMiss) {\n";
3472 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3473 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003474 OS << " DEBUG_WITH_TYPE(\n";
3475 OS << " \"asm-matcher\",\n";
3476 OS << " dbgs()\n";
3477 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003478 OS << " NearMisses->push_back(OperandNearMiss);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003479 OS << " } else {\n";
3480 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3481 OS << " \"types of mismatch, so not \"\n";
3482 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003483 OS << " }\n";
3484 OS << " continue;\n";
3485 OS << " }\n\n";
3486 }
3487
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003488 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003489 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003490 OS << " return Match_Success;\n";
3491 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003492 OS << " // We have selected a definite instruction, convert the parsed\n"
3493 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003494 if (HasOptionalOperands) {
3495 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3496 << " OptionalOperandsMask);\n";
3497 } else {
3498 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3499 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003500 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003501
Jim Grosbach120a96a2011-08-15 23:03:29 +00003502 // Verify the instruction with the target-specific match predicate function.
3503 OS << " // We have a potential match. Check the target predicate to\n"
3504 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003505 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3506 << " Match_Success) {\n"
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003507 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3508 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3509 << " << MatchResult << \"\\n\");\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003510 << " Inst.clear();\n";
3511 if (ReportMultipleNearMisses) {
3512 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3513 } else {
3514 OS << " RetCode = MatchResult;\n"
3515 << " HadMatchOtherThanPredicate = true;\n"
3516 << " continue;\n";
3517 }
3518 OS << " }\n\n";
3519
3520 if (ReportMultipleNearMisses) {
3521 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3522 OS << " (int)(bool)FeaturesNearMiss +\n";
3523 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3524 OS << " (int)(bool)LatePredicateNearMiss);\n";
3525 OS << " if (NumNearMisses == 1) {\n";
3526 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3527 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003528 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3529 OS << " \"mismatch, so reporting a \"\n";
3530 OS << " \"near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003531 OS << " if (NearMisses && FeaturesNearMiss)\n";
3532 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3533 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3534 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3535 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3536 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3537 OS << "\n";
3538 OS << " continue;\n";
3539 OS << " } else if (NumNearMisses > 1) {\n";
3540 OS << " // This instruction missed in more than one way, so ignore it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003541 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3542 OS << " \"types of mismatch, so not \"\n";
3543 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003544 OS << " continue;\n";
3545 OS << " }\n";
3546 }
Jim Grosbach120a96a2011-08-15 23:03:29 +00003547
Daniel Dunbar451a4352010-03-18 20:05:56 +00003548 // Call the post-processing function, if used.
Craig Topperbcd3c372017-05-31 21:12:46 +00003549 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
Daniel Dunbar451a4352010-03-18 20:05:56 +00003550 if (!InsnCleanupFn.empty())
3551 OS << " " << InsnCleanupFn << "(Inst);\n";
3552
Joey Gouly0e76fa72013-09-12 10:28:05 +00003553 if (HasDeprecation) {
3554 OS << " std::string Info;\n";
Weiming Zhaob38cfce2016-12-05 23:55:13 +00003555 OS << " if (!getParser().getTargetParser().\n";
3556 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3557 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003558 OS << " SMLoc Loc = ((" << Target.getName()
3559 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003560 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003561 OS << " }\n";
3562 }
3563
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003564 OS << " DEBUG_WITH_TYPE(\n";
3565 OS << " \"asm-matcher\",\n";
3566 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00003567 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003568 OS << " }\n\n";
3569
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003570 if (ReportMultipleNearMisses) {
3571 OS << " // No instruction variants matched exactly.\n";
3572 OS << " return Match_NearMisses;\n";
3573 } else {
3574 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3575 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3576 OS << " return RetCode;\n\n";
3577 OS << " // Missing feature matches return which features were missing\n";
3578 OS << " ErrorInfo = MissingFeatures;\n";
3579 OS << " return Match_MissingFeature;\n";
3580 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003581 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003582
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003583 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003584 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00003585 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003586
Chris Lattner3e4582a2010-09-06 19:11:01 +00003587 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Craig Topper2a060282017-10-26 06:46:40 +00003588
3589 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3590 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3591
3592 emitMnemonicSpellChecker(OS, Target, VariantCount);
3593
3594 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003595}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003596
3597namespace llvm {
3598
3599void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3600 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3601 AsmMatcherEmitter(RK).run(OS);
3602}
3603
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003604} // end namespace llvm