blob: 96e882b19fd13848968a1b93f2efab5f5a17ea1d [file] [log] [blame]
Daniel Dunbard51ffcf2009-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 Lopese7a54522011-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 Dunbard51ffcf2009-07-11 19:39:44 +000016//
Daniel Dunbar20927f22009-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 Grosbacha7c78222010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbar20927f22009-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 Dunbar20927f22009-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 Lopese7a54522011-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
80// identifiers that need to be mapped to specific valeus in the final encoded
81// 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 Lattner7a2bdde2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopese7a54522011-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 Dunbard51ffcf2009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
99#include "AsmMatcherEmitter.h"
100#include "CodeGenTarget.h"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +0000101#include "StringToOffsetTable.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000102#include "llvm/ADT/OwningPtr.h"
Chris Lattnerc07bd402010-11-04 02:11:18 +0000103#include "llvm/ADT/PointerUnion.h"
Chris Lattner1de88232010-11-01 01:47:07 +0000104#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000105#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000106#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000107#include "llvm/ADT/StringExtras.h"
108#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000109#include "llvm/Support/Debug.h"
Craig Topper655b8de2012-02-05 07:21:30 +0000110#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +0000111#include "llvm/TableGen/Error.h"
112#include "llvm/TableGen/Record.h"
Douglas Gregorf657da22012-05-02 17:32:48 +0000113#include "llvm/TableGen/StringMatcher.h"
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000114#include <map>
115#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +0000116using namespace llvm;
117
Daniel Dunbar27249152009-08-07 20:33:39 +0000118static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000119MatchPrefix("match-prefix", cl::init(""),
120 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +0000121
Daniel Dunbar20927f22009-08-07 08:26:05 +0000122namespace {
Bob Wilson828295b2011-01-26 21:26:19 +0000123class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000124struct SubtargetFeatureInfo;
125
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000126/// ClassInfo - Helper class for storing the information about a particular
127/// class of operands which can be matched.
128struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000129 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000130 /// Invalid kind, for use as a sentinel value.
131 Invalid = 0,
132
133 /// The class for a particular token.
134 Token,
135
136 /// The (first) register class, subsequent register classes are
137 /// RegisterClass0+1, and so on.
138 RegisterClass0,
139
140 /// The (first) user defined class, subsequent user defined classes are
141 /// UserClass0+1, and so on.
142 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000143 };
144
145 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
146 /// N) for the Nth user defined class.
147 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000148
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000149 /// SuperClasses - The super classes of this class. Note that for simplicities
150 /// sake user operands only record their immediate super class, while register
151 /// operands include all superclasses.
152 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000153
Daniel Dunbar6745d422009-08-09 05:18:30 +0000154 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000155 std::string Name;
156
Daniel Dunbar6745d422009-08-09 05:18:30 +0000157 /// ClassName - The unadorned generic name for this class (e.g., Token).
158 std::string ClassName;
159
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000160 /// ValueName - The name of the value this class represents; for a token this
161 /// is the literal token string, for an operand it is the TableGen class (or
162 /// empty if this is a derived class).
163 std::string ValueName;
164
165 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000166 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000167 std::string PredicateMethod;
168
169 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000170 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000171 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000172
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000173 /// ParserMethod - The name of the operand method to do a target specific
174 /// parsing on the operand.
175 std::string ParserMethod;
176
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000177 /// For register classes, the records for all the registers in this class.
178 std::set<Record*> Registers;
179
180public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000181 /// isRegisterClass() - Check if this is a register class.
182 bool isRegisterClass() const {
183 return Kind >= RegisterClass0 && Kind < UserClass0;
184 }
185
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000186 /// isUserClass() - Check if this is a user defined class.
187 bool isUserClass() const {
188 return Kind >= UserClass0;
189 }
190
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000191 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
192 /// are related if they are in the same class hierarchy.
193 bool isRelatedTo(const ClassInfo &RHS) const {
194 // Tokens are only related to tokens.
195 if (Kind == Token || RHS.Kind == Token)
196 return Kind == Token && RHS.Kind == Token;
197
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000198 // Registers classes are only related to registers classes, and only if
199 // their intersection is non-empty.
200 if (isRegisterClass() || RHS.isRegisterClass()) {
201 if (!isRegisterClass() || !RHS.isRegisterClass())
202 return false;
203
204 std::set<Record*> Tmp;
205 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000206 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000207 RHS.Registers.begin(), RHS.Registers.end(),
208 II);
209
210 return !Tmp.empty();
211 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000212
213 // Otherwise we have two users operands; they are related if they are in the
214 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000215 //
216 // FIXME: This is an oversimplification, they should only be related if they
217 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000218 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
219 const ClassInfo *Root = this;
220 while (!Root->SuperClasses.empty())
221 Root = Root->SuperClasses.front();
222
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000223 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000224 while (!RHSRoot->SuperClasses.empty())
225 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000226
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000227 return Root == RHSRoot;
228 }
229
Jim Grosbacha7c78222010-10-29 22:13:48 +0000230 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000231 bool isSubsetOf(const ClassInfo &RHS) const {
232 // This is a subset of RHS if it is the same class...
233 if (this == &RHS)
234 return true;
235
236 // ... or if any of its super classes are a subset of RHS.
237 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
238 ie = SuperClasses.end(); it != ie; ++it)
239 if ((*it)->isSubsetOf(RHS))
240 return true;
241
242 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000243 }
244
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000245 /// operator< - Compare two classes.
246 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000247 if (this == &RHS)
248 return false;
249
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000250 // Unrelated classes can be ordered by kind.
251 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000252 return Kind < RHS.Kind;
253
254 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000255 case Invalid:
Craig Topper655b8de2012-02-05 07:21:30 +0000256 llvm_unreachable("Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000257
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000258 default:
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000259 // This class precedes the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000260 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000261 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000262 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000263 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000264
265 // Otherwise, order by name to ensure we have a total ordering.
266 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000267 }
268 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000269};
270
Chris Lattner22bc5c42010-11-01 05:06:45 +0000271/// MatchableInfo - Helper class for storing the necessary information for an
272/// instruction or alias which is capable of being matched.
273struct MatchableInfo {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000274 struct AsmOperand {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000275 /// Token - This is the token that the operand came from.
276 StringRef Token;
Bob Wilson828295b2011-01-26 21:26:19 +0000277
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000278 /// The unique class instance this operand should match.
279 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000280
Chris Lattner567820c2010-11-04 01:42:59 +0000281 /// The operand name this is, if anything.
282 StringRef SrcOpName;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000283
284 /// The suboperand index within SrcOpName, or -1 for the entire operand.
285 int SubOpIdx;
Bob Wilson828295b2011-01-26 21:26:19 +0000286
Devang Patel63faf822012-01-07 01:33:34 +0000287 /// Register record if this token is singleton register.
288 Record *SingletonReg;
289
Jim Grosbachf35307c2012-01-24 21:06:59 +0000290 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
Jim Grosbach11fc6462012-04-11 21:02:33 +0000291 SingletonReg(0) {}
Daniel Dunbar20927f22009-08-07 08:26:05 +0000292 };
Bob Wilson828295b2011-01-26 21:26:19 +0000293
Chris Lattner1d13bda2010-11-04 00:43:46 +0000294 /// ResOperand - This represents a single operand in the result instruction
295 /// generated by the match. In cases (like addressing modes) where a single
296 /// assembler operand expands to multiple MCOperands, this represents the
297 /// single assembler operand, not the MCOperand.
298 struct ResOperand {
299 enum {
300 /// RenderAsmOperand - This represents an operand result that is
301 /// generated by calling the render method on the assembly operand. The
302 /// corresponding AsmOperand is specified by AsmOperandNum.
303 RenderAsmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000304
Chris Lattner1d13bda2010-11-04 00:43:46 +0000305 /// TiedOperand - This represents a result operand that is a duplicate of
306 /// a previous result operand.
Chris Lattner98c870f2010-11-06 19:25:43 +0000307 TiedOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000308
Chris Lattner98c870f2010-11-06 19:25:43 +0000309 /// ImmOperand - This represents an immediate value that is dumped into
310 /// the operand.
Chris Lattner90fd7972010-11-06 19:57:21 +0000311 ImmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000312
Chris Lattner90fd7972010-11-06 19:57:21 +0000313 /// RegOperand - This represents a fixed register that is dumped in.
314 RegOperand
Chris Lattner1d13bda2010-11-04 00:43:46 +0000315 } Kind;
Bob Wilson828295b2011-01-26 21:26:19 +0000316
Chris Lattner1d13bda2010-11-04 00:43:46 +0000317 union {
318 /// This is the operand # in the AsmOperands list that this should be
319 /// copied from.
320 unsigned AsmOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000321
Chris Lattner1d13bda2010-11-04 00:43:46 +0000322 /// TiedOperandNum - This is the (earlier) result operand that should be
323 /// copied from.
324 unsigned TiedOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000325
Chris Lattner98c870f2010-11-06 19:25:43 +0000326 /// ImmVal - This is the immediate value added to the instruction.
327 int64_t ImmVal;
Bob Wilson828295b2011-01-26 21:26:19 +0000328
Chris Lattner90fd7972010-11-06 19:57:21 +0000329 /// Register - This is the register record.
330 Record *Register;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000331 };
Bob Wilson828295b2011-01-26 21:26:19 +0000332
Bob Wilsona49c7df2011-01-26 19:44:55 +0000333 /// MINumOperands - The number of MCInst operands populated by this
334 /// operand.
335 unsigned MINumOperands;
Bob Wilson828295b2011-01-26 21:26:19 +0000336
Bob Wilsona49c7df2011-01-26 19:44:55 +0000337 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000338 ResOperand X;
339 X.Kind = RenderAsmOperand;
340 X.AsmOperandNum = AsmOpNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000341 X.MINumOperands = NumOperands;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000342 return X;
343 }
Bob Wilson828295b2011-01-26 21:26:19 +0000344
Bob Wilsona49c7df2011-01-26 19:44:55 +0000345 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000346 ResOperand X;
347 X.Kind = TiedOperand;
348 X.TiedOperandNum = TiedOperandNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000349 X.MINumOperands = 1;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000350 return X;
351 }
Bob Wilson828295b2011-01-26 21:26:19 +0000352
Bob Wilsona49c7df2011-01-26 19:44:55 +0000353 static ResOperand getImmOp(int64_t Val) {
Chris Lattner98c870f2010-11-06 19:25:43 +0000354 ResOperand X;
355 X.Kind = ImmOperand;
356 X.ImmVal = Val;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000357 X.MINumOperands = 1;
Chris Lattner98c870f2010-11-06 19:25:43 +0000358 return X;
359 }
Bob Wilson828295b2011-01-26 21:26:19 +0000360
Bob Wilsona49c7df2011-01-26 19:44:55 +0000361 static ResOperand getRegOp(Record *Reg) {
Chris Lattner90fd7972010-11-06 19:57:21 +0000362 ResOperand X;
363 X.Kind = RegOperand;
364 X.Register = Reg;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000365 X.MINumOperands = 1;
Chris Lattner90fd7972010-11-06 19:57:21 +0000366 return X;
367 }
Chris Lattner1d13bda2010-11-04 00:43:46 +0000368 };
Daniel Dunbar20927f22009-08-07 08:26:05 +0000369
Devang Patel56315d32012-01-10 17:50:43 +0000370 /// AsmVariantID - Target's assembly syntax variant no.
371 int AsmVariantID;
372
Chris Lattner3b5aec62010-11-02 17:34:28 +0000373 /// TheDef - This is the definition of the instruction or InstAlias that this
374 /// matchable came from.
Chris Lattner5bc93872010-11-01 04:34:44 +0000375 Record *const TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000376
Chris Lattnerc07bd402010-11-04 02:11:18 +0000377 /// DefRec - This is the definition that it came from.
378 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilson828295b2011-01-26 21:26:19 +0000379
Chris Lattner662e5a32010-11-06 07:14:44 +0000380 const CodeGenInstruction *getResultInst() const {
381 if (DefRec.is<const CodeGenInstruction*>())
382 return DefRec.get<const CodeGenInstruction*>();
383 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
384 }
Bob Wilson828295b2011-01-26 21:26:19 +0000385
Chris Lattner1d13bda2010-11-04 00:43:46 +0000386 /// ResOperands - This is the operand list that should be built for the result
387 /// MCInst.
Jim Grosbachb423d182012-04-19 17:52:34 +0000388 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000389
390 /// AsmString - The assembly string for this instruction (with variants
Chris Lattner3b5aec62010-11-02 17:34:28 +0000391 /// removed), e.g. "movsx $src, $dst".
Daniel Dunbar20927f22009-08-07 08:26:05 +0000392 std::string AsmString;
393
Chris Lattnerd19ec052010-11-02 17:30:52 +0000394 /// Mnemonic - This is the first token of the matched instruction, its
395 /// mnemonic.
396 StringRef Mnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +0000397
Chris Lattner3116fef2010-11-02 01:03:43 +0000398 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattner3b5aec62010-11-02 17:34:28 +0000399 /// annotated with a class and where in the OperandList they were defined.
400 /// This directly corresponds to the tokenized AsmString after the mnemonic is
401 /// removed.
Jim Grosbachb423d182012-04-19 17:52:34 +0000402 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000403
Daniel Dunbar54074b52010-07-19 05:44:09 +0000404 /// Predicates - The required subtarget features to match this instruction.
405 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
406
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000407 /// ConversionFnKind - The enum value which is passed to the generated
408 /// ConvertToMCInst to convert parsed operands into an MCInst for this
409 /// function.
410 std::string ConversionFnKind;
Bob Wilson828295b2011-01-26 21:26:19 +0000411
Chris Lattner22bc5c42010-11-01 05:06:45 +0000412 MatchableInfo(const CodeGenInstruction &CGI)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000413 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
Devang Patel56315d32012-01-10 17:50:43 +0000414 AsmString(CGI.AsmString) {
Chris Lattner5bc93872010-11-01 04:34:44 +0000415 }
416
Chris Lattner22bc5c42010-11-01 05:06:45 +0000417 MatchableInfo(const CodeGenInstAlias *Alias)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000418 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
Devang Patel56315d32012-01-10 17:50:43 +0000419 AsmString(Alias->AsmString) {
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000420 }
Bob Wilson828295b2011-01-26 21:26:19 +0000421
Jim Grosbachc1922c72012-04-19 23:59:23 +0000422 // Two-operand aliases clone from the main matchable, but mark the second
423 // operand as a tied operand of the first for purposes of the assembler.
424 void formTwoOperandAlias(StringRef Constraint);
425
Jim Grosbach8caecde2012-04-19 17:52:32 +0000426 void initialize(const AsmMatcherInfo &Info,
Jim Grosbachf35307c2012-01-24 21:06:59 +0000427 SmallPtrSet<Record*, 16> &SingletonRegisters,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000428 int AsmVariantNo, std::string &RegisterPrefix);
Bob Wilson828295b2011-01-26 21:26:19 +0000429
Jim Grosbach8caecde2012-04-19 17:52:32 +0000430 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattner22bc5c42010-11-01 05:06:45 +0000431 /// and perform a bunch of validity checking.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000432 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilson828295b2011-01-26 21:26:19 +0000433
Jim Grosbachf35307c2012-01-24 21:06:59 +0000434 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Patel63faf822012-01-07 01:33:34 +0000435 /// if present, from specified token.
436 void
437 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
438 std::string &RegisterPrefix);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000439
Jim Grosbach8caecde2012-04-19 17:52:32 +0000440 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsona49c7df2011-01-26 19:44:55 +0000441 /// suboperand index.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000442 int findAsmOperand(StringRef N, int SubOpIdx) const {
Bob Wilsona49c7df2011-01-26 19:44:55 +0000443 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
444 if (N == AsmOperands[i].SrcOpName &&
445 SubOpIdx == AsmOperands[i].SubOpIdx)
446 return i;
447 return -1;
448 }
Bob Wilson828295b2011-01-26 21:26:19 +0000449
Jim Grosbach8caecde2012-04-19 17:52:32 +0000450 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000451 /// This does not check the suboperand index.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000452 int findAsmOperandNamed(StringRef N) const {
Chris Lattnerba3b5b62010-11-04 01:55:23 +0000453 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
454 if (N == AsmOperands[i].SrcOpName)
455 return i;
456 return -1;
457 }
Bob Wilson828295b2011-01-26 21:26:19 +0000458
Jim Grosbach8caecde2012-04-19 17:52:32 +0000459 void buildInstructionResultOperands();
460 void buildAliasResultOperands();
Chris Lattner1d13bda2010-11-04 00:43:46 +0000461
Chris Lattner22bc5c42010-11-01 05:06:45 +0000462 /// operator< - Compare two matchables.
463 bool operator<(const MatchableInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000464 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000465 if (Mnemonic != RHS.Mnemonic)
466 return Mnemonic < RHS.Mnemonic;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000467
Chris Lattner3116fef2010-11-02 01:03:43 +0000468 if (AsmOperands.size() != RHS.AsmOperands.size())
469 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000470
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000471 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8caecde2012-04-19 17:52:32 +0000472 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattner3116fef2010-11-02 01:03:43 +0000473 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
474 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000475 return true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000476 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000477 return false;
478 }
479
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000480 return false;
481 }
482
Jim Grosbach8caecde2012-04-19 17:52:32 +0000483 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Daniel Dunbar2b544812009-08-09 06:05:33 +0000484 /// ambiguously match the same set of operands as \arg RHS (without being a
485 /// strictly superior match).
Jim Grosbach8caecde2012-04-19 17:52:32 +0000486 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000487 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000488 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000489 return false;
Bob Wilson828295b2011-01-26 21:26:19 +0000490
Daniel Dunbar2b544812009-08-09 06:05:33 +0000491 // The number of operands is unambiguous.
Chris Lattner3116fef2010-11-02 01:03:43 +0000492 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbar2b544812009-08-09 06:05:33 +0000493 return false;
494
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000495 // Otherwise, make sure the ordering of the two instructions is unambiguous
496 // by checking that either (a) a token or operand kind discriminates them,
497 // or (b) the ordering among equivalent kinds is consistent.
498
Daniel Dunbar2b544812009-08-09 06:05:33 +0000499 // Tokens and operand kinds are unambiguous (assuming a correct target
500 // specific parser).
Chris Lattner3116fef2010-11-02 01:03:43 +0000501 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
502 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
503 AsmOperands[i].Class->Kind == ClassInfo::Token)
504 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
505 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000506 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000507
Daniel Dunbar2b544812009-08-09 06:05:33 +0000508 // Otherwise, this operand could commute if all operands are equivalent, or
509 // there is a pair of operands that compare less than and a pair that
510 // compare greater than.
511 bool HasLT = false, HasGT = false;
Chris Lattner3116fef2010-11-02 01:03:43 +0000512 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
513 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000514 HasLT = true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000515 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000516 HasGT = true;
517 }
518
519 return !(HasLT ^ HasGT);
520 }
521
Daniel Dunbar20927f22009-08-07 08:26:05 +0000522 void dump();
Bob Wilson828295b2011-01-26 21:26:19 +0000523
Chris Lattnerd19ec052010-11-02 17:30:52 +0000524private:
Jim Grosbach8caecde2012-04-19 17:52:32 +0000525 void tokenizeAsmString(const AsmMatcherInfo &Info);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000526};
527
Daniel Dunbar54074b52010-07-19 05:44:09 +0000528/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
529/// feature which participates in instruction matching.
530struct SubtargetFeatureInfo {
531 /// \brief The predicate record for this feature.
532 Record *TheDef;
533
534 /// \brief An unique index assigned to represent this feature.
535 unsigned Index;
536
Chris Lattner0aed1e72010-10-30 20:07:57 +0000537 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
Bob Wilson828295b2011-01-26 21:26:19 +0000538
Daniel Dunbar54074b52010-07-19 05:44:09 +0000539 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000540 std::string getEnumName() const {
541 return "Feature_" + TheDef->getName();
542 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000543};
544
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000545struct OperandMatchEntry {
546 unsigned OperandMask;
547 MatchableInfo* MI;
548 ClassInfo *CI;
549
Jim Grosbach8caecde2012-04-19 17:52:32 +0000550 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000551 unsigned opMask) {
552 OperandMatchEntry X;
553 X.OperandMask = opMask;
554 X.CI = ci;
555 X.MI = mi;
556 return X;
557 }
558};
559
560
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000561class AsmMatcherInfo {
562public:
Chris Lattner67db8832010-12-13 00:23:57 +0000563 /// Tracked Records
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000564 RecordKeeper &Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000565
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000566 /// The tablegen AsmParser record.
567 Record *AsmParser;
568
Chris Lattner02bcbc92010-11-01 01:37:30 +0000569 /// Target - The target information.
570 CodeGenTarget &Target;
571
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000572 /// The classes which are needed for matching.
573 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000574
Chris Lattner22bc5c42010-11-01 05:06:45 +0000575 /// The information on the matchables to match.
576 std::vector<MatchableInfo*> Matchables;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000577
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000578 /// Info for custom matching operands by user defined methods.
579 std::vector<OperandMatchEntry> OperandMatchInfo;
580
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000581 /// Map of Register records to their class information.
582 std::map<Record*, ClassInfo*> RegisterClasses;
583
Daniel Dunbar54074b52010-07-19 05:44:09 +0000584 /// Map of Predicate records to their subtarget information.
585 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Bob Wilson828295b2011-01-26 21:26:19 +0000586
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000587private:
588 /// Map of token to class information which has already been constructed.
589 std::map<std::string, ClassInfo*> TokenClasses;
590
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000591 /// Map of RegisterClass records to their class information.
592 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000593
Daniel Dunbar338825c2009-08-10 18:41:10 +0000594 /// Map of AsmOperandClass records to their class information.
595 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000596
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000597private:
598 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000599 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000600
601 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000602 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbach48c1f842011-10-28 22:32:53 +0000603 int SubOpIdx);
604 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000605
Jim Grosbach8caecde2012-04-19 17:52:32 +0000606 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000607 /// classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000608 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000609
Jim Grosbach8caecde2012-04-19 17:52:32 +0000610 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000611 /// operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000612 void buildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000613
Jim Grosbach8caecde2012-04-19 17:52:32 +0000614 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsona49c7df2011-01-26 19:44:55 +0000615 unsigned AsmOpIdx);
Jim Grosbach8caecde2012-04-19 17:52:32 +0000616 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattnerc07bd402010-11-04 02:11:18 +0000617 MatchableInfo::AsmOperand &Op);
Bob Wilson828295b2011-01-26 21:26:19 +0000618
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000619public:
Bob Wilson828295b2011-01-26 21:26:19 +0000620 AsmMatcherInfo(Record *AsmParser,
621 CodeGenTarget &Target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000622 RecordKeeper &Records);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000623
Jim Grosbach8caecde2012-04-19 17:52:32 +0000624 /// buildInfo - Construct the various tables used during matching.
625 void buildInfo();
Bob Wilson828295b2011-01-26 21:26:19 +0000626
Jim Grosbach8caecde2012-04-19 17:52:32 +0000627 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000628 /// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000629 void buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000630
Chris Lattner6fa152c2010-10-30 20:15:02 +0000631 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
632 /// given operand.
633 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
634 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
635 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
636 SubtargetFeatures.find(Def);
637 return I == SubtargetFeatures.end() ? 0 : I->second;
638 }
Chris Lattner67db8832010-12-13 00:23:57 +0000639
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000640 RecordKeeper &getRecords() const {
641 return Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000642 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000643};
644
Daniel Dunbar20927f22009-08-07 08:26:05 +0000645}
646
Chris Lattner22bc5c42010-11-01 05:06:45 +0000647void MatchableInfo::dump() {
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000648 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000649
Chris Lattner3116fef2010-11-02 01:03:43 +0000650 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000651 AsmOperand &Op = AsmOperands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000652 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner0bb780c2010-11-04 00:57:06 +0000653 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000654 }
655}
656
Jim Grosbachc1922c72012-04-19 23:59:23 +0000657static std::pair<StringRef, StringRef>
658parseTwoOperandConstraint(StringRef S, SMLoc Loc) {
659 // Split via the '='.
660 std::pair<StringRef, StringRef> Ops = S.split('=');
661 if (Ops.second == "")
662 throw TGError(Loc, "missing '=' in two-operand alias constraint");
663 // Trim whitespace and the leading '$' on the operand names.
664 size_t start = Ops.first.find_first_of('$');
665 if (start == std::string::npos)
666 throw TGError(Loc, "expected '$' prefix on asm operand name");
667 Ops.first = Ops.first.slice(start + 1, std::string::npos);
668 size_t end = Ops.first.find_last_of(" \t");
669 Ops.first = Ops.first.slice(0, end);
670 // Now the second operand.
671 start = Ops.second.find_first_of('$');
672 if (start == std::string::npos)
673 throw TGError(Loc, "expected '$' prefix on asm operand name");
674 Ops.second = Ops.second.slice(start + 1, std::string::npos);
675 end = Ops.second.find_last_of(" \t");
676 Ops.first = Ops.first.slice(0, end);
677 return Ops;
678}
679
680void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
681 // Figure out which operands are aliased and mark them as tied.
682 std::pair<StringRef, StringRef> Ops =
683 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
684
685 // Find the AsmOperands that refer to the operands we're aliasing.
686 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
687 int DstAsmOperand = findAsmOperandNamed(Ops.second);
688 if (SrcAsmOperand == -1)
689 throw TGError(TheDef->getLoc(),
690 "unknown source two-operand alias operand '" +
691 Ops.first.str() + "'.");
692 if (DstAsmOperand == -1)
693 throw TGError(TheDef->getLoc(),
694 "unknown destination two-operand alias operand '" +
695 Ops.second.str() + "'.");
696
697 // Find the ResOperand that refers to the operand we're aliasing away
698 // and update it to refer to the combined operand instead.
699 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
700 ResOperand &Op = ResOperands[i];
701 if (Op.Kind == ResOperand::RenderAsmOperand &&
702 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
703 Op.AsmOperandNum = DstAsmOperand;
704 break;
705 }
706 }
707 // Remove the AsmOperand for the alias operand.
708 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
709 // Adjust the ResOperand references to any AsmOperands that followed
710 // the one we just deleted.
711 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
712 ResOperand &Op = ResOperands[i];
713 switch(Op.Kind) {
714 default:
715 // Nothing to do for operands that don't reference AsmOperands.
716 break;
717 case ResOperand::RenderAsmOperand:
718 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
719 --Op.AsmOperandNum;
720 break;
721 case ResOperand::TiedOperand:
722 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
723 --Op.TiedOperandNum;
724 break;
725 }
726 }
727}
728
Jim Grosbach8caecde2012-04-19 17:52:32 +0000729void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Devang Patel63faf822012-01-07 01:33:34 +0000730 SmallPtrSet<Record*, 16> &SingletonRegisters,
731 int AsmVariantNo, std::string &RegisterPrefix) {
Devang Patel56315d32012-01-10 17:50:43 +0000732 AsmVariantID = AsmVariantNo;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000733 AsmString =
Devang Patel63faf822012-01-07 01:33:34 +0000734 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
Bob Wilson828295b2011-01-26 21:26:19 +0000735
Jim Grosbach8caecde2012-04-19 17:52:32 +0000736 tokenizeAsmString(Info);
Bob Wilson828295b2011-01-26 21:26:19 +0000737
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000738 // Compute the require features.
739 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
740 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
741 if (SubtargetFeatureInfo *Feature =
742 Info.getSubtargetFeature(Predicates[i]))
743 RequiredFeatures.push_back(Feature);
Bob Wilson828295b2011-01-26 21:26:19 +0000744
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000745 // Collect singleton registers, if used.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000746 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Devang Patel63faf822012-01-07 01:33:34 +0000747 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
748 if (Record *Reg = AsmOperands[i].SingletonReg)
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000749 SingletonRegisters.insert(Reg);
750 }
751}
752
Jim Grosbach8caecde2012-04-19 17:52:32 +0000753/// tokenizeAsmString - Tokenize a simplified assembly string.
754void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000755 StringRef String = AsmString;
756 unsigned Prev = 0;
757 bool InTok = true;
758 for (unsigned i = 0, e = String.size(); i != e; ++i) {
759 switch (String[i]) {
760 case '[':
761 case ']':
762 case '*':
763 case '!':
764 case ' ':
765 case '\t':
766 case ',':
767 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000768 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000769 InTok = false;
770 }
771 if (!isspace(String[i]) && String[i] != ',')
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000772 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000773 Prev = i + 1;
774 break;
775
776 case '\\':
777 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000778 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000779 InTok = false;
780 }
781 ++i;
782 assert(i != String.size() && "Invalid quoted character");
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000783 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000784 Prev = i + 1;
785 break;
786
787 case '$': {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000788 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000789 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000790 InTok = false;
791 }
Bob Wilson828295b2011-01-26 21:26:19 +0000792
Chris Lattner7ad31472010-11-06 22:06:03 +0000793 // If this isn't "${", treat like a normal token.
794 if (i + 1 == String.size() || String[i + 1] != '{') {
795 Prev = i;
796 break;
797 }
Chris Lattnerd19ec052010-11-02 17:30:52 +0000798
799 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
800 assert(End != String.end() && "Missing brace in operand reference!");
801 size_t EndPos = End - String.begin();
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000802 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000803 Prev = EndPos + 1;
804 i = EndPos;
805 break;
806 }
807
808 case '.':
809 if (InTok)
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000810 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000811 Prev = i;
812 InTok = true;
813 break;
814
815 default:
816 InTok = true;
817 }
818 }
819 if (InTok && Prev != String.size())
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000820 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
Bob Wilson828295b2011-01-26 21:26:19 +0000821
Chris Lattnerd19ec052010-11-02 17:30:52 +0000822 // The first token of the instruction is the mnemonic, which must be a
823 // simple string, not a $foo variable or a singleton register.
Jim Grosbach4a2242c2011-11-30 23:16:25 +0000824 if (AsmOperands.empty())
825 throw TGError(TheDef->getLoc(),
826 "Instruction '" + TheDef->getName() + "' has no tokens");
Chris Lattnerd19ec052010-11-02 17:30:52 +0000827 Mnemonic = AsmOperands[0].Token;
Jim Grosbach8e27c962012-05-06 17:33:14 +0000828 if (Mnemonic.empty())
829 throw TGError(TheDef->getLoc(),
830 "Missing instruction mnemonic");
Devang Patel63faf822012-01-07 01:33:34 +0000831 // FIXME : Check and raise an error if it is a register.
Devang Patelb78307f2012-01-07 01:22:23 +0000832 if (Mnemonic[0] == '$')
Chris Lattnerd19ec052010-11-02 17:30:52 +0000833 throw TGError(TheDef->getLoc(),
834 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Bob Wilson828295b2011-01-26 21:26:19 +0000835
Chris Lattnerd19ec052010-11-02 17:30:52 +0000836 // Remove the first operand, it is tracked in the mnemonic field.
837 AsmOperands.erase(AsmOperands.begin());
838}
839
Jim Grosbach8caecde2012-04-19 17:52:32 +0000840bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattner22bc5c42010-11-01 05:06:45 +0000841 // Reject matchables with no .s string.
Chris Lattner5bc93872010-11-01 04:34:44 +0000842 if (AsmString.empty())
843 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilson828295b2011-01-26 21:26:19 +0000844
Chris Lattner22bc5c42010-11-01 05:06:45 +0000845 // Reject any matchables with a newline in them, they should be marked
Chris Lattner5bc93872010-11-01 04:34:44 +0000846 // isCodeGenOnly if they are pseudo instructions.
847 if (AsmString.find('\n') != std::string::npos)
848 throw TGError(TheDef->getLoc(),
849 "multiline instruction is not valid for the asmparser, "
850 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000851
Chris Lattner4164f6b2010-11-01 04:44:29 +0000852 // Remove comments from the asm string. We know that the asmstring only
853 // has one line.
854 if (!CommentDelimiter.empty() &&
855 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
856 throw TGError(TheDef->getLoc(),
857 "asmstring for instruction has comment character in it, "
858 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000859
Chris Lattner22bc5c42010-11-01 05:06:45 +0000860 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson906bc362011-01-20 18:38:07 +0000861 // handle, the target should be refactored to use operands instead of
862 // modifiers.
Chris Lattner5bc93872010-11-01 04:34:44 +0000863 //
864 // Also, check for instructions which reference the operand multiple times;
865 // this implies a constraint we would not honor.
866 std::set<std::string> OperandNames;
Chris Lattnerd19ec052010-11-02 17:30:52 +0000867 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
868 StringRef Tok = AsmOperands[i].Token;
869 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Chris Lattner5bc93872010-11-01 04:34:44 +0000870 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000871 "matchable with operand modifier '" + Tok.str() +
Chris Lattner5bc93872010-11-01 04:34:44 +0000872 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilson828295b2011-01-26 21:26:19 +0000873
Chris Lattner22bc5c42010-11-01 05:06:45 +0000874 // Verify that any operand is only mentioned once.
Chris Lattnerd51257a2010-11-02 23:18:43 +0000875 // We reject aliases and ignore instructions for now.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000876 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattner22bc5c42010-11-01 05:06:45 +0000877 if (!Hack)
878 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000879 "ERROR: matchable with tied operand '" + Tok.str() +
Chris Lattner22bc5c42010-11-01 05:06:45 +0000880 "' can never be matched!");
881 // FIXME: Should reject these. The ARM backend hits this with $lane in a
882 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner5bc93872010-11-01 04:34:44 +0000883 DEBUG({
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000884 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattner22bc5c42010-11-01 05:06:45 +0000885 << "ignoring instruction with tied operand '"
Chris Lattnerd19ec052010-11-02 17:30:52 +0000886 << Tok.str() << "'\n";
Chris Lattner5bc93872010-11-01 04:34:44 +0000887 });
888 return false;
889 }
890 }
Bob Wilson828295b2011-01-26 21:26:19 +0000891
Chris Lattner5bc93872010-11-01 04:34:44 +0000892 return true;
893}
894
Jim Grosbachf35307c2012-01-24 21:06:59 +0000895/// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Pateld06b01c2012-01-09 21:30:46 +0000896/// if present, from specified token.
Devang Patel63faf822012-01-07 01:33:34 +0000897void MatchableInfo::
Jim Grosbachf35307c2012-01-24 21:06:59 +0000898extractSingletonRegisterForAsmOperand(unsigned OperandNo,
Devang Pateld06b01c2012-01-09 21:30:46 +0000899 const AsmMatcherInfo &Info,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000900 std::string &RegisterPrefix) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000901 StringRef Tok = AsmOperands[OperandNo].Token;
Devang Patel63faf822012-01-07 01:33:34 +0000902 if (RegisterPrefix.empty()) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000903 std::string LoweredTok = Tok.lower();
904 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
905 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Devang Patel63faf822012-01-07 01:33:34 +0000906 return;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000907 }
Bob Wilson828295b2011-01-26 21:26:19 +0000908
Devang Patel63faf822012-01-07 01:33:34 +0000909 if (!Tok.startswith(RegisterPrefix))
910 return;
911
912 StringRef RegName = Tok.substr(RegisterPrefix.size());
Chris Lattnerec6f0962010-11-02 18:10:06 +0000913 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
Devang Pateld06b01c2012-01-09 21:30:46 +0000914 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000915
Chris Lattner1de88232010-11-01 01:47:07 +0000916 // If there is no register prefix (i.e. "%" in "%eax"), then this may
917 // be some random non-register token, just ignore it.
Devang Patel63faf822012-01-07 01:33:34 +0000918 return;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000919}
920
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000921static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000922 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000923
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000924 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
925 switch (*it) {
926 case '*': Res += "_STAR_"; break;
927 case '%': Res += "_PCT_"; break;
928 case ':': Res += "_COLON_"; break;
Bill Wendlingbd9c77b2010-11-18 23:36:54 +0000929 case '!': Res += "_EXCLAIM_"; break;
Bill Wendling0ef755d2011-01-22 09:44:32 +0000930 case '.': Res += "_DOT_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000931 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000932 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000933 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000934 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000935 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000936 }
937 }
938
939 return Res;
940}
941
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000942ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000943 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000944
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000945 if (!Entry) {
946 Entry = new ClassInfo();
947 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000948 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000949 Entry->Name = "MCK_" + getEnumNameForToken(Token);
950 Entry->ValueName = Token;
951 Entry->PredicateMethod = "<invalid>";
952 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000953 Entry->ParserMethod = "";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000954 Classes.push_back(Entry);
955 }
956
957 return Entry;
958}
959
960ClassInfo *
Bob Wilsona49c7df2011-01-26 19:44:55 +0000961AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
962 int SubOpIdx) {
963 Record *Rec = OI.Rec;
964 if (SubOpIdx != -1)
David Greene05bce0b2011-07-29 22:43:06 +0000965 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbach48c1f842011-10-28 22:32:53 +0000966 return getOperandClass(Rec, SubOpIdx);
967}
Bob Wilsona49c7df2011-01-26 19:44:55 +0000968
Jim Grosbach48c1f842011-10-28 22:32:53 +0000969ClassInfo *
970AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000971 if (Rec->isSubClassOf("RegisterOperand")) {
972 // RegisterOperand may have an associated ParserMatchClass. If it does,
973 // use it, else just fall back to the underlying register class.
974 const RecordVal *R = Rec->getValue("ParserMatchClass");
975 if (R == 0 || R->getValue() == 0)
976 throw "Record `" + Rec->getName() +
977 "' does not have a ParserMatchClass!\n";
978
David Greene05bce0b2011-07-29 22:43:06 +0000979 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000980 Record *MatchClass = DI->getDef();
981 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
982 return CI;
983 }
984
985 // No custom match class. Just use the register class.
986 Record *ClassRec = Rec->getValueAsDef("RegClass");
987 if (!ClassRec)
988 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
989 "' has no associated register class!\n");
990 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
991 return CI;
992 throw TGError(Rec->getLoc(), "register class has no class info!");
993 }
994
995
Bob Wilsona49c7df2011-01-26 19:44:55 +0000996 if (Rec->isSubClassOf("RegisterClass")) {
997 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattnerec6f0962010-11-02 18:10:06 +0000998 return CI;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000999 throw TGError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001000 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001001
Bob Wilsona49c7df2011-01-26 19:44:55 +00001002 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1003 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattnerec6f0962010-11-02 18:10:06 +00001004 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1005 return CI;
Daniel Dunbar338825c2009-08-10 18:41:10 +00001006
Bob Wilsona49c7df2011-01-26 19:44:55 +00001007 throw TGError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001008}
1009
Chris Lattner1de88232010-11-01 01:47:07 +00001010void AsmMatcherInfo::
Jim Grosbach8caecde2012-04-19 17:52:32 +00001011buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001012 const std::vector<CodeGenRegister*> &Registers =
1013 Target.getRegBank().getRegisters();
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001014 ArrayRef<CodeGenRegisterClass*> RegClassList =
1015 Target.getRegBank().getRegClasses();
Daniel Dunbar338825c2009-08-10 18:41:10 +00001016
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001017 // The register sets used for matching.
1018 std::set< std::set<Record*> > RegisterSets;
1019
Jim Grosbacha7c78222010-10-29 22:13:48 +00001020 // Gather the defined sets.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001021 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
Chris Lattnerec6f0962010-11-02 18:10:06 +00001022 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001023 RegisterSets.insert(std::set<Record*>(
1024 (*it)->getOrder().begin(), (*it)->getOrder().end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001025
1026 // Add any required singleton sets.
Chris Lattner1de88232010-11-01 01:47:07 +00001027 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1028 ie = SingletonRegisters.end(); it != ie; ++it) {
1029 Record *Rec = *it;
1030 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
1031 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001032
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001033 // Introduce derived sets where necessary (when a register does not determine
1034 // a unique register set class), and build the mapping of registers to the set
1035 // they should classify to.
1036 std::map<Record*, std::set<Record*> > RegisterMap;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001037 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001038 ie = Registers.end(); it != ie; ++it) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001039 const CodeGenRegister &CGR = **it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001040 // Compute the intersection of all sets containing this register.
1041 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001042
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001043 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1044 ie = RegisterSets.end(); it != ie; ++it) {
1045 if (!it->count(CGR.TheDef))
1046 continue;
1047
1048 if (ContainingSet.empty()) {
1049 ContainingSet = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001050 continue;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001051 }
Bob Wilson828295b2011-01-26 21:26:19 +00001052
Chris Lattnerec6f0962010-11-02 18:10:06 +00001053 std::set<Record*> Tmp;
1054 std::swap(Tmp, ContainingSet);
1055 std::insert_iterator< std::set<Record*> > II(ContainingSet,
1056 ContainingSet.begin());
1057 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001058 }
1059
1060 if (!ContainingSet.empty()) {
1061 RegisterSets.insert(ContainingSet);
1062 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1063 }
1064 }
1065
1066 // Construct the register classes.
1067 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
1068 unsigned Index = 0;
1069 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1070 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1071 ClassInfo *CI = new ClassInfo();
1072 CI->Kind = ClassInfo::RegisterClass0 + Index;
1073 CI->ClassName = "Reg" + utostr(Index);
1074 CI->Name = "MCK_Reg" + utostr(Index);
1075 CI->ValueName = "";
1076 CI->PredicateMethod = ""; // unused
1077 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +00001078 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001079 Classes.push_back(CI);
1080 RegisterSetClasses.insert(std::make_pair(*it, CI));
1081 }
1082
1083 // Find the superclasses; we could compute only the subgroup lattice edges,
1084 // but there isn't really a point.
1085 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1086 ie = RegisterSets.end(); it != ie; ++it) {
1087 ClassInfo *CI = RegisterSetClasses[*it];
1088 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1089 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001090 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001091 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1092 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1093 }
1094
1095 // Name the register classes which correspond to a user defined RegisterClass.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001096 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
Chris Lattnerec6f0962010-11-02 18:10:06 +00001097 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001098 const CodeGenRegisterClass &RC = **it;
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001099 // Def will be NULL for non-user defined register classes.
1100 Record *Def = RC.getDef();
1101 if (!Def)
1102 continue;
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001103 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1104 RC.getOrder().end())];
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001105 if (CI->ValueName.empty()) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001106 CI->ClassName = RC.getName();
1107 CI->Name = "MCK_" + RC.getName();
1108 CI->ValueName = RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001109 } else
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001110 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001111
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001112 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001113 }
1114
1115 // Populate the map for individual registers.
1116 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1117 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattnerec6f0962010-11-02 18:10:06 +00001118 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001119
1120 // Name the register classes which correspond to singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +00001121 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1122 ie = SingletonRegisters.end(); it != ie; ++it) {
1123 Record *Rec = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001124 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattner1de88232010-11-01 01:47:07 +00001125 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001126
Chris Lattner1de88232010-11-01 01:47:07 +00001127 if (CI->ValueName.empty()) {
1128 CI->ClassName = Rec->getName();
1129 CI->Name = "MCK_" + Rec->getName();
1130 CI->ValueName = Rec->getName();
1131 } else
1132 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001133 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001134}
1135
Jim Grosbach8caecde2012-04-19 17:52:32 +00001136void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere66b7eb2010-11-01 23:57:23 +00001137 std::vector<Record*> AsmOperands =
1138 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001139
1140 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001141 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001142 ie = AsmOperands.end(); it != ie; ++it)
1143 AsmOperandClasses[*it] = new ClassInfo();
1144
Daniel Dunbar338825c2009-08-10 18:41:10 +00001145 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001146 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +00001147 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001148 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +00001149 CI->Kind = ClassInfo::UserClass0 + Index;
1150
David Greene05bce0b2011-07-29 22:43:06 +00001151 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001152 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00001153 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001154 if (!DI) {
1155 PrintError((*it)->getLoc(), "Invalid super class reference!");
1156 continue;
1157 }
1158
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001159 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1160 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +00001161 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001162 else
1163 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +00001164 }
1165 CI->ClassName = (*it)->getValueAsString("Name");
1166 CI->Name = "MCK_" + CI->ClassName;
1167 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001168
1169 // Get or construct the predicate method name.
David Greene05bce0b2011-07-29 22:43:06 +00001170 Init *PMName = (*it)->getValueInit("PredicateMethod");
1171 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001172 CI->PredicateMethod = SI->getValue();
1173 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001174 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001175 "Unexpected PredicateMethod field!");
1176 CI->PredicateMethod = "is" + CI->ClassName;
1177 }
1178
1179 // Get or construct the render method name.
David Greene05bce0b2011-07-29 22:43:06 +00001180 Init *RMName = (*it)->getValueInit("RenderMethod");
1181 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001182 CI->RenderMethod = SI->getValue();
1183 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001184 assert(dynamic_cast<UnsetInit*>(RMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001185 "Unexpected RenderMethod field!");
1186 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1187 }
1188
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001189 // Get the parse method name or leave it as empty.
David Greene05bce0b2011-07-29 22:43:06 +00001190 Init *PRMName = (*it)->getValueInit("ParserMethod");
1191 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001192 CI->ParserMethod = SI->getValue();
1193
Daniel Dunbar338825c2009-08-10 18:41:10 +00001194 AsmOperandClasses[*it] = CI;
1195 Classes.push_back(CI);
1196 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001197}
1198
Bob Wilson828295b2011-01-26 21:26:19 +00001199AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1200 CodeGenTarget &target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +00001201 RecordKeeper &records)
Devang Patel63faf822012-01-07 01:33:34 +00001202 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001203}
1204
Jim Grosbach8caecde2012-04-19 17:52:32 +00001205/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001206/// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001207void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001208
Jim Grosbachd4824fc2012-04-18 23:46:25 +00001209 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001210 /// that class inside a instruction.
1211 std::map<ClassInfo*, unsigned> OpClassMask;
1212
1213 for (std::vector<MatchableInfo*>::const_iterator it =
1214 Matchables.begin(), ie = Matchables.end();
1215 it != ie; ++it) {
1216 MatchableInfo &II = **it;
1217 OpClassMask.clear();
1218
1219 // Keep track of all operands of this instructions which belong to the
1220 // same class.
1221 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1222 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1223 if (Op.Class->ParserMethod.empty())
1224 continue;
1225 unsigned &OperandMask = OpClassMask[Op.Class];
1226 OperandMask |= (1 << i);
1227 }
1228
1229 // Generate operand match info for each mnemonic/operand class pair.
1230 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1231 iie = OpClassMask.end(); iit != iie; ++iit) {
1232 unsigned OpMask = iit->second;
1233 ClassInfo *CI = iit->first;
Jim Grosbach8caecde2012-04-19 17:52:32 +00001234 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001235 }
1236 }
1237}
1238
Jim Grosbach8caecde2012-04-19 17:52:32 +00001239void AsmMatcherInfo::buildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +00001240 // Build information about all of the AssemblerPredicates.
1241 std::vector<Record*> AllPredicates =
1242 Records.getAllDerivedDefinitions("Predicate");
1243 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1244 Record *Pred = AllPredicates[i];
1245 // Ignore predicates that are not intended for the assembler.
1246 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1247 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001248
Chris Lattner4164f6b2010-11-01 04:44:29 +00001249 if (Pred->getName().empty())
1250 throw TGError(Pred->getLoc(), "Predicate has no name!");
Bob Wilson828295b2011-01-26 21:26:19 +00001251
Chris Lattner0aed1e72010-10-30 20:07:57 +00001252 unsigned FeatureNo = SubtargetFeatures.size();
1253 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1254 assert(FeatureNo < 32 && "Too many subtarget features!");
1255 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001256
Chris Lattner39ee0362010-10-31 19:10:56 +00001257 // Parse the instructions; we need to do this first so that we can gather the
1258 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +00001259 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel0dbcada2012-01-09 19:13:28 +00001260 unsigned VariantCount = Target.getAsmParserVariantCount();
1261 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1262 Record *AsmVariant = Target.getAsmParserVariant(VC);
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001263 std::string CommentDelimiter =
1264 AsmVariant->getValueAsString("CommentDelimiter");
Devang Patel0dbcada2012-01-09 19:13:28 +00001265 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1266 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbachf35307c2012-01-24 21:06:59 +00001267
Devang Patel0dbcada2012-01-09 19:13:28 +00001268 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
Jim Grosbach11fc6462012-04-11 21:02:33 +00001269 E = Target.inst_end(); I != E; ++I) {
Devang Patel0dbcada2012-01-09 19:13:28 +00001270 const CodeGenInstruction &CGI = **I;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001271
Devang Patel0dbcada2012-01-09 19:13:28 +00001272 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1273 // filter the set of instructions we consider.
1274 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001275 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001276
Devang Patel0dbcada2012-01-09 19:13:28 +00001277 // Ignore "codegen only" instructions.
1278 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001279 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001280
Devang Patel0dbcada2012-01-09 19:13:28 +00001281 // Validate the operand list to ensure we can handle this instruction.
1282 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
Jim Grosbach11fc6462012-04-11 21:02:33 +00001283 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1284
1285 // Validate tied operands.
1286 if (OI.getTiedRegister() != -1) {
1287 // If we have a tied operand that consists of multiple MCOperands,
1288 // reject it. We reject aliases and ignore instructions for now.
1289 if (OI.MINumOperands != 1) {
1290 // FIXME: Should reject these. The ARM backend hits this with $lane
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001291 // in a bunch of instructions. The right answer is unclear.
Jim Grosbach11fc6462012-04-11 21:02:33 +00001292 DEBUG({
1293 errs() << "warning: '" << CGI.TheDef->getName() << "': "
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001294 << "ignoring instruction with multi-operand tied operand '"
1295 << OI.Name << "'\n";
Jim Grosbach11fc6462012-04-11 21:02:33 +00001296 });
1297 continue;
1298 }
1299 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001300 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001301
Devang Patel0dbcada2012-01-09 19:13:28 +00001302 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001303
Jim Grosbach8caecde2012-04-19 17:52:32 +00001304 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001305
Devang Patel0dbcada2012-01-09 19:13:28 +00001306 // Ignore instructions which shouldn't be matched and diagnose invalid
1307 // instruction definitions with an error.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001308 if (!II->validate(CommentDelimiter, true))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001309 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001310
Devang Patel0dbcada2012-01-09 19:13:28 +00001311 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1312 //
1313 // FIXME: This is a total hack.
1314 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
Jim Grosbach11fc6462012-04-11 21:02:33 +00001315 StringRef(II->TheDef->getName()).endswith("_Int"))
1316 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001317
Devang Patel0dbcada2012-01-09 19:13:28 +00001318 Matchables.push_back(II.take());
Chris Lattner1d13bda2010-11-04 00:43:46 +00001319 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001320
Devang Patel0dbcada2012-01-09 19:13:28 +00001321 // Parse all of the InstAlias definitions and stick them in the list of
1322 // matchables.
1323 std::vector<Record*> AllInstAliases =
1324 Records.getAllDerivedDefinitions("InstAlias");
1325 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1326 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001327
Devang Patel0dbcada2012-01-09 19:13:28 +00001328 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1329 // filter the set of instruction aliases we consider, based on the target
1330 // instruction.
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001331 if (!StringRef(Alias->ResultInst->TheDef->getName())
1332 .startswith( MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001333 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001334
Devang Patel0dbcada2012-01-09 19:13:28 +00001335 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001336
Jim Grosbach8caecde2012-04-19 17:52:32 +00001337 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001338
Devang Patel0dbcada2012-01-09 19:13:28 +00001339 // Validate the alias definitions.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001340 II->validate(CommentDelimiter, false);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001341
Devang Patel0dbcada2012-01-09 19:13:28 +00001342 Matchables.push_back(II.take());
1343 }
Chris Lattnerc76e80d2010-11-01 04:05:41 +00001344 }
Chris Lattnerc240bb02010-11-01 04:03:32 +00001345
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001346 // Build info for the register classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001347 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001348
1349 // Build info for the user defined assembly operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001350 buildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001351
Chris Lattner0bb780c2010-11-04 00:57:06 +00001352 // Build the information about matchables, now that we have fully formed
1353 // classes.
Jim Grosbachc1922c72012-04-19 23:59:23 +00001354 std::vector<MatchableInfo*> NewMatchables;
Chris Lattner22bc5c42010-11-01 05:06:45 +00001355 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1356 ie = Matchables.end(); it != ie; ++it) {
1357 MatchableInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001358
Chris Lattnere206fcf2010-09-06 21:01:37 +00001359 // Parse the tokens after the mnemonic.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001360 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsona49c7df2011-01-26 19:44:55 +00001361 // don't precompute the loop bound.
1362 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +00001363 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattnerd19ec052010-11-02 17:30:52 +00001364 StringRef Token = Op.Token;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001365
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001366 // Check for singleton registers.
Devang Patel63faf822012-01-07 01:33:34 +00001367 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001368 Op.Class = RegisterClasses[RegRecord];
Chris Lattner02bcbc92010-11-01 01:37:30 +00001369 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1370 "Unexpected class for singleton register");
Chris Lattner02bcbc92010-11-01 01:37:30 +00001371 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001372 }
1373
Daniel Dunbar20927f22009-08-07 08:26:05 +00001374 // Check for simple tokens.
1375 if (Token[0] != '$') {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001376 Op.Class = getTokenClass(Token);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001377 continue;
1378 }
1379
Chris Lattner7ad31472010-11-06 22:06:03 +00001380 if (Token.size() > 1 && isdigit(Token[1])) {
1381 Op.Class = getTokenClass(Token);
1382 continue;
1383 }
Bob Wilson828295b2011-01-26 21:26:19 +00001384
Chris Lattnerc07bd402010-11-04 02:11:18 +00001385 // Otherwise this is an operand reference.
Chris Lattner5f4280c2010-11-04 01:58:23 +00001386 StringRef OperandName;
1387 if (Token[1] == '{')
1388 OperandName = Token.substr(2, Token.size() - 3);
1389 else
1390 OperandName = Token.substr(1);
Bob Wilson828295b2011-01-26 21:26:19 +00001391
Chris Lattnerc07bd402010-11-04 02:11:18 +00001392 if (II->DefRec.is<const CodeGenInstruction*>())
Jim Grosbach8caecde2012-04-19 17:52:32 +00001393 buildInstructionOperandReference(II, OperandName, i);
Chris Lattnerc07bd402010-11-04 02:11:18 +00001394 else
Jim Grosbach8caecde2012-04-19 17:52:32 +00001395 buildAliasOperandReference(II, OperandName, Op);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001396 }
Bob Wilson828295b2011-01-26 21:26:19 +00001397
Jim Grosbachc1922c72012-04-19 23:59:23 +00001398 if (II->DefRec.is<const CodeGenInstruction*>()) {
Jim Grosbach8caecde2012-04-19 17:52:32 +00001399 II->buildInstructionResultOperands();
Jim Grosbachc1922c72012-04-19 23:59:23 +00001400 // If the instruction has a two-operand alias, build up the
1401 // matchable here. We'll add them in bulk at the end to avoid
1402 // confusing this loop.
1403 std::string Constraint =
1404 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1405 if (Constraint != "") {
1406 // Start by making a copy of the original matchable.
1407 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II));
1408
1409 // Adjust it to be a two-operand alias.
1410 AliasII->formTwoOperandAlias(Constraint);
1411
1412 // Add the alias to the matchables list.
1413 NewMatchables.push_back(AliasII.take());
1414 }
1415 } else
Jim Grosbach8caecde2012-04-19 17:52:32 +00001416 II->buildAliasResultOperands();
Daniel Dunbar20927f22009-08-07 08:26:05 +00001417 }
Jim Grosbachc1922c72012-04-19 23:59:23 +00001418 if (!NewMatchables.empty())
1419 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1420 NewMatchables.end());
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001421
Jim Grosbacha66512e2011-12-06 23:43:54 +00001422 // Process token alias definitions and set up the associated superclass
1423 // information.
1424 std::vector<Record*> AllTokenAliases =
1425 Records.getAllDerivedDefinitions("TokenAlias");
1426 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1427 Record *Rec = AllTokenAliases[i];
1428 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1429 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach67cd20d2012-04-17 21:23:52 +00001430 if (FromClass == ToClass)
1431 throw TGError(Rec->getLoc(),
1432 "error: Destination value identical to source value.");
Jim Grosbacha66512e2011-12-06 23:43:54 +00001433 FromClass->SuperClasses.push_back(ToClass);
1434 }
1435
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001436 // Reorder classes so that classes precede super classes.
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001437 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001438}
1439
Jim Grosbach8caecde2012-04-19 17:52:32 +00001440/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner0bb780c2010-11-04 00:57:06 +00001441/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1442void AsmMatcherInfo::
Jim Grosbach8caecde2012-04-19 17:52:32 +00001443buildInstructionOperandReference(MatchableInfo *II,
Chris Lattner5f4280c2010-11-04 01:58:23 +00001444 StringRef OperandName,
Bob Wilsona49c7df2011-01-26 19:44:55 +00001445 unsigned AsmOpIdx) {
Chris Lattnerc07bd402010-11-04 02:11:18 +00001446 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1447 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001448 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilson828295b2011-01-26 21:26:19 +00001449
Chris Lattner662e5a32010-11-06 07:14:44 +00001450 // Map this token to an operand.
Chris Lattner0bb780c2010-11-04 00:57:06 +00001451 unsigned Idx;
1452 if (!Operands.hasOperandNamed(OperandName, Idx))
1453 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1454 OperandName.str() + "'");
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001455
Bob Wilsona49c7df2011-01-26 19:44:55 +00001456 // If the instruction operand has multiple suboperands, but the parser
1457 // match class for the asm operand is still the default "ImmAsmOperand",
1458 // then handle each suboperand separately.
1459 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1460 Record *Rec = Operands[Idx].Rec;
1461 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1462 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1463 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1464 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1465 StringRef Token = Op->Token; // save this in case Op gets moved
1466 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1467 MatchableInfo::AsmOperand NewAsmOp(Token);
1468 NewAsmOp.SubOpIdx = SI;
1469 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1470 }
1471 // Replace Op with first suboperand.
1472 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1473 Op->SubOpIdx = 0;
1474 }
1475 }
1476
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001477 // Set up the operand class.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001478 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001479
1480 // If the named operand is tied, canonicalize it to the untied operand.
1481 // For example, something like:
1482 // (outs GPR:$dst), (ins GPR:$src)
1483 // with an asmstring of
1484 // "inc $src"
1485 // we want to canonicalize to:
1486 // "inc $dst"
1487 // so that we know how to provide the $dst operand when filling in the result.
1488 int OITied = Operands[Idx].getTiedRegister();
Chris Lattner0bb780c2010-11-04 00:57:06 +00001489 if (OITied != -1) {
1490 // The tied operand index is an MIOperand index, find the operand that
1491 // contains it.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001492 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1493 OperandName = Operands[Idx.first].Name;
1494 Op->SubOpIdx = Idx.second;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001495 }
Bob Wilson828295b2011-01-26 21:26:19 +00001496
Bob Wilsona49c7df2011-01-26 19:44:55 +00001497 Op->SrcOpName = OperandName;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001498}
1499
Jim Grosbach8caecde2012-04-19 17:52:32 +00001500/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001501/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1502/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001503void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattnerc07bd402010-11-04 02:11:18 +00001504 StringRef OperandName,
1505 MatchableInfo::AsmOperand &Op) {
1506 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilson828295b2011-01-26 21:26:19 +00001507
Chris Lattnerc07bd402010-11-04 02:11:18 +00001508 // Set up the operand class.
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001509 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattner98c870f2010-11-06 19:25:43 +00001510 if (CGA.ResultOperands[i].isRecord() &&
1511 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattner662e5a32010-11-06 07:14:44 +00001512 // It's safe to go with the first one we find, because CodeGenInstAlias
1513 // validates that all operands with the same name have the same record.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001514 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbach48c1f842011-10-28 22:32:53 +00001515 // Use the match class from the Alias definition, not the
1516 // destination instruction, as we may have an immediate that's
1517 // being munged by the match class.
1518 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsona49c7df2011-01-26 19:44:55 +00001519 Op.SubOpIdx);
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001520 Op.SrcOpName = OperandName;
1521 return;
Chris Lattnerc07bd402010-11-04 02:11:18 +00001522 }
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001523
1524 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1525 OperandName.str() + "'");
Chris Lattnerc07bd402010-11-04 02:11:18 +00001526}
1527
Jim Grosbach8caecde2012-04-19 17:52:32 +00001528void MatchableInfo::buildInstructionResultOperands() {
Chris Lattner662e5a32010-11-06 07:14:44 +00001529 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001530
Chris Lattner662e5a32010-11-06 07:14:44 +00001531 // Loop over all operands of the result instruction, determining how to
1532 // populate them.
1533 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1534 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
Chris Lattner567820c2010-11-04 01:42:59 +00001535
1536 // If this is a tied operand, just copy from the previously handled operand.
1537 int TiedOp = OpInfo.getTiedRegister();
1538 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001539 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner567820c2010-11-04 01:42:59 +00001540 continue;
1541 }
Bob Wilson828295b2011-01-26 21:26:19 +00001542
Bob Wilsona49c7df2011-01-26 19:44:55 +00001543 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001544 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001545 if (OpInfo.Name.empty() || SrcOperand == -1)
1546 throw TGError(TheDef->getLoc(), "Instruction '" +
1547 TheDef->getName() + "' has operand '" + OpInfo.Name +
1548 "' that doesn't appear in asm string!");
Chris Lattner567820c2010-11-04 01:42:59 +00001549
Bob Wilsona49c7df2011-01-26 19:44:55 +00001550 // Check if the one AsmOperand populates the entire operand.
1551 unsigned NumOperands = OpInfo.MINumOperands;
1552 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1553 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner1d13bda2010-11-04 00:43:46 +00001554 continue;
1555 }
Bob Wilsona49c7df2011-01-26 19:44:55 +00001556
1557 // Add a separate ResOperand for each suboperand.
1558 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1559 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1560 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1561 "unexpected AsmOperands for suboperands");
1562 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1563 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001564 }
1565}
1566
Jim Grosbach8caecde2012-04-19 17:52:32 +00001567void MatchableInfo::buildAliasResultOperands() {
Chris Lattner41409852010-11-06 07:31:43 +00001568 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1569 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001570
Chris Lattner41409852010-11-06 07:31:43 +00001571 // Loop over all operands of the result instruction, determining how to
1572 // populate them.
1573 unsigned AliasOpNo = 0;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001574 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner41409852010-11-06 07:31:43 +00001575 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001576 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilson828295b2011-01-26 21:26:19 +00001577
Chris Lattner41409852010-11-06 07:31:43 +00001578 // If this is a tied operand, just copy from the previously handled operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001579 int TiedOp = OpInfo->getTiedRegister();
Chris Lattner41409852010-11-06 07:31:43 +00001580 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001581 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner90fd7972010-11-06 19:57:21 +00001582 continue;
1583 }
1584
Bob Wilsona49c7df2011-01-26 19:44:55 +00001585 // Handle all the suboperands for this operand.
1586 const std::string &OpName = OpInfo->Name;
1587 for ( ; AliasOpNo < LastOpNo &&
1588 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1589 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1590
1591 // Find out what operand from the asmparser that this MCInst operand
1592 // comes from.
1593 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001594 case CodeGenInstAlias::ResultOperand::K_Record: {
1595 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8caecde2012-04-19 17:52:32 +00001596 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001597 if (SrcOperand == -1)
1598 throw TGError(TheDef->getLoc(), "Instruction '" +
1599 TheDef->getName() + "' has operand '" + OpName +
1600 "' that doesn't appear in asm string!");
1601 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1602 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1603 NumOperands));
1604 break;
1605 }
1606 case CodeGenInstAlias::ResultOperand::K_Imm: {
1607 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1608 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1609 break;
1610 }
1611 case CodeGenInstAlias::ResultOperand::K_Reg: {
1612 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1613 ResOperands.push_back(ResOperand::getRegOp(Reg));
1614 break;
1615 }
1616 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001617 }
Chris Lattner41409852010-11-06 07:31:43 +00001618 }
1619}
Chris Lattner1d13bda2010-11-04 00:43:46 +00001620
Jim Grosbach8caecde2012-04-19 17:52:32 +00001621static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
Chris Lattner22bc5c42010-11-01 05:06:45 +00001622 std::vector<MatchableInfo*> &Infos,
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001623 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001624 // Write the convert function to a separate stream, so we can drop it after
1625 // the enum.
1626 std::string ConvertFnBody;
1627 raw_string_ostream CvtOS(ConvertFnBody);
1628
Daniel Dunbar20927f22009-08-07 08:26:05 +00001629 // Function we have already generated.
1630 std::set<std::string> GeneratedFns;
1631
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001632 // Start the unified conversion function.
Daniel Dunbar5c228a92011-02-04 23:17:40 +00001633 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1634 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001635 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001636 << " const SmallVectorImpl<MCParsedAsmOperand*"
1637 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001638 CvtOS << " Inst.setOpcode(Opcode);\n";
1639 CvtOS << " switch (Kind) {\n";
1640 CvtOS << " default:\n";
1641
1642 // Start the enum, which we will generate inline.
1643
Chris Lattnerd51257a2010-11-02 23:18:43 +00001644 OS << "// Unified function for converting operands to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001645 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001646
Chris Lattner98986712010-01-14 22:21:20 +00001647 // TargetOperandClass - This is the target's operand class, like X86Operand.
1648 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001649
Chris Lattner22bc5c42010-11-01 05:06:45 +00001650 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
Daniel Dunbar20927f22009-08-07 08:26:05 +00001651 ie = Infos.end(); it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00001652 MatchableInfo &II = **it;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001653
Daniel Dunbarcf120672011-02-04 17:12:15 +00001654 // Check if we have a custom match function.
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001655 std::string AsmMatchConverter =
1656 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Daniel Dunbarcf120672011-02-04 17:12:15 +00001657 if (!AsmMatchConverter.empty()) {
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001658 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Daniel Dunbarcf120672011-02-04 17:12:15 +00001659 II.ConversionFnKind = Signature;
1660
1661 // Check if we have already generated this signature.
1662 if (!GeneratedFns.insert(Signature).second)
1663 continue;
1664
1665 // If not, emit it now. Add to the enum list.
1666 OS << " " << Signature << ",\n";
1667
1668 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001669 CvtOS << " return " << AsmMatchConverter
1670 << "(Inst, Opcode, Operands);\n";
Daniel Dunbarcf120672011-02-04 17:12:15 +00001671 continue;
1672 }
1673
Daniel Dunbar20927f22009-08-07 08:26:05 +00001674 // Build the conversion function signature.
1675 std::string Signature = "Convert";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001676 std::string CaseBody;
1677 raw_string_ostream CaseOS(CaseBody);
Bob Wilson828295b2011-01-26 21:26:19 +00001678
Chris Lattnerdda855d2010-11-02 21:49:44 +00001679 // Compute the convert enum and the case body.
Chris Lattner1d13bda2010-11-04 00:43:46 +00001680 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1681 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001682
Chris Lattner1d13bda2010-11-04 00:43:46 +00001683 // Generate code to populate each result operand.
1684 switch (OpInfo.Kind) {
Chris Lattner1d13bda2010-11-04 00:43:46 +00001685 case MatchableInfo::ResOperand::RenderAsmOperand: {
1686 // This comes from something we parsed.
1687 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
Bob Wilson828295b2011-01-26 21:26:19 +00001688
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001689 // Registers are always converted the same, don't duplicate the
1690 // conversion function based on them.
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001691 Signature += "__";
1692 if (Op.Class->isRegisterClass())
1693 Signature += "Reg";
1694 else
1695 Signature += Op.Class->ClassName;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001696 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner1d13bda2010-11-04 00:43:46 +00001697 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilson828295b2011-01-26 21:26:19 +00001698
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001699 CaseOS << " ((" << TargetOperandClass << "*)Operands["
Chris Lattner1d13bda2010-11-04 00:43:46 +00001700 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
Bob Wilsona49c7df2011-01-26 19:44:55 +00001701 << "(Inst, " << OpInfo.MINumOperands << ");\n";
Chris Lattner1d13bda2010-11-04 00:43:46 +00001702 break;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001703 }
Bob Wilson828295b2011-01-26 21:26:19 +00001704
Chris Lattner1d13bda2010-11-04 00:43:46 +00001705 case MatchableInfo::ResOperand::TiedOperand: {
1706 // If this operand is tied to a previous one, just copy the MCInst
1707 // operand from the earlier one.We can only tie single MCOperand values.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001708 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001709 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001710 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001711 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1712 Signature += "__Tie" + utostr(TiedOp);
1713 break;
1714 }
Chris Lattner98c870f2010-11-06 19:25:43 +00001715 case MatchableInfo::ResOperand::ImmOperand: {
1716 int64_t Val = OpInfo.ImmVal;
1717 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1718 Signature += "__imm" + itostr(Val);
1719 break;
1720 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001721 case MatchableInfo::ResOperand::RegOperand: {
Bob Wilsondc1a2bd2011-01-14 22:58:09 +00001722 if (OpInfo.Register == 0) {
1723 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1724 Signature += "__reg0";
1725 } else {
1726 std::string N = getQualifiedName(OpInfo.Register);
1727 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1728 Signature += "__reg" + OpInfo.Register->getName();
1729 }
Bob Wilson828295b2011-01-26 21:26:19 +00001730 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001731 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001732 }
Bob Wilson828295b2011-01-26 21:26:19 +00001733
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001734 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001735
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001736 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001737 if (!GeneratedFns.insert(Signature).second)
1738 continue;
1739
Chris Lattnerdda855d2010-11-02 21:49:44 +00001740 // If not, emit it now. Add to the enum list.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001741 OS << " " << Signature << ",\n";
1742
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001743 CvtOS << " case " << Signature << ":\n";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001744 CvtOS << CaseOS.str();
Daniel Dunbarb4129152011-02-04 17:12:23 +00001745 CvtOS << " return true;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001746 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001747
1748 // Finish the convert function.
1749
1750 CvtOS << " }\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001751 CvtOS << " return false;\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001752 CvtOS << "}\n\n";
1753
1754 // Finish the enum, and drop the convert function after it.
1755
1756 OS << " NumConversionVariants\n";
1757 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001758
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001759 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001760}
1761
Jim Grosbach8caecde2012-04-19 17:52:32 +00001762/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1763static void emitMatchClassEnumeration(CodeGenTarget &Target,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001764 std::vector<ClassInfo*> &Infos,
1765 raw_ostream &OS) {
1766 OS << "namespace {\n\n";
1767
1768 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1769 << "/// instruction matching.\n";
1770 OS << "enum MatchClassKind {\n";
1771 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001772 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001773 ie = Infos.end(); it != ie; ++it) {
1774 ClassInfo &CI = **it;
1775 OS << " " << CI.Name << ", // ";
1776 if (CI.Kind == ClassInfo::Token) {
1777 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001778 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001779 if (!CI.ValueName.empty())
1780 OS << "register class '" << CI.ValueName << "'\n";
1781 else
1782 OS << "derived register class\n";
1783 } else {
1784 OS << "user defined class '" << CI.ValueName << "'\n";
1785 }
1786 }
1787 OS << " NumMatchClassKinds\n";
1788 OS << "};\n\n";
1789
1790 OS << "}\n\n";
1791}
1792
Jim Grosbach8caecde2012-04-19 17:52:32 +00001793/// emitValidateOperandClass - Emit the function to validate an operand class.
1794static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001795 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001796 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001797 << "MatchClassKind Kind) {\n";
1798 OS << " " << Info.Target.getName() << "Operand &Operand = *("
Chris Lattner02bcbc92010-11-01 01:37:30 +00001799 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001800
Kevin Enderby89381832011-07-15 18:30:43 +00001801 // The InvalidMatchClass is not to match any operand.
1802 OS << " if (Kind == InvalidMatchClass)\n";
1803 OS << " return false;\n\n";
1804
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001805 // Check for Token operands first.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001806 OS << " if (Operand.isToken())\n";
Jim Grosbacha66512e2011-12-06 23:43:54 +00001807 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1808 << "\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001809
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001810 // Check for register operands, including sub-classes.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001811 OS << " if (Operand.isReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001812 OS << " MatchClassKind OpKind;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001813 OS << " switch (Operand.getReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001814 OS << " default: OpKind = InvalidMatchClass; break;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001815 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001816 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1817 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001818 OS << " case " << Info.Target.getName() << "::"
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001819 << it->first->getName() << ": OpKind = " << it->second->Name
1820 << "; break;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001821 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001822 OS << " return isSubclass(OpKind, Kind);\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001823 OS << " }\n\n";
1824
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001825 // Check the user classes. We don't care what order since we're only
1826 // actually matching against one of them.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001827 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001828 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001829 ClassInfo &CI = **it;
1830
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001831 if (!CI.isUserClass())
1832 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001833
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001834 OS << " // '" << CI.ClassName << "' class\n";
1835 OS << " if (Kind == " << CI.Name
1836 << " && Operand." << CI.PredicateMethod << "()) {\n";
1837 OS << " return true;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001838 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001839 }
Bob Wilson828295b2011-01-26 21:26:19 +00001840
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001841 OS << " return false;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001842 OS << "}\n\n";
1843}
1844
Jim Grosbach8caecde2012-04-19 17:52:32 +00001845/// emitIsSubclass - Emit the subclass predicate function.
1846static void emitIsSubclass(CodeGenTarget &Target,
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001847 std::vector<ClassInfo*> &Infos,
1848 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001849 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1850 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001851 OS << " if (A == B)\n";
1852 OS << " return true;\n\n";
1853
1854 OS << " switch (A) {\n";
1855 OS << " default:\n";
1856 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001857 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001858 ie = Infos.end(); it != ie; ++it) {
1859 ClassInfo &A = **it;
1860
Jim Grosbacha66512e2011-12-06 23:43:54 +00001861 std::vector<StringRef> SuperClasses;
1862 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1863 ie = Infos.end(); it != ie; ++it) {
1864 ClassInfo &B = **it;
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001865
Jim Grosbacha66512e2011-12-06 23:43:54 +00001866 if (&A != &B && A.isSubsetOf(B))
1867 SuperClasses.push_back(B.Name);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001868 }
Jim Grosbacha66512e2011-12-06 23:43:54 +00001869
1870 if (SuperClasses.empty())
1871 continue;
1872
1873 OS << "\n case " << A.Name << ":\n";
1874
1875 if (SuperClasses.size() == 1) {
1876 OS << " return B == " << SuperClasses.back() << ";\n";
1877 continue;
1878 }
1879
1880 OS << " switch (B) {\n";
1881 OS << " default: return false;\n";
1882 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1883 OS << " case " << SuperClasses[i] << ": return true;\n";
1884 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001885 }
1886 OS << " }\n";
1887 OS << "}\n\n";
1888}
1889
Jim Grosbach8caecde2012-04-19 17:52:32 +00001890/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar245f0582009-08-08 21:22:41 +00001891/// appropriate match class value.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001892static void emitMatchTokenString(CodeGenTarget &Target,
Daniel Dunbar245f0582009-08-08 21:22:41 +00001893 std::vector<ClassInfo*> &Infos,
1894 raw_ostream &OS) {
1895 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001896 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001897 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001898 ie = Infos.end(); it != ie; ++it) {
1899 ClassInfo &CI = **it;
1900
1901 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001902 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1903 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001904 }
1905
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001906 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001907
Chris Lattner5845e5c2010-09-06 02:01:51 +00001908 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001909
1910 OS << " return InvalidMatchClass;\n";
1911 OS << "}\n\n";
1912}
Chris Lattner70add882009-08-08 20:02:57 +00001913
Jim Grosbach8caecde2012-04-19 17:52:32 +00001914/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001915/// specific register enum.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001916static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001917 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001918 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001919 std::vector<StringMatcher::StringPair> Matches;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001920 const std::vector<CodeGenRegister*> &Regs =
1921 Target.getRegBank().getRegisters();
1922 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1923 const CodeGenRegister *Reg = Regs[i];
1924 if (Reg->TheDef->getValueAsString("AsmName").empty())
Daniel Dunbar22be5222009-07-17 18:51:11 +00001925 continue;
1926
Chris Lattner5845e5c2010-09-06 02:01:51 +00001927 Matches.push_back(StringMatcher::StringPair(
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001928 Reg->TheDef->getValueAsString("AsmName"),
1929 "return " + utostr(Reg->EnumValue) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001930 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001931
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001932 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001933
Chris Lattner5845e5c2010-09-06 02:01:51 +00001934 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001935
Daniel Dunbar245f0582009-08-08 21:22:41 +00001936 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001937 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001938}
Daniel Dunbara027d222009-07-31 02:32:59 +00001939
Jim Grosbach8caecde2012-04-19 17:52:32 +00001940/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
Daniel Dunbar54074b52010-07-19 05:44:09 +00001941/// definitions.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001942static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001943 raw_ostream &OS) {
1944 OS << "// Flags for subtarget features that participate in "
1945 << "instruction matching.\n";
1946 OS << "enum SubtargetFeatureFlag {\n";
1947 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1948 it = Info.SubtargetFeatures.begin(),
1949 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1950 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001951 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001952 }
1953 OS << " Feature_None = 0\n";
1954 OS << "};\n\n";
1955}
1956
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00001957/// emitGetSubtargetFeatureName - Emit the helper function to get the
1958/// user-level name for a subtarget feature.
1959static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
1960 OS << "// User-level names for subtarget features that participate in\n"
1961 << "// instruction matching.\n"
1962 << "static const char *getSubtargetFeatureName(unsigned Val) {\n"
1963 << " switch(Val) {\n";
1964 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1965 it = Info.SubtargetFeatures.begin(),
1966 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1967 SubtargetFeatureInfo &SFI = *it->second;
1968 // FIXME: Totally just a placeholder name to get the algorithm working.
1969 OS << " case " << SFI.getEnumName() << ": return \""
1970 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
1971 }
1972 OS << " default: return \"(unknown)\";\n";
1973 OS << " }\n}\n\n";
1974}
1975
Jim Grosbach8caecde2012-04-19 17:52:32 +00001976/// emitComputeAvailableFeatures - Emit the function to compute the list of
Daniel Dunbar54074b52010-07-19 05:44:09 +00001977/// available features given a subtarget.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001978static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001979 raw_ostream &OS) {
1980 std::string ClassName =
1981 Info.AsmParser->getValueAsString("AsmParserClassName");
1982
Chris Lattner02bcbc92010-11-01 01:37:30 +00001983 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
Evan Chengebdeeab2011-07-08 01:53:10 +00001984 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001985 OS << " unsigned Features = 0;\n";
1986 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1987 it = Info.SubtargetFeatures.begin(),
1988 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1989 SubtargetFeatureInfo &SFI = *it->second;
Evan Chengebdeeab2011-07-08 01:53:10 +00001990
1991 OS << " if (";
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001992 std::string CondStorage =
1993 SFI.TheDef->getValueAsString("AssemblerCondString");
Evan Chengfbc38d22011-07-08 18:04:22 +00001994 StringRef Conds = CondStorage;
Evan Chengebdeeab2011-07-08 01:53:10 +00001995 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1996 bool First = true;
1997 do {
1998 if (!First)
1999 OS << " && ";
2000
2001 bool Neg = false;
2002 StringRef Cond = Comma.first;
2003 if (Cond[0] == '!') {
2004 Neg = true;
2005 Cond = Cond.substr(1);
2006 }
2007
2008 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2009 if (Neg)
2010 OS << " == 0";
2011 else
2012 OS << " != 0";
2013 OS << ")";
2014
2015 if (Comma.second.empty())
2016 break;
2017
2018 First = false;
2019 Comma = Comma.second.split(',');
2020 } while (true);
2021
2022 OS << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00002023 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002024 }
2025 OS << " return Features;\n";
2026 OS << "}\n\n";
2027}
2028
Chris Lattner6fa152c2010-10-30 20:15:02 +00002029static std::string GetAliasRequiredFeatures(Record *R,
2030 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00002031 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00002032 std::string Result;
2033 unsigned NumFeatures = 0;
2034 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner4a74ee72010-11-01 02:09:21 +00002035 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilson828295b2011-01-26 21:26:19 +00002036
Chris Lattner4a74ee72010-11-01 02:09:21 +00002037 if (F == 0)
2038 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2039 "' is not marked as an AssemblerPredicate!");
Bob Wilson828295b2011-01-26 21:26:19 +00002040
Chris Lattner4a74ee72010-11-01 02:09:21 +00002041 if (NumFeatures)
2042 Result += '|';
Bob Wilson828295b2011-01-26 21:26:19 +00002043
Chris Lattner4a74ee72010-11-01 02:09:21 +00002044 Result += F->getEnumName();
2045 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00002046 }
Bob Wilson828295b2011-01-26 21:26:19 +00002047
Chris Lattner693173f2010-10-30 19:23:13 +00002048 if (NumFeatures > 1)
2049 Result = '(' + Result + ')';
2050 return Result;
2051}
2052
Jim Grosbach8caecde2012-04-19 17:52:32 +00002053/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00002054/// emit a function for them and return true, otherwise return false.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002055static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Daniel Dunbarc0a70072011-01-24 23:26:31 +00002056 // Ignore aliases when match-prefix is set.
2057 if (!MatchPrefix.empty())
2058 return false;
2059
Chris Lattner674c1dc2010-10-30 17:36:36 +00002060 std::vector<Record*> Aliases =
Chris Lattner67db8832010-12-13 00:23:57 +00002061 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00002062 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002063
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002064 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00002065 "unsigned Features) {\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002066
Chris Lattner4fd32c62010-10-30 18:56:12 +00002067 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2068 // iteration order of the map is stable.
2069 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +00002070
Chris Lattner674c1dc2010-10-30 17:36:36 +00002071 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2072 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00002073 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00002074 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00002075
2076 // Process each alias a "from" mnemonic at a time, building the code executed
2077 // by the string remapper.
2078 std::vector<StringMatcher::StringPair> Cases;
2079 for (std::map<std::string, std::vector<Record*> >::iterator
2080 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2081 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00002082 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00002083
2084 // Loop through each alias and emit code that handles each case. If there
2085 // are two instructions without predicates, emit an error. If there is one,
2086 // emit it last.
2087 std::string MatchCode;
2088 int AliasWithNoPredicate = -1;
Bob Wilson828295b2011-01-26 21:26:19 +00002089
Chris Lattner693173f2010-10-30 19:23:13 +00002090 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2091 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00002092 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002093
Chris Lattner693173f2010-10-30 19:23:13 +00002094 // If this unconditionally matches, remember it for later and diagnose
2095 // duplicates.
2096 if (FeatureMask.empty()) {
2097 if (AliasWithNoPredicate != -1) {
2098 // We can't have two aliases from the same mnemonic with no predicate.
2099 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2100 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner4164f6b2010-11-01 04:44:29 +00002101 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner693173f2010-10-30 19:23:13 +00002102 }
Bob Wilson828295b2011-01-26 21:26:19 +00002103
Chris Lattner693173f2010-10-30 19:23:13 +00002104 AliasWithNoPredicate = i;
2105 continue;
2106 }
Joerg Sonnenberger6ef6ced2011-02-17 23:22:19 +00002107 if (R->getValueAsString("ToMnemonic") == I->first)
2108 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilson828295b2011-01-26 21:26:19 +00002109
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002110 if (!MatchCode.empty())
2111 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00002112 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2113 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00002114 }
Bob Wilson828295b2011-01-26 21:26:19 +00002115
Chris Lattner693173f2010-10-30 19:23:13 +00002116 if (AliasWithNoPredicate != -1) {
2117 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002118 if (!MatchCode.empty())
2119 MatchCode += "else\n ";
2120 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00002121 }
Bob Wilson828295b2011-01-26 21:26:19 +00002122
Chris Lattner693173f2010-10-30 19:23:13 +00002123 MatchCode += "return;";
2124
2125 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00002126 }
Bob Wilson828295b2011-01-26 21:26:19 +00002127
Chris Lattner674c1dc2010-10-30 17:36:36 +00002128 StringMatcher("Mnemonic", Cases, OS).Emit();
Daniel Dunbar55b5e852011-01-18 01:59:30 +00002129 OS << "}\n\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002130
Chris Lattner7fd44892010-10-30 18:48:18 +00002131 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002132}
2133
Jim Grosbach194f3fa2012-03-01 17:30:35 +00002134static const char *getMinimalTypeForRange(uint64_t Range) {
2135 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2136 if (Range > 0xFFFF)
2137 return "uint32_t";
2138 if (Range > 0xFF)
2139 return "uint16_t";
2140 return "uint8_t";
2141}
2142
Jim Grosbach8caecde2012-04-19 17:52:32 +00002143static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002144 const AsmMatcherInfo &Info, StringRef ClassName) {
2145 // Emit the static custom operand parsing table;
2146 OS << "namespace {\n";
2147 OS << " struct OperandMatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002148 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002149 OS << " uint32_t OperandMask;\n";
2150 OS << " uint32_t Mnemonic;\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002151 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
Craig Topperfab3f7e2012-04-02 07:48:39 +00002152 << " RequiredFeatures;\n";
2153 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2154 << " Class;\n\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002155 OS << " StringRef getMnemonic() const {\n";
2156 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2157 OS << " MnemonicTable[Mnemonic]);\n";
2158 OS << " }\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002159 OS << " };\n\n";
2160
2161 OS << " // Predicate for searching for an opcode.\n";
2162 OS << " struct LessOpcodeOperand {\n";
2163 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002164 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002165 OS << " }\n";
2166 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002167 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002168 OS << " }\n";
2169 OS << " bool operator()(const OperandMatchEntry &LHS,";
2170 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002171 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002172 OS << " }\n";
2173 OS << " };\n";
2174
2175 OS << "} // end anonymous namespace.\n\n";
2176
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002177 StringToOffsetTable StringTable;
2178
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002179 OS << "static const OperandMatchEntry OperandMatchTable["
2180 << Info.OperandMatchInfo.size() << "] = {\n";
2181
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002182 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002183 for (std::vector<OperandMatchEntry>::const_iterator it =
2184 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2185 it != ie; ++it) {
2186 const OperandMatchEntry &OMI = *it;
2187 const MatchableInfo &II = *OMI.MI;
2188
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002189 OS << " { " << OMI.OperandMask;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002190
2191 OS << " /* ";
2192 bool printComma = false;
2193 for (int i = 0, e = 31; i !=e; ++i)
2194 if (OMI.OperandMask & (1 << i)) {
2195 if (printComma)
2196 OS << ", ";
2197 OS << i;
2198 printComma = true;
2199 }
2200 OS << " */";
2201
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002202 // Store a pascal-style length byte in the mnemonic.
2203 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Jakob Stoklund Olesenbcfa9822012-03-15 18:05:57 +00002204 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Craig Topperfab3f7e2012-04-02 07:48:39 +00002205 << " /* " << II.Mnemonic << " */, ";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002206
2207 // Write the required features mask.
2208 if (!II.RequiredFeatures.empty()) {
2209 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2210 if (i) OS << "|";
2211 OS << II.RequiredFeatures[i]->getEnumName();
2212 }
2213 } else
2214 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002215
2216 OS << ", " << OMI.CI->Name;
2217
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002218 OS << " },\n";
2219 }
2220 OS << "};\n\n";
2221
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002222 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002223 StringTable.EmitString(OS);
2224 OS << ";\n\n";
2225
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002226 // Emit the operand class switch to call the correct custom parser for
2227 // the found operand class.
Jim Grosbachf922c472011-02-12 01:34:40 +00002228 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2229 << Target.getName() << ClassName << "::\n"
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002230 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002231 << " &Operands,\n unsigned MCK) {\n\n"
2232 << " switch(MCK) {\n";
2233
2234 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2235 ie = Info.Classes.end(); it != ie; ++it) {
2236 ClassInfo *CI = *it;
2237 if (CI->ParserMethod.empty())
2238 continue;
2239 OS << " case " << CI->Name << ":\n"
2240 << " return " << CI->ParserMethod << "(Operands);\n";
2241 }
2242
2243 OS << " default:\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002244 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002245 OS << " }\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002246 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002247 OS << "}\n\n";
2248
2249 // Emit the static custom operand parser. This code is very similar with
2250 // the other matcher. Also use MatchResultTy here just in case we go for
2251 // a better error handling.
Jim Grosbachf922c472011-02-12 01:34:40 +00002252 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002253 << Target.getName() << ClassName << "::\n"
2254 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2255 << " &Operands,\n StringRef Mnemonic) {\n";
2256
2257 // Emit code to get the available features.
2258 OS << " // Get the current feature set.\n";
2259 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2260
2261 OS << " // Get the next operand index.\n";
2262 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2263
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002264 // Emit code to search the table.
2265 OS << " // Search the table.\n";
2266 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2267 OS << " MnemonicRange =\n";
2268 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2269 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2270 << " LessOpcodeOperand());\n\n";
2271
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002272 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002273 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002274
2275 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2276 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2277
2278 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002279 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002280
2281 // Emit check that the required features are available.
2282 OS << " // check if the available features match\n";
2283 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2284 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002285 OS << " continue;\n";
2286 OS << " }\n\n";
2287
2288 // Emit check to ensure the operand number matches.
2289 OS << " // check if the operand in question has a custom parser.\n";
2290 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2291 OS << " continue;\n\n";
2292
2293 // Emit call to the custom parser method
2294 OS << " // call custom parse method to handle the operand\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002295 OS << " OperandMatchResultTy Result = ";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002296 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002297 OS << " if (Result != MatchOperand_NoMatch)\n";
2298 OS << " return Result;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002299 OS << " }\n\n";
2300
Jim Grosbachf922c472011-02-12 01:34:40 +00002301 OS << " // Okay, we had no match.\n";
2302 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002303 OS << "}\n\n";
2304}
2305
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002306void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner67db8832010-12-13 00:23:57 +00002307 CodeGenTarget Target(Records);
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002308 Record *AsmParser = Target.getAsmParser();
2309 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2310
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002311 // Compute the information on the instructions to match.
Chris Lattner67db8832010-12-13 00:23:57 +00002312 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8caecde2012-04-19 17:52:32 +00002313 Info.buildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00002314
Daniel Dunbare1f6de32010-02-02 23:46:36 +00002315 // Sort the instruction table using the partial order on classes. We use
2316 // stable_sort to ensure that ambiguous instructions are still
2317 // deterministically ordered.
Chris Lattner22bc5c42010-11-01 05:06:45 +00002318 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2319 less_ptr<MatchableInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002320
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002321 DEBUG_WITH_TYPE("instruction_info", {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002322 for (std::vector<MatchableInfo*>::iterator
2323 it = Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002324 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00002325 (*it)->dump();
2326 });
Daniel Dunbara027d222009-07-31 02:32:59 +00002327
Chris Lattner22bc5c42010-11-01 05:06:45 +00002328 // Check for ambiguous matchables.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002329 DEBUG_WITH_TYPE("ambiguous_instrs", {
2330 unsigned NumAmbiguous = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002331 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
Chris Lattner87410362010-09-06 20:21:47 +00002332 for (unsigned j = i + 1; j != e; ++j) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002333 MatchableInfo &A = *Info.Matchables[i];
2334 MatchableInfo &B = *Info.Matchables[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00002335
Jim Grosbach8caecde2012-04-19 17:52:32 +00002336 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002337 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002338 A.dump();
2339 errs() << "\nis incomparable with:\n";
2340 B.dump();
2341 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00002342 ++NumAmbiguous;
2343 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00002344 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002345 }
Chris Lattner87410362010-09-06 20:21:47 +00002346 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00002347 errs() << "warning: " << NumAmbiguous
Chris Lattner22bc5c42010-11-01 05:06:45 +00002348 << " ambiguous matchables!\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002349 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002350
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002351 // Compute the information on the custom operand parsing.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002352 Info.buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002353
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002354 // Write the output.
2355
2356 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2357
Chris Lattner0692ee62010-09-06 19:11:01 +00002358 // Information for the class declaration.
2359 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2360 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002361 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng94b95502011-07-26 00:24:13 +00002362 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Evan Chengebdeeab2011-07-08 01:53:10 +00002363 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
Daniel Dunbar5c228a92011-02-04 23:17:40 +00002364 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2365 << "unsigned Opcode,\n"
2366 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2367 << "&Operands);\n";
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002368 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002369 OS << " unsigned MatchInstructionImpl(\n";
Daniel Dunbar083203d2011-01-10 15:26:11 +00002370 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
Devang Patel56315d32012-01-10 17:50:43 +00002371 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002372
2373 if (Info.OperandMatchInfo.size()) {
Jim Grosbachf922c472011-02-12 01:34:40 +00002374 OS << "\n enum OperandMatchResultTy {\n";
2375 OS << " MatchOperand_Success, // operand matched successfully\n";
2376 OS << " MatchOperand_NoMatch, // operand did not match\n";
2377 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2378 OS << " };\n";
2379 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002380 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2381 OS << " StringRef Mnemonic);\n";
2382
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002383 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002384 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2385 OS << " unsigned MCK);\n\n";
2386 }
2387
Chris Lattner0692ee62010-09-06 19:11:01 +00002388 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2389
Chris Lattner0692ee62010-09-06 19:11:01 +00002390 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2391 OS << "#undef GET_REGISTER_MATCHER\n\n";
2392
Daniel Dunbar54074b52010-07-19 05:44:09 +00002393 // Emit the subtarget feature enumeration.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002394 emitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002395
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002396 // Emit the function to match a register name to number.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002397 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00002398
2399 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002400
Craig Topper8030e1a2012-04-25 06:56:34 +00002401 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2402 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002403
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002404 // Generate the helper function to get the names for subtarget features.
2405 emitGetSubtargetFeatureName(Info, OS);
2406
Craig Topper8030e1a2012-04-25 06:56:34 +00002407 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2408
2409 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2410 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2411
Chris Lattner7fd44892010-10-30 18:48:18 +00002412 // Generate the function that remaps for mnemonic aliases.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002413 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002414
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002415 // Generate the unified function to convert operands into an MCInst.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002416 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002417
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002418 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002419 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002420
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002421 // Emit the routine to match token strings to their match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002422 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002423
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002424 // Emit the subclass predicate routine.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002425 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002426
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002427 // Emit the routine to validate an operand against a match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002428 emitValidateOperandClass(Info, OS);
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002429
Daniel Dunbar54074b52010-07-19 05:44:09 +00002430 // Emit the available features compute function.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002431 emitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002432
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002433
2434 size_t MaxNumOperands = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002435 for (std::vector<MatchableInfo*>::const_iterator it =
2436 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002437 it != ie; ++it)
Chris Lattner3116fef2010-11-02 01:03:43 +00002438 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002439
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002440 // Emit the static match table; unused classes get initalized to 0 which is
2441 // guaranteed to be InvalidMatchClass.
2442 //
2443 // FIXME: We can reduce the size of this table very easily. First, we change
2444 // it so that store the kinds in separate bit-fields for each index, which
2445 // only needs to be the max width used for classes at that index (we also need
2446 // to reject based on this during classification). If we then make sure to
2447 // order the match kinds appropriately (putting mnemonics last), then we
2448 // should only end up using a few bits for each class, especially the ones
2449 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00002450 OS << "namespace {\n";
2451 OS << " struct MatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002452 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002453 OS << " uint32_t Mnemonic;\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002454 OS << " uint16_t Opcode;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002455 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2456 << " ConvertFn;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002457 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2458 << " RequiredFeatures;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002459 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2460 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002461 OS << " uint8_t AsmVariantID;\n\n";
2462 OS << " StringRef getMnemonic() const {\n";
2463 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2464 OS << " MnemonicTable[Mnemonic]);\n";
2465 OS << " }\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002466 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002467
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002468 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002469 OS << " struct LessOpcode {\n";
2470 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002471 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002472 OS << " }\n";
2473 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002474 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002475 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002476 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002477 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002478 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00002479 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002480
Chris Lattner96352e52010-09-06 21:08:38 +00002481 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002482
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002483 StringToOffsetTable StringTable;
2484
Chris Lattner96352e52010-09-06 21:08:38 +00002485 OS << "static const MatchEntry MatchTable["
Chris Lattner22bc5c42010-11-01 05:06:45 +00002486 << Info.Matchables.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002487
Chris Lattner22bc5c42010-11-01 05:06:45 +00002488 for (std::vector<MatchableInfo*>::const_iterator it =
2489 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002490 it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002491 MatchableInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00002492
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002493 // Store a pascal-style length byte in the mnemonic.
2494 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Craig Topperfab3f7e2012-04-02 07:48:39 +00002495 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2496 << " /* " << II.Mnemonic << " */, "
2497 << Target.getName() << "::"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002498 << II.getResultInst()->TheDef->getName() << ", "
Craig Topperfab3f7e2012-04-02 07:48:39 +00002499 << II.ConversionFnKind << ", ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002500
Daniel Dunbar54074b52010-07-19 05:44:09 +00002501 // Write the required features mask.
2502 if (!II.RequiredFeatures.empty()) {
2503 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2504 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00002505 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00002506 }
2507 } else
2508 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002509
2510 OS << ", { ";
2511 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2512 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2513
2514 if (i) OS << ", ";
2515 OS << Op.Class->Name;
2516 }
2517 OS << " }, " << II.AsmVariantID;
Daniel Dunbar54074b52010-07-19 05:44:09 +00002518 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002519 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00002520
Chris Lattner96352e52010-09-06 21:08:38 +00002521 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002522
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002523 OS << "const char *const MatchEntry::MnemonicTable =\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002524 StringTable.EmitString(OS);
2525 OS << ";\n\n";
2526
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002527 // A method to determine if a mnemonic is in the list.
2528 OS << "bool " << Target.getName() << ClassName << "::\n"
2529 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2530 OS << " // Search the table.\n";
2531 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2532 OS << " std::equal_range(MatchTable, MatchTable+"
2533 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2534 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2535 OS << "}\n\n";
2536
Chris Lattner96352e52010-09-06 21:08:38 +00002537 // Finally, build the match function.
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002538 OS << "unsigned "
Chris Lattner96352e52010-09-06 21:08:38 +00002539 << Target.getName() << ClassName << "::\n"
2540 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2541 << " &Operands,\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002542 OS << " MCInst &Inst, unsigned &ErrorInfo, ";
2543 OS << "unsigned VariantID) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002544
2545 // Emit code to get the available features.
2546 OS << " // Get the current feature set.\n";
2547 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2548
Chris Lattner674c1dc2010-10-30 17:36:36 +00002549 OS << " // Get the instruction mnemonic, which is the first token.\n";
2550 OS << " StringRef Mnemonic = ((" << Target.getName()
2551 << "Operand*)Operands[0])->getToken();\n\n";
2552
Chris Lattner7fd44892010-10-30 18:48:18 +00002553 if (HasMnemonicAliases) {
2554 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Devang Patel40bced02012-01-17 18:30:45 +00002555 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2556 OS << " if (!VariantID)\n";
2557 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
Chris Lattner7fd44892010-10-30 18:48:18 +00002558 }
Bob Wilson828295b2011-01-26 21:26:19 +00002559
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002560 // Emit code to compute the class list for this operand vector.
2561 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002562 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2563 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2564 OS << " return Match_InvalidOperand;\n";
2565 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002566
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002567 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002568 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002569 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002570 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002571 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002572 OS << " // wrong for all instances of the instruction.\n";
2573 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002574
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002575 // Emit code to search the table.
2576 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002577 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2578 OS << " std::equal_range(MatchTable, MatchTable+"
Chris Lattner22bc5c42010-11-01 05:06:45 +00002579 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002580
Chris Lattnera008e8a2010-09-06 21:54:15 +00002581 OS << " // Return a more specific error code if no mnemonics match.\n";
2582 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2583 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002584
Chris Lattner2b1f9432010-09-06 21:22:45 +00002585 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00002586 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002587 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002588
Gabor Greife53ee3b2010-09-07 06:06:06 +00002589 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002590 OS << " assert(Mnemonic == it->getMnemonic());\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002591
Daniel Dunbar54074b52010-07-19 05:44:09 +00002592 // Emit check that the subclasses match.
Devang Patel56315d32012-01-10 17:50:43 +00002593 OS << " if (VariantID != it->AsmVariantID) continue;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002594 OS << " bool OperandsValid = true;\n";
2595 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002596 OS << " if (i + 1 >= Operands.size()) {\n";
2597 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
Jim Grosbachb9d5af02011-05-03 19:09:56 +00002598 OS << " break;\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002599 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002600 OS << " if (validateOperandClass(Operands[i+1], "
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002601 "(MatchClassKind)it->Classes[i]))\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002602 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002603 OS << " // If this operand is broken for all of the instances of this\n";
2604 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Kevin Enderby79fcb6d2011-02-02 18:20:55 +00002605 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002606 OS << " ErrorInfo = i+1;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002607 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2608 OS << " OperandsValid = false;\n";
2609 OS << " break;\n";
2610 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002611
Chris Lattnerce4a3352010-09-06 22:11:18 +00002612 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00002613
2614 // Emit check that the required features are available.
2615 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2616 << "!= it->RequiredFeatures) {\n";
2617 OS << " HadMatchOtherThanFeatures = true;\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002618 OS << " ErrorInfo = it->RequiredFeatures & ~AvailableFeatures;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00002619 OS << " continue;\n";
2620 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002621 OS << "\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00002622 OS << " // We have selected a definite instruction, convert the parsed\n"
2623 << " // operands into the appropriate MCInst.\n";
2624 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2625 << " it->Opcode, Operands))\n";
2626 OS << " return Match_ConversionFail;\n";
2627 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002628
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002629 // Verify the instruction with the target-specific match predicate function.
2630 OS << " // We have a potential match. Check the target predicate to\n"
2631 << " // handle any context sensitive constraints.\n"
2632 << " unsigned MatchResult;\n"
2633 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2634 << " Match_Success) {\n"
2635 << " Inst.clear();\n"
2636 << " RetCode = MatchResult;\n"
Jim Grosbach578071a2011-08-16 20:12:35 +00002637 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002638 << " continue;\n"
2639 << " }\n\n";
2640
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002641 // Call the post-processing function, if used.
2642 std::string InsnCleanupFn =
2643 AsmParser->getValueAsString("AsmParserInstCleanup");
2644 if (!InsnCleanupFn.empty())
2645 OS << " " << InsnCleanupFn << "(Inst);\n";
2646
Chris Lattner79ed3f72010-09-06 19:22:17 +00002647 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002648 OS << " }\n\n";
2649
Chris Lattnerec6789f2010-09-06 20:08:02 +00002650 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002651 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2652 OS << " return RetCode;\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002653 OS << " assert(ErrorInfo && \"missing feature(s) but what?!\");";
Jim Grosbach578071a2011-08-16 20:12:35 +00002654 OS << " return Match_MissingFeature;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002655 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002656
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002657 if (Info.OperandMatchInfo.size())
Jim Grosbach8caecde2012-04-19 17:52:32 +00002658 emitCustomOperandParsing(OS, Target, Info, ClassName);
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002659
Chris Lattner0692ee62010-09-06 19:11:01 +00002660 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00002661}