blob: 9ff24100009fc30b3eb5697df96699d314d9ae0f [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"
Nico Weber432a3882018-04-30 14:59:11 +0000108#include "llvm/Config/llvm-config.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000109#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000110#include "llvm/Support/Debug.h"
Craig Topperc4965bc2012-02-05 07:21:30 +0000111#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +0000112#include "llvm/TableGen/Error.h"
113#include "llvm/TableGen/Record.h"
Douglas Gregor12c1cd32012-05-02 17:32:48 +0000114#include "llvm/TableGen/StringMatcher.h"
Craig Topper3e1d5da2013-08-29 05:09:55 +0000115#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000116#include "llvm/TableGen/TableGenBackend.h"
117#include <cassert>
Will Dietz981af002013-10-12 00:55:57 +0000118#include <cctype>
Mehdi Aminib550cb12016-04-18 09:17:29 +0000119#include <forward_list>
Daniel Dunbar71330282009-08-08 05:24:34 +0000120#include <map>
121#include <set>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000122
Daniel Dunbar3085b572009-07-11 19:39:44 +0000123using namespace llvm;
124
Chandler Carruthe96dd892014-04-21 22:55:11 +0000125#define DEBUG_TYPE "asm-matcher-emitter"
126
Daniel Sanders0848b232017-03-27 13:15:13 +0000127cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
128
Daniel Dunbar15b80372009-08-07 20:33:39 +0000129static cl::opt<std::string>
Daniel Sanders0848b232017-03-27 13:15:13 +0000130 MatchPrefix("match-prefix", cl::init(""),
131 cl::desc("Only match instructions with the given prefix"),
132 cl::cat(AsmMatcherEmitterCat));
Daniel Dunbare10787e2009-08-07 08:26:05 +0000133
Daniel Dunbare10787e2009-08-07 08:26:05 +0000134namespace {
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000135class AsmMatcherInfo;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000136
Tim Northoverc74e6912013-09-16 16:43:19 +0000137// Register sets are used as keys in some second-order sets TableGen creates
138// when generating its data structures. This means that the order of two
139// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
140// can even affect compiler output (at least seen in diagnostics produced when
141// all matches fail). So we use a type that sorts them consistently.
142typedef std::set<Record*, LessRecordByID> RegisterSet;
143
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000144class AsmMatcherEmitter {
145 RecordKeeper &Records;
146public:
147 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
148
149 void run(raw_ostream &o);
150};
151
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000152/// ClassInfo - Helper class for storing the information about a particular
153/// class of operands which can be matched.
154struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000155 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000156 /// Invalid kind, for use as a sentinel value.
157 Invalid = 0,
158
159 /// The class for a particular token.
160 Token,
161
162 /// The (first) register class, subsequent register classes are
163 /// RegisterClass0+1, and so on.
164 RegisterClass0,
165
166 /// The (first) user defined class, subsequent user defined classes are
167 /// UserClass0+1, and so on.
168 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000169 };
170
171 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
172 /// N) for the Nth user defined class.
173 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000174
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000175 /// SuperClasses - The super classes of this class. Note that for simplicities
176 /// sake user operands only record their immediate super class, while register
177 /// operands include all superclasses.
178 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000179
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000180 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000181 std::string Name;
182
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000183 /// ClassName - The unadorned generic name for this class (e.g., Token).
184 std::string ClassName;
185
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000186 /// ValueName - The name of the value this class represents; for a token this
187 /// is the literal token string, for an operand it is the TableGen class (or
188 /// empty if this is a derived class).
189 std::string ValueName;
190
191 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000192 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000193 std::string PredicateMethod;
194
195 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000196 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000197 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000198
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000199 /// ParserMethod - The name of the operand method to do a target specific
200 /// parsing on the operand.
201 std::string ParserMethod;
202
Eric Christopher650c8f22014-05-20 17:11:11 +0000203 /// For register classes: the records for all the registers in this class.
Tim Northoverc74e6912013-09-16 16:43:19 +0000204 RegisterSet Registers;
Daniel Dunbar34c87912009-08-11 20:10:07 +0000205
Eric Christopher650c8f22014-05-20 17:11:11 +0000206 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000207 std::string DiagnosticType;
Tom Stellardb9f235e2016-02-05 19:59:33 +0000208
Oliver Stannard41dfac32017-10-03 14:34:57 +0000209 /// For custom match classes: the diagnostic string for when the predicate fails.
210 std::string DiagnosticString;
211
Tom Stellardb9f235e2016-02-05 19:59:33 +0000212 /// Is this operand optional and not always required.
213 bool IsOptional;
214
Sam Kolton5f10a132016-05-06 11:31:17 +0000215 /// DefaultMethod - The name of the method that returns the default operand
216 /// for optional operand
217 std::string DefaultMethod;
218
Daniel Dunbar34c87912009-08-11 20:10:07 +0000219public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000220 /// isRegisterClass() - Check if this is a register class.
221 bool isRegisterClass() const {
222 return Kind >= RegisterClass0 && Kind < UserClass0;
223 }
224
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000225 /// isUserClass() - Check if this is a user defined class.
226 bool isUserClass() const {
227 return Kind >= UserClass0;
228 }
229
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000230 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000231 /// are related if they are in the same class hierarchy.
232 bool isRelatedTo(const ClassInfo &RHS) const {
233 // Tokens are only related to tokens.
234 if (Kind == Token || RHS.Kind == Token)
235 return Kind == Token && RHS.Kind == Token;
236
Daniel Dunbar34c87912009-08-11 20:10:07 +0000237 // Registers classes are only related to registers classes, and only if
238 // their intersection is non-empty.
239 if (isRegisterClass() || RHS.isRegisterClass()) {
240 if (!isRegisterClass() || !RHS.isRegisterClass())
241 return false;
242
Tim Northoverc74e6912013-09-16 16:43:19 +0000243 RegisterSet Tmp;
244 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000245 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000246 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +0000247 II, LessRecordByID());
Daniel Dunbar34c87912009-08-11 20:10:07 +0000248
249 return !Tmp.empty();
250 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000251
252 // Otherwise we have two users operands; they are related if they are in the
253 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000254 //
255 // FIXME: This is an oversimplification, they should only be related if they
256 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000257 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
258 const ClassInfo *Root = this;
259 while (!Root->SuperClasses.empty())
260 Root = Root->SuperClasses.front();
261
Daniel Dunbar34c87912009-08-11 20:10:07 +0000262 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000263 while (!RHSRoot->SuperClasses.empty())
264 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000265
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000266 return Root == RHSRoot;
267 }
268
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000269 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000270 bool isSubsetOf(const ClassInfo &RHS) const {
271 // This is a subset of RHS if it is the same class...
272 if (this == &RHS)
273 return true;
274
275 // ... or if any of its super classes are a subset of RHS.
Craig Topper03ec8012014-11-25 20:11:31 +0000276 for (const ClassInfo *CI : SuperClasses)
277 if (CI->isSubsetOf(RHS))
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000278 return true;
279
280 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000281 }
282
Oliver Stannard7772f022016-01-25 10:20:19 +0000283 int getTreeDepth() const {
284 int Depth = 0;
285 const ClassInfo *Root = this;
286 while (!Root->SuperClasses.empty()) {
287 Depth++;
288 Root = Root->SuperClasses.front();
289 }
290 return Depth;
291 }
292
293 const ClassInfo *findRoot() const {
294 const ClassInfo *Root = this;
295 while (!Root->SuperClasses.empty())
296 Root = Root->SuperClasses.front();
297 return Root;
298 }
299
300 /// Compare two classes. This does not produce a total ordering, but does
301 /// guarantee that subclasses are sorted before their parents, and that the
302 /// ordering is transitive.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000303 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000304 if (this == &RHS)
305 return false;
306
Oliver Stannard7772f022016-01-25 10:20:19 +0000307 // First, enforce the ordering between the three different types of class.
308 // Tokens sort before registers, which sort before user classes.
309 if (Kind == Token) {
310 if (RHS.Kind != Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000311 return true;
Oliver Stannard7772f022016-01-25 10:20:19 +0000312 assert(RHS.Kind == Token);
313 } else if (isRegisterClass()) {
314 if (RHS.Kind == Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000315 return false;
Oliver Stannard7772f022016-01-25 10:20:19 +0000316 else if (RHS.isUserClass())
317 return true;
318 assert(RHS.isRegisterClass());
319 } else if (isUserClass()) {
320 if (!RHS.isUserClass())
321 return false;
322 assert(RHS.isUserClass());
323 } else {
324 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000325 }
Oliver Stannard7772f022016-01-25 10:20:19 +0000326
327 if (Kind == Token || isUserClass()) {
328 // Related tokens and user classes get sorted by depth in the inheritence
329 // tree (so that subclasses are before their parents).
330 if (isRelatedTo(RHS)) {
331 if (getTreeDepth() > RHS.getTreeDepth())
332 return true;
333 if (getTreeDepth() < RHS.getTreeDepth())
334 return false;
335 } else {
336 // Unrelated tokens and user classes are ordered by the name of their
337 // root nodes, so that there is a consistent ordering between
338 // unconnected trees.
339 return findRoot()->ValueName < RHS.findRoot()->ValueName;
340 }
341 } else if (isRegisterClass()) {
342 // For register sets, sort by number of registers. This guarantees that
343 // a set will always sort before all of it's strict supersets.
344 if (Registers.size() != RHS.Registers.size())
345 return Registers.size() < RHS.Registers.size();
346 } else {
347 llvm_unreachable("Unknown ClassInfoKind");
348 }
349
350 // FIXME: We should be able to just return false here, as we only need a
351 // partial order (we use stable sorts, so this is deterministic) and the
352 // name of a class shouldn't be significant. However, some of the backends
353 // accidentally rely on this behaviour, so it will have to stay like this
354 // until they are fixed.
355 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000356 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000357};
358
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000359class AsmVariantInfo {
360public:
Craig Topperbcd3c372017-05-31 21:12:46 +0000361 StringRef RegisterPrefix;
362 StringRef TokenizingCharacters;
363 StringRef SeparatorCharacters;
364 StringRef BreakCharacters;
365 StringRef Name;
Craig Topperc8b5b252015-12-30 06:00:18 +0000366 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000367};
368
Chris Lattnerad776812010-11-01 05:06:45 +0000369/// MatchableInfo - Helper class for storing the necessary information for an
370/// instruction or alias which is capable of being matched.
371struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000372 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000373 /// Token - This is the token that the operand came from.
374 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000375
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000376 /// The unique class instance this operand should match.
377 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000378
Chris Lattner7108dad2010-11-04 01:42:59 +0000379 /// The operand name this is, if anything.
380 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000381
Sander de Smalen5b691a12018-02-04 16:24:17 +0000382 /// The operand name this is, before renaming for tied operands.
383 StringRef OrigSrcOpName;
384
Bob Wilsonb9b24222011-01-26 19:44:55 +0000385 /// The suboperand index within SrcOpName, or -1 for the entire operand.
386 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000387
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000388 /// Whether the token is "isolated", i.e., it is preceded and followed
389 /// by separators.
390 bool IsIsolatedToken;
391
Devang Patel6d676e42012-01-07 01:33:34 +0000392 /// Register record if this token is singleton register.
393 Record *SingletonReg;
394
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000395 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
396 : Token(T), Class(nullptr), SubOpIdx(-1),
397 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000398 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000399
Chris Lattner743081d2010-11-04 00:43:46 +0000400 /// ResOperand - This represents a single operand in the result instruction
401 /// generated by the match. In cases (like addressing modes) where a single
402 /// assembler operand expands to multiple MCOperands, this represents the
403 /// single assembler operand, not the MCOperand.
404 struct ResOperand {
405 enum {
406 /// RenderAsmOperand - This represents an operand result that is
407 /// generated by calling the render method on the assembly operand. The
408 /// corresponding AsmOperand is specified by AsmOperandNum.
409 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000410
Chris Lattner743081d2010-11-04 00:43:46 +0000411 /// TiedOperand - This represents a result operand that is a duplicate of
412 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000413 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000414
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000415 /// ImmOperand - This represents an immediate value that is dumped into
416 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000417 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000418
Chris Lattner4869d342010-11-06 19:57:21 +0000419 /// RegOperand - This represents a fixed register that is dumped in.
420 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000421 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000422
Sander de Smalen5b691a12018-02-04 16:24:17 +0000423 /// Tuple containing the index of the (earlier) result operand that should
424 /// be copied from, as well as the indices of the corresponding (parsed)
425 /// operands in the asm string.
426 struct TiedOperandsTuple {
427 unsigned ResOpnd;
428 unsigned SrcOpnd1Idx;
429 unsigned SrcOpnd2Idx;
430 };
431
Chris Lattner743081d2010-11-04 00:43:46 +0000432 union {
433 /// This is the operand # in the AsmOperands list that this should be
434 /// copied from.
435 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000436
Sander de Smalen5b691a12018-02-04 16:24:17 +0000437 /// Description of tied operands.
438 TiedOperandsTuple TiedOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000439
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000440 /// ImmVal - This is the immediate value added to the instruction.
441 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000442
Chris Lattner4869d342010-11-06 19:57:21 +0000443 /// Register - This is the register record.
444 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000445 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000446
Bob Wilsonb9b24222011-01-26 19:44:55 +0000447 /// MINumOperands - The number of MCInst operands populated by this
448 /// operand.
449 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000450
Bob Wilsonb9b24222011-01-26 19:44:55 +0000451 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000452 ResOperand X;
453 X.Kind = RenderAsmOperand;
454 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000455 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000456 return X;
457 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000458
Sander de Smalen5b691a12018-02-04 16:24:17 +0000459 static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
460 unsigned SrcOperand2) {
Chris Lattner743081d2010-11-04 00:43:46 +0000461 ResOperand X;
462 X.Kind = TiedOperand;
Sander de Smalen5b691a12018-02-04 16:24:17 +0000463 X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
Bob Wilsonb9b24222011-01-26 19:44:55 +0000464 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000465 return X;
466 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000467
Bob Wilsonb9b24222011-01-26 19:44:55 +0000468 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000469 ResOperand X;
470 X.Kind = ImmOperand;
471 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000472 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000473 return X;
474 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000475
Bob Wilsonb9b24222011-01-26 19:44:55 +0000476 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000477 ResOperand X;
478 X.Kind = RegOperand;
479 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000480 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000481 return X;
482 }
Chris Lattner743081d2010-11-04 00:43:46 +0000483 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000484
Devang Patel9bdc5052012-01-10 17:50:43 +0000485 /// AsmVariantID - Target's assembly syntax variant no.
486 int AsmVariantID;
487
David Blaikieba4e00f2014-12-22 21:26:26 +0000488 /// AsmString - The assembly string for this instruction (with variants
489 /// removed), e.g. "movsx $src, $dst".
490 std::string AsmString;
491
Chris Lattnera7a903e2010-11-02 17:34:28 +0000492 /// TheDef - This is the definition of the instruction or InstAlias that this
493 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000494 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000495
Chris Lattner4efe13d2010-11-04 02:11:18 +0000496 /// DefRec - This is the definition that it came from.
497 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000498
Chris Lattnerfecdad62010-11-06 07:14:44 +0000499 const CodeGenInstruction *getResultInst() const {
500 if (DefRec.is<const CodeGenInstruction*>())
501 return DefRec.get<const CodeGenInstruction*>();
502 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
503 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000504
Chris Lattner743081d2010-11-04 00:43:46 +0000505 /// ResOperands - This is the operand list that should be built for the result
506 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000507 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000508
Chris Lattner28ea9b12010-11-02 17:30:52 +0000509 /// Mnemonic - This is the first token of the matched instruction, its
510 /// mnemonic.
511 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000512
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000513 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000514 /// annotated with a class and where in the OperandList they were defined.
515 /// This directly corresponds to the tokenized AsmString after the mnemonic is
516 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000517 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000518
Sander de Smalen886510f2018-01-10 10:10:56 +0000519 /// AsmOperandEqualityConstraints - an array of pairs holding operand
520 /// constraints.
521 /// Each constraint is represented as a pair holding position of the token of
522 /// the operand asm name.
523 /// For example, an "AsmString" "add $Vd.s, $Vn.s, $Xn" would be
524 /// split in the following list of tokens:
525 ///
526 /// ['add', '$Vd', '.s', '$Vn', '.s', '$Xn']
527 ///
528 /// A constraint "$Vd = $Vn" (e.g. for a destructive operation) is rendered
529 /// as the pair {1,3} into this set (note that tokens are numbered starting
530 /// from 0).
531 SmallVector<std::pair<unsigned,unsigned>, 1> AsmOperandTiedConstraints;
532
Daniel Dunbareefe8612010-07-19 05:44:09 +0000533 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000534 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000535
Daniel Dunbar71330282009-08-08 05:24:34 +0000536 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000537 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000538 /// function.
539 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000540
Joey Gouly0e76fa72013-09-12 10:28:05 +0000541 /// If this instruction is deprecated in some form.
542 bool HasDeprecation;
543
Tom Stellard74c87c82015-05-26 15:55:50 +0000544 /// If this is an alias, this is use to determine whether or not to using
545 /// the conversion function defined by the instruction's AsmMatchConverter
546 /// or to use the function generated by the alias.
547 bool UseInstAsmMatchConverter;
548
Chris Lattnerad776812010-11-01 05:06:45 +0000549 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000550 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
551 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000552 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000553
David Blaikieba4e00f2014-12-22 21:26:26 +0000554 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000555 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
556 DefRec(Alias.release()),
557 UseInstAsmMatchConverter(
558 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000559 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000560
David Blaikie6e48a812015-08-01 01:08:30 +0000561 // Could remove this and the dtor if PointerUnion supported unique_ptr
562 // elements with a dynamic failure/assertion (like the one below) in the case
563 // where it was copied while being in an owning state.
564 MatchableInfo(const MatchableInfo &RHS)
565 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
566 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
567 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
568 RequiredFeatures(RHS.RequiredFeatures),
569 ConversionFnKind(RHS.ConversionFnKind),
570 HasDeprecation(RHS.HasDeprecation),
571 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
572 assert(!DefRec.is<const CodeGenInstAlias *>());
573 }
574
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000575 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000576 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000577 }
Craig Topperce274892014-11-28 05:01:21 +0000578
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000579 // Two-operand aliases clone from the main matchable, but mark the second
580 // operand as a tied operand of the first for purposes of the assembler.
581 void formTwoOperandAlias(StringRef Constraint);
582
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000583 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000584 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000585 AsmVariantInfo const &Variant,
586 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000587
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000588 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000589 /// and perform a bunch of validity checking.
Sander de Smalen5b691a12018-02-04 16:24:17 +0000590 bool validate(StringRef CommentDelimiter, bool IsAlias) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000591
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000592 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000593 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000594 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000595 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
596 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
597 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000598 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000599 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000600
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000601 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000602 /// This does not check the suboperand index.
Sander de Smalen5b691a12018-02-04 16:24:17 +0000603 int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
604 auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
David Majnemer562e8292016-08-12 00:18:03 +0000605 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000606 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000607 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000608
Sander de Smalen5b691a12018-02-04 16:24:17 +0000609 int findAsmOperandOriginallyNamed(StringRef N) const {
610 auto I =
611 find_if(AsmOperands,
612 [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
613 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
614 }
615
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000616 void buildInstructionResultOperands();
Sander de Smalen5b691a12018-02-04 16:24:17 +0000617 void buildAliasResultOperands(bool AliasConstraintsAreChecked);
Chris Lattner743081d2010-11-04 00:43:46 +0000618
Chris Lattnerad776812010-11-01 05:06:45 +0000619 /// operator< - Compare two matchables.
620 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000621 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000622 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
623 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000624
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000625 if (AsmOperands.size() != RHS.AsmOperands.size())
626 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000627
Daniel Dunbard9631912009-08-09 08:23:23 +0000628 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000629 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000630 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
631 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000632 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000633 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000634 return false;
635 }
636
Andrew Trick818f5ac2012-08-29 03:52:57 +0000637 // Give matches that require more features higher precedence. This is useful
638 // because we cannot define AssemblerPredicates with the negation of
639 // processor features. For example, ARM v6 "nop" may be either a HINT or
640 // MOV. With v6, we want to match HINT. The assembler has no way to
641 // predicate MOV under "NoV6", but HINT will always match first because it
642 // requires V6 while MOV does not.
643 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
644 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
645
Daniel Dunbar3239f022009-08-09 04:00:06 +0000646 return false;
647 }
648
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000649 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000650 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000651 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000652 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000653 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000654 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000655 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000656
Craig Topperad895412018-01-06 19:20:32 +0000657 // Different variants can't conflict.
658 if (AsmVariantID != RHS.AsmVariantID)
659 return false;
660
Daniel Dunbarf573b562009-08-09 06:05:33 +0000661 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000662 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000663 return false;
664
Daniel Dunbare1974092010-01-23 00:26:16 +0000665 // Otherwise, make sure the ordering of the two instructions is unambiguous
666 // by checking that either (a) a token or operand kind discriminates them,
667 // or (b) the ordering among equivalent kinds is consistent.
668
Daniel Dunbarf573b562009-08-09 06:05:33 +0000669 // Tokens and operand kinds are unambiguous (assuming a correct target
670 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000671 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
672 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
673 AsmOperands[i].Class->Kind == ClassInfo::Token)
674 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
675 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000676 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000677
Daniel Dunbarf573b562009-08-09 06:05:33 +0000678 // Otherwise, this operand could commute if all operands are equivalent, or
679 // there is a pair of operands that compare less than and a pair that
680 // compare greater than.
681 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000682 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
683 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000684 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000685 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000686 HasGT = true;
687 }
688
Craig Topper322b67f2016-01-03 07:33:39 +0000689 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000690 }
691
Craig Topper42bd8192014-11-28 03:53:00 +0000692 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000693
Chris Lattner28ea9b12010-11-02 17:30:52 +0000694private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000695 void tokenizeAsmString(AsmMatcherInfo const &Info,
696 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000697 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000698};
699
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000700struct OperandMatchEntry {
701 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000702 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000703 ClassInfo *CI;
704
Craig Topper42bd8192014-11-28 03:53:00 +0000705 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000706 unsigned opMask) {
707 OperandMatchEntry X;
708 X.OperandMask = opMask;
709 X.CI = ci;
710 X.MI = mi;
711 return X;
712 }
713};
714
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000715class AsmMatcherInfo {
716public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000717 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000718 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000719
Daniel Dunbare4318712009-08-11 20:59:47 +0000720 /// The tablegen AsmParser record.
721 Record *AsmParser;
722
Chris Lattnerb80ab362010-11-01 01:37:30 +0000723 /// Target - The target information.
724 CodeGenTarget &Target;
725
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000726 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000727 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000728
Chris Lattnerad776812010-11-01 05:06:45 +0000729 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000730 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000731
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000732 /// Info for custom matching operands by user defined methods.
733 std::vector<OperandMatchEntry> OperandMatchInfo;
734
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000735 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000736 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
737 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000738
Daniel Dunbareefe8612010-07-19 05:44:09 +0000739 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000740 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000741
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000742 /// Map of AsmOperandClass records to their class information.
743 std::map<Record*, ClassInfo*> AsmOperandClasses;
744
Oliver Stannard29ffd3f2017-10-10 11:00:40 +0000745 /// Map of RegisterClass records to their class information.
746 std::map<Record*, ClassInfo*> RegisterClassClasses;
747
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000748private:
749 /// Map of token to class information which has already been constructed.
750 std::map<std::string, ClassInfo*> TokenClasses;
751
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000752private:
753 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000754 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000755
756 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000757 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000758 int SubOpIdx);
759 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000760
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000761 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000762 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000763 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000764
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000765 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000766 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000767 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000768
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000769 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000770 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000771 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000772 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000773
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000774public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000775 AsmMatcherInfo(Record *AsmParser,
776 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000777 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000778
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000779 /// Construct the various tables used during matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000780 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000781
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000782 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000783 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000784 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000785
Chris Lattner43690072010-10-30 20:15:02 +0000786 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
787 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000788 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000789 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000790 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000791 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000792 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000793
Chris Lattner89dcb682010-12-15 04:48:22 +0000794 RecordKeeper &getRecords() const {
795 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000796 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000797
798 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000799 return find_if(Classes, [](const ClassInfo &Class) {
800 return Class.IsOptional;
801 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000802 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000803};
804
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000805} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000806
Aaron Ballman615eb472017-10-15 14:32:27 +0000807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000808LLVM_DUMP_METHOD void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000809 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000810
Craig Topperad895412018-01-06 19:20:32 +0000811 errs() << " variant: " << AsmVariantID << "\n";
812
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000813 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000814 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000815 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000816 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000817 }
818}
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000819#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +0000820
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000821static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000822parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000823 // Split via the '='.
824 std::pair<StringRef, StringRef> Ops = S.split('=');
825 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000826 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000827 // Trim whitespace and the leading '$' on the operand names.
828 size_t start = Ops.first.find_first_of('$');
829 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000830 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000831 Ops.first = Ops.first.slice(start + 1, std::string::npos);
832 size_t end = Ops.first.find_last_of(" \t");
833 Ops.first = Ops.first.slice(0, end);
834 // Now the second operand.
835 start = Ops.second.find_first_of('$');
836 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000837 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000838 Ops.second = Ops.second.slice(start + 1, std::string::npos);
839 end = Ops.second.find_last_of(" \t");
840 Ops.first = Ops.first.slice(0, end);
841 return Ops;
842}
843
844void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
845 // Figure out which operands are aliased and mark them as tied.
846 std::pair<StringRef, StringRef> Ops =
847 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
848
849 // Find the AsmOperands that refer to the operands we're aliasing.
850 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
851 int DstAsmOperand = findAsmOperandNamed(Ops.second);
852 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000853 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000854 "unknown source two-operand alias operand '" + Ops.first +
855 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000856 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000857 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000858 "unknown destination two-operand alias operand '" +
859 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000860
861 // Find the ResOperand that refers to the operand we're aliasing away
862 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000863 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000864 if (Op.Kind == ResOperand::RenderAsmOperand &&
865 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
866 Op.AsmOperandNum = DstAsmOperand;
867 break;
868 }
869 }
870 // Remove the AsmOperand for the alias operand.
871 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
872 // Adjust the ResOperand references to any AsmOperands that followed
873 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000874 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000875 switch(Op.Kind) {
876 default:
877 // Nothing to do for operands that don't reference AsmOperands.
878 break;
879 case ResOperand::RenderAsmOperand:
880 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
881 --Op.AsmOperandNum;
882 break;
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000883 }
884 }
885}
886
Craig Topper22fa45f2015-09-13 18:01:25 +0000887/// extractSingletonRegisterForAsmOperand - Extract singleton register,
888/// if present, from specified token.
889static void
890extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
891 const AsmMatcherInfo &Info,
892 StringRef RegisterPrefix) {
893 StringRef Tok = Op.Token;
894
895 // If this token is not an isolated token, i.e., it isn't separated from
896 // other tokens (e.g. with whitespace), don't interpret it as a register name.
897 if (!Op.IsIsolatedToken)
898 return;
899
900 if (RegisterPrefix.empty()) {
901 std::string LoweredTok = Tok.lower();
902 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
903 Op.SingletonReg = Reg->TheDef;
904 return;
905 }
906
907 if (!Tok.startswith(RegisterPrefix))
908 return;
909
910 StringRef RegName = Tok.substr(RegisterPrefix.size());
911 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
912 Op.SingletonReg = Reg->TheDef;
913
914 // If there is no register prefix (i.e. "%" in "%eax"), then this may
915 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000916}
917
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000918void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000919 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000920 AsmVariantInfo const &Variant,
921 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000922 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000923 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000924 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
925 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000926
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000927 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000928
Craig Topperfd2c6a32015-12-31 08:18:23 +0000929 // The first token of the instruction is the mnemonic, which must be a
930 // simple string, not a $foo variable or a singleton register.
931 if (AsmOperands.empty())
932 PrintFatalError(TheDef->getLoc(),
933 "Instruction '" + TheDef->getName() + "' has no tokens");
934
935 assert(!AsmOperands[0].Token.empty());
936 if (HasMnemonicFirst) {
937 Mnemonic = AsmOperands[0].Token;
938 if (Mnemonic[0] == '$')
939 PrintFatalError(TheDef->getLoc(),
940 "Invalid instruction mnemonic '" + Mnemonic + "'!");
941
942 // Remove the first operand, it is tracked in the mnemonic field.
943 AsmOperands.erase(AsmOperands.begin());
944 } else if (AsmOperands[0].Token[0] != '$')
945 Mnemonic = AsmOperands[0].Token;
946
Chris Lattnerba465f92010-11-01 04:53:48 +0000947 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000948 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000949 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000950 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000951 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000952
Chris Lattnerba465f92010-11-01 04:53:48 +0000953 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000954 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000955 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000956 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000957 SingletonRegisters.insert(Reg);
958 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000959
960 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
961 if (!DepMask)
962 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
963
964 HasDeprecation =
965 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000966}
967
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000968/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000969void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
970 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000971}
972
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000973/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000974void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
975 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000976 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000977 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000978 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000979 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000980 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000981 char Char = String[i];
982 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
983 if (InTok) {
984 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000985 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000986 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000987 }
988 InTok = true;
989 continue;
990 }
Craig Topperbc22e262015-12-31 05:01:45 +0000991 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
992 if (InTok) {
993 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000994 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000995 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000996 }
Craig Topperbc22e262015-12-31 05:01:45 +0000997 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000998 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000999 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001000 continue;
1001 }
Craig Topperbc22e262015-12-31 05:01:45 +00001002 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
1003 if (InTok) {
1004 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001005 InTok = false;
1006 }
1007 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +00001008 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001009 continue;
1010 }
Craig Topperbc22e262015-12-31 05:01:45 +00001011
1012 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001013 case '\\':
1014 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +00001015 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001016 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001017 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001018 }
1019 ++i;
1020 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +00001021 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001022 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +00001023 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001024 break;
1025
1026 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +00001027 if (InTok) {
1028 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001029 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001030 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001031 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001032
Colin LeMahieu3d905742015-08-10 19:58:06 +00001033 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +00001034 if (i + 1 == String.size() || String[i + 1] != '{') {
1035 Prev = i;
1036 break;
1037 }
Chris Lattner28ea9b12010-11-02 17:30:52 +00001038
Craig Topperba614322015-12-30 06:00:15 +00001039 size_t EndPos = String.find('}', i);
1040 assert(EndPos != StringRef::npos &&
1041 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001042 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001043 Prev = EndPos + 1;
1044 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001045 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001046 break;
1047 }
Craig Topperbc22e262015-12-31 05:01:45 +00001048
Chris Lattner28ea9b12010-11-02 17:30:52 +00001049 default:
1050 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001051 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001052 }
1053 }
1054 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001055 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001056}
1057
Sander de Smalen5b691a12018-02-04 16:24:17 +00001058bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001059 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001060 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001061 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001062
Chris Lattnerad776812010-11-01 05:06:45 +00001063 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001064 // isCodeGenOnly if they are pseudo instructions.
1065 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001066 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001067 "multiline instruction is not valid for the asmparser, "
1068 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001069
Chris Lattner178f4bb2010-11-01 04:44:29 +00001070 // Remove comments from the asm string. We know that the asmstring only
1071 // has one line.
1072 if (!CommentDelimiter.empty() &&
1073 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001074 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001075 "asmstring for instruction has comment character in it, "
1076 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001077
Chris Lattnerad776812010-11-01 05:06:45 +00001078 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001079 // handle, the target should be refactored to use operands instead of
1080 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001081 //
1082 // Also, check for instructions which reference the operand multiple times;
1083 // this implies a constraint we would not honor.
1084 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001085 for (const AsmOperand &Op : AsmOperands) {
1086 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001087 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001088 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001089 "matchable with operand modifier '" + Tok +
1090 "' not supported by asm matcher. Mark isCodeGenOnly!");
Chris Lattnerad776812010-11-01 05:06:45 +00001091 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001092 // We reject aliases and ignore instructions for now.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001093 if (!IsAlias && Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001094 LLVM_DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001095 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001096 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001097 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001098 });
1099 return false;
1100 }
1101 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001102
Chris Lattner39bc53b2010-11-01 04:34:44 +00001103 return true;
1104}
1105
Chris Lattner60db0a62010-02-09 00:34:28 +00001106static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001107 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001108
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001109 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1110 switch (*it) {
1111 case '*': Res += "_STAR_"; break;
1112 case '%': Res += "_PCT_"; break;
1113 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001114 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001115 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001116 case '<': Res += "_LT_"; break;
1117 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001118 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001119 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001120 if ((*it >= 'A' && *it <= 'Z') ||
1121 (*it >= 'a' && *it <= 'z') ||
1122 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001123 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001124 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001125 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001126 }
1127 }
1128
1129 return Res;
1130}
1131
Chris Lattner60db0a62010-02-09 00:34:28 +00001132ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001133 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001134
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001135 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001136 Classes.emplace_front();
1137 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001138 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001139 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001140 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1141 Entry->ValueName = Token;
1142 Entry->PredicateMethod = "<invalid>";
1143 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001144 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001145 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001146 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001147 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001148 }
1149
1150 return Entry;
1151}
1152
1153ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001154AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1155 int SubOpIdx) {
1156 Record *Rec = OI.Rec;
1157 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001158 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001159 return getOperandClass(Rec, SubOpIdx);
1160}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001161
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001162ClassInfo *
1163AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001164 if (Rec->isSubClassOf("RegisterOperand")) {
1165 // RegisterOperand may have an associated ParserMatchClass. If it does,
1166 // use it, else just fall back to the underlying register class.
1167 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001168 if (!R || !R->getValue())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001169 PrintFatalError("Record `" + Rec->getName() +
1170 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001171
Sean Silvafb509ed2012-10-10 20:24:43 +00001172 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001173 Record *MatchClass = DI->getDef();
1174 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1175 return CI;
1176 }
1177
1178 // No custom match class. Just use the register class.
1179 Record *ClassRec = Rec->getValueAsDef("RegClass");
1180 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001181 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001182 "' has no associated register class!\n");
1183 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1184 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001185 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001186 }
1187
Bob Wilsonb9b24222011-01-26 19:44:55 +00001188 if (Rec->isSubClassOf("RegisterClass")) {
1189 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001190 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001191 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001192 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001193
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001194 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001195 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001196 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001197 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001198 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1199 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001200
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001201 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001202}
1203
Tim Northoverc74e6912013-09-16 16:43:19 +00001204struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001205 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001206 // std::set<T> defines its own compariso "operator<", but it
1207 // performs a lexicographical comparison by T's innate comparison
1208 // for some reason. We don't want non-deterministic pointer
1209 // comparisons so use this instead.
1210 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1211 RHS.begin(), RHS.end(),
1212 LessRecordByID());
1213 }
1214};
1215
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001216void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001217buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001218 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001219 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001220
Tim Northoverc74e6912013-09-16 16:43:19 +00001221 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1222
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001223 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001224 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001225
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001226 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001227 for (const CodeGenRegisterClass &RC : RegClassList)
1228 RegisterSets.insert(
1229 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001230
1231 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001232 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001233 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001234 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001235
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001236 // Introduce derived sets where necessary (when a register does not determine
1237 // a unique register set class), and build the mapping of registers to the set
1238 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001239 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001240 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001241 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001242 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001243
Craig Topper03ec8012014-11-25 20:11:31 +00001244 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001245 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001246 continue;
1247
1248 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001249 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001250 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001251 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001252
Tim Northoverc74e6912013-09-16 16:43:19 +00001253 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001254 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001255 std::insert_iterator<RegisterSet> II(ContainingSet,
1256 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001257 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001258 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001259 }
1260
1261 if (!ContainingSet.empty()) {
1262 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001263 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001264 }
1265 }
1266
1267 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001268 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001269 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001270 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001271 Classes.emplace_front();
1272 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001273 CI->Kind = ClassInfo::RegisterClass0 + Index;
1274 CI->ClassName = "Reg" + utostr(Index);
1275 CI->Name = "MCK_Reg" + utostr(Index);
1276 CI->ValueName = "";
1277 CI->PredicateMethod = ""; // unused
1278 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001279 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001280 // FIXME: diagnostic type.
1281 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001282 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001283 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001284 RegisterSetClasses.insert(std::make_pair(RS, CI));
1285 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001286 }
1287
1288 // Find the superclasses; we could compute only the subgroup lattice edges,
1289 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001290 for (const RegisterSet &RS : RegisterSets) {
1291 ClassInfo *CI = RegisterSetClasses[RS];
1292 for (const RegisterSet &RS2 : RegisterSets)
1293 if (RS != RS2 &&
1294 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001295 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001296 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001297 }
1298
1299 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001300 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001301 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001302 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001303 if (!Def)
1304 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001305 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1306 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001307 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001308 CI->ClassName = RC.getName();
1309 CI->Name = "MCK_" + RC.getName();
1310 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001311 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001312 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001313
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00001314 Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1315 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1316 CI->DiagnosticType = SI->getValue();
1317
1318 Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1319 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1320 CI->DiagnosticString = SI->getValue();
1321
1322 // If we have a diagnostic string but the diagnostic type is not specified
1323 // explicitly, create an anonymous diagnostic type.
1324 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1325 CI->DiagnosticType = RC.getName();
1326
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001327 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001328 }
1329
1330 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001331 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001332 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001333 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001334
1335 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001336 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001337 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001338 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001339
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001340 if (CI->ValueName.empty()) {
1341 CI->ClassName = Rec->getName();
Matthias Braun4a86d452016-12-04 05:48:16 +00001342 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001343 CI->ValueName = Rec->getName();
1344 } else
Matthias Braun4a86d452016-12-04 05:48:16 +00001345 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001346 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001347}
1348
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001349void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001350 std::vector<Record*> AsmOperands =
1351 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001352
1353 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001354 for (Record *Rec : AsmOperands) {
1355 Classes.emplace_front();
1356 AsmOperandClasses[Rec] = &Classes.front();
1357 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001358
Daniel Dunbar17410a42009-08-10 18:41:10 +00001359 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001360 for (Record *Rec : AsmOperands) {
1361 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001362 CI->Kind = ClassInfo::UserClass0 + Index;
1363
Craig Topper03ec8012014-11-25 20:11:31 +00001364 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001365 for (Init *I : Supers->getValues()) {
1366 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001367 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001368 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001369 continue;
1370 }
1371
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001372 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1373 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001374 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001375 else
1376 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001377 }
Craig Topper03ec8012014-11-25 20:11:31 +00001378 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001379 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001380 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001381
1382 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001383 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001384 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001385 CI->PredicateMethod = SI->getValue();
1386 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001387 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001388 CI->PredicateMethod = "is" + CI->ClassName;
1389 }
1390
1391 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001392 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001393 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001394 CI->RenderMethod = SI->getValue();
1395 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001396 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001397 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1398 }
1399
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001400 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001401 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001402 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001403 CI->ParserMethod = SI->getValue();
1404
Oliver Stannard41dfac32017-10-03 14:34:57 +00001405 // Get the diagnostic type and string or leave them as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001406 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001407 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001408 CI->DiagnosticType = SI->getValue();
Oliver Stannard41dfac32017-10-03 14:34:57 +00001409 Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1410 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1411 CI->DiagnosticString = SI->getValue();
1412 // If we have a DiagnosticString, we need a DiagnosticType for use within
1413 // the matcher.
1414 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1415 CI->DiagnosticType = CI->ClassName;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001416
Tom Stellardb9f235e2016-02-05 19:59:33 +00001417 Init *IsOptional = Rec->getValueInit("IsOptional");
1418 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1419 CI->IsOptional = BI->getValue();
1420
Sam Kolton5f10a132016-05-06 11:31:17 +00001421 // Get or construct the default method name.
1422 Init *DMName = Rec->getValueInit("DefaultMethod");
1423 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1424 CI->DefaultMethod = SI->getValue();
1425 } else {
1426 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1427 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1428 }
1429
Craig Topper03ec8012014-11-25 20:11:31 +00001430 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001431 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001432}
1433
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001434AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1435 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001436 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001437 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001438}
1439
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001440/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001441/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001442void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001443
Jim Grosbach925a6d02012-04-18 23:46:25 +00001444 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001445 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001446 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001447 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001448
Craig Topperf34dad92014-11-28 03:53:02 +00001449 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001450 OpClassMask.clear();
1451
1452 // Keep track of all operands of this instructions which belong to the
1453 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001454 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1455 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001456 if (Op.Class->ParserMethod.empty())
1457 continue;
1458 unsigned &OperandMask = OpClassMask[Op.Class];
1459 OperandMask |= (1 << i);
1460 }
1461
1462 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001463 for (const auto &OCM : OpClassMask) {
1464 unsigned OpMask = OCM.second;
1465 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001466 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1467 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001468 }
1469 }
1470}
1471
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001472void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001473 // Build information about all of the AssemblerPredicates.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001474 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1475 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1476 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1477 SubtargetFeaturePairs.end());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001478#ifndef NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001479 for (const auto &Pair : SubtargetFeatures)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001480 LLVM_DEBUG(Pair.second.dump());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001481#endif // NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001482 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001483
Craig Topperfd2c6a32015-12-31 08:18:23 +00001484 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001485 bool ReportMultipleNearMisses =
1486 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00001487
Chris Lattner33fc3e02010-10-31 19:10:56 +00001488 // Parse the instructions; we need to do this first so that we can gather the
1489 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001490 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001491 unsigned VariantCount = Target.getAsmParserVariantCount();
1492 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1493 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperbcd3c372017-05-31 21:12:46 +00001494 StringRef CommentDelimiter =
1495 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001496 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001497 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001498 Variant.TokenizingCharacters =
1499 AsmVariant->getValueAsString("TokenizingCharacters");
1500 Variant.SeparatorCharacters =
1501 AsmVariant->getValueAsString("SeparatorCharacters");
1502 Variant.BreakCharacters =
1503 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001504 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001505 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001506
Craig Topper8cc904d2016-01-17 20:38:18 +00001507 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001508
Devang Patel85d684a2012-01-09 19:13:28 +00001509 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1510 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001511 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001512 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001513
Devang Patel85d684a2012-01-09 19:13:28 +00001514 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001515 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001516 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001517
Sam Kolton1b746d12016-09-08 15:50:52 +00001518 // Ignore instructions for different instructions
Craig Topperbcd3c372017-05-31 21:12:46 +00001519 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001520 if (!V.empty() && V != Variant.Name)
1521 continue;
1522
Craig Topper1c8fbd22015-09-06 03:44:50 +00001523 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001524
Craig Topperfd2c6a32015-12-31 08:18:23 +00001525 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001526
Devang Patel85d684a2012-01-09 19:13:28 +00001527 // Ignore instructions which shouldn't be matched and diagnose invalid
1528 // instruction definitions with an error.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001529 if (!II->validate(CommentDelimiter, false))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001530 continue;
1531
1532 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001533 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001534
Devang Patel85d684a2012-01-09 19:13:28 +00001535 // Parse all of the InstAlias definitions and stick them in the list of
1536 // matchables.
1537 std::vector<Record*> AllInstAliases =
1538 Records.getAllDerivedDefinitions("InstAlias");
1539 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001540 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001541 Variant.AsmVariantNo,
1542 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001543
Devang Patel85d684a2012-01-09 19:13:28 +00001544 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1545 // filter the set of instruction aliases we consider, based on the target
1546 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001547 if (!StringRef(Alias->ResultInst->TheDef->getName())
1548 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001549 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001550
Craig Topperbcd3c372017-05-31 21:12:46 +00001551 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001552 if (!V.empty() && V != Variant.Name)
1553 continue;
1554
Craig Topper1c8fbd22015-09-06 03:44:50 +00001555 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001556
Craig Topperfd2c6a32015-12-31 08:18:23 +00001557 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001558
Devang Patel85d684a2012-01-09 19:13:28 +00001559 // Validate the alias definitions.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001560 II->validate(CommentDelimiter, true);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001561
1562 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001563 }
Chris Lattner488c2012010-11-01 04:05:41 +00001564 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001565
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001566 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001567 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001568
1569 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001570 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001571
Chris Lattner4779e3e92010-11-04 00:57:06 +00001572 // Build the information about matchables, now that we have fully formed
1573 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001574 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001575 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001576 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001577 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001578 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001579 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1580 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001581 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001582
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001583 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001584 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001585 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001586 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1587 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001588 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001589 }
1590
Daniel Dunbare10787e2009-08-07 08:26:05 +00001591 // Check for simple tokens.
1592 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001593 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001594 continue;
1595 }
1596
Chris Lattnerd6746d52010-11-06 22:06:03 +00001597 if (Token.size() > 1 && isdigit(Token[1])) {
1598 Op.Class = getTokenClass(Token);
1599 continue;
1600 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001601
Chris Lattner4efe13d2010-11-04 02:11:18 +00001602 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001603 StringRef OperandName;
1604 if (Token[1] == '{')
1605 OperandName = Token.substr(2, Token.size() - 3);
1606 else
1607 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001608
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001609 if (II->DefRec.is<const CodeGenInstruction*>())
1610 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001611 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001612 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001613 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001614
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001615 if (II->DefRec.is<const CodeGenInstruction*>()) {
1616 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001617 // If the instruction has a two-operand alias, build up the
1618 // matchable here. We'll add them in bulk at the end to avoid
1619 // confusing this loop.
Craig Topperbcd3c372017-05-31 21:12:46 +00001620 StringRef Constraint =
1621 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001622 if (Constraint != "") {
1623 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001624 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001625
1626 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001627 AliasII->formTwoOperandAlias(Constraint);
1628
1629 // Add the alias to the matchables list.
1630 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001631 }
1632 } else
Sander de Smalen5b691a12018-02-04 16:24:17 +00001633 // FIXME: The tied operands checking is not yet integrated with the
1634 // framework for reporting multiple near misses. To prevent invalid
1635 // formats from being matched with an alias if a tied-operands check
1636 // would otherwise have disallowed it, we just disallow such constructs
1637 // in TableGen completely.
1638 II->buildAliasResultOperands(!ReportMultipleNearMisses);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001639 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001640 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001641 Matchables.insert(Matchables.end(),
1642 std::make_move_iterator(NewMatchables.begin()),
1643 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001644
Jim Grosbachba395922011-12-06 23:43:54 +00001645 // Process token alias definitions and set up the associated superclass
1646 // information.
1647 std::vector<Record*> AllTokenAliases =
1648 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001649 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001650 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1651 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001652 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001653 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001654 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001655 FromClass->SuperClasses.push_back(ToClass);
1656 }
1657
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001658 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001659 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001660
Matthias Brauna8eed312016-12-05 19:44:31 +00001661#ifdef EXPENSIVE_CHECKS
1662 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard7772f022016-01-25 10:20:19 +00001663 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1664 for (auto J = I; J != E; ++J) {
1665 assert(!(*J < *I));
1666 assert(I == J || !J->isSubsetOf(*I));
1667 }
1668 }
Matthias Brauna8eed312016-12-05 19:44:31 +00001669#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +00001670}
1671
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001672/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001673/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1674void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001675buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001676 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001677 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001678 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1679 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001680 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001681
Chris Lattnerfecdad62010-11-06 07:14:44 +00001682 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001683 unsigned Idx;
1684 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001685 PrintFatalError(II->TheDef->getLoc(),
1686 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001687
Bob Wilsonb9b24222011-01-26 19:44:55 +00001688 // If the instruction operand has multiple suboperands, but the parser
1689 // match class for the asm operand is still the default "ImmAsmOperand",
1690 // then handle each suboperand separately.
1691 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1692 Record *Rec = Operands[Idx].Rec;
1693 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1694 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1695 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1696 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1697 StringRef Token = Op->Token; // save this in case Op gets moved
1698 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001699 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001700 NewAsmOp.SubOpIdx = SI;
1701 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1702 }
1703 // Replace Op with first suboperand.
1704 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1705 Op->SubOpIdx = 0;
1706 }
1707 }
1708
Chris Lattner897a1402010-11-04 01:55:23 +00001709 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001710 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Sander de Smalen5b691a12018-02-04 16:24:17 +00001711 Op->OrigSrcOpName = OperandName;
Chris Lattner897a1402010-11-04 01:55:23 +00001712
1713 // If the named operand is tied, canonicalize it to the untied operand.
1714 // For example, something like:
1715 // (outs GPR:$dst), (ins GPR:$src)
1716 // with an asmstring of
1717 // "inc $src"
1718 // we want to canonicalize to:
1719 // "inc $dst"
1720 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001721 int OITied = -1;
1722 if (Operands[Idx].MINumOperands == 1)
1723 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001724 if (OITied != -1) {
1725 // The tied operand index is an MIOperand index, find the operand that
1726 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001727 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1728 OperandName = Operands[Idx.first].Name;
1729 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001730 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001731
Bob Wilsonb9b24222011-01-26 19:44:55 +00001732 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001733}
1734
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001735/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001736/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1737/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001738void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001739 StringRef OperandName,
1740 MatchableInfo::AsmOperand &Op) {
1741 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001742
Chris Lattner4efe13d2010-11-04 02:11:18 +00001743 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001744 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001745 if (CGA.ResultOperands[i].isRecord() &&
1746 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001747 // It's safe to go with the first one we find, because CodeGenInstAlias
1748 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001749 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001750 // Use the match class from the Alias definition, not the
1751 // destination instruction, as we may have an immediate that's
1752 // being munged by the match class.
1753 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001754 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001755 Op.SrcOpName = OperandName;
Sander de Smalen5b691a12018-02-04 16:24:17 +00001756 Op.OrigSrcOpName = OperandName;
Chris Lattnerb625dd22010-11-06 07:06:09 +00001757 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001758 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001759
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001760 PrintFatalError(II->TheDef->getLoc(),
1761 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001762}
1763
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001764void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001765 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001766
Chris Lattnerfecdad62010-11-06 07:14:44 +00001767 // Loop over all operands of the result instruction, determining how to
1768 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001769 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001770 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001771 int TiedOp = -1;
1772 if (OpInfo.MINumOperands == 1)
1773 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001774 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001775 int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1776 if (TiedSrcOperand != -1 &&
1777 ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1778 ResOperands.push_back(ResOperand::getTiedOp(
1779 TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1780 else
1781 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
Chris Lattner7108dad2010-11-04 01:42:59 +00001782 continue;
1783 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001784
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001785 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001786 if (OpInfo.Name.empty() || SrcOperand == -1) {
1787 // This may happen for operands that are tied to a suboperand of a
1788 // complex operand. Simply use a dummy value here; nobody should
1789 // use this operand slot.
1790 // FIXME: The long term goal is for the MCOperand list to not contain
1791 // tied operands at all.
1792 ResOperands.push_back(ResOperand::getImmOp(0));
1793 continue;
1794 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001795
Bob Wilsonb9b24222011-01-26 19:44:55 +00001796 // Check if the one AsmOperand populates the entire operand.
1797 unsigned NumOperands = OpInfo.MINumOperands;
1798 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1799 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001800 continue;
1801 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001802
1803 // Add a separate ResOperand for each suboperand.
1804 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1805 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1806 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1807 "unexpected AsmOperands for suboperands");
1808 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1809 }
Chris Lattner743081d2010-11-04 00:43:46 +00001810 }
1811}
1812
Sander de Smalen5b691a12018-02-04 16:24:17 +00001813void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
Chris Lattner8188fb22010-11-06 07:31:43 +00001814 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1815 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001816
Sander de Smalen5b691a12018-02-04 16:24:17 +00001817 // Map of: $reg -> #lastref
1818 // where $reg is the name of the operand in the asm string
1819 // where #lastref is the last processed index where $reg was referenced in
1820 // the asm string.
1821 SmallDenseMap<StringRef, int> OperandRefs;
1822
Chris Lattner8188fb22010-11-06 07:31:43 +00001823 // Loop over all operands of the result instruction, determining how to
1824 // populate them.
1825 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001826 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001827 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001828 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001829
Chris Lattner8188fb22010-11-06 07:31:43 +00001830 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001831 int TiedOp = -1;
1832 if (OpInfo->MINumOperands == 1)
1833 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001834 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001835 unsigned SrcOp1 = 0;
1836 unsigned SrcOp2 = 0;
1837
1838 // If an operand has been specified twice in the asm string,
1839 // add the two source operand's indices to the TiedOp so that
1840 // at runtime the 'tied' constraint is checked.
1841 if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1842 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1843
1844 // Find the next operand (similarly named operand) in the string.
1845 StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1846 auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1847 SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1848
1849 // Not updating the record in OperandRefs will cause TableGen
1850 // to fail with an error at the end of this function.
1851 if (AliasConstraintsAreChecked)
1852 Insert.first->second = SrcOp2;
1853
1854 // In case it only has one reference in the asm string,
1855 // it doesn't need to be checked for tied constraints.
1856 SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1857 }
1858
1859 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
Chris Lattner4869d342010-11-06 19:57:21 +00001860 continue;
1861 }
1862
Bob Wilsonb9b24222011-01-26 19:44:55 +00001863 // Handle all the suboperands for this operand.
1864 const std::string &OpName = OpInfo->Name;
1865 for ( ; AliasOpNo < LastOpNo &&
1866 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1867 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1868
1869 // Find out what operand from the asmparser that this MCInst operand
1870 // comes from.
1871 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001872 case CodeGenInstAlias::ResultOperand::K_Record: {
1873 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001874 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001875 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001876 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001877 TheDef->getName() + "' has operand '" + OpName +
1878 "' that doesn't appear in asm string!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001879
1880 // Add it to the operand references. If it is added a second time, the
1881 // record won't be updated and it will fail later on.
1882 OperandRefs.try_emplace(Name, SrcOperand);
1883
Bob Wilsonb9b24222011-01-26 19:44:55 +00001884 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1885 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1886 NumOperands));
1887 break;
1888 }
1889 case CodeGenInstAlias::ResultOperand::K_Imm: {
1890 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1891 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1892 break;
1893 }
1894 case CodeGenInstAlias::ResultOperand::K_Reg: {
1895 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1896 ResOperands.push_back(ResOperand::getRegOp(Reg));
1897 break;
1898 }
1899 }
Chris Lattner4869d342010-11-06 19:57:21 +00001900 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001901 }
Sander de Smalen5b691a12018-02-04 16:24:17 +00001902
1903 // Check that operands are not repeated more times than is supported.
1904 for (auto &T : OperandRefs) {
1905 if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1906 PrintFatalError(TheDef->getLoc(),
1907 "Operand '" + T.first + "' can never be matched");
1908 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001909}
Chris Lattner743081d2010-11-04 00:43:46 +00001910
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001911static unsigned
1912getConverterOperandID(const std::string &Name,
1913 SmallSetVector<CachedHashString, 16> &Table,
1914 bool &IsNew) {
1915 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001916
David Majnemer0d955d02016-08-11 22:21:41 +00001917 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001918
1919 assert(ID < Table.size());
1920
1921 return ID;
1922}
1923
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001924static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001925 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Kolton5f10a132016-05-06 11:31:17 +00001926 bool HasMnemonicFirst, bool HasOptionalOperands,
1927 raw_ostream &OS) {
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001928 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1929 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001930 std::vector<std::vector<uint8_t> > ConversionTable;
1931 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001932
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001933 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun4a86d452016-12-04 05:48:16 +00001934 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001935
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001936 // Write the convert function to a separate stream, so we can drop it after
1937 // the enum. We'll build up the conversion handlers for the individual
1938 // operand types opportunistically as we encounter them.
1939 std::string ConvertFnBody;
1940 raw_string_ostream CvtOS(ConvertFnBody);
1941 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001942 if (HasOptionalOperands) {
1943 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1944 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1945 << "unsigned Opcode,\n"
1946 << " const OperandVector &Operands,\n"
1947 << " const SmallBitVector &OptionalOperandsMask) {\n";
1948 } else {
1949 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1950 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1951 << "unsigned Opcode,\n"
1952 << " const OperandVector &Operands) {\n";
1953 }
1954 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1955 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1956 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001957 size_t MaxNumOperands = 0;
1958 for (const auto &MI : Infos) {
1959 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1960 }
1961 CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1962 << "] = { 0 };\n";
1963 CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1964 << ");\n";
1965 CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1966 << "; ++i) {\n";
1967 CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
1968 CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1969 CvtOS << " }\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001970 }
1971 CvtOS << " unsigned OpIdx;\n";
1972 CvtOS << " Inst.setOpcode(Opcode);\n";
1973 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1974 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001975 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001976 } else {
1977 CvtOS << " OpIdx = *(p + 1);\n";
1978 }
1979 CvtOS << " switch (*p) {\n";
1980 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1981 CvtOS << " case CVT_Reg:\n";
1982 CvtOS << " static_cast<" << TargetOperandClass
1983 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1984 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001985 CvtOS << " case CVT_Tied: {\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00001986 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1987 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001988 CvtOS << " \"Tied operand not found\");\n";
1989 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
1990 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001991 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001992 CvtOS << " }\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001993
Chad Rosier738ea252012-08-30 17:59:25 +00001994 std::string OperandFnBody;
1995 raw_string_ostream OpOS(OperandFnBody);
1996 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001997 OpOS << "void " << Target.getName() << ClassName << "::\n"
1998 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00001999 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00002000 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002001 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002002 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00002003 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2004 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002005 << " switch (*p) {\n"
2006 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2007 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002008 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00002009 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002010 << " ++NumMCOperands;\n"
2011 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002012 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002013 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002014 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002015
2016 // Pre-populate the operand conversion kinds with the standard always
2017 // available entries.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002018 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2019 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2020 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002021 enum { CVT_Done, CVT_Reg, CVT_Tied };
2022
Sander de Smalen5b691a12018-02-04 16:24:17 +00002023 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2024 std::map<std::tuple<unsigned, unsigned, unsigned>, std::string>
2025 TiedOperandsEnumMap;
2026
Craig Topperf34dad92014-11-28 03:53:02 +00002027 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002028 // Check if we have a custom match function.
Craig Topperbcd3c372017-05-31 21:12:46 +00002029 StringRef AsmMatchConverter =
2030 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00002031 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Craig Topperbcd3c372017-05-31 21:12:46 +00002032 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002033 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002034
2035 // Check if we have already generated this signature.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002036 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002037 continue;
2038
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002039 // Remember this converter for the kind enum.
2040 unsigned KindID = OperandConversionKinds.size();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002041 OperandConversionKinds.insert(
2042 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002043
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002044 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002045 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002046 ConversionTable.back().push_back(KindID);
2047 ConversionTable.back().push_back(CVT_Done);
2048
2049 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00002050 CvtOS << " case CVT_"
2051 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00002052 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002053 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002054
Chad Rosier738ea252012-08-30 17:59:25 +00002055 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002056 continue;
2057 }
2058
Daniel Dunbare10787e2009-08-07 08:26:05 +00002059 // Build the conversion function signature.
2060 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002061
2062 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002063
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00002064 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002065 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002066
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002067 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2068 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002069
Chris Lattner743081d2010-11-04 00:43:46 +00002070 // Generate code to populate each result operand.
2071 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00002072 case MatchableInfo::ResOperand::RenderAsmOperand: {
2073 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00002074 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002075 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002076
Chris Lattnere032dbf2010-11-02 22:55:03 +00002077 // Registers are always converted the same, don't duplicate the
2078 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00002079 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002080 std::string Class;
2081 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2082 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00002083 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00002084 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002085
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002086 // Add the conversion kind, if necessary, and get the associated ID
2087 // the index of its entry in the vector).
2088 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
2089 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00002090 if (Op.Class->IsOptional) {
2091 // For optional operands we must also care about DefaultMethod
2092 assert(HasOptionalOperands);
2093 Name += "_" + Op.Class->DefaultMethod;
2094 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00002095 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002096
2097 bool IsNewConverter = false;
2098 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2099 IsNewConverter);
2100
2101 // Add the operand entry to the instruction kind conversion row.
2102 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00002103 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002104
2105 if (!IsNewConverter)
2106 break;
2107
2108 // This is a new operand kind. Add a handler for it to the
2109 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00002110 CvtOS << " case " << Name << ":\n";
2111 if (Op.Class->IsOptional) {
2112 // If optional operand is not present in actual instruction then we
2113 // should call its DefaultMethod before RenderMethod
2114 assert(HasOptionalOperands);
2115 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2116 << " " << Op.Class->DefaultMethod << "()"
2117 << "->" << Op.Class->RenderMethod << "(Inst, "
2118 << OpInfo.MINumOperands << ");\n"
Sam Kolton5f10a132016-05-06 11:31:17 +00002119 << " } else {\n"
2120 << " static_cast<" << TargetOperandClass
2121 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2122 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2123 << " }\n";
2124 } else {
2125 CvtOS << " static_cast<" << TargetOperandClass
2126 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2127 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2128 }
2129 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002130
2131 // Add a handler for the operand number lookup.
2132 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002133 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2134
2135 if (Op.Class->isRegisterClass())
2136 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2137 else
2138 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2139 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002140 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002141 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002142 }
Chris Lattner743081d2010-11-04 00:43:46 +00002143 case MatchableInfo::ResOperand::TiedOperand: {
2144 // If this operand is tied to a previous one, just copy the MCInst
2145 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002146 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002147 unsigned TiedOp = OpInfo.TiedOperands.ResOpnd;
2148 unsigned SrcOp1 = OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2149 unsigned SrcOp2 = OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002150 assert(i > TiedOp && "Tied operand precedes its target!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002151 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2152 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2153 Signature += "__" + TiedTupleName;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002154 ConversionRow.push_back(CVT_Tied);
2155 ConversionRow.push_back(TiedOp);
Sander de Smalen5b691a12018-02-04 16:24:17 +00002156 ConversionRow.push_back(SrcOp1);
2157 ConversionRow.push_back(SrcOp2);
2158
2159 // Also create an 'enum' for this combination of tied operands.
2160 auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
2161 TiedOperandsEnumMap.emplace(Key, TiedTupleName);
Chris Lattner743081d2010-11-04 00:43:46 +00002162 break;
2163 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002164 case MatchableInfo::ResOperand::ImmOperand: {
2165 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002166 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002167 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002168 Signature += "__" + Ty;
2169
2170 std::string Name = "CVT_" + Ty;
2171 bool IsNewConverter = false;
2172 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2173 IsNewConverter);
2174 // Add the operand entry to the instruction kind conversion row.
2175 ConversionRow.push_back(ID);
2176 ConversionRow.push_back(0);
2177
2178 if (!IsNewConverter)
2179 break;
2180
2181 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002182 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002183 << " break;\n";
2184
Chad Rosier738ea252012-08-30 17:59:25 +00002185 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002186 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2187 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002188 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002189 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002190 break;
2191 }
Chris Lattner4869d342010-11-06 19:57:21 +00002192 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002193 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002194 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002195 Name = "reg0";
2196 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002197 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002198 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun4a86d452016-12-04 05:48:16 +00002199 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilson03912ab2011-01-14 22:58:09 +00002200 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002201 Signature += "__" + Name;
2202 Name = "CVT_" + Name;
2203 bool IsNewConverter = false;
2204 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2205 IsNewConverter);
2206 // Add the operand entry to the instruction kind conversion row.
2207 ConversionRow.push_back(ID);
2208 ConversionRow.push_back(0);
2209
2210 if (!IsNewConverter)
2211 break;
2212 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002213 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002214 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002215
2216 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002217 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2218 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002219 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002220 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002221 }
Chris Lattner743081d2010-11-04 00:43:46 +00002222 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002223 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002224
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002225 // If there were no operands, add to the signature to that effect
2226 if (Signature == "Convert")
2227 Signature += "_NoOperands";
2228
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002229 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002230
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002231 // Save the signature. If we already have it, don't add a new row
2232 // to the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002233 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002234 continue;
2235
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002236 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002237 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002238 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002239
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002240 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002241 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002242
Chad Rosier738ea252012-08-30 17:59:25 +00002243 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002244 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002245
Sander de Smalen5b691a12018-02-04 16:24:17 +00002246 // Output a static table for tied operands.
2247 if (TiedOperandsEnumMap.size()) {
2248 // The number of tied operand combinations will be small in practice,
2249 // but just add the assert to be sure.
2250 assert(TiedOperandsEnumMap.size() <= 255 &&
2251 "Too many tied-operand combinations to reference with "
2252 "an 8bit offset from the conversion table");
2253
2254 OS << "enum {\n";
2255 for (auto &KV : TiedOperandsEnumMap) {
2256 OS << " " << KV.second << ",\n";
2257 }
2258 OS << "};\n\n";
2259
2260 OS << "const char TiedAsmOperandTable[][3] = {\n";
2261 for (auto &KV : TiedOperandsEnumMap) {
2262 OS << " /* " << KV.second << " */ { " << std::get<0>(KV.first) << ", "
2263 << std::get<1>(KV.first) << ", " << std::get<2>(KV.first) << " },\n";
2264 }
2265 OS << "};\n\n";
2266 } else
2267 OS << "const char TiedAsmOperandTable[][3] = { /* empty */ {0, 0, 0} "
2268 "};\n\n";
2269
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002270 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002271
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002272 // Output the operand conversion kind enum.
2273 OS << "enum OperatorConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002274 for (const auto &Converter : OperandConversionKinds)
Craig Topper6e526f12016-01-03 07:33:30 +00002275 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002276 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002277 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002278
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002279 // Output the instruction conversion kind enum.
2280 OS << "enum InstructionConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002281 for (const auto &Signature : InstructionConversionKinds)
Craig Topper802d3d32015-08-16 21:27:10 +00002282 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002283 OS << " CVT_NUM_SIGNATURES\n";
2284 OS << "};\n\n";
2285
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002286 OS << "} // end anonymous namespace\n\n";
2287
2288 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002289 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002290 << MaxRowLength << "] = {\n";
2291
2292 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2293 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2294 OS << " // " << InstructionConversionKinds[Row] << "\n";
2295 OS << " { ";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002296 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2297 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2298 if (OperandConversionKinds[ConversionTable[Row][i]] !=
2299 CachedHashString("CVT_Tied")) {
2300 OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2301 continue;
2302 }
2303
2304 // For a tied operand, emit a reference to the TiedAsmOperandTable
2305 // that contains the operand to copy, and the parsed operands to
2306 // check for their tied constraints.
2307 auto Key = std::make_tuple((unsigned)ConversionTable[Row][i + 1],
2308 (unsigned)ConversionTable[Row][i + 2],
2309 (unsigned)ConversionTable[Row][i + 3]);
2310 auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2311 assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2312 "No record for tied operand pair");
2313 OS << TiedOpndEnum->second << ", ";
2314 i += 2;
2315 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002316 OS << "CVT_Done },\n";
2317 }
2318
2319 OS << "};\n\n";
2320
2321 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002322 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002323
Chad Rosier738ea252012-08-30 17:59:25 +00002324 // Spit out the operand number lookup function.
2325 OS << OpOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002326}
2327
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002328/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2329static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002330 std::forward_list<ClassInfo> &Infos,
2331 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002332 OS << "namespace {\n\n";
2333
2334 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2335 << "/// instruction matching.\n";
2336 OS << "enum MatchClassKind {\n";
2337 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002338 OS << " OptionalMatchClass = 1,\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002339 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2340 StringRef LastName = "OptionalMatchClass";
Craig Topperf34dad92014-11-28 03:53:02 +00002341 for (const auto &CI : Infos) {
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002342 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2343 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2344 } else if (LastKind < ClassInfo::UserClass0 &&
2345 CI.Kind >= ClassInfo::UserClass0) {
2346 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2347 }
2348 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2349 LastName = CI.Name;
2350
David Blaikied749e342014-11-28 20:35:57 +00002351 OS << " " << CI.Name << ", // ";
2352 if (CI.Kind == ClassInfo::Token) {
2353 OS << "'" << CI.ValueName << "'\n";
2354 } else if (CI.isRegisterClass()) {
2355 if (!CI.ValueName.empty())
2356 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002357 else
2358 OS << "derived register class\n";
2359 } else {
David Blaikied749e342014-11-28 20:35:57 +00002360 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002361 }
2362 }
2363 OS << " NumMatchClassKinds\n";
2364 OS << "};\n\n";
2365
2366 OS << "}\n\n";
2367}
2368
Oliver Stannard41dfac32017-10-03 14:34:57 +00002369/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2370/// used when an assembly operand does not match the expected operand class.
2371static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2372 // If the target does not use DiagnosticString for any operands, don't emit
2373 // an unused function.
2374 if (std::all_of(
2375 Info.Classes.begin(), Info.Classes.end(),
2376 [](const ClassInfo &CI) { return CI.DiagnosticString.empty(); }))
2377 return;
2378
2379 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2380 << "AsmParser::" << Info.Target.getName()
2381 << "MatchResultTy MatchResult) {\n";
2382 OS << " switch (MatchResult) {\n";
2383
2384 for (const auto &CI: Info.Classes) {
2385 if (!CI.DiagnosticString.empty()) {
2386 assert(!CI.DiagnosticType.empty() &&
2387 "DiagnosticString set without DiagnosticType");
2388 OS << " case " << Info.Target.getName()
2389 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2390 OS << " return \"" << CI.DiagnosticString << "\";\n";
2391 }
2392 }
2393
2394 OS << " default:\n";
2395 OS << " return nullptr;\n";
2396
2397 OS << " }\n";
2398 OS << "}\n\n";
2399}
2400
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002401static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2402 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2403 "RegisterClass) {\n";
Oliver Stannarddab52122017-10-12 09:28:23 +00002404 if (std::none_of(Info.Classes.begin(), Info.Classes.end(),
2405 [](const ClassInfo &CI) {
2406 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2407 })) {
2408 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2409 } else {
2410 OS << " switch (RegisterClass) {\n";
2411 for (const auto &CI: Info.Classes) {
2412 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2413 OS << " case " << CI.Name << ":\n";
2414 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2415 << CI.DiagnosticType << ";\n";
2416 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002417 }
Oliver Stannarddab52122017-10-12 09:28:23 +00002418
2419 OS << " default:\n";
2420 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2421
2422 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002423 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002424 OS << "}\n\n";
2425}
2426
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002427/// emitValidateOperandClass - Emit the function to validate an operand class.
2428static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002429 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002430 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002431 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002432 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2433 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002434
Kevin Enderby1b87c802011-07-15 18:30:43 +00002435 // The InvalidMatchClass is not to match any operand.
2436 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002437 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002438
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002439 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002440 // FIXME: Use a more specific diagnostic type.
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002441 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002442 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2443 << " MCTargetAsmParser::Match_Success :\n"
2444 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002445
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002446 // Check the user classes. We don't care what order since we're only
2447 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002448 OS << " switch (Kind) {\n"
2449 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002450 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002451 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002452 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002453
David Blaikied749e342014-11-28 20:35:57 +00002454 OS << " // '" << CI.ClassName << "' class\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002455 OS << " case " << CI.Name << ": {\n";
2456 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2457 << "());\n";
2458 OS << " if (DP.isMatch())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002459 OS << " return MCTargetAsmParser::Match_Success;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002460 if (!CI.DiagnosticType.empty()) {
2461 OS << " if (DP.isNearMatch())\n";
2462 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002463 << CI.DiagnosticType << ";\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002464 OS << " break;\n";
2465 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002466 else
2467 OS << " break;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002468 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002469 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002470 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002471
Owen Anderson8a503f22012-07-16 23:20:09 +00002472 // Check for register operands, including sub-classes.
2473 OS << " if (Operand.isReg()) {\n";
2474 OS << " MatchClassKind OpKind;\n";
2475 OS << " switch (Operand.getReg()) {\n";
2476 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002477 for (const auto &RC : Info.RegisterClasses)
Craig Topper2b347eb2017-07-07 05:19:25 +00002478 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002479 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002480 << "; break;\n";
2481 OS << " }\n";
2482 OS << " return isSubclass(OpKind, Kind) ? "
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002483 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2484 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2485
2486 // Expected operand is a register, but actual is not.
2487 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2488 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
Owen Anderson8a503f22012-07-16 23:20:09 +00002489
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002490 // Generic fallthrough match failure case for operands that don't have
2491 // specialized diagnostic types.
2492 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002493 OS << "}\n\n";
2494}
2495
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002496/// emitIsSubclass - Emit the subclass predicate function.
2497static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002498 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002499 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002500 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002501 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002502 OS << " if (A == B)\n";
2503 OS << " return true;\n\n";
2504
Craig Topper39311c72015-12-30 06:00:22 +00002505 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002506 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002507 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002508 if (A.IsOptional)
2509 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002510 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002511 if (&A != &B && A.isSubsetOf(B))
2512 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002513 }
Jim Grosbachba395922011-12-06 23:43:54 +00002514
2515 if (SuperClasses.empty())
2516 continue;
2517
Craig Topper39311c72015-12-30 06:00:22 +00002518 // If this is the first SuperClass, emit the switch header.
2519 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002520 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002521 OS << " default:\n";
2522 OS << " return false;\n";
2523 EmittedSwitch = true;
2524 }
2525
2526 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002527
2528 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002529 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002530 continue;
2531 }
2532
Aaron Ballmane59e3582013-07-15 16:53:32 +00002533 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002534 OS << " switch (B) {\n";
2535 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002536 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002537 OS << " case " << SC << ": return true;\n";
2538 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002539 } else {
2540 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002541 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002542 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002543 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002544
Craig Topper39311c72015-12-30 06:00:22 +00002545 // If there were case statements emitted into the string stream write the
2546 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002547 if (EmittedSwitch)
2548 OS << " }\n";
2549 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002550 OS << " return false;\n";
2551
Daniel Dunbar2587b612009-08-10 16:05:47 +00002552 OS << "}\n\n";
2553}
2554
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002555/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002556/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002557static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002558 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002559 raw_ostream &OS) {
2560 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002561 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002562 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002563 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002564 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002565 }
2566
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002567 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002568
Chris Lattnerca5a3552010-09-06 02:01:51 +00002569 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002570
2571 OS << " return InvalidMatchClass;\n";
2572 OS << "}\n\n";
2573}
Chris Lattner00e2e742009-08-08 20:02:57 +00002574
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002575/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002576/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002577static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002578 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002579 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002580 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002581 const auto &Regs = Target.getRegBank().getRegisters();
2582 for (const CodeGenRegister &Reg : Regs) {
2583 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002584 continue;
2585
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002586 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2587 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002588 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002589
Chris Lattner60db0a62010-02-09 00:34:28 +00002590 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002591
Alex Bradburyd590c8572017-12-07 09:51:55 +00002592 bool IgnoreDuplicates =
2593 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2594 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002595
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002596 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002597 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002598}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002599
Dylan McKaybff960a2016-02-03 10:30:16 +00002600/// Emit the function to match a string to the target
2601/// specific register enum.
2602static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2603 raw_ostream &OS) {
2604 // Construct the match list.
2605 std::vector<StringMatcher::StringPair> Matches;
2606 const auto &Regs = Target.getRegBank().getRegisters();
2607 for (const CodeGenRegister &Reg : Regs) {
2608
2609 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2610
2611 for (auto AltName : AltNames) {
2612 AltName = StringRef(AltName).trim();
2613
2614 // don't handle empty alternative names
2615 if (AltName.empty())
2616 continue;
2617
2618 Matches.emplace_back(AltName,
2619 "return " + utostr(Reg.EnumValue) + ";");
2620 }
2621 }
2622
2623 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2624
Alex Bradburyd590c8572017-12-07 09:51:55 +00002625 bool IgnoreDuplicates =
2626 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2627 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Dylan McKaybff960a2016-02-03 10:30:16 +00002628
2629 OS << " return 0;\n";
2630 OS << "}\n\n";
2631}
2632
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002633/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2634static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2635 // Get the set of diagnostic types from all of the operand classes.
2636 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002637 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2638 if (!OpClassEntry.second->DiagnosticType.empty())
2639 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002640 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002641 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2642 if (!OpClassEntry.second->DiagnosticType.empty())
2643 Types.insert(OpClassEntry.second->DiagnosticType);
2644 }
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002645
2646 if (Types.empty()) return;
2647
2648 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002649 for (StringRef Type : Types)
2650 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002651 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2652}
2653
Jim Grosbach5117ef72012-04-24 22:40:08 +00002654/// emitGetSubtargetFeatureName - Emit the helper function to get the
2655/// user-level name for a subtarget feature.
2656static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2657 OS << "// User-level names for subtarget features that participate in\n"
2658 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002659 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002660 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002661 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002662 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002663 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002664 // FIXME: Totally just a placeholder name to get the algorithm working.
2665 OS << " case " << SFI.getEnumName() << ": return \""
2666 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2667 }
2668 OS << " default: return \"(unknown)\";\n";
2669 OS << " }\n";
2670 } else {
2671 // Nothing to emit, so skip the switch
2672 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002673 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002674 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002675}
2676
Chris Lattner43690072010-10-30 20:15:02 +00002677static std::string GetAliasRequiredFeatures(Record *R,
2678 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002679 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002680 std::string Result;
2681 unsigned NumFeatures = 0;
2682 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002683 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002684
Craig Topper24064772014-04-15 07:20:03 +00002685 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002686 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002687 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002688
Chris Lattner517dc952010-11-01 02:09:21 +00002689 if (NumFeatures)
2690 Result += '|';
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002691
Chris Lattner517dc952010-11-01 02:09:21 +00002692 Result += F->getEnumName();
2693 ++NumFeatures;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002694 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002695
Chris Lattner2cb092d2010-10-30 19:23:13 +00002696 if (NumFeatures > 1)
2697 Result = '(' + Result + ')';
2698 return Result;
2699}
2700
Chad Rosier9f7a2212013-04-18 22:35:36 +00002701static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2702 std::vector<Record*> &Aliases,
2703 unsigned Indent = 0,
2704 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002705 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2706 // iteration order of the map is stable.
2707 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002708
Craig Topper6e526f12016-01-03 07:33:30 +00002709 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002710 // FIXME: Allow AssemblerVariantName to be a comma separated list.
Craig Topperbcd3c372017-05-31 21:12:46 +00002711 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002712 if (AsmVariantName != AsmParserVariantName)
2713 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002714 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002715 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002716 if (AliasesFromMnemonic.empty())
2717 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002718
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002719 // Process each alias a "from" mnemonic at a time, building the code executed
2720 // by the string remapper.
2721 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002722 for (const auto &AliasEntry : AliasesFromMnemonic) {
2723 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002724
2725 // Loop through each alias and emit code that handles each case. If there
2726 // are two instructions without predicates, emit an error. If there is one,
2727 // emit it last.
2728 std::string MatchCode;
2729 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002730
Chris Lattner2cb092d2010-10-30 19:23:13 +00002731 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2732 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002733 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002734
Chris Lattner2cb092d2010-10-30 19:23:13 +00002735 // If this unconditionally matches, remember it for later and diagnose
2736 // duplicates.
2737 if (FeatureMask.empty()) {
2738 if (AliasWithNoPredicate != -1) {
2739 // We can't have two aliases from the same mnemonic with no predicate.
2740 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2741 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002742 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002743 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002744
Chris Lattner2cb092d2010-10-30 19:23:13 +00002745 AliasWithNoPredicate = i;
2746 continue;
2747 }
Craig Topper6e526f12016-01-03 07:33:30 +00002748 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002749 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002750
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002751 if (!MatchCode.empty())
2752 MatchCode += "else ";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002753 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Craig Topper2b8419a2017-05-31 19:01:11 +00002754 MatchCode += " Mnemonic = \"";
2755 MatchCode += R->getValueAsString("ToMnemonic");
2756 MatchCode += "\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002757 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002758
Chris Lattner2cb092d2010-10-30 19:23:13 +00002759 if (AliasWithNoPredicate != -1) {
2760 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002761 if (!MatchCode.empty())
2762 MatchCode += "else\n ";
Craig Topper2b8419a2017-05-31 19:01:11 +00002763 MatchCode += "Mnemonic = \"";
2764 MatchCode += R->getValueAsString("ToMnemonic");
2765 MatchCode += "\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002766 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002767
Chris Lattner2cb092d2010-10-30 19:23:13 +00002768 MatchCode += "return;";
2769
Craig Topper6e526f12016-01-03 07:33:30 +00002770 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002771 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002772 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2773}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002774
Chad Rosier9f7a2212013-04-18 22:35:36 +00002775/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2776/// emit a function for them and return true, otherwise return false.
2777static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2778 CodeGenTarget &Target) {
2779 // Ignore aliases when match-prefix is set.
2780 if (!MatchPrefix.empty())
2781 return false;
2782
2783 std::vector<Record*> Aliases =
2784 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2785 if (Aliases.empty()) return false;
2786
2787 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002788 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002789 OS << " switch (VariantID) {\n";
2790 unsigned VariantCount = Target.getAsmParserVariantCount();
2791 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2792 Record *AsmVariant = Target.getAsmParserVariant(VC);
2793 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
Craig Topperbcd3c372017-05-31 21:12:46 +00002794 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002795 OS << " case " << AsmParserVariantNo << ":\n";
2796 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2797 AsmParserVariantName);
2798 OS << " break;\n";
2799 }
2800 OS << " }\n";
2801
2802 // Emit aliases that apply to all variants.
2803 emitMnemonicAliasVariant(OS, Info, Aliases);
2804
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002805 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002806
Chris Lattner477fba4f2010-10-30 18:48:18 +00002807 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002808}
2809
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002810static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002811 const AsmMatcherInfo &Info, StringRef ClassName,
2812 StringToOffsetTable &StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00002813 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002814 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002815 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2816 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002817 }
2818
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002819 // Emit the static custom operand parsing table;
2820 OS << "namespace {\n";
2821 OS << " struct OperandMatchEntry {\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00002822 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002823 << " RequiredFeatures;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002824 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2825 << " Mnemonic;\n";
David Blaikied749e342014-11-28 20:35:57 +00002826 OS << " " << getMinimalTypeForRange(std::distance(
2827 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002828 OS << " " << getMinimalTypeForRange(MaxMask)
2829 << " OperandMask;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002830 OS << " StringRef getMnemonic() const {\n";
2831 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2832 OS << " MnemonicTable[Mnemonic]);\n";
2833 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002834 OS << " };\n\n";
2835
2836 OS << " // Predicate for searching for an opcode.\n";
2837 OS << " struct LessOpcodeOperand {\n";
2838 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002839 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002840 OS << " }\n";
2841 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002842 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002843 OS << " }\n";
2844 OS << " bool operator()(const OperandMatchEntry &LHS,";
2845 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002846 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002847 OS << " }\n";
2848 OS << " };\n";
2849
2850 OS << "} // end anonymous namespace.\n\n";
2851
2852 OS << "static const OperandMatchEntry OperandMatchTable["
2853 << Info.OperandMatchInfo.size() << "] = {\n";
2854
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002855 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002856 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002857 const MatchableInfo &II = *OMI.MI;
2858
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002859 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002860
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002861 // Write the required features mask.
2862 if (!II.RequiredFeatures.empty()) {
2863 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002864 if (i) OS << "|";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002865 OS << II.RequiredFeatures[i]->getEnumName();
2866 }
2867 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002868 OS << "0";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002869
2870 // Store a pascal-style length byte in the mnemonic.
2871 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2872 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2873 << " /* " << II.Mnemonic << " */, ";
2874
2875 OS << OMI.CI->Name;
2876
2877 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002878 OS << " /* ";
2879 bool printComma = false;
2880 for (int i = 0, e = 31; i !=e; ++i)
2881 if (OMI.OperandMask & (1 << i)) {
2882 if (printComma)
2883 OS << ", ";
2884 OS << i;
2885 printComma = true;
2886 }
2887 OS << " */";
2888
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002889 OS << " },\n";
2890 }
2891 OS << "};\n\n";
2892
2893 // Emit the operand class switch to call the correct custom parser for
2894 // the found operand class.
Alex Bradbury58eba092016-11-01 16:32:05 +00002895 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002896 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002897 << " &Operands,\n unsigned MCK) {\n\n"
2898 << " switch(MCK) {\n";
2899
Craig Topperf34dad92014-11-28 03:53:02 +00002900 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002901 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002902 continue;
David Blaikied749e342014-11-28 20:35:57 +00002903 OS << " case " << CI.Name << ":\n"
2904 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002905 }
2906
2907 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002908 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002909 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002910 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002911 OS << "}\n\n";
2912
2913 // Emit the static custom operand parser. This code is very similar with
2914 // the other matcher. Also use MatchResultTy here just in case we go for
2915 // a better error handling.
Alex Bradbury58eba092016-11-01 16:32:05 +00002916 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002917 << "MatchOperandParserImpl(OperandVector"
Sander de Smalencd6be962017-12-20 11:02:42 +00002918 << " &Operands,\n StringRef Mnemonic,\n"
2919 << " bool ParseForAllFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002920
2921 // Emit code to get the available features.
2922 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002923 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002924
2925 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002926 OS << " unsigned NextOpNum = Operands.size()"
2927 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002928
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002929 // Emit code to search the table.
2930 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002931 if (HasMnemonicFirst) {
2932 OS << " auto MnemonicRange =\n";
2933 OS << " std::equal_range(std::begin(OperandMatchTable), "
2934 "std::end(OperandMatchTable),\n";
2935 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2936 } else {
2937 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2938 " std::end(OperandMatchTable));\n";
2939 OS << " if (!Mnemonic.empty())\n";
2940 OS << " MnemonicRange =\n";
2941 OS << " std::equal_range(std::begin(OperandMatchTable), "
2942 "std::end(OperandMatchTable),\n";
2943 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2944 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002945
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002946 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002947 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002948
2949 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2950 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2951
2952 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002953 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002954
2955 // Emit check that the required features are available.
2956 OS << " // check if the available features match\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00002957 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
2958 "it->RequiredFeatures) != it->RequiredFeatures)\n";
2959 OS << " continue;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002960
2961 // Emit check to ensure the operand number matches.
2962 OS << " // check if the operand in question has a custom parser.\n";
2963 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2964 OS << " continue;\n\n";
2965
2966 // Emit call to the custom parser method
2967 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002968 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002969 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002970 OS << " if (Result != MatchOperand_NoMatch)\n";
2971 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002972 OS << " }\n\n";
2973
Jim Grosbach861e49c2011-02-12 01:34:40 +00002974 OS << " // Okay, we had no match.\n";
2975 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002976 OS << "}\n\n";
2977}
2978
Sander de Smalen886510f2018-01-10 10:10:56 +00002979static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
2980 AsmMatcherInfo &Info,
2981 raw_ostream &OS) {
Sander de Smalen886510f2018-01-10 10:10:56 +00002982 OS << "static bool ";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002983 OS << "checkAsmTiedOperandConstraints(unsigned Kind,\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00002984 OS << " const OperandVector &Operands,\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002985 OS << " uint64_t &ErrorInfo) {\n";
2986 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
2987 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
2988 OS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
2989 OS << " switch (*p) {\n";
2990 OS << " case CVT_Tied: {\n";
2991 OS << " unsigned OpIdx = *(p+1);\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00002992 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
2993 OS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002994 OS << " \"Tied operand not found\");\n";
2995 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
2996 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
2997 OS << " if (OpndNum1 != OpndNum2) {\n";
2998 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
2999 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
3000 OS << " if (SrcOp1->isReg() && SrcOp2->isReg() &&\n";
3001 OS << " SrcOp1->getReg() != SrcOp2->getReg()) {\n";
3002 OS << " ErrorInfo = OpndNum2;\n";
3003 OS << " return false;\n";
3004 OS << " }\n";
3005 OS << " }\n";
3006 OS << " break;\n";
3007 OS << " }\n";
3008 OS << " default:\n";
3009 OS << " break;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003010 OS << " }\n";
3011 OS << " }\n";
3012 OS << " return true;\n";
3013 OS << "}\n\n";
3014}
3015
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003016static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3017 unsigned VariantCount) {
Craig Topper2a060282017-10-26 06:46:40 +00003018 OS << "static std::string " << Target.getName()
Craig Topper05515562017-10-26 06:46:41 +00003019 << "MnemonicSpellCheck(StringRef S, uint64_t FBS, unsigned VariantID) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003020 if (!VariantCount)
3021 OS << " return \"\";";
3022 else {
3023 OS << " const unsigned MaxEditDist = 2;\n";
3024 OS << " std::vector<StringRef> Candidates;\n";
Craig Topper05515562017-10-26 06:46:41 +00003025 OS << " StringRef Prev = \"\";\n\n";
3026
3027 OS << " // Find the appropriate table for this asm variant.\n";
3028 OS << " const MatchEntry *Start, *End;\n";
3029 OS << " switch (VariantID) {\n";
3030 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3031 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3032 Record *AsmVariant = Target.getAsmParserVariant(VC);
3033 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3034 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3035 << "); End = std::end(MatchTable" << VC << "); break;\n";
3036 }
3037 OS << " }\n\n";
3038 OS << " for (auto I = Start; I < End; I++) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003039 OS << " // Ignore unsupported instructions.\n";
3040 OS << " if ((FBS & I->RequiredFeatures) != I->RequiredFeatures)\n";
3041 OS << " continue;\n";
3042 OS << "\n";
3043 OS << " StringRef T = I->getMnemonic();\n";
3044 OS << " // Avoid recomputing the edit distance for the same string.\n";
3045 OS << " if (T.equals(Prev))\n";
3046 OS << " continue;\n";
3047 OS << "\n";
3048 OS << " Prev = T;\n";
3049 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3050 OS << " if (Dist <= MaxEditDist)\n";
3051 OS << " Candidates.push_back(T);\n";
3052 OS << " }\n";
3053 OS << "\n";
3054 OS << " if (Candidates.empty())\n";
3055 OS << " return \"\";\n";
3056 OS << "\n";
3057 OS << " std::string Res = \", did you mean: \";\n";
3058 OS << " unsigned i = 0;\n";
3059 OS << " for( ; i < Candidates.size() - 1; i++)\n";
3060 OS << " Res += Candidates[i].str() + \", \";\n";
3061 OS << " return Res + Candidates[i].str() + \"?\";\n";
3062 }
3063 OS << "}\n";
3064 OS << "\n";
3065}
3066
3067
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003068// Emit a function mapping match classes to strings, for debugging.
3069static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3070 raw_ostream &OS) {
3071 OS << "#ifndef NDEBUG\n";
3072 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3073 OS << " switch (Kind) {\n";
3074
3075 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3076 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3077 for (const auto &CI : Infos) {
3078 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3079 }
3080 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3081
3082 OS << " }\n";
3083 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3084 OS << "}\n\n";
3085 OS << "#endif // NDEBUG\n";
3086}
3087
Daniel Dunbard0470d72009-08-07 21:01:44 +00003088void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003089 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00003090 Record *AsmParser = Target.getAsmParser();
Craig Topperbcd3c372017-05-31 21:12:46 +00003091 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
Daniel Dunbard0470d72009-08-07 21:01:44 +00003092
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003093 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00003094 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003095 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003096
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00003097 // Sort the instruction table using the partial order on classes. We use
3098 // stable_sort to ensure that ambiguous instructions are still
3099 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003100 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
3101 [](const std::unique_ptr<MatchableInfo> &a,
3102 const std::unique_ptr<MatchableInfo> &b){
3103 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003104
Matthias Brauna8eed312016-12-05 19:44:31 +00003105#ifdef EXPENSIVE_CHECKS
3106 // Verify that the table is sorted and operator < works transitively.
3107 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3108 ++I) {
3109 for (auto J = I; J != E; ++J) {
3110 assert(!(**J < **I));
3111 }
3112 }
3113#endif
3114
Daniel Dunbar71330282009-08-08 05:24:34 +00003115 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00003116 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003117 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00003118 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003119
Chris Lattnerad776812010-11-01 05:06:45 +00003120 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003121 DEBUG_WITH_TYPE("ambiguous_instrs", {
3122 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00003123 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3124 ++I) {
3125 for (auto J = std::next(I); J != E; ++J) {
3126 const MatchableInfo &A = **I;
3127 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003128
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003129 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00003130 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003131 A.dump();
3132 errs() << "\nis incomparable with:\n";
3133 B.dump();
3134 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003135 ++NumAmbiguous;
3136 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00003137 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00003138 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003139 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003140 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00003141 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003142 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00003143
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003144 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003145 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003146
Craig Topperfd2c6a32015-12-31 08:18:23 +00003147 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00003148 bool HasOptionalOperands = Info.hasOptionalOperands();
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003149 bool ReportMultipleNearMisses =
3150 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00003151
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003152 // Write the output.
3153
Chris Lattner3e4582a2010-09-06 19:11:01 +00003154 // Information for the class declaration.
3155 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3156 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00003157 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00003158 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003159 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003160 if (HasOptionalOperands) {
3161 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3162 << "unsigned Opcode,\n"
3163 << " const OperandVector &Operands,\n"
3164 << " const SmallBitVector &OptionalOperandsMask);\n";
3165 } else {
3166 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3167 << "unsigned Opcode,\n"
3168 << " const OperandVector &Operands);\n";
3169 }
Chad Rosier380a74a2012-10-02 00:25:57 +00003170 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00003171 OS << " const OperandVector &Operands) override;\n";
Craig Toppera5754e62015-01-03 08:16:29 +00003172 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003173 << " MCInst &Inst,\n";
3174 if (ReportMultipleNearMisses)
3175 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3176 else
3177 OS << " uint64_t &ErrorInfo,\n";
3178 OS << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00003179 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003180
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003181 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00003182 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003183 OS << " OperandVector &Operands,\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003184 OS << " StringRef Mnemonic,\n";
3185 OS << " bool ParseForAllFeatures = false);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003186
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00003187 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003188 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003189 OS << " unsigned MCK);\n\n";
3190 }
3191
Chris Lattner3e4582a2010-09-06 19:11:01 +00003192 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3193
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003194 // Emit the operand match diagnostic enum names.
3195 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3196 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3197 emitOperandDiagnosticTypes(Info, OS);
3198 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3199
Chris Lattner3e4582a2010-09-06 19:11:01 +00003200 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3201 OS << "#undef GET_REGISTER_MATCHER\n\n";
3202
Daniel Dunbareefe8612010-07-19 05:44:09 +00003203 // Emit the subtarget feature enumeration.
Daniel Sanders72db2a32016-11-19 13:05:44 +00003204 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(
3205 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003206
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003207 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00003208 // This should be omitted for Mips target
3209 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3210 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00003211
Dylan McKaybff960a2016-02-03 10:30:16 +00003212 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3213 emitMatchRegisterAltName(Target, AsmParser, OS);
3214
Chris Lattner3e4582a2010-09-06 19:11:01 +00003215 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003216
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003217 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3218 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003219
Jim Grosbach5117ef72012-04-24 22:40:08 +00003220 // Generate the helper function to get the names for subtarget features.
3221 emitGetSubtargetFeatureName(Info, OS);
3222
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003223 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3224
3225 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3226 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3227
Chris Lattner477fba4f2010-10-30 18:48:18 +00003228 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00003229 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003230
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003231 // Generate the convertToMCInst function to convert operands into an MCInst.
3232 // Also, generate the convertToMapAndConstraints function for MS-style inline
3233 // assembly. The latter doesn't actually generate a MCInst.
Sam Kolton5f10a132016-05-06 11:31:17 +00003234 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
3235 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003236
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003237 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003238 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003239
Oliver Stannard41dfac32017-10-03 14:34:57 +00003240 // Emit a function to get the user-visible string to describe an operand
3241 // match failure in diagnostics.
3242 emitOperandMatchErrorDiagStrings(Info, OS);
3243
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003244 // Emit a function to map register classes to operand match failure codes.
3245 emitRegisterMatchErrorFunc(Info, OS);
3246
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003247 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003248 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003249
Daniel Dunbar2587b612009-08-10 16:05:47 +00003250 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003251 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00003252
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003253 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003254 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003255
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003256 emitMatchClassKindNames(Info.Classes, OS);
3257
Daniel Dunbareefe8612010-07-19 05:44:09 +00003258 // Emit the available features compute function.
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003259 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003260 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3261 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003262
Sander de Smalen886510f2018-01-10 10:10:56 +00003263 if (!ReportMultipleNearMisses)
3264 emitAsmTiedOperandConstraints(Target, Info, OS);
3265
Craig Toppere2cfeb32012-09-18 06:10:45 +00003266 StringToOffsetTable StringTable;
3267
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003268 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003269 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00003270 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00003271 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003272 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3273 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003274
3275 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003276 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00003277 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3278 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3279 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003280
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003281 OS << "static const char *const MnemonicTable =\n";
3282 StringTable.EmitString(OS);
3283 OS << ";\n\n";
3284
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00003285 // Emit the static match table; unused classes get initialized to 0 which is
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003286 // guaranteed to be InvalidMatchClass.
3287 //
3288 // FIXME: We can reduce the size of this table very easily. First, we change
3289 // it so that store the kinds in separate bit-fields for each index, which
3290 // only needs to be the max width used for classes at that index (we also need
3291 // to reject based on this during classification). If we then make sure to
3292 // order the match kinds appropriately (putting mnemonics last), then we
3293 // should only end up using a few bits for each class, especially the ones
3294 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003295 OS << "namespace {\n";
3296 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00003297 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3298 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003299 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003300 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3301 << " ConvertFn;\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00003302 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003303 << " RequiredFeatures;\n";
David Blaikied749e342014-11-28 20:35:57 +00003304 OS << " " << getMinimalTypeForRange(
3305 std::distance(Info.Classes.begin(), Info.Classes.end()))
3306 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003307 OS << " StringRef getMnemonic() const {\n";
3308 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3309 OS << " MnemonicTable[Mnemonic]);\n";
3310 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003311 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003312
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003313 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003314 OS << " struct LessOpcode {\n";
3315 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003316 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003317 OS << " }\n";
3318 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003319 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003320 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003321 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003322 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003323 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003324 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003325
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003326 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003327
Craig Topper690d8ea2013-07-24 07:33:14 +00003328 unsigned VariantCount = Target.getAsmParserVariantCount();
3329 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3330 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003331 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003332
Craig Topper690d8ea2013-07-24 07:33:14 +00003333 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003334
Craig Topperf34dad92014-11-28 03:53:02 +00003335 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003336 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003337 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003338
Craig Topper690d8ea2013-07-24 07:33:14 +00003339 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003340 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003341 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003342 << " /* " << MI->Mnemonic << " */, "
Craig Topper2b347eb2017-07-07 05:19:25 +00003343 << Target.getInstNamespace() << "::"
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003344 << MI->getResultInst()->TheDef->getName() << ", "
3345 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003346
3347 // Write the required features mask.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003348 if (!MI->RequiredFeatures.empty()) {
3349 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003350 if (i) OS << "|";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003351 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003352 }
3353 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003354 OS << "0";
Craig Topper690d8ea2013-07-24 07:33:14 +00003355
3356 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003357 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3358 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003359
3360 if (i) OS << ", ";
3361 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003362 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003363 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003364 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003365
Craig Topper690d8ea2013-07-24 07:33:14 +00003366 OS << "};\n\n";
3367 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003368
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003369 OS << "#include \"llvm/Support/Debug.h\"\n";
3370 OS << "#include \"llvm/Support/Format.h\"\n\n";
3371
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003372 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003373 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003374 << "MatchInstructionImpl(const OperandVector &Operands,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003375 OS << " MCInst &Inst,\n";
3376 if (ReportMultipleNearMisses)
3377 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3378 else
3379 OS << " uint64_t &ErrorInfo,\n";
3380 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003381
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003382 if (!ReportMultipleNearMisses) {
3383 OS << " // Eliminate obvious mismatches.\n";
3384 OS << " if (Operands.size() > "
3385 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3386 OS << " ErrorInfo = "
3387 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3388 OS << " return Match_InvalidOperand;\n";
3389 OS << " }\n\n";
3390 }
Chad Rosiereac13a32012-08-30 21:43:05 +00003391
Daniel Dunbareefe8612010-07-19 05:44:09 +00003392 // Emit code to get the available features.
3393 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003394 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003395
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003396 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003397 if (HasMnemonicFirst) {
3398 OS << " StringRef Mnemonic = ((" << Target.getName()
3399 << "Operand&)*Operands[0]).getToken();\n\n";
3400 } else {
3401 OS << " StringRef Mnemonic;\n";
3402 OS << " if (Operands[0]->isToken())\n";
3403 OS << " Mnemonic = ((" << Target.getName()
3404 << "Operand&)*Operands[0]).getToken();\n\n";
3405 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003406
Chris Lattner477fba4f2010-10-30 18:48:18 +00003407 if (HasMnemonicAliases) {
3408 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003409 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003410 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003411
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003412 // Emit code to compute the class list for this operand vector.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003413 if (!ReportMultipleNearMisses) {
3414 OS << " // Some state to try to produce better error messages.\n";
3415 OS << " bool HadMatchOtherThanFeatures = false;\n";
3416 OS << " bool HadMatchOtherThanPredicate = false;\n";
3417 OS << " unsigned RetCode = Match_InvalidOperand;\n";
3418 OS << " uint64_t MissingFeatures = ~0ULL;\n";
3419 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3420 OS << " // wrong for all instances of the instruction.\n";
3421 OS << " ErrorInfo = ~0ULL;\n";
3422 }
3423
Sam Kolton5f10a132016-05-06 11:31:17 +00003424 if (HasOptionalOperands) {
3425 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3426 }
Chris Lattner81301972010-09-06 21:22:45 +00003427
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003428 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003429 OS << " // Find the appropriate table for this asm variant.\n";
3430 OS << " const MatchEntry *Start, *End;\n";
3431 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003432 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003433 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3434 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003435 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003436 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3437 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003438 }
3439 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003440
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003441 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003442 if (HasMnemonicFirst) {
3443 OS << " auto MnemonicRange = "
3444 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3445 } else {
3446 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3447 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3448 OS << " if (!Mnemonic.empty())\n";
3449 OS << " MnemonicRange = "
3450 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3451 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003452
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003453 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3454 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3455 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3456
Chris Lattner628fbec2010-09-06 21:54:15 +00003457 OS << " // Return a more specific error code if no mnemonics match.\n";
3458 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3459 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003460
Chris Lattner81301972010-09-06 21:22:45 +00003461 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003462 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003463 OS << " it != ie; ++it) {\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003464 OS << " bool HasRequiredFeatures =\n";
3465 OS << " (AvailableFeatures & it->RequiredFeatures) == "
3466 "it->RequiredFeatures;\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003467 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3468 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3469
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003470 if (ReportMultipleNearMisses) {
3471 OS << " // Some state to record ways in which this instruction did not match.\n";
3472 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3473 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3474 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3475 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003476 OS << " bool MultipleInvalidOperands = false;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003477 }
3478
Craig Topperfd2c6a32015-12-31 08:18:23 +00003479 if (HasMnemonicFirst) {
3480 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3481 OS << " assert(Mnemonic == it->getMnemonic());\n";
3482 }
3483
Daniel Dunbareefe8612010-07-19 05:44:09 +00003484 // Emit check that the subclasses match.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003485 if (!ReportMultipleNearMisses)
3486 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003487 if (HasOptionalOperands) {
3488 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3489 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003490 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3491 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3492 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3493 OS << " auto Formal = "
3494 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003495 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3496 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3497 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3498 OS << " if (ActualIdx < Operands.size())\n";
3499 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3500 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3501 OS << " else\n";
3502 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003503 OS << " if (ActualIdx >= Operands.size()) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003504 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003505 if (ReportMultipleNearMisses) {
3506 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3507 "isSubclass(Formal, OptionalMatchClass);\n";
3508 OS << " if (!ThisOperandValid) {\n";
3509 OS << " if (!OperandNearMiss) {\n";
3510 OS << " // Record info about match failure for later use.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003511 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003512 OS << " OperandNearMiss =\n";
3513 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
Oliver Stannard1e73e952017-11-21 15:16:50 +00003514 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003515 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003516 OS << " DEBUG_WITH_TYPE(\n";
3517 OS << " \"asm-matcher\",\n";
3518 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003519 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003520 OS << " break;\n";
3521 OS << " }\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003522 OS << " } else {\n";
3523 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
Oliver Stannard6e943312017-11-21 15:12:05 +00003524 OS << " break;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003525 OS << " }\n";
3526 OS << " continue;\n";
3527 } else {
3528 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3529 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3530 if (HasOptionalOperands) {
3531 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3532 << ");\n";
3533 }
3534 OS << " break;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003535 }
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003536 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003537 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003538 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003539 OS << " if (Diag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003540 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3541 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003542 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003543 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003544 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003545 OS << " // If the generic handler indicates an invalid operand\n";
3546 OS << " // failure, check for a special case.\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003547 OS << " if (Diag != Match_Success) {\n";
3548 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3549 OS << " if (TargetDiag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003550 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3551 OS << " dbgs() << \"match success using target matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003552 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003553 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003554 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003555 OS << " // If the target matcher returned a specific error code use\n";
3556 OS << " // that, else use the one from the generic matcher.\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003557 OS << " if (TargetDiag != Match_InvalidOperand && "
3558 "HasRequiredFeatures)\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003559 OS << " Diag = TargetDiag;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003560 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003561 OS << " // If current formal operand wasn't matched and it is optional\n"
3562 << " // then try to match next formal operand\n";
3563 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003564 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3565 if (HasOptionalOperands) {
3566 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3567 }
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003568 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003569 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003570 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003571
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003572 if (ReportMultipleNearMisses) {
3573 OS << " if (!OperandNearMiss) {\n";
3574 OS << " // If this is the first invalid operand we have seen, record some\n";
3575 OS << " // information about it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003576 OS << " DEBUG_WITH_TYPE(\n";
3577 OS << " \"asm-matcher\",\n";
3578 OS << " dbgs()\n";
3579 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3580 OS << " << Diag << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003581 OS << " OperandNearMiss =\n";
3582 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3583 OS << " ++ActualIdx;\n";
3584 OS << " } else {\n";
3585 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003586 OS << " DEBUG_WITH_TYPE(\n";
3587 OS << " \"asm-matcher\",\n";
3588 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003589 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003590 OS << " break;\n";
3591 OS << " }\n";
3592 OS << " }\n\n";
3593 } else {
3594 OS << " // If this operand is broken for all of the instances of this\n";
3595 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3596 OS << " // If we already had a match that only failed due to a\n";
3597 OS << " // target predicate, that diagnostic is preferred.\n";
3598 OS << " if (!HadMatchOtherThanPredicate &&\n";
3599 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003600 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3601 "!= Match_InvalidOperand))\n";
Sander de Smalen4acd57e2017-11-21 15:07:43 +00003602 OS << " RetCode = Diag;\n";
Sander de Smalen14e36ee2017-12-14 16:09:48 +00003603 OS << " ErrorInfo = ActualIdx;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003604 OS << " }\n";
3605 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3606 OS << " OperandsValid = false;\n";
3607 OS << " break;\n";
3608 OS << " }\n\n";
3609 }
3610
Oliver Stannard7ab60602017-12-04 13:42:22 +00003611 if (ReportMultipleNearMisses)
3612 OS << " if (MultipleInvalidOperands) {\n";
3613 else
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003614 OS << " if (!OperandsValid) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003615 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3616 OS << " \"operand mismatches, ignoring \"\n";
3617 OS << " \"this opcode\\n\");\n";
3618 OS << " continue;\n";
3619 OS << " }\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003620
3621 // Emit check that the required features are available.
Sander de Smalencd6be962017-12-20 11:02:42 +00003622 OS << " if (!HasRequiredFeatures) {\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003623 if (!ReportMultipleNearMisses)
3624 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003625 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003626 "~AvailableFeatures;\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003627 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features: \"\n";
3628 OS << " << format_hex(NewMissingFeatures, 18)\n";
3629 OS << " << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003630 if (ReportMultipleNearMisses) {
3631 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3632 } else {
3633 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3634 " countPopulation(MissingFeatures))\n";
3635 OS << " MissingFeatures = NewMissingFeatures;\n";
3636 OS << " continue;\n";
3637 }
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003638 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003639 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003640 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003641 OS << " Inst.setOpcode(it->Opcode);\n";
3642 // Verify the instruction with the target-specific match predicate function.
3643 OS << " // We have a potential match but have not rendered the operands.\n"
3644 << " // Check the target predicate to handle any context sensitive\n"
3645 " // constraints.\n"
3646 << " // For example, Ties that are referenced multiple times must be\n"
3647 " // checked here to ensure the input is the same for each match\n"
3648 " // constraints. If we leave it any later the ties will have been\n"
3649 " // canonicalized\n"
3650 << " unsigned MatchResult;\n"
3651 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3652 "Operands)) != Match_Success) {\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003653 << " Inst.clear();\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003654 OS << " DEBUG_WITH_TYPE(\n";
3655 OS << " \"asm-matcher\",\n";
3656 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3657 OS << " << MatchResult << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003658 if (ReportMultipleNearMisses) {
3659 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3660 } else {
3661 OS << " RetCode = MatchResult;\n"
3662 << " HadMatchOtherThanPredicate = true;\n"
3663 << " continue;\n";
3664 }
3665 OS << " }\n\n";
3666
3667 if (ReportMultipleNearMisses) {
3668 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3669 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3670 OS << " if (OperandNearMiss) {\n";
3671 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3672 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003673 OS << " DEBUG_WITH_TYPE(\n";
3674 OS << " \"asm-matcher\",\n";
3675 OS << " dbgs()\n";
3676 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003677 OS << " NearMisses->push_back(OperandNearMiss);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003678 OS << " } else {\n";
3679 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3680 OS << " \"types of mismatch, so not \"\n";
3681 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003682 OS << " }\n";
3683 OS << " continue;\n";
3684 OS << " }\n\n";
3685 }
3686
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003687 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003688 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003689 if (!ReportMultipleNearMisses) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00003690 OS << " if (!checkAsmTiedOperandConstraints(it->ConvertFn, Operands, ErrorInfo))\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003691 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003692 OS << "\n";
3693 }
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003694 OS << " return Match_Success;\n";
3695 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003696 OS << " // We have selected a definite instruction, convert the parsed\n"
3697 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003698 if (HasOptionalOperands) {
3699 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3700 << " OptionalOperandsMask);\n";
3701 } else {
3702 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3703 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003704 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003705
Jim Grosbach120a96a2011-08-15 23:03:29 +00003706 // Verify the instruction with the target-specific match predicate function.
3707 OS << " // We have a potential match. Check the target predicate to\n"
3708 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003709 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3710 << " Match_Success) {\n"
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003711 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3712 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3713 << " << MatchResult << \"\\n\");\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003714 << " Inst.clear();\n";
3715 if (ReportMultipleNearMisses) {
3716 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3717 } else {
3718 OS << " RetCode = MatchResult;\n"
3719 << " HadMatchOtherThanPredicate = true;\n"
3720 << " continue;\n";
3721 }
3722 OS << " }\n\n";
3723
3724 if (ReportMultipleNearMisses) {
3725 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3726 OS << " (int)(bool)FeaturesNearMiss +\n";
3727 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3728 OS << " (int)(bool)LatePredicateNearMiss);\n";
3729 OS << " if (NumNearMisses == 1) {\n";
3730 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3731 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003732 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3733 OS << " \"mismatch, so reporting a \"\n";
3734 OS << " \"near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003735 OS << " if (NearMisses && FeaturesNearMiss)\n";
3736 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3737 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3738 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3739 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3740 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3741 OS << "\n";
3742 OS << " continue;\n";
3743 OS << " } else if (NumNearMisses > 1) {\n";
3744 OS << " // This instruction missed in more than one way, so ignore it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003745 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3746 OS << " \"types of mismatch, so not \"\n";
3747 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003748 OS << " continue;\n";
3749 OS << " }\n";
3750 }
Jim Grosbach120a96a2011-08-15 23:03:29 +00003751
Daniel Dunbar451a4352010-03-18 20:05:56 +00003752 // Call the post-processing function, if used.
Craig Topperbcd3c372017-05-31 21:12:46 +00003753 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
Daniel Dunbar451a4352010-03-18 20:05:56 +00003754 if (!InsnCleanupFn.empty())
3755 OS << " " << InsnCleanupFn << "(Inst);\n";
3756
Joey Gouly0e76fa72013-09-12 10:28:05 +00003757 if (HasDeprecation) {
3758 OS << " std::string Info;\n";
Weiming Zhaob38cfce2016-12-05 23:55:13 +00003759 OS << " if (!getParser().getTargetParser().\n";
3760 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3761 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003762 OS << " SMLoc Loc = ((" << Target.getName()
3763 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003764 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003765 OS << " }\n";
3766 }
3767
Sander de Smalen886510f2018-01-10 10:10:56 +00003768 if (!ReportMultipleNearMisses) {
Craig Topper773ead22018-04-25 06:24:51 +00003769 OS << " if (!checkAsmTiedOperandConstraints(it->ConvertFn, Operands, ErrorInfo))\n";
3770 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003771 OS << "\n";
3772 }
3773
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003774 OS << " DEBUG_WITH_TYPE(\n";
3775 OS << " \"asm-matcher\",\n";
3776 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00003777 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003778 OS << " }\n\n";
3779
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003780 if (ReportMultipleNearMisses) {
3781 OS << " // No instruction variants matched exactly.\n";
3782 OS << " return Match_NearMisses;\n";
3783 } else {
3784 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3785 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3786 OS << " return RetCode;\n\n";
3787 OS << " // Missing feature matches return which features were missing\n";
3788 OS << " ErrorInfo = MissingFeatures;\n";
3789 OS << " return Match_MissingFeature;\n";
3790 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003791 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003792
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003793 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003794 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00003795 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003796
Chris Lattner3e4582a2010-09-06 19:11:01 +00003797 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Craig Topper2a060282017-10-26 06:46:40 +00003798
3799 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3800 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3801
3802 emitMnemonicSpellChecker(OS, Target, VariantCount);
3803
3804 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003805}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003806
3807namespace llvm {
3808
3809void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3810 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3811 AsmMatcherEmitter(RK).run(OS);
3812}
3813
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003814} // end namespace llvm