blob: 5953bdc7301faf9ec3e150d6ed2ceeedd876730f [file] [log] [blame]
Daniel Dunbar3085b572009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000011// assembly operands in the MCInst structures. It also emits a matcher for
12// custom operand parsing.
13//
14// Converting assembly operands into MCInst structures
15// ---------------------------------------------------
Daniel Dunbar3085b572009-07-11 19:39:44 +000016//
Daniel Dunbare10787e2009-08-07 08:26:05 +000017// The input to the target specific matcher is a list of literal tokens and
18// operands. The target specific parser should generally eliminate any syntax
19// which is not relevant for matching; for example, comma tokens should have
20// already been consumed and eliminated by the parser. Most instructions will
21// end up with a single literal token (the instruction name) and some number of
22// operands.
23//
24// Some example inputs, for X86:
25// 'addl' (immediate ...) (register ...)
26// 'add' (immediate ...) (memory ...)
Jim Grosbach0eccfc22010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbare10787e2009-08-07 08:26:05 +000028//
29// The assembly matcher is responsible for converting this input into a precise
30// machine instruction (i.e., an instruction with a well defined encoding). This
31// mapping has several properties which complicate matching:
32//
33// - It may be ambiguous; many architectures can legally encode particular
34// variants of an instruction in different ways (for example, using a smaller
35// encoding for small immediates). Such ambiguities should never be
36// arbitrarily resolved by the assembler, the assembler is always responsible
37// for choosing the "best" available instruction.
38//
39// - It may depend on the subtarget or the assembler context. Instructions
40// which are invalid for the current mode, but otherwise unambiguous (e.g.,
41// an SSE instruction in a file being assembled for i486) should be accepted
42// and rejected by the assembler front end. However, if the proper encoding
43// for an instruction is dependent on the assembler context then the matcher
44// is responsible for selecting the correct machine instruction for the
45// current mode.
46//
47// The core matching algorithm attempts to exploit the regularity in most
48// instruction sets to quickly determine the set of possibly matching
49// instructions, and the simplify the generated code. Additionally, this helps
50// to ensure that the ambiguities are intentionally resolved by the user.
51//
52// The matching is divided into two distinct phases:
53//
54// 1. Classification: Each operand is mapped to the unique set which (a)
55// contains it, and (b) is the largest such subset for which a single
56// instruction could match all members.
57//
58// For register classes, we can generate these subgroups automatically. For
59// arbitrary operands, we expect the user to define the classes and their
60// relations to one another (for example, 8-bit signed immediates as a
61// subset of 32-bit immediates).
62//
63// By partitioning the operands in this way, we guarantee that for any
64// tuple of classes, any single instruction must match either all or none
65// of the sets of operands which could classify to that tuple.
66//
67// In addition, the subset relation amongst classes induces a partial order
68// on such tuples, which we use to resolve ambiguities.
69//
Daniel Dunbare10787e2009-08-07 08:26:05 +000070// 2. The input can now be treated as a tuple of classes (static tokens are
71// simple singleton sets). Each such tuple should generally map to a single
72// instruction (we currently ignore cases where this isn't true, whee!!!),
73// which we can emit a simple matcher for.
74//
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000075// Custom Operand Parsing
76// ----------------------
77//
78// Some targets need a custom way to parse operands, some specific instructions
79// can contain arguments that can represent processor flags and other kinds of
Craig Topperaae8fb82012-09-18 01:13:36 +000080// identifiers that need to be mapped to specific values in the final encoded
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000081// instructions. The target specific custom operand parsing works in the
82// following way:
83//
84// 1. A operand match table is built, each entry contains a mnemonic, an
85// operand class, a mask for all operand positions for that same
86// class/mnemonic and target features to be checked while trying to match.
87//
88// 2. The operand matcher will try every possible entry with the same
89// mnemonic and will check if the target feature for this mnemonic also
90// matches. After that, if the operand to be matched has its index
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000092// to the regular operand parsing.
93//
94// 3. For a match success, each operand class that has a 'ParserMethod'
95// becomes part of a switch from where the custom method is called.
96//
Daniel Dunbar3085b572009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
Daniel Dunbar3085b572009-07-11 19:39:44 +000099#include "CodeGenTarget.h"
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000100#include "SubtargetFeatureInfo.h"
Daniel Sandersca89f3a2016-11-19 12:21:34 +0000101#include "Types.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000102#include "llvm/ADT/CachedHashString.h"
Chris Lattner4efe13d2010-11-04 02:11:18 +0000103#include "llvm/ADT/PointerUnion.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +0000104#include "llvm/ADT/STLExtras.h"
Chris Lattnerf7a01e92010-11-01 01:47:07 +0000105#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000106#include "llvm/ADT/SmallVector.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000107#include "llvm/ADT/StringExtras.h"
108#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000109#include "llvm/Support/Debug.h"
Craig Topperc4965bc2012-02-05 07:21:30 +0000110#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +0000111#include "llvm/TableGen/Error.h"
112#include "llvm/TableGen/Record.h"
Douglas Gregor12c1cd32012-05-02 17:32:48 +0000113#include "llvm/TableGen/StringMatcher.h"
Craig Topper3e1d5da2013-08-29 05:09:55 +0000114#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000115#include "llvm/TableGen/TableGenBackend.h"
116#include <cassert>
Will Dietz981af002013-10-12 00:55:57 +0000117#include <cctype>
Mehdi Aminib550cb12016-04-18 09:17:29 +0000118#include <forward_list>
Daniel Dunbar71330282009-08-08 05:24:34 +0000119#include <map>
120#include <set>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000121
Daniel Dunbar3085b572009-07-11 19:39:44 +0000122using namespace llvm;
123
Chandler Carruthe96dd892014-04-21 22:55:11 +0000124#define DEBUG_TYPE "asm-matcher-emitter"
125
Daniel Sanders0848b232017-03-27 13:15:13 +0000126cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
127
Daniel Dunbar15b80372009-08-07 20:33:39 +0000128static cl::opt<std::string>
Daniel Sanders0848b232017-03-27 13:15:13 +0000129 MatchPrefix("match-prefix", cl::init(""),
130 cl::desc("Only match instructions with the given prefix"),
131 cl::cat(AsmMatcherEmitterCat));
Daniel Dunbare10787e2009-08-07 08:26:05 +0000132
Daniel Dunbare10787e2009-08-07 08:26:05 +0000133namespace {
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000134class AsmMatcherInfo;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000135
Tim Northoverc74e6912013-09-16 16:43:19 +0000136// Register sets are used as keys in some second-order sets TableGen creates
137// when generating its data structures. This means that the order of two
138// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
139// can even affect compiler output (at least seen in diagnostics produced when
140// all matches fail). So we use a type that sorts them consistently.
141typedef std::set<Record*, LessRecordByID> RegisterSet;
142
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000143class AsmMatcherEmitter {
144 RecordKeeper &Records;
145public:
146 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
147
148 void run(raw_ostream &o);
149};
150
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000151/// ClassInfo - Helper class for storing the information about a particular
152/// class of operands which can be matched.
153struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000154 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000155 /// Invalid kind, for use as a sentinel value.
156 Invalid = 0,
157
158 /// The class for a particular token.
159 Token,
160
161 /// The (first) register class, subsequent register classes are
162 /// RegisterClass0+1, and so on.
163 RegisterClass0,
164
165 /// The (first) user defined class, subsequent user defined classes are
166 /// UserClass0+1, and so on.
167 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000168 };
169
170 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
171 /// N) for the Nth user defined class.
172 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000173
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000174 /// SuperClasses - The super classes of this class. Note that for simplicities
175 /// sake user operands only record their immediate super class, while register
176 /// operands include all superclasses.
177 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000178
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000179 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000180 std::string Name;
181
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000182 /// ClassName - The unadorned generic name for this class (e.g., Token).
183 std::string ClassName;
184
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000185 /// ValueName - The name of the value this class represents; for a token this
186 /// is the literal token string, for an operand it is the TableGen class (or
187 /// empty if this is a derived class).
188 std::string ValueName;
189
190 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000191 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000192 std::string PredicateMethod;
193
194 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000195 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000196 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000197
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000198 /// ParserMethod - The name of the operand method to do a target specific
199 /// parsing on the operand.
200 std::string ParserMethod;
201
Eric Christopher650c8f22014-05-20 17:11:11 +0000202 /// For register classes: the records for all the registers in this class.
Tim Northoverc74e6912013-09-16 16:43:19 +0000203 RegisterSet Registers;
Daniel Dunbar34c87912009-08-11 20:10:07 +0000204
Eric Christopher650c8f22014-05-20 17:11:11 +0000205 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000206 std::string DiagnosticType;
Tom Stellardb9f235e2016-02-05 19:59:33 +0000207
208 /// Is this operand optional and not always required.
209 bool IsOptional;
210
Sam Kolton5f10a132016-05-06 11:31:17 +0000211 /// DefaultMethod - The name of the method that returns the default operand
212 /// for optional operand
213 std::string DefaultMethod;
214
Daniel Dunbar34c87912009-08-11 20:10:07 +0000215public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000216 /// isRegisterClass() - Check if this is a register class.
217 bool isRegisterClass() const {
218 return Kind >= RegisterClass0 && Kind < UserClass0;
219 }
220
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000221 /// isUserClass() - Check if this is a user defined class.
222 bool isUserClass() const {
223 return Kind >= UserClass0;
224 }
225
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000226 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000227 /// are related if they are in the same class hierarchy.
228 bool isRelatedTo(const ClassInfo &RHS) const {
229 // Tokens are only related to tokens.
230 if (Kind == Token || RHS.Kind == Token)
231 return Kind == Token && RHS.Kind == Token;
232
Daniel Dunbar34c87912009-08-11 20:10:07 +0000233 // Registers classes are only related to registers classes, and only if
234 // their intersection is non-empty.
235 if (isRegisterClass() || RHS.isRegisterClass()) {
236 if (!isRegisterClass() || !RHS.isRegisterClass())
237 return false;
238
Tim Northoverc74e6912013-09-16 16:43:19 +0000239 RegisterSet Tmp;
240 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000241 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000242 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +0000243 II, LessRecordByID());
Daniel Dunbar34c87912009-08-11 20:10:07 +0000244
245 return !Tmp.empty();
246 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000247
248 // Otherwise we have two users operands; they are related if they are in the
249 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000250 //
251 // FIXME: This is an oversimplification, they should only be related if they
252 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000253 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
254 const ClassInfo *Root = this;
255 while (!Root->SuperClasses.empty())
256 Root = Root->SuperClasses.front();
257
Daniel Dunbar34c87912009-08-11 20:10:07 +0000258 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000259 while (!RHSRoot->SuperClasses.empty())
260 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000261
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000262 return Root == RHSRoot;
263 }
264
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000265 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000266 bool isSubsetOf(const ClassInfo &RHS) const {
267 // This is a subset of RHS if it is the same class...
268 if (this == &RHS)
269 return true;
270
271 // ... or if any of its super classes are a subset of RHS.
Craig Topper03ec8012014-11-25 20:11:31 +0000272 for (const ClassInfo *CI : SuperClasses)
273 if (CI->isSubsetOf(RHS))
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000274 return true;
275
276 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000277 }
278
Oliver Stannard7772f022016-01-25 10:20:19 +0000279 int getTreeDepth() const {
280 int Depth = 0;
281 const ClassInfo *Root = this;
282 while (!Root->SuperClasses.empty()) {
283 Depth++;
284 Root = Root->SuperClasses.front();
285 }
286 return Depth;
287 }
288
289 const ClassInfo *findRoot() const {
290 const ClassInfo *Root = this;
291 while (!Root->SuperClasses.empty())
292 Root = Root->SuperClasses.front();
293 return Root;
294 }
295
296 /// Compare two classes. This does not produce a total ordering, but does
297 /// guarantee that subclasses are sorted before their parents, and that the
298 /// ordering is transitive.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000299 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000300 if (this == &RHS)
301 return false;
302
Oliver Stannard7772f022016-01-25 10:20:19 +0000303 // First, enforce the ordering between the three different types of class.
304 // Tokens sort before registers, which sort before user classes.
305 if (Kind == Token) {
306 if (RHS.Kind != Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000307 return true;
Oliver Stannard7772f022016-01-25 10:20:19 +0000308 assert(RHS.Kind == Token);
309 } else if (isRegisterClass()) {
310 if (RHS.Kind == Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000311 return false;
Oliver Stannard7772f022016-01-25 10:20:19 +0000312 else if (RHS.isUserClass())
313 return true;
314 assert(RHS.isRegisterClass());
315 } else if (isUserClass()) {
316 if (!RHS.isUserClass())
317 return false;
318 assert(RHS.isUserClass());
319 } else {
320 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000321 }
Oliver Stannard7772f022016-01-25 10:20:19 +0000322
323 if (Kind == Token || isUserClass()) {
324 // Related tokens and user classes get sorted by depth in the inheritence
325 // tree (so that subclasses are before their parents).
326 if (isRelatedTo(RHS)) {
327 if (getTreeDepth() > RHS.getTreeDepth())
328 return true;
329 if (getTreeDepth() < RHS.getTreeDepth())
330 return false;
331 } else {
332 // Unrelated tokens and user classes are ordered by the name of their
333 // root nodes, so that there is a consistent ordering between
334 // unconnected trees.
335 return findRoot()->ValueName < RHS.findRoot()->ValueName;
336 }
337 } else if (isRegisterClass()) {
338 // For register sets, sort by number of registers. This guarantees that
339 // a set will always sort before all of it's strict supersets.
340 if (Registers.size() != RHS.Registers.size())
341 return Registers.size() < RHS.Registers.size();
342 } else {
343 llvm_unreachable("Unknown ClassInfoKind");
344 }
345
346 // FIXME: We should be able to just return false here, as we only need a
347 // partial order (we use stable sorts, so this is deterministic) and the
348 // name of a class shouldn't be significant. However, some of the backends
349 // accidentally rely on this behaviour, so it will have to stay like this
350 // until they are fixed.
351 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000352 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000353};
354
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000355class AsmVariantInfo {
356public:
Craig Topperc8b5b252015-12-30 06:00:18 +0000357 std::string RegisterPrefix;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000358 std::string TokenizingCharacters;
359 std::string SeparatorCharacters;
360 std::string BreakCharacters;
Sam Kolton1b746d12016-09-08 15:50:52 +0000361 std::string Name;
Craig Topperc8b5b252015-12-30 06:00:18 +0000362 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000363};
364
Chris Lattnerad776812010-11-01 05:06:45 +0000365/// MatchableInfo - Helper class for storing the necessary information for an
366/// instruction or alias which is capable of being matched.
367struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000368 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000369 /// Token - This is the token that the operand came from.
370 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000371
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000372 /// The unique class instance this operand should match.
373 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000374
Chris Lattner7108dad2010-11-04 01:42:59 +0000375 /// The operand name this is, if anything.
376 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000377
378 /// The suboperand index within SrcOpName, or -1 for the entire operand.
379 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000380
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000381 /// Whether the token is "isolated", i.e., it is preceded and followed
382 /// by separators.
383 bool IsIsolatedToken;
384
Devang Patel6d676e42012-01-07 01:33:34 +0000385 /// Register record if this token is singleton register.
386 Record *SingletonReg;
387
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000388 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
389 : Token(T), Class(nullptr), SubOpIdx(-1),
390 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000391 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000392
Chris Lattner743081d2010-11-04 00:43:46 +0000393 /// ResOperand - This represents a single operand in the result instruction
394 /// generated by the match. In cases (like addressing modes) where a single
395 /// assembler operand expands to multiple MCOperands, this represents the
396 /// single assembler operand, not the MCOperand.
397 struct ResOperand {
398 enum {
399 /// RenderAsmOperand - This represents an operand result that is
400 /// generated by calling the render method on the assembly operand. The
401 /// corresponding AsmOperand is specified by AsmOperandNum.
402 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000403
Chris Lattner743081d2010-11-04 00:43:46 +0000404 /// TiedOperand - This represents a result operand that is a duplicate of
405 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000406 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000407
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000408 /// ImmOperand - This represents an immediate value that is dumped into
409 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000410 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000411
Chris Lattner4869d342010-11-06 19:57:21 +0000412 /// RegOperand - This represents a fixed register that is dumped in.
413 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000414 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000415
Chris Lattner743081d2010-11-04 00:43:46 +0000416 union {
417 /// This is the operand # in the AsmOperands list that this should be
418 /// copied from.
419 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000420
Chris Lattner743081d2010-11-04 00:43:46 +0000421 /// TiedOperandNum - This is the (earlier) result operand that should be
422 /// copied from.
423 unsigned TiedOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000424
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000425 /// ImmVal - This is the immediate value added to the instruction.
426 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000427
Chris Lattner4869d342010-11-06 19:57:21 +0000428 /// Register - This is the register record.
429 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000430 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000431
Bob Wilsonb9b24222011-01-26 19:44:55 +0000432 /// MINumOperands - The number of MCInst operands populated by this
433 /// operand.
434 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000435
Bob Wilsonb9b24222011-01-26 19:44:55 +0000436 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000437 ResOperand X;
438 X.Kind = RenderAsmOperand;
439 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000440 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000441 return X;
442 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000443
Bob Wilsonb9b24222011-01-26 19:44:55 +0000444 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner743081d2010-11-04 00:43:46 +0000445 ResOperand X;
446 X.Kind = TiedOperand;
447 X.TiedOperandNum = TiedOperandNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000448 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000449 return X;
450 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000451
Bob Wilsonb9b24222011-01-26 19:44:55 +0000452 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000453 ResOperand X;
454 X.Kind = ImmOperand;
455 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000456 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000457 return X;
458 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000459
Bob Wilsonb9b24222011-01-26 19:44:55 +0000460 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000461 ResOperand X;
462 X.Kind = RegOperand;
463 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000464 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000465 return X;
466 }
Chris Lattner743081d2010-11-04 00:43:46 +0000467 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000468
Devang Patel9bdc5052012-01-10 17:50:43 +0000469 /// AsmVariantID - Target's assembly syntax variant no.
470 int AsmVariantID;
471
David Blaikieba4e00f2014-12-22 21:26:26 +0000472 /// AsmString - The assembly string for this instruction (with variants
473 /// removed), e.g. "movsx $src, $dst".
474 std::string AsmString;
475
Chris Lattnera7a903e2010-11-02 17:34:28 +0000476 /// TheDef - This is the definition of the instruction or InstAlias that this
477 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000478 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000479
Chris Lattner4efe13d2010-11-04 02:11:18 +0000480 /// DefRec - This is the definition that it came from.
481 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000482
Chris Lattnerfecdad62010-11-06 07:14:44 +0000483 const CodeGenInstruction *getResultInst() const {
484 if (DefRec.is<const CodeGenInstruction*>())
485 return DefRec.get<const CodeGenInstruction*>();
486 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
487 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000488
Chris Lattner743081d2010-11-04 00:43:46 +0000489 /// ResOperands - This is the operand list that should be built for the result
490 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000491 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000492
Chris Lattner28ea9b12010-11-02 17:30:52 +0000493 /// Mnemonic - This is the first token of the matched instruction, its
494 /// mnemonic.
495 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000496
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000497 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000498 /// annotated with a class and where in the OperandList they were defined.
499 /// This directly corresponds to the tokenized AsmString after the mnemonic is
500 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000501 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000502
Daniel Dunbareefe8612010-07-19 05:44:09 +0000503 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000504 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000505
Daniel Dunbar71330282009-08-08 05:24:34 +0000506 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000507 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000508 /// function.
509 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000510
Joey Gouly0e76fa72013-09-12 10:28:05 +0000511 /// If this instruction is deprecated in some form.
512 bool HasDeprecation;
513
Tom Stellard74c87c82015-05-26 15:55:50 +0000514 /// If this is an alias, this is use to determine whether or not to using
515 /// the conversion function defined by the instruction's AsmMatchConverter
516 /// or to use the function generated by the alias.
517 bool UseInstAsmMatchConverter;
518
Chris Lattnerad776812010-11-01 05:06:45 +0000519 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000520 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
521 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000522 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000523
David Blaikieba4e00f2014-12-22 21:26:26 +0000524 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000525 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
526 DefRec(Alias.release()),
527 UseInstAsmMatchConverter(
528 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000529 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000530
David Blaikie6e48a812015-08-01 01:08:30 +0000531 // Could remove this and the dtor if PointerUnion supported unique_ptr
532 // elements with a dynamic failure/assertion (like the one below) in the case
533 // where it was copied while being in an owning state.
534 MatchableInfo(const MatchableInfo &RHS)
535 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
536 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
537 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
538 RequiredFeatures(RHS.RequiredFeatures),
539 ConversionFnKind(RHS.ConversionFnKind),
540 HasDeprecation(RHS.HasDeprecation),
541 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
542 assert(!DefRec.is<const CodeGenInstAlias *>());
543 }
544
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000545 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000546 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000547 }
Craig Topperce274892014-11-28 05:01:21 +0000548
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000549 // Two-operand aliases clone from the main matchable, but mark the second
550 // operand as a tied operand of the first for purposes of the assembler.
551 void formTwoOperandAlias(StringRef Constraint);
552
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000553 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000554 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000555 AsmVariantInfo const &Variant,
556 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000557
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000558 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000559 /// and perform a bunch of validity checking.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000560 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000561
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000562 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000563 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000564 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000565 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
566 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
567 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000568 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000569 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000570
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000571 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000572 /// This does not check the suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000573 int findAsmOperandNamed(StringRef N) const {
David Majnemer562e8292016-08-12 00:18:03 +0000574 auto I = find_if(AsmOperands,
575 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000576 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000577 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000578
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000579 void buildInstructionResultOperands();
580 void buildAliasResultOperands();
Chris Lattner743081d2010-11-04 00:43:46 +0000581
Chris Lattnerad776812010-11-01 05:06:45 +0000582 /// operator< - Compare two matchables.
583 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000584 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000585 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
586 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000587
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000588 if (AsmOperands.size() != RHS.AsmOperands.size())
589 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000590
Daniel Dunbard9631912009-08-09 08:23:23 +0000591 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000592 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000593 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
594 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000595 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000596 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000597 return false;
598 }
599
Andrew Trick818f5ac2012-08-29 03:52:57 +0000600 // Give matches that require more features higher precedence. This is useful
601 // because we cannot define AssemblerPredicates with the negation of
602 // processor features. For example, ARM v6 "nop" may be either a HINT or
603 // MOV. With v6, we want to match HINT. The assembler has no way to
604 // predicate MOV under "NoV6", but HINT will always match first because it
605 // requires V6 while MOV does not.
606 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
607 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
608
Daniel Dunbar3239f022009-08-09 04:00:06 +0000609 return false;
610 }
611
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000612 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000613 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000614 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000615 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000616 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000617 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000618 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000619
Daniel Dunbarf573b562009-08-09 06:05:33 +0000620 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000621 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000622 return false;
623
Daniel Dunbare1974092010-01-23 00:26:16 +0000624 // Otherwise, make sure the ordering of the two instructions is unambiguous
625 // by checking that either (a) a token or operand kind discriminates them,
626 // or (b) the ordering among equivalent kinds is consistent.
627
Daniel Dunbarf573b562009-08-09 06:05:33 +0000628 // Tokens and operand kinds are unambiguous (assuming a correct target
629 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000630 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
631 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
632 AsmOperands[i].Class->Kind == ClassInfo::Token)
633 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
634 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000635 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000636
Daniel Dunbarf573b562009-08-09 06:05:33 +0000637 // Otherwise, this operand could commute if all operands are equivalent, or
638 // there is a pair of operands that compare less than and a pair that
639 // compare greater than.
640 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000641 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
642 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000643 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000644 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000645 HasGT = true;
646 }
647
Craig Topper322b67f2016-01-03 07:33:39 +0000648 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000649 }
650
Craig Topper42bd8192014-11-28 03:53:00 +0000651 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000652
Chris Lattner28ea9b12010-11-02 17:30:52 +0000653private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000654 void tokenizeAsmString(AsmMatcherInfo const &Info,
655 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000656 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000657};
658
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000659struct OperandMatchEntry {
660 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000661 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000662 ClassInfo *CI;
663
Craig Topper42bd8192014-11-28 03:53:00 +0000664 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000665 unsigned opMask) {
666 OperandMatchEntry X;
667 X.OperandMask = opMask;
668 X.CI = ci;
669 X.MI = mi;
670 return X;
671 }
672};
673
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000674class AsmMatcherInfo {
675public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000676 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000677 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000678
Daniel Dunbare4318712009-08-11 20:59:47 +0000679 /// The tablegen AsmParser record.
680 Record *AsmParser;
681
Chris Lattnerb80ab362010-11-01 01:37:30 +0000682 /// Target - The target information.
683 CodeGenTarget &Target;
684
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000685 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000686 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000687
Chris Lattnerad776812010-11-01 05:06:45 +0000688 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000689 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000690
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000691 /// Info for custom matching operands by user defined methods.
692 std::vector<OperandMatchEntry> OperandMatchInfo;
693
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000694 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000695 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
696 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000697
Daniel Dunbareefe8612010-07-19 05:44:09 +0000698 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000699 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000700
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000701 /// Map of AsmOperandClass records to their class information.
702 std::map<Record*, ClassInfo*> AsmOperandClasses;
703
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000704private:
705 /// Map of token to class information which has already been constructed.
706 std::map<std::string, ClassInfo*> TokenClasses;
707
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000708 /// Map of RegisterClass records to their class information.
709 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000710
711private:
712 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000713 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000714
715 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000716 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000717 int SubOpIdx);
718 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000719
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000720 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000721 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000722 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000723
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000724 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000725 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000726 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000727
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000728 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000729 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000730 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000731 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000732
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000733public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000734 AsmMatcherInfo(Record *AsmParser,
735 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000736 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000737
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000738 /// Construct the various tables used during matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000739 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000740
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000741 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000742 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000743 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000744
Chris Lattner43690072010-10-30 20:15:02 +0000745 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
746 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000747 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000748 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000749 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000750 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000751 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000752
Chris Lattner89dcb682010-12-15 04:48:22 +0000753 RecordKeeper &getRecords() const {
754 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000755 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000756
757 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000758 return find_if(Classes, [](const ClassInfo &Class) {
759 return Class.IsOptional;
760 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000761 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000762};
763
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000764} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000765
Craig Topper42bd8192014-11-28 03:53:00 +0000766void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000767 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000768
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000769 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000770 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000771 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000772 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000773 }
774}
775
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000776static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000777parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000778 // Split via the '='.
779 std::pair<StringRef, StringRef> Ops = S.split('=');
780 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000781 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000782 // Trim whitespace and the leading '$' on the operand names.
783 size_t start = Ops.first.find_first_of('$');
784 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000785 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000786 Ops.first = Ops.first.slice(start + 1, std::string::npos);
787 size_t end = Ops.first.find_last_of(" \t");
788 Ops.first = Ops.first.slice(0, end);
789 // Now the second operand.
790 start = Ops.second.find_first_of('$');
791 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000792 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000793 Ops.second = Ops.second.slice(start + 1, std::string::npos);
794 end = Ops.second.find_last_of(" \t");
795 Ops.first = Ops.first.slice(0, end);
796 return Ops;
797}
798
799void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
800 // Figure out which operands are aliased and mark them as tied.
801 std::pair<StringRef, StringRef> Ops =
802 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
803
804 // Find the AsmOperands that refer to the operands we're aliasing.
805 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
806 int DstAsmOperand = findAsmOperandNamed(Ops.second);
807 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000808 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000809 "unknown source two-operand alias operand '" + Ops.first +
810 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000811 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000812 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000813 "unknown destination two-operand alias operand '" +
814 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000815
816 // Find the ResOperand that refers to the operand we're aliasing away
817 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000818 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000819 if (Op.Kind == ResOperand::RenderAsmOperand &&
820 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
821 Op.AsmOperandNum = DstAsmOperand;
822 break;
823 }
824 }
825 // Remove the AsmOperand for the alias operand.
826 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
827 // Adjust the ResOperand references to any AsmOperands that followed
828 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000829 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000830 switch(Op.Kind) {
831 default:
832 // Nothing to do for operands that don't reference AsmOperands.
833 break;
834 case ResOperand::RenderAsmOperand:
835 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
836 --Op.AsmOperandNum;
837 break;
838 case ResOperand::TiedOperand:
839 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
840 --Op.TiedOperandNum;
841 break;
842 }
843 }
844}
845
Craig Topper22fa45f2015-09-13 18:01:25 +0000846/// extractSingletonRegisterForAsmOperand - Extract singleton register,
847/// if present, from specified token.
848static void
849extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
850 const AsmMatcherInfo &Info,
851 StringRef RegisterPrefix) {
852 StringRef Tok = Op.Token;
853
854 // If this token is not an isolated token, i.e., it isn't separated from
855 // other tokens (e.g. with whitespace), don't interpret it as a register name.
856 if (!Op.IsIsolatedToken)
857 return;
858
859 if (RegisterPrefix.empty()) {
860 std::string LoweredTok = Tok.lower();
861 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
862 Op.SingletonReg = Reg->TheDef;
863 return;
864 }
865
866 if (!Tok.startswith(RegisterPrefix))
867 return;
868
869 StringRef RegName = Tok.substr(RegisterPrefix.size());
870 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
871 Op.SingletonReg = Reg->TheDef;
872
873 // If there is no register prefix (i.e. "%" in "%eax"), then this may
874 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000875}
876
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000877void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000878 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000879 AsmVariantInfo const &Variant,
880 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000881 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000882 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000883 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
884 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000885
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000886 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000887
Craig Topperfd2c6a32015-12-31 08:18:23 +0000888 // The first token of the instruction is the mnemonic, which must be a
889 // simple string, not a $foo variable or a singleton register.
890 if (AsmOperands.empty())
891 PrintFatalError(TheDef->getLoc(),
892 "Instruction '" + TheDef->getName() + "' has no tokens");
893
894 assert(!AsmOperands[0].Token.empty());
895 if (HasMnemonicFirst) {
896 Mnemonic = AsmOperands[0].Token;
897 if (Mnemonic[0] == '$')
898 PrintFatalError(TheDef->getLoc(),
899 "Invalid instruction mnemonic '" + Mnemonic + "'!");
900
901 // Remove the first operand, it is tracked in the mnemonic field.
902 AsmOperands.erase(AsmOperands.begin());
903 } else if (AsmOperands[0].Token[0] != '$')
904 Mnemonic = AsmOperands[0].Token;
905
Chris Lattnerba465f92010-11-01 04:53:48 +0000906 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000907 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000908 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000909 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000910 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000911
Chris Lattnerba465f92010-11-01 04:53:48 +0000912 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000913 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000914 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000915 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000916 SingletonRegisters.insert(Reg);
917 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000918
919 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
920 if (!DepMask)
921 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
922
923 HasDeprecation =
924 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000925}
926
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000927/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000928void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
929 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000930}
931
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000932/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000933void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
934 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000935 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000936 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000937 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000938 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000939 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000940 char Char = String[i];
941 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
942 if (InTok) {
943 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000944 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000945 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000946 }
947 InTok = true;
948 continue;
949 }
Craig Topperbc22e262015-12-31 05:01:45 +0000950 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
951 if (InTok) {
952 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000953 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000954 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000955 }
Craig Topperbc22e262015-12-31 05:01:45 +0000956 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000957 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000958 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000959 continue;
960 }
Craig Topperbc22e262015-12-31 05:01:45 +0000961 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
962 if (InTok) {
963 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000964 InTok = false;
965 }
966 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000967 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000968 continue;
969 }
Craig Topperbc22e262015-12-31 05:01:45 +0000970
971 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000972 case '\\':
973 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +0000974 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000975 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000976 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000977 }
978 ++i;
979 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +0000980 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000981 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000982 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000983 break;
984
985 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +0000986 if (InTok) {
987 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000988 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000989 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000990 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000991
Colin LeMahieu3d905742015-08-10 19:58:06 +0000992 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +0000993 if (i + 1 == String.size() || String[i + 1] != '{') {
994 Prev = i;
995 break;
996 }
Chris Lattner28ea9b12010-11-02 17:30:52 +0000997
Craig Topperba614322015-12-30 06:00:15 +0000998 size_t EndPos = String.find('}', i);
999 assert(EndPos != StringRef::npos &&
1000 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001001 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001002 Prev = EndPos + 1;
1003 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001004 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001005 break;
1006 }
Craig Topperbc22e262015-12-31 05:01:45 +00001007
Chris Lattner28ea9b12010-11-02 17:30:52 +00001008 default:
1009 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001010 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001011 }
1012 }
1013 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001014 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001015}
1016
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001017bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001018 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001019 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001020 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001021
Chris Lattnerad776812010-11-01 05:06:45 +00001022 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001023 // isCodeGenOnly if they are pseudo instructions.
1024 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001025 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001026 "multiline instruction is not valid for the asmparser, "
1027 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001028
Chris Lattner178f4bb2010-11-01 04:44:29 +00001029 // Remove comments from the asm string. We know that the asmstring only
1030 // has one line.
1031 if (!CommentDelimiter.empty() &&
1032 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001033 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001034 "asmstring for instruction has comment character in it, "
1035 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001036
Chris Lattnerad776812010-11-01 05:06:45 +00001037 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001038 // handle, the target should be refactored to use operands instead of
1039 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001040 //
1041 // Also, check for instructions which reference the operand multiple times;
1042 // this implies a constraint we would not honor.
1043 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001044 for (const AsmOperand &Op : AsmOperands) {
1045 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001046 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001047 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001048 "matchable with operand modifier '" + Tok +
1049 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001050
Chris Lattnerad776812010-11-01 05:06:45 +00001051 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001052 // We reject aliases and ignore instructions for now.
Chris Lattner28ea9b12010-11-02 17:30:52 +00001053 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattnerad776812010-11-01 05:06:45 +00001054 if (!Hack)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001055 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001056 "ERROR: matchable with tied operand '" + Tok +
1057 "' can never be matched!");
Chris Lattnerad776812010-11-01 05:06:45 +00001058 // FIXME: Should reject these. The ARM backend hits this with $lane in a
1059 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001060 DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001061 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001062 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001063 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001064 });
1065 return false;
1066 }
1067 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001068
Chris Lattner39bc53b2010-11-01 04:34:44 +00001069 return true;
1070}
1071
Chris Lattner60db0a62010-02-09 00:34:28 +00001072static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001073 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001074
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001075 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1076 switch (*it) {
1077 case '*': Res += "_STAR_"; break;
1078 case '%': Res += "_PCT_"; break;
1079 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001080 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001081 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001082 case '<': Res += "_LT_"; break;
1083 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001084 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001085 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001086 if ((*it >= 'A' && *it <= 'Z') ||
1087 (*it >= 'a' && *it <= 'z') ||
1088 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001089 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001090 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001091 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001092 }
1093 }
1094
1095 return Res;
1096}
1097
Chris Lattner60db0a62010-02-09 00:34:28 +00001098ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001099 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001100
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001101 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001102 Classes.emplace_front();
1103 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001104 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001105 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001106 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1107 Entry->ValueName = Token;
1108 Entry->PredicateMethod = "<invalid>";
1109 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001110 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001111 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001112 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001113 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001114 }
1115
1116 return Entry;
1117}
1118
1119ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001120AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1121 int SubOpIdx) {
1122 Record *Rec = OI.Rec;
1123 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001124 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001125 return getOperandClass(Rec, SubOpIdx);
1126}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001127
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001128ClassInfo *
1129AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001130 if (Rec->isSubClassOf("RegisterOperand")) {
1131 // RegisterOperand may have an associated ParserMatchClass. If it does,
1132 // use it, else just fall back to the underlying register class.
1133 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001134 if (!R || !R->getValue())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001135 PrintFatalError("Record `" + Rec->getName() +
1136 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001137
Sean Silvafb509ed2012-10-10 20:24:43 +00001138 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001139 Record *MatchClass = DI->getDef();
1140 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1141 return CI;
1142 }
1143
1144 // No custom match class. Just use the register class.
1145 Record *ClassRec = Rec->getValueAsDef("RegClass");
1146 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001147 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001148 "' has no associated register class!\n");
1149 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1150 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001151 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001152 }
1153
Bob Wilsonb9b24222011-01-26 19:44:55 +00001154 if (Rec->isSubClassOf("RegisterClass")) {
1155 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001156 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001157 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001158 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001159
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001160 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001161 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001162 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001163 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001164 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1165 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001166
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001167 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001168}
1169
Tim Northoverc74e6912013-09-16 16:43:19 +00001170struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001171 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001172 // std::set<T> defines its own compariso "operator<", but it
1173 // performs a lexicographical comparison by T's innate comparison
1174 // for some reason. We don't want non-deterministic pointer
1175 // comparisons so use this instead.
1176 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1177 RHS.begin(), RHS.end(),
1178 LessRecordByID());
1179 }
1180};
1181
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001182void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001183buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001184 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001185 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001186
Tim Northoverc74e6912013-09-16 16:43:19 +00001187 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1188
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001189 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001190 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001191
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001192 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001193 for (const CodeGenRegisterClass &RC : RegClassList)
1194 RegisterSets.insert(
1195 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001196
1197 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001198 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001199 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001200 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001201
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001202 // Introduce derived sets where necessary (when a register does not determine
1203 // a unique register set class), and build the mapping of registers to the set
1204 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001205 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001206 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001207 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001208 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001209
Craig Topper03ec8012014-11-25 20:11:31 +00001210 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001211 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001212 continue;
1213
1214 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001215 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001216 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001217 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001218
Tim Northoverc74e6912013-09-16 16:43:19 +00001219 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001220 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001221 std::insert_iterator<RegisterSet> II(ContainingSet,
1222 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001223 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001224 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001225 }
1226
1227 if (!ContainingSet.empty()) {
1228 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001229 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001230 }
1231 }
1232
1233 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001234 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001235 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001236 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001237 Classes.emplace_front();
1238 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001239 CI->Kind = ClassInfo::RegisterClass0 + Index;
1240 CI->ClassName = "Reg" + utostr(Index);
1241 CI->Name = "MCK_Reg" + utostr(Index);
1242 CI->ValueName = "";
1243 CI->PredicateMethod = ""; // unused
1244 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001245 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001246 // FIXME: diagnostic type.
1247 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001248 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001249 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001250 RegisterSetClasses.insert(std::make_pair(RS, CI));
1251 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001252 }
1253
1254 // Find the superclasses; we could compute only the subgroup lattice edges,
1255 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001256 for (const RegisterSet &RS : RegisterSets) {
1257 ClassInfo *CI = RegisterSetClasses[RS];
1258 for (const RegisterSet &RS2 : RegisterSets)
1259 if (RS != RS2 &&
1260 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001261 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001262 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001263 }
1264
1265 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001266 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001267 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001268 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001269 if (!Def)
1270 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001271 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1272 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001273 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001274 CI->ClassName = RC.getName();
1275 CI->Name = "MCK_" + RC.getName();
1276 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001277 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001278 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001279
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001280 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001281 }
1282
1283 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001284 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001285 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001286 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001287
1288 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001289 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001290 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001291 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001292
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001293 if (CI->ValueName.empty()) {
1294 CI->ClassName = Rec->getName();
Matthias Braun4a86d452016-12-04 05:48:16 +00001295 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001296 CI->ValueName = Rec->getName();
1297 } else
Matthias Braun4a86d452016-12-04 05:48:16 +00001298 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001299 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001300}
1301
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001302void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001303 std::vector<Record*> AsmOperands =
1304 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001305
1306 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001307 for (Record *Rec : AsmOperands) {
1308 Classes.emplace_front();
1309 AsmOperandClasses[Rec] = &Classes.front();
1310 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001311
Daniel Dunbar17410a42009-08-10 18:41:10 +00001312 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001313 for (Record *Rec : AsmOperands) {
1314 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001315 CI->Kind = ClassInfo::UserClass0 + Index;
1316
Craig Topper03ec8012014-11-25 20:11:31 +00001317 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001318 for (Init *I : Supers->getValues()) {
1319 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001320 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001321 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001322 continue;
1323 }
1324
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001325 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1326 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001327 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001328 else
1329 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001330 }
Craig Topper03ec8012014-11-25 20:11:31 +00001331 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001332 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001333 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001334
1335 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001336 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001337 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001338 CI->PredicateMethod = SI->getValue();
1339 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001340 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001341 CI->PredicateMethod = "is" + CI->ClassName;
1342 }
1343
1344 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001345 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001346 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001347 CI->RenderMethod = SI->getValue();
1348 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001349 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001350 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1351 }
1352
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001353 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001354 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001355 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001356 CI->ParserMethod = SI->getValue();
1357
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001358 // Get the diagnostic type or leave it as empty.
1359 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001360 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001361 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001362 CI->DiagnosticType = SI->getValue();
1363
Tom Stellardb9f235e2016-02-05 19:59:33 +00001364 Init *IsOptional = Rec->getValueInit("IsOptional");
1365 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1366 CI->IsOptional = BI->getValue();
1367
Sam Kolton5f10a132016-05-06 11:31:17 +00001368 // Get or construct the default method name.
1369 Init *DMName = Rec->getValueInit("DefaultMethod");
1370 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1371 CI->DefaultMethod = SI->getValue();
1372 } else {
1373 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1374 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1375 }
1376
Craig Topper03ec8012014-11-25 20:11:31 +00001377 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001378 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001379}
1380
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001381AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1382 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001383 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001384 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001385}
1386
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001387/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001388/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001389void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001390
Jim Grosbach925a6d02012-04-18 23:46:25 +00001391 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001392 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001393 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001394 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001395
Craig Topperf34dad92014-11-28 03:53:02 +00001396 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001397 OpClassMask.clear();
1398
1399 // Keep track of all operands of this instructions which belong to the
1400 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001401 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1402 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001403 if (Op.Class->ParserMethod.empty())
1404 continue;
1405 unsigned &OperandMask = OpClassMask[Op.Class];
1406 OperandMask |= (1 << i);
1407 }
1408
1409 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001410 for (const auto &OCM : OpClassMask) {
1411 unsigned OpMask = OCM.second;
1412 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001413 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1414 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001415 }
1416 }
1417}
1418
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001419void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001420 // Build information about all of the AssemblerPredicates.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001421 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1422 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1423 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1424 SubtargetFeaturePairs.end());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001425#ifndef NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001426 for (const auto &Pair : SubtargetFeatures)
1427 DEBUG(Pair.second.dump());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001428#endif // NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001429 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001430
Craig Topperfd2c6a32015-12-31 08:18:23 +00001431 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1432
Chris Lattner33fc3e02010-10-31 19:10:56 +00001433 // Parse the instructions; we need to do this first so that we can gather the
1434 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001435 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001436 unsigned VariantCount = Target.getAsmParserVariantCount();
1437 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1438 Record *AsmVariant = Target.getAsmParserVariant(VC);
Jim Grosbach56e63262012-04-17 00:01:04 +00001439 std::string CommentDelimiter =
1440 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001441 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001442 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001443 Variant.TokenizingCharacters =
1444 AsmVariant->getValueAsString("TokenizingCharacters");
1445 Variant.SeparatorCharacters =
1446 AsmVariant->getValueAsString("SeparatorCharacters");
1447 Variant.BreakCharacters =
1448 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001449 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001450 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001451
Craig Topper8cc904d2016-01-17 20:38:18 +00001452 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001453
Devang Patel85d684a2012-01-09 19:13:28 +00001454 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1455 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001456 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001457 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001458
Devang Patel85d684a2012-01-09 19:13:28 +00001459 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001460 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001461 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001462
Sam Kolton1b746d12016-09-08 15:50:52 +00001463 // Ignore instructions for different instructions
1464 const std::string V = CGI->TheDef->getValueAsString("AsmVariantName");
1465 if (!V.empty() && V != Variant.Name)
1466 continue;
1467
Craig Topper1c8fbd22015-09-06 03:44:50 +00001468 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001469
Craig Topperfd2c6a32015-12-31 08:18:23 +00001470 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001471
Devang Patel85d684a2012-01-09 19:13:28 +00001472 // Ignore instructions which shouldn't be matched and diagnose invalid
1473 // instruction definitions with an error.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001474 if (!II->validate(CommentDelimiter, true))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001475 continue;
1476
1477 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001478 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001479
Devang Patel85d684a2012-01-09 19:13:28 +00001480 // Parse all of the InstAlias definitions and stick them in the list of
1481 // matchables.
1482 std::vector<Record*> AllInstAliases =
1483 Records.getAllDerivedDefinitions("InstAlias");
1484 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001485 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001486 Variant.AsmVariantNo,
1487 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001488
Devang Patel85d684a2012-01-09 19:13:28 +00001489 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1490 // filter the set of instruction aliases we consider, based on the target
1491 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001492 if (!StringRef(Alias->ResultInst->TheDef->getName())
1493 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001494 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001495
Sam Kolton1b746d12016-09-08 15:50:52 +00001496 const std::string V = Alias->TheDef->getValueAsString("AsmVariantName");
1497 if (!V.empty() && V != Variant.Name)
1498 continue;
1499
Craig Topper1c8fbd22015-09-06 03:44:50 +00001500 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001501
Craig Topperfd2c6a32015-12-31 08:18:23 +00001502 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001503
Devang Patel85d684a2012-01-09 19:13:28 +00001504 // Validate the alias definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001505 II->validate(CommentDelimiter, false);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001506
1507 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001508 }
Chris Lattner488c2012010-11-01 04:05:41 +00001509 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001510
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001511 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001512 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001513
1514 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001515 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001516
Chris Lattner4779e3e92010-11-04 00:57:06 +00001517 // Build the information about matchables, now that we have fully formed
1518 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001519 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001520 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001521 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001522 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001523 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001524 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1525 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001526 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001527
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001528 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001529 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001530 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001531 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1532 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001533 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001534 }
1535
Daniel Dunbare10787e2009-08-07 08:26:05 +00001536 // Check for simple tokens.
1537 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001538 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001539 continue;
1540 }
1541
Chris Lattnerd6746d52010-11-06 22:06:03 +00001542 if (Token.size() > 1 && isdigit(Token[1])) {
1543 Op.Class = getTokenClass(Token);
1544 continue;
1545 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001546
Chris Lattner4efe13d2010-11-04 02:11:18 +00001547 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001548 StringRef OperandName;
1549 if (Token[1] == '{')
1550 OperandName = Token.substr(2, Token.size() - 3);
1551 else
1552 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001553
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001554 if (II->DefRec.is<const CodeGenInstruction*>())
1555 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001556 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001557 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001558 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001559
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001560 if (II->DefRec.is<const CodeGenInstruction*>()) {
1561 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001562 // If the instruction has a two-operand alias, build up the
1563 // matchable here. We'll add them in bulk at the end to avoid
1564 // confusing this loop.
1565 std::string Constraint =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001566 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001567 if (Constraint != "") {
1568 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001569 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001570
1571 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001572 AliasII->formTwoOperandAlias(Constraint);
1573
1574 // Add the alias to the matchables list.
1575 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001576 }
1577 } else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001578 II->buildAliasResultOperands();
Daniel Dunbare10787e2009-08-07 08:26:05 +00001579 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001580 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001581 Matchables.insert(Matchables.end(),
1582 std::make_move_iterator(NewMatchables.begin()),
1583 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001584
Jim Grosbachba395922011-12-06 23:43:54 +00001585 // Process token alias definitions and set up the associated superclass
1586 // information.
1587 std::vector<Record*> AllTokenAliases =
1588 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001589 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001590 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1591 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001592 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001593 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001594 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001595 FromClass->SuperClasses.push_back(ToClass);
1596 }
1597
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001598 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001599 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001600
Matthias Brauna8eed312016-12-05 19:44:31 +00001601#ifdef EXPENSIVE_CHECKS
1602 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard7772f022016-01-25 10:20:19 +00001603 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1604 for (auto J = I; J != E; ++J) {
1605 assert(!(*J < *I));
1606 assert(I == J || !J->isSubsetOf(*I));
1607 }
1608 }
Matthias Brauna8eed312016-12-05 19:44:31 +00001609#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +00001610}
1611
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001612/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001613/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1614void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001615buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001616 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001617 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001618 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1619 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001620 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001621
Chris Lattnerfecdad62010-11-06 07:14:44 +00001622 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001623 unsigned Idx;
1624 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001625 PrintFatalError(II->TheDef->getLoc(),
1626 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001627
Bob Wilsonb9b24222011-01-26 19:44:55 +00001628 // If the instruction operand has multiple suboperands, but the parser
1629 // match class for the asm operand is still the default "ImmAsmOperand",
1630 // then handle each suboperand separately.
1631 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1632 Record *Rec = Operands[Idx].Rec;
1633 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1634 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1635 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1636 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1637 StringRef Token = Op->Token; // save this in case Op gets moved
1638 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001639 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001640 NewAsmOp.SubOpIdx = SI;
1641 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1642 }
1643 // Replace Op with first suboperand.
1644 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1645 Op->SubOpIdx = 0;
1646 }
1647 }
1648
Chris Lattner897a1402010-11-04 01:55:23 +00001649 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001650 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattner897a1402010-11-04 01:55:23 +00001651
1652 // If the named operand is tied, canonicalize it to the untied operand.
1653 // For example, something like:
1654 // (outs GPR:$dst), (ins GPR:$src)
1655 // with an asmstring of
1656 // "inc $src"
1657 // we want to canonicalize to:
1658 // "inc $dst"
1659 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001660 int OITied = -1;
1661 if (Operands[Idx].MINumOperands == 1)
1662 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001663 if (OITied != -1) {
1664 // The tied operand index is an MIOperand index, find the operand that
1665 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001666 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1667 OperandName = Operands[Idx.first].Name;
1668 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001669 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001670
Bob Wilsonb9b24222011-01-26 19:44:55 +00001671 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001672}
1673
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001674/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001675/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1676/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001677void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001678 StringRef OperandName,
1679 MatchableInfo::AsmOperand &Op) {
1680 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001681
Chris Lattner4efe13d2010-11-04 02:11:18 +00001682 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001683 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001684 if (CGA.ResultOperands[i].isRecord() &&
1685 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001686 // It's safe to go with the first one we find, because CodeGenInstAlias
1687 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001688 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001689 // Use the match class from the Alias definition, not the
1690 // destination instruction, as we may have an immediate that's
1691 // being munged by the match class.
1692 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001693 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001694 Op.SrcOpName = OperandName;
1695 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001696 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001697
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001698 PrintFatalError(II->TheDef->getLoc(),
1699 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001700}
1701
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001702void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001703 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001704
Chris Lattnerfecdad62010-11-06 07:14:44 +00001705 // Loop over all operands of the result instruction, determining how to
1706 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001707 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001708 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001709 int TiedOp = -1;
1710 if (OpInfo.MINumOperands == 1)
1711 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001712 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001713 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner7108dad2010-11-04 01:42:59 +00001714 continue;
1715 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001716
Bob Wilsonb9b24222011-01-26 19:44:55 +00001717 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001718 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001719 if (OpInfo.Name.empty() || SrcOperand == -1) {
1720 // This may happen for operands that are tied to a suboperand of a
1721 // complex operand. Simply use a dummy value here; nobody should
1722 // use this operand slot.
1723 // FIXME: The long term goal is for the MCOperand list to not contain
1724 // tied operands at all.
1725 ResOperands.push_back(ResOperand::getImmOp(0));
1726 continue;
1727 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001728
Bob Wilsonb9b24222011-01-26 19:44:55 +00001729 // Check if the one AsmOperand populates the entire operand.
1730 unsigned NumOperands = OpInfo.MINumOperands;
1731 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1732 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001733 continue;
1734 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001735
1736 // Add a separate ResOperand for each suboperand.
1737 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1738 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1739 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1740 "unexpected AsmOperands for suboperands");
1741 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1742 }
Chris Lattner743081d2010-11-04 00:43:46 +00001743 }
1744}
1745
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001746void MatchableInfo::buildAliasResultOperands() {
Chris Lattner8188fb22010-11-06 07:31:43 +00001747 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1748 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001749
Chris Lattner8188fb22010-11-06 07:31:43 +00001750 // Loop over all operands of the result instruction, determining how to
1751 // populate them.
1752 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001753 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001754 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001755 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001756
Chris Lattner8188fb22010-11-06 07:31:43 +00001757 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001758 int TiedOp = -1;
1759 if (OpInfo->MINumOperands == 1)
1760 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001761 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001762 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner4869d342010-11-06 19:57:21 +00001763 continue;
1764 }
1765
Bob Wilsonb9b24222011-01-26 19:44:55 +00001766 // Handle all the suboperands for this operand.
1767 const std::string &OpName = OpInfo->Name;
1768 for ( ; AliasOpNo < LastOpNo &&
1769 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1770 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1771
1772 // Find out what operand from the asmparser that this MCInst operand
1773 // comes from.
1774 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001775 case CodeGenInstAlias::ResultOperand::K_Record: {
1776 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001777 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001778 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001779 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001780 TheDef->getName() + "' has operand '" + OpName +
1781 "' that doesn't appear in asm string!");
1782 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1783 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1784 NumOperands));
1785 break;
1786 }
1787 case CodeGenInstAlias::ResultOperand::K_Imm: {
1788 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1789 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1790 break;
1791 }
1792 case CodeGenInstAlias::ResultOperand::K_Reg: {
1793 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1794 ResOperands.push_back(ResOperand::getRegOp(Reg));
1795 break;
1796 }
1797 }
Chris Lattner4869d342010-11-06 19:57:21 +00001798 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001799 }
1800}
Chris Lattner743081d2010-11-04 00:43:46 +00001801
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001802static unsigned
1803getConverterOperandID(const std::string &Name,
1804 SmallSetVector<CachedHashString, 16> &Table,
1805 bool &IsNew) {
1806 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001807
David Majnemer0d955d02016-08-11 22:21:41 +00001808 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001809
1810 assert(ID < Table.size());
1811
1812 return ID;
1813}
1814
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001815static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001816 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Kolton5f10a132016-05-06 11:31:17 +00001817 bool HasMnemonicFirst, bool HasOptionalOperands,
1818 raw_ostream &OS) {
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001819 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1820 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001821 std::vector<std::vector<uint8_t> > ConversionTable;
1822 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001823
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001824 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun4a86d452016-12-04 05:48:16 +00001825 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001826
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001827 // Write the convert function to a separate stream, so we can drop it after
1828 // the enum. We'll build up the conversion handlers for the individual
1829 // operand types opportunistically as we encounter them.
1830 std::string ConvertFnBody;
1831 raw_string_ostream CvtOS(ConvertFnBody);
1832 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001833 if (HasOptionalOperands) {
1834 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1835 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1836 << "unsigned Opcode,\n"
1837 << " const OperandVector &Operands,\n"
1838 << " const SmallBitVector &OptionalOperandsMask) {\n";
1839 } else {
1840 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1841 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1842 << "unsigned Opcode,\n"
1843 << " const OperandVector &Operands) {\n";
1844 }
1845 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1846 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1847 if (HasOptionalOperands) {
1848 CvtOS << " unsigned NumDefaults = 0;\n";
1849 }
1850 CvtOS << " unsigned OpIdx;\n";
1851 CvtOS << " Inst.setOpcode(Opcode);\n";
1852 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1853 if (HasOptionalOperands) {
1854 CvtOS << " OpIdx = *(p + 1) - NumDefaults;\n";
1855 } else {
1856 CvtOS << " OpIdx = *(p + 1);\n";
1857 }
1858 CvtOS << " switch (*p) {\n";
1859 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1860 CvtOS << " case CVT_Reg:\n";
1861 CvtOS << " static_cast<" << TargetOperandClass
1862 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1863 CvtOS << " break;\n";
1864 CvtOS << " case CVT_Tied:\n";
1865 CvtOS << " Inst.addOperand(Inst.getOperand(OpIdx));\n";
1866 CvtOS << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001867
Chad Rosier738ea252012-08-30 17:59:25 +00001868 std::string OperandFnBody;
1869 raw_string_ostream OpOS(OperandFnBody);
1870 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001871 OpOS << "void " << Target.getName() << ClassName << "::\n"
1872 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00001873 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00001874 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001875 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001876 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00001877 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1878 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001879 << " switch (*p) {\n"
1880 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1881 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001882 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00001883 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001884 << " ++NumMCOperands;\n"
1885 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001886 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001887 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001888 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001889
1890 // Pre-populate the operand conversion kinds with the standard always
1891 // available entries.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001892 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
1893 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
1894 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001895 enum { CVT_Done, CVT_Reg, CVT_Tied };
1896
Craig Topperf34dad92014-11-28 03:53:02 +00001897 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001898 // Check if we have a custom match function.
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001899 std::string AsmMatchConverter =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001900 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00001901 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001902 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001903 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001904
1905 // Check if we have already generated this signature.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001906 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001907 continue;
1908
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001909 // Remember this converter for the kind enum.
1910 unsigned KindID = OperandConversionKinds.size();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001911 OperandConversionKinds.insert(
1912 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001913
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001914 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001915 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001916 ConversionTable.back().push_back(KindID);
1917 ConversionTable.back().push_back(CVT_Done);
1918
1919 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00001920 CvtOS << " case CVT_"
1921 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00001922 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001923 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001924
Chad Rosier738ea252012-08-30 17:59:25 +00001925 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001926 continue;
1927 }
1928
Daniel Dunbare10787e2009-08-07 08:26:05 +00001929 // Build the conversion function signature.
1930 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001931
1932 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001933
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00001934 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001935 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001936
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001937 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
1938 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001939
Chris Lattner743081d2010-11-04 00:43:46 +00001940 // Generate code to populate each result operand.
1941 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00001942 case MatchableInfo::ResOperand::RenderAsmOperand: {
1943 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00001944 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001945 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001946
Chris Lattnere032dbf2010-11-02 22:55:03 +00001947 // Registers are always converted the same, don't duplicate the
1948 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00001949 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001950 std::string Class;
1951 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1952 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001953 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00001954 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001955
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001956 // Add the conversion kind, if necessary, and get the associated ID
1957 // the index of its entry in the vector).
1958 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1959 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00001960 if (Op.Class->IsOptional) {
1961 // For optional operands we must also care about DefaultMethod
1962 assert(HasOptionalOperands);
1963 Name += "_" + Op.Class->DefaultMethod;
1964 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00001965 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001966
1967 bool IsNewConverter = false;
1968 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1969 IsNewConverter);
1970
1971 // Add the operand entry to the instruction kind conversion row.
1972 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00001973 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001974
1975 if (!IsNewConverter)
1976 break;
1977
1978 // This is a new operand kind. Add a handler for it to the
1979 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00001980 CvtOS << " case " << Name << ":\n";
1981 if (Op.Class->IsOptional) {
1982 // If optional operand is not present in actual instruction then we
1983 // should call its DefaultMethod before RenderMethod
1984 assert(HasOptionalOperands);
1985 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
1986 << " " << Op.Class->DefaultMethod << "()"
1987 << "->" << Op.Class->RenderMethod << "(Inst, "
1988 << OpInfo.MINumOperands << ");\n"
1989 << " ++NumDefaults;\n"
1990 << " } else {\n"
1991 << " static_cast<" << TargetOperandClass
1992 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
1993 << "(Inst, " << OpInfo.MINumOperands << ");\n"
1994 << " }\n";
1995 } else {
1996 CvtOS << " static_cast<" << TargetOperandClass
1997 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
1998 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1999 }
2000 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002001
2002 // Add a handler for the operand number lookup.
2003 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002004 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2005
2006 if (Op.Class->isRegisterClass())
2007 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2008 else
2009 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2010 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002011 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002012 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002013 }
Chris Lattner743081d2010-11-04 00:43:46 +00002014 case MatchableInfo::ResOperand::TiedOperand: {
2015 // If this operand is tied to a previous one, just copy the MCInst
2016 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002017 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner743081d2010-11-04 00:43:46 +00002018 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002019 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner743081d2010-11-04 00:43:46 +00002020 Signature += "__Tie" + utostr(TiedOp);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002021 ConversionRow.push_back(CVT_Tied);
2022 ConversionRow.push_back(TiedOp);
Chris Lattner743081d2010-11-04 00:43:46 +00002023 break;
2024 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002025 case MatchableInfo::ResOperand::ImmOperand: {
2026 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002027 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002028 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002029 Signature += "__" + Ty;
2030
2031 std::string Name = "CVT_" + Ty;
2032 bool IsNewConverter = false;
2033 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2034 IsNewConverter);
2035 // Add the operand entry to the instruction kind conversion row.
2036 ConversionRow.push_back(ID);
2037 ConversionRow.push_back(0);
2038
2039 if (!IsNewConverter)
2040 break;
2041
2042 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002043 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002044 << " break;\n";
2045
Chad Rosier738ea252012-08-30 17:59:25 +00002046 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002047 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2048 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002049 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002050 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002051 break;
2052 }
Chris Lattner4869d342010-11-06 19:57:21 +00002053 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002054 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002055 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002056 Name = "reg0";
2057 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002058 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002059 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun4a86d452016-12-04 05:48:16 +00002060 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilson03912ab2011-01-14 22:58:09 +00002061 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002062 Signature += "__" + Name;
2063 Name = "CVT_" + Name;
2064 bool IsNewConverter = false;
2065 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2066 IsNewConverter);
2067 // Add the operand entry to the instruction kind conversion row.
2068 ConversionRow.push_back(ID);
2069 ConversionRow.push_back(0);
2070
2071 if (!IsNewConverter)
2072 break;
2073 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002074 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002075 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002076
2077 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002078 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2079 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002080 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002081 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002082 }
Chris Lattner743081d2010-11-04 00:43:46 +00002083 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002084 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002085
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002086 // If there were no operands, add to the signature to that effect
2087 if (Signature == "Convert")
2088 Signature += "_NoOperands";
2089
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002090 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002091
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002092 // Save the signature. If we already have it, don't add a new row
2093 // to the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002094 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002095 continue;
2096
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002097 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002098 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002099 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002100
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002101 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002102 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002103
Chad Rosier738ea252012-08-30 17:59:25 +00002104 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002105 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002106
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002107 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002108
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002109 // Output the operand conversion kind enum.
2110 OS << "enum OperatorConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002111 for (const auto &Converter : OperandConversionKinds)
Craig Topper6e526f12016-01-03 07:33:30 +00002112 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002113 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002114 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002115
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002116 // Output the instruction conversion kind enum.
2117 OS << "enum InstructionConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002118 for (const auto &Signature : InstructionConversionKinds)
Craig Topper802d3d32015-08-16 21:27:10 +00002119 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002120 OS << " CVT_NUM_SIGNATURES\n";
2121 OS << "};\n\n";
2122
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002123 OS << "} // end anonymous namespace\n\n";
2124
2125 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002126 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002127 << MaxRowLength << "] = {\n";
2128
2129 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2130 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2131 OS << " // " << InstructionConversionKinds[Row] << "\n";
2132 OS << " { ";
2133 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
2134 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
2135 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2136 OS << "CVT_Done },\n";
2137 }
2138
2139 OS << "};\n\n";
2140
2141 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002142 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002143
Chad Rosier738ea252012-08-30 17:59:25 +00002144 // Spit out the operand number lookup function.
2145 OS << OpOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002146}
2147
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002148/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2149static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002150 std::forward_list<ClassInfo> &Infos,
2151 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002152 OS << "namespace {\n\n";
2153
2154 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2155 << "/// instruction matching.\n";
2156 OS << "enum MatchClassKind {\n";
2157 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002158 OS << " OptionalMatchClass = 1,\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002159 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002160 OS << " " << CI.Name << ", // ";
2161 if (CI.Kind == ClassInfo::Token) {
2162 OS << "'" << CI.ValueName << "'\n";
2163 } else if (CI.isRegisterClass()) {
2164 if (!CI.ValueName.empty())
2165 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002166 else
2167 OS << "derived register class\n";
2168 } else {
David Blaikied749e342014-11-28 20:35:57 +00002169 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002170 }
2171 }
2172 OS << " NumMatchClassKinds\n";
2173 OS << "};\n\n";
2174
2175 OS << "}\n\n";
2176}
2177
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002178/// emitValidateOperandClass - Emit the function to validate an operand class.
2179static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002180 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002181 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002182 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002183 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2184 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002185
Kevin Enderby1b87c802011-07-15 18:30:43 +00002186 // The InvalidMatchClass is not to match any operand.
2187 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002188 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002189
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002190 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002191 // FIXME: Use a more specific diagnostic type.
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002192 OS << " if (Operand.isToken())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002193 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2194 << " MCTargetAsmParser::Match_Success :\n"
2195 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002196
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002197 // Check the user classes. We don't care what order since we're only
2198 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002199 OS << " switch (Kind) {\n"
2200 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002201 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002202 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002203 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002204
David Blaikied749e342014-11-28 20:35:57 +00002205 OS << " // '" << CI.ClassName << "' class\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002206 OS << " case " << CI.Name << ":\n";
David Blaikied749e342014-11-28 20:35:57 +00002207 OS << " if (Operand." << CI.PredicateMethod << "())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002208 OS << " return MCTargetAsmParser::Match_Success;\n";
David Blaikied749e342014-11-28 20:35:57 +00002209 if (!CI.DiagnosticType.empty())
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002210 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002211 << CI.DiagnosticType << ";\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002212 else
2213 OS << " break;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002214 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002215 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002216
Owen Anderson8a503f22012-07-16 23:20:09 +00002217 // Check for register operands, including sub-classes.
2218 OS << " if (Operand.isReg()) {\n";
2219 OS << " MatchClassKind OpKind;\n";
2220 OS << " switch (Operand.getReg()) {\n";
2221 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002222 for (const auto &RC : Info.RegisterClasses)
Owen Anderson8a503f22012-07-16 23:20:09 +00002223 OS << " case " << Info.Target.getName() << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002224 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002225 << "; break;\n";
2226 OS << " }\n";
2227 OS << " return isSubclass(OpKind, Kind) ? "
2228 << "MCTargetAsmParser::Match_Success :\n "
2229 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
2230
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002231 // Generic fallthrough match failure case for operands that don't have
2232 // specialized diagnostic types.
2233 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002234 OS << "}\n\n";
2235}
2236
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002237/// emitIsSubclass - Emit the subclass predicate function.
2238static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002239 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002240 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002241 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002242 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002243 OS << " if (A == B)\n";
2244 OS << " return true;\n\n";
2245
Craig Topper39311c72015-12-30 06:00:22 +00002246 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002247 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002248 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002249 if (A.IsOptional)
2250 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002251 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002252 if (&A != &B && A.isSubsetOf(B))
2253 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002254 }
Jim Grosbachba395922011-12-06 23:43:54 +00002255
2256 if (SuperClasses.empty())
2257 continue;
2258
Craig Topper39311c72015-12-30 06:00:22 +00002259 // If this is the first SuperClass, emit the switch header.
2260 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002261 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002262 OS << " default:\n";
2263 OS << " return false;\n";
2264 EmittedSwitch = true;
2265 }
2266
2267 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002268
2269 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002270 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002271 continue;
2272 }
2273
Aaron Ballmane59e3582013-07-15 16:53:32 +00002274 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002275 OS << " switch (B) {\n";
2276 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002277 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002278 OS << " case " << SC << ": return true;\n";
2279 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002280 } else {
2281 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002282 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002283 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002284 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002285
Craig Topper39311c72015-12-30 06:00:22 +00002286 // If there were case statements emitted into the string stream write the
2287 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002288 if (EmittedSwitch)
2289 OS << " }\n";
2290 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002291 OS << " return false;\n";
2292
Daniel Dunbar2587b612009-08-10 16:05:47 +00002293 OS << "}\n\n";
2294}
2295
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002296/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002297/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002298static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002299 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002300 raw_ostream &OS) {
2301 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002302 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002303 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002304 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002305 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002306 }
2307
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002308 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002309
Chris Lattnerca5a3552010-09-06 02:01:51 +00002310 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002311
2312 OS << " return InvalidMatchClass;\n";
2313 OS << "}\n\n";
2314}
Chris Lattner00e2e742009-08-08 20:02:57 +00002315
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002316/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002317/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002318static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002319 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002320 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002321 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002322 const auto &Regs = Target.getRegBank().getRegisters();
2323 for (const CodeGenRegister &Reg : Regs) {
2324 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002325 continue;
2326
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002327 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2328 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002329 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002330
Chris Lattner60db0a62010-02-09 00:34:28 +00002331 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002332
Chris Lattnerca5a3552010-09-06 02:01:51 +00002333 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002334
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002335 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002336 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002337}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002338
Dylan McKaybff960a2016-02-03 10:30:16 +00002339/// Emit the function to match a string to the target
2340/// specific register enum.
2341static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2342 raw_ostream &OS) {
2343 // Construct the match list.
2344 std::vector<StringMatcher::StringPair> Matches;
2345 const auto &Regs = Target.getRegBank().getRegisters();
2346 for (const CodeGenRegister &Reg : Regs) {
2347
2348 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2349
2350 for (auto AltName : AltNames) {
2351 AltName = StringRef(AltName).trim();
2352
2353 // don't handle empty alternative names
2354 if (AltName.empty())
2355 continue;
2356
2357 Matches.emplace_back(AltName,
2358 "return " + utostr(Reg.EnumValue) + ";");
2359 }
2360 }
2361
2362 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2363
2364 StringMatcher("Name", Matches, OS).Emit();
2365
2366 OS << " return 0;\n";
2367 OS << "}\n\n";
2368}
2369
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002370/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2371static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2372 // Get the set of diagnostic types from all of the operand classes.
2373 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002374 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2375 if (!OpClassEntry.second->DiagnosticType.empty())
2376 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002377 }
2378
2379 if (Types.empty()) return;
2380
2381 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002382 for (StringRef Type : Types)
2383 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002384 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2385}
2386
Jim Grosbach5117ef72012-04-24 22:40:08 +00002387/// emitGetSubtargetFeatureName - Emit the helper function to get the
2388/// user-level name for a subtarget feature.
2389static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2390 OS << "// User-level names for subtarget features that participate in\n"
2391 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002392 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002393 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002394 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002395 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002396 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002397 // FIXME: Totally just a placeholder name to get the algorithm working.
2398 OS << " case " << SFI.getEnumName() << ": return \""
2399 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2400 }
2401 OS << " default: return \"(unknown)\";\n";
2402 OS << " }\n";
2403 } else {
2404 // Nothing to emit, so skip the switch
2405 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002406 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002407 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002408}
2409
Chris Lattner43690072010-10-30 20:15:02 +00002410static std::string GetAliasRequiredFeatures(Record *R,
2411 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002412 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002413 std::string Result;
2414 unsigned NumFeatures = 0;
2415 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002416 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002417
Craig Topper24064772014-04-15 07:20:03 +00002418 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002419 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002420 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002421
Chris Lattner517dc952010-11-01 02:09:21 +00002422 if (NumFeatures)
2423 Result += '|';
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002424
Chris Lattner517dc952010-11-01 02:09:21 +00002425 Result += F->getEnumName();
2426 ++NumFeatures;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002427 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002428
Chris Lattner2cb092d2010-10-30 19:23:13 +00002429 if (NumFeatures > 1)
2430 Result = '(' + Result + ')';
2431 return Result;
2432}
2433
Chad Rosier9f7a2212013-04-18 22:35:36 +00002434static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2435 std::vector<Record*> &Aliases,
2436 unsigned Indent = 0,
2437 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002438 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2439 // iteration order of the map is stable.
2440 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002441
Craig Topper6e526f12016-01-03 07:33:30 +00002442 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002443 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2444 std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2445 if (AsmVariantName != AsmParserVariantName)
2446 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002447 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002448 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002449 if (AliasesFromMnemonic.empty())
2450 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002451
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002452 // Process each alias a "from" mnemonic at a time, building the code executed
2453 // by the string remapper.
2454 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002455 for (const auto &AliasEntry : AliasesFromMnemonic) {
2456 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002457
2458 // Loop through each alias and emit code that handles each case. If there
2459 // are two instructions without predicates, emit an error. If there is one,
2460 // emit it last.
2461 std::string MatchCode;
2462 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002463
Chris Lattner2cb092d2010-10-30 19:23:13 +00002464 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2465 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002466 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002467
Chris Lattner2cb092d2010-10-30 19:23:13 +00002468 // If this unconditionally matches, remember it for later and diagnose
2469 // duplicates.
2470 if (FeatureMask.empty()) {
2471 if (AliasWithNoPredicate != -1) {
2472 // We can't have two aliases from the same mnemonic with no predicate.
2473 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2474 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002475 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002476 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002477
Chris Lattner2cb092d2010-10-30 19:23:13 +00002478 AliasWithNoPredicate = i;
2479 continue;
2480 }
Craig Topper6e526f12016-01-03 07:33:30 +00002481 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002482 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002483
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002484 if (!MatchCode.empty())
2485 MatchCode += "else ";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002486 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002487 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002488 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002489
Chris Lattner2cb092d2010-10-30 19:23:13 +00002490 if (AliasWithNoPredicate != -1) {
2491 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002492 if (!MatchCode.empty())
2493 MatchCode += "else\n ";
2494 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002495 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002496
Chris Lattner2cb092d2010-10-30 19:23:13 +00002497 MatchCode += "return;";
2498
Craig Topper6e526f12016-01-03 07:33:30 +00002499 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002500 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002501 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2502}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002503
Chad Rosier9f7a2212013-04-18 22:35:36 +00002504/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2505/// emit a function for them and return true, otherwise return false.
2506static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2507 CodeGenTarget &Target) {
2508 // Ignore aliases when match-prefix is set.
2509 if (!MatchPrefix.empty())
2510 return false;
2511
2512 std::vector<Record*> Aliases =
2513 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2514 if (Aliases.empty()) return false;
2515
2516 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002517 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002518 OS << " switch (VariantID) {\n";
2519 unsigned VariantCount = Target.getAsmParserVariantCount();
2520 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2521 Record *AsmVariant = Target.getAsmParserVariant(VC);
2522 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2523 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2524 OS << " case " << AsmParserVariantNo << ":\n";
2525 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2526 AsmParserVariantName);
2527 OS << " break;\n";
2528 }
2529 OS << " }\n";
2530
2531 // Emit aliases that apply to all variants.
2532 emitMnemonicAliasVariant(OS, Info, Aliases);
2533
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002534 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002535
Chris Lattner477fba4f2010-10-30 18:48:18 +00002536 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002537}
2538
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002539static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002540 const AsmMatcherInfo &Info, StringRef ClassName,
2541 StringToOffsetTable &StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00002542 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002543 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002544 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2545 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002546 }
2547
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002548 // Emit the static custom operand parsing table;
2549 OS << "namespace {\n";
2550 OS << " struct OperandMatchEntry {\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00002551 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002552 << " RequiredFeatures;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002553 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2554 << " Mnemonic;\n";
David Blaikied749e342014-11-28 20:35:57 +00002555 OS << " " << getMinimalTypeForRange(std::distance(
2556 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002557 OS << " " << getMinimalTypeForRange(MaxMask)
2558 << " OperandMask;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002559 OS << " StringRef getMnemonic() const {\n";
2560 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2561 OS << " MnemonicTable[Mnemonic]);\n";
2562 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002563 OS << " };\n\n";
2564
2565 OS << " // Predicate for searching for an opcode.\n";
2566 OS << " struct LessOpcodeOperand {\n";
2567 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002568 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002569 OS << " }\n";
2570 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002571 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002572 OS << " }\n";
2573 OS << " bool operator()(const OperandMatchEntry &LHS,";
2574 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002575 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002576 OS << " }\n";
2577 OS << " };\n";
2578
2579 OS << "} // end anonymous namespace.\n\n";
2580
2581 OS << "static const OperandMatchEntry OperandMatchTable["
2582 << Info.OperandMatchInfo.size() << "] = {\n";
2583
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002584 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002585 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002586 const MatchableInfo &II = *OMI.MI;
2587
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002588 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002589
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002590 // Write the required features mask.
2591 if (!II.RequiredFeatures.empty()) {
2592 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002593 if (i) OS << "|";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002594 OS << II.RequiredFeatures[i]->getEnumName();
2595 }
2596 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002597 OS << "0";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002598
2599 // Store a pascal-style length byte in the mnemonic.
2600 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2601 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2602 << " /* " << II.Mnemonic << " */, ";
2603
2604 OS << OMI.CI->Name;
2605
2606 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002607 OS << " /* ";
2608 bool printComma = false;
2609 for (int i = 0, e = 31; i !=e; ++i)
2610 if (OMI.OperandMask & (1 << i)) {
2611 if (printComma)
2612 OS << ", ";
2613 OS << i;
2614 printComma = true;
2615 }
2616 OS << " */";
2617
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002618 OS << " },\n";
2619 }
2620 OS << "};\n\n";
2621
2622 // Emit the operand class switch to call the correct custom parser for
2623 // the found operand class.
Alex Bradbury58eba092016-11-01 16:32:05 +00002624 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002625 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002626 << " &Operands,\n unsigned MCK) {\n\n"
2627 << " switch(MCK) {\n";
2628
Craig Topperf34dad92014-11-28 03:53:02 +00002629 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002630 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002631 continue;
David Blaikied749e342014-11-28 20:35:57 +00002632 OS << " case " << CI.Name << ":\n"
2633 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002634 }
2635
2636 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002637 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002638 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002639 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002640 OS << "}\n\n";
2641
2642 // Emit the static custom operand parser. This code is very similar with
2643 // the other matcher. Also use MatchResultTy here just in case we go for
2644 // a better error handling.
Alex Bradbury58eba092016-11-01 16:32:05 +00002645 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002646 << "MatchOperandParserImpl(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002647 << " &Operands,\n StringRef Mnemonic) {\n";
2648
2649 // Emit code to get the available features.
2650 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002651 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002652
2653 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002654 OS << " unsigned NextOpNum = Operands.size()"
2655 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002656
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002657 // Emit code to search the table.
2658 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002659 if (HasMnemonicFirst) {
2660 OS << " auto MnemonicRange =\n";
2661 OS << " std::equal_range(std::begin(OperandMatchTable), "
2662 "std::end(OperandMatchTable),\n";
2663 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2664 } else {
2665 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2666 " std::end(OperandMatchTable));\n";
2667 OS << " if (!Mnemonic.empty())\n";
2668 OS << " MnemonicRange =\n";
2669 OS << " std::equal_range(std::begin(OperandMatchTable), "
2670 "std::end(OperandMatchTable),\n";
2671 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2672 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002673
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002674 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002675 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002676
2677 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2678 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2679
2680 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002681 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002682
2683 // Emit check that the required features are available.
2684 OS << " // check if the available features match\n";
2685 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2686 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002687 OS << " continue;\n";
2688 OS << " }\n\n";
2689
2690 // Emit check to ensure the operand number matches.
2691 OS << " // check if the operand in question has a custom parser.\n";
2692 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2693 OS << " continue;\n\n";
2694
2695 // Emit call to the custom parser method
2696 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002697 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002698 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002699 OS << " if (Result != MatchOperand_NoMatch)\n";
2700 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002701 OS << " }\n\n";
2702
Jim Grosbach861e49c2011-02-12 01:34:40 +00002703 OS << " // Okay, we had no match.\n";
2704 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002705 OS << "}\n\n";
2706}
2707
Daniel Dunbard0470d72009-08-07 21:01:44 +00002708void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002709 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00002710 Record *AsmParser = Target.getAsmParser();
2711 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2712
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002713 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00002714 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002715 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002716
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00002717 // Sort the instruction table using the partial order on classes. We use
2718 // stable_sort to ensure that ambiguous instructions are still
2719 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002720 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2721 [](const std::unique_ptr<MatchableInfo> &a,
2722 const std::unique_ptr<MatchableInfo> &b){
2723 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002724
Matthias Brauna8eed312016-12-05 19:44:31 +00002725#ifdef EXPENSIVE_CHECKS
2726 // Verify that the table is sorted and operator < works transitively.
2727 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2728 ++I) {
2729 for (auto J = I; J != E; ++J) {
2730 assert(!(**J < **I));
2731 }
2732 }
2733#endif
2734
Daniel Dunbar71330282009-08-08 05:24:34 +00002735 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00002736 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002737 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00002738 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002739
Chris Lattnerad776812010-11-01 05:06:45 +00002740 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002741 DEBUG_WITH_TYPE("ambiguous_instrs", {
2742 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00002743 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2744 ++I) {
2745 for (auto J = std::next(I); J != E; ++J) {
2746 const MatchableInfo &A = **I;
2747 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002748
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002749 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00002750 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002751 A.dump();
2752 errs() << "\nis incomparable with:\n";
2753 B.dump();
2754 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002755 ++NumAmbiguous;
2756 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00002757 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00002758 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002759 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002760 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00002761 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002762 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00002763
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002764 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002765 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002766
Craig Topperfd2c6a32015-12-31 08:18:23 +00002767 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00002768 bool HasOptionalOperands = Info.hasOptionalOperands();
Craig Topperfd2c6a32015-12-31 08:18:23 +00002769
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002770 // Write the output.
2771
Chris Lattner3e4582a2010-09-06 19:11:01 +00002772 // Information for the class declaration.
2773 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2774 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00002775 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00002776 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002777 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00002778 if (HasOptionalOperands) {
2779 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2780 << "unsigned Opcode,\n"
2781 << " const OperandVector &Operands,\n"
2782 << " const SmallBitVector &OptionalOperandsMask);\n";
2783 } else {
2784 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2785 << "unsigned Opcode,\n"
2786 << " const OperandVector &Operands);\n";
2787 }
Chad Rosier380a74a2012-10-02 00:25:57 +00002788 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00002789 OS << " const OperandVector &Operands) override;\n";
Craig Toppera5754e62015-01-03 08:16:29 +00002790 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002791 << " MCInst &Inst,\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002792 << " uint64_t &ErrorInfo,"
2793 << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00002794 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002795
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002796 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00002797 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002798 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002799 OS << " StringRef Mnemonic);\n";
2800
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002801 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002802 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002803 OS << " unsigned MCK);\n\n";
2804 }
2805
Chris Lattner3e4582a2010-09-06 19:11:01 +00002806 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2807
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002808 // Emit the operand match diagnostic enum names.
2809 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2810 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2811 emitOperandDiagnosticTypes(Info, OS);
2812 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2813
Chris Lattner3e4582a2010-09-06 19:11:01 +00002814 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2815 OS << "#undef GET_REGISTER_MATCHER\n\n";
2816
Daniel Dunbareefe8612010-07-19 05:44:09 +00002817 // Emit the subtarget feature enumeration.
Daniel Sanders72db2a32016-11-19 13:05:44 +00002818 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(
2819 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002820
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002821 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00002822 // This should be omitted for Mips target
2823 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2824 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00002825
Dylan McKaybff960a2016-02-03 10:30:16 +00002826 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
2827 emitMatchRegisterAltName(Target, AsmParser, OS);
2828
Chris Lattner3e4582a2010-09-06 19:11:01 +00002829 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002830
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002831 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2832 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002833
Jim Grosbach5117ef72012-04-24 22:40:08 +00002834 // Generate the helper function to get the names for subtarget features.
2835 emitGetSubtargetFeatureName(Info, OS);
2836
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002837 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2838
2839 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2840 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2841
Chris Lattner477fba4f2010-10-30 18:48:18 +00002842 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00002843 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002844
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002845 // Generate the convertToMCInst function to convert operands into an MCInst.
2846 // Also, generate the convertToMapAndConstraints function for MS-style inline
2847 // assembly. The latter doesn't actually generate a MCInst.
Sam Kolton5f10a132016-05-06 11:31:17 +00002848 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
2849 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002850
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002851 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002852 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002853
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002854 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002855 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002856
Daniel Dunbar2587b612009-08-10 16:05:47 +00002857 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002858 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002859
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002860 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002861 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002862
Daniel Dunbareefe8612010-07-19 05:44:09 +00002863 // Emit the available features compute function.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00002864 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanders72db2a32016-11-19 13:05:44 +00002865 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
2866 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002867
Craig Toppere2cfeb32012-09-18 06:10:45 +00002868 StringToOffsetTable StringTable;
2869
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002870 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002871 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00002872 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002873 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002874 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
2875 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002876
2877 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002878 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00002879 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2880 StringTable.GetOrAddStringOffset(LenMnemonic, false));
2881 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002882
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002883 OS << "static const char *const MnemonicTable =\n";
2884 StringTable.EmitString(OS);
2885 OS << ";\n\n";
2886
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002887 // Emit the static match table; unused classes get initalized to 0 which is
2888 // guaranteed to be InvalidMatchClass.
2889 //
2890 // FIXME: We can reduce the size of this table very easily. First, we change
2891 // it so that store the kinds in separate bit-fields for each index, which
2892 // only needs to be the max width used for classes at that index (we also need
2893 // to reject based on this during classification). If we then make sure to
2894 // order the match kinds appropriately (putting mnemonics last), then we
2895 // should only end up using a few bits for each class, especially the ones
2896 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00002897 OS << "namespace {\n";
2898 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00002899 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2900 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00002901 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002902 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2903 << " ConvertFn;\n";
Daniel Sanders72db2a32016-11-19 13:05:44 +00002904 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002905 << " RequiredFeatures;\n";
David Blaikied749e342014-11-28 20:35:57 +00002906 OS << " " << getMinimalTypeForRange(
2907 std::distance(Info.Classes.begin(), Info.Classes.end()))
2908 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00002909 OS << " StringRef getMnemonic() const {\n";
2910 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2911 OS << " MnemonicTable[Mnemonic]);\n";
2912 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00002913 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002914
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002915 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00002916 OS << " struct LessOpcode {\n";
2917 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00002918 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00002919 OS << " }\n";
2920 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00002921 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00002922 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00002923 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00002924 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00002925 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00002926 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002927
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00002928 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002929
Craig Topper690d8ea2013-07-24 07:33:14 +00002930 unsigned VariantCount = Target.getAsmParserVariantCount();
2931 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2932 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00002933 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002934
Craig Topper690d8ea2013-07-24 07:33:14 +00002935 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002936
Craig Topperf34dad92014-11-28 03:53:02 +00002937 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002938 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00002939 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002940
Craig Topper690d8ea2013-07-24 07:33:14 +00002941 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002942 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00002943 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002944 << " /* " << MI->Mnemonic << " */, "
2945 << Target.getName() << "::"
2946 << MI->getResultInst()->TheDef->getName() << ", "
2947 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00002948
2949 // Write the required features mask.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002950 if (!MI->RequiredFeatures.empty()) {
2951 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002952 if (i) OS << "|";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002953 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topper690d8ea2013-07-24 07:33:14 +00002954 }
2955 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002956 OS << "0";
Craig Topper690d8ea2013-07-24 07:33:14 +00002957
2958 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002959 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
2960 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00002961
2962 if (i) OS << ", ";
2963 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00002964 }
Craig Topper690d8ea2013-07-24 07:33:14 +00002965 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00002966 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002967
Craig Topper690d8ea2013-07-24 07:33:14 +00002968 OS << "};\n\n";
2969 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002970
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00002971 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00002972 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00002973 << "MatchInstructionImpl(const OperandVector &Operands,\n";
2974 OS << " MCInst &Inst, uint64_t &ErrorInfo,\n"
2975 << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002976
Chad Rosiereac13a32012-08-30 21:43:05 +00002977 OS << " // Eliminate obvious mismatches.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002978 OS << " if (Operands.size() > "
2979 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
2980 OS << " ErrorInfo = "
2981 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
Chad Rosiereac13a32012-08-30 21:43:05 +00002982 OS << " return Match_InvalidOperand;\n";
2983 OS << " }\n\n";
2984
Daniel Dunbareefe8612010-07-19 05:44:09 +00002985 // Emit code to get the available features.
2986 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002987 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002988
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002989 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002990 if (HasMnemonicFirst) {
2991 OS << " StringRef Mnemonic = ((" << Target.getName()
2992 << "Operand&)*Operands[0]).getToken();\n\n";
2993 } else {
2994 OS << " StringRef Mnemonic;\n";
2995 OS << " if (Operands[0]->isToken())\n";
2996 OS << " Mnemonic = ((" << Target.getName()
2997 << "Operand&)*Operands[0]).getToken();\n\n";
2998 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002999
Chris Lattner477fba4f2010-10-30 18:48:18 +00003000 if (HasMnemonicAliases) {
3001 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003002 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003003 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003004
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003005 // Emit code to compute the class list for this operand vector.
Chris Lattnerabfe4222010-09-06 23:37:39 +00003006 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003007 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003008 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003009 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003010 OS << " uint64_t MissingFeatures = ~0ULL;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003011 if (HasOptionalOperands) {
3012 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3013 }
Jim Grosbach860a84d2011-02-11 21:31:55 +00003014 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003015 OS << " // wrong for all instances of the instruction.\n";
Tom Stellard5698d632015-03-05 19:46:55 +00003016 OS << " ErrorInfo = ~0ULL;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003017
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003018 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003019 OS << " // Find the appropriate table for this asm variant.\n";
3020 OS << " const MatchEntry *Start, *End;\n";
3021 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003022 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003023 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3024 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003025 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003026 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3027 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003028 }
3029 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003030
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003031 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003032 if (HasMnemonicFirst) {
3033 OS << " auto MnemonicRange = "
3034 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3035 } else {
3036 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3037 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3038 OS << " if (!Mnemonic.empty())\n";
3039 OS << " MnemonicRange = "
3040 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3041 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003042
Chris Lattner628fbec2010-09-06 21:54:15 +00003043 OS << " // Return a more specific error code if no mnemonics match.\n";
3044 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3045 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003046
Chris Lattner81301972010-09-06 21:22:45 +00003047 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003048 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003049 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003050
Craig Topperfd2c6a32015-12-31 08:18:23 +00003051 if (HasMnemonicFirst) {
3052 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3053 OS << " assert(Mnemonic == it->getMnemonic());\n";
3054 }
3055
Daniel Dunbareefe8612010-07-19 05:44:09 +00003056 // Emit check that the subclasses match.
Chris Lattner339cc7b2010-09-06 22:11:18 +00003057 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003058 if (HasOptionalOperands) {
3059 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3060 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003061 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3062 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3063 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3064 OS << " auto Formal = "
3065 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3066 OS << " if (ActualIdx >= Operands.size()) {\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00003067 OS << " OperandsValid = (Formal == " <<"InvalidMatchClass) || "
3068 "isSubclass(Formal, OptionalMatchClass);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003069 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003070 if (HasOptionalOperands) {
3071 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3072 << ");\n";
3073 }
Jim Grosbache6ce2052011-05-03 19:09:56 +00003074 OS << " break;\n";
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003075 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003076 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003077 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003078 OS << " if (Diag == Match_Success) {\n";
3079 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003080 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003081 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003082 OS << " // If the generic handler indicates an invalid operand\n";
3083 OS << " // failure, check for a special case.\n";
3084 OS << " if (Diag == Match_InvalidOperand) {\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003085 OS << " Diag = validateTargetOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003086 OS << " if (Diag == Match_Success) {\n";
3087 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003088 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003089 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003090 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003091 OS << " // If current formal operand wasn't matched and it is optional\n"
3092 << " // then try to match next formal operand\n";
3093 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003094 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3095 if (HasOptionalOperands) {
3096 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3097 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003098 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003099 OS << " }\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003100 OS << " // If this operand is broken for all of the instances of this\n";
3101 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003102 OS << " // If we already had a match that only failed due to a\n";
3103 OS << " // target predicate, that diagnostic is preferred.\n";
3104 OS << " if (!HadMatchOtherThanPredicate &&\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003105 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3106 OS << " ErrorInfo = ActualIdx;\n";
Jim Grosbach8ccdbd12012-06-26 22:58:01 +00003107 OS << " // InvalidOperand is the default. Prefer specificity.\n";
3108 OS << " if (Diag != Match_InvalidOperand)\n";
3109 OS << " RetCode = Diag;\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003110 OS << " }\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003111 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3112 OS << " OperandsValid = false;\n";
3113 OS << " break;\n";
3114 OS << " }\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003115
Chris Lattner339cc7b2010-09-06 22:11:18 +00003116 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003117
3118 // Emit check that the required features are available.
3119 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3120 << "!= it->RequiredFeatures) {\n";
3121 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003122 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003123 "~AvailableFeatures;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003124 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3125 " countPopulation(MissingFeatures))\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003126 OS << " MissingFeatures = NewMissingFeatures;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003127 OS << " continue;\n";
3128 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003129 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003130 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003131 OS << " Inst.setOpcode(it->Opcode);\n";
3132 // Verify the instruction with the target-specific match predicate function.
3133 OS << " // We have a potential match but have not rendered the operands.\n"
3134 << " // Check the target predicate to handle any context sensitive\n"
3135 " // constraints.\n"
3136 << " // For example, Ties that are referenced multiple times must be\n"
3137 " // checked here to ensure the input is the same for each match\n"
3138 " // constraints. If we leave it any later the ties will have been\n"
3139 " // canonicalized\n"
3140 << " unsigned MatchResult;\n"
3141 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3142 "Operands)) != Match_Success) {\n"
3143 << " Inst.clear();\n"
3144 << " RetCode = MatchResult;\n"
3145 << " HadMatchOtherThanPredicate = true;\n"
3146 << " continue;\n"
3147 << " }\n\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003148 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003149 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003150 OS << " return Match_Success;\n";
3151 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003152 OS << " // We have selected a definite instruction, convert the parsed\n"
3153 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003154 if (HasOptionalOperands) {
3155 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3156 << " OptionalOperandsMask);\n";
3157 } else {
3158 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3159 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003160 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003161
Jim Grosbach120a96a2011-08-15 23:03:29 +00003162 // Verify the instruction with the target-specific match predicate function.
3163 OS << " // We have a potential match. Check the target predicate to\n"
3164 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003165 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3166 << " Match_Success) {\n"
3167 << " Inst.clear();\n"
3168 << " RetCode = MatchResult;\n"
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003169 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003170 << " continue;\n"
3171 << " }\n\n";
3172
Daniel Dunbar451a4352010-03-18 20:05:56 +00003173 // Call the post-processing function, if used.
3174 std::string InsnCleanupFn =
3175 AsmParser->getValueAsString("AsmParserInstCleanup");
3176 if (!InsnCleanupFn.empty())
3177 OS << " " << InsnCleanupFn << "(Inst);\n";
3178
Joey Gouly0e76fa72013-09-12 10:28:05 +00003179 if (HasDeprecation) {
3180 OS << " std::string Info;\n";
Weiming Zhaob38cfce2016-12-05 23:55:13 +00003181 OS << " if (!getParser().getTargetParser().\n";
3182 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3183 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003184 OS << " SMLoc Loc = ((" << Target.getName()
3185 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003186 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003187 OS << " }\n";
3188 }
3189
Chris Lattnera22a3682010-09-06 19:22:17 +00003190 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003191 OS << " }\n\n";
3192
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003193 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Chad Rosier4ee03842012-08-21 17:22:47 +00003194 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3195 OS << " return RetCode;\n\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003196 OS << " // Missing feature matches return which features were missing\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003197 OS << " ErrorInfo = MissingFeatures;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003198 OS << " return Match_MissingFeature;\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003199 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003200
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003201 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003202 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00003203 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003204
Chris Lattner3e4582a2010-09-06 19:11:01 +00003205 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003206}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003207
3208namespace llvm {
3209
3210void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3211 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3212 AsmMatcherEmitter(RK).run(OS);
3213}
3214
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003215} // end namespace llvm