blob: 2cfcadd5e80a24233c1b5c450b9d9813c48b4311 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
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/// \file
11/// This tablegen backend emits code for use by the GlobalISel instruction
12/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13///
14/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15/// backend, filters out the ones that are unsupported, maps
16/// SelectionDAG-specific constructs to their GlobalISel counterpart
17/// (when applicable: MVT to LLT; SDNode to generic Instruction).
18///
19/// Not all patterns are supported: pass the tablegen invocation
20/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21/// as well as why.
22///
23/// The generated file defines a single method:
24/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25/// intended to be used in InstructionSelector::select as the first-step
26/// selector for the patterns that don't require complex C++.
27///
28/// FIXME: We'll probably want to eventually define a base
29/// "TargetGenInstructionSelector" class.
30///
31//===----------------------------------------------------------------------===//
32
33#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000034#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000035#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000036#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000037#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/MachineValueType.h"
39#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000040#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000041#include "llvm/Support/LowLevelTypeImpl.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
46#include <string>
Daniel Sanders8a4bae92017-03-14 21:32:08 +000047#include <numeric>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000055STATISTIC(NumPatternEmitted, "Number of patterns emitted");
Daniel Sandersc60abe32017-07-04 15:31:50 +000056/// A unique identifier for a MatchTable.
57static unsigned CurrentMatchTableID = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +000058
Daniel Sanders0848b232017-03-27 13:15:13 +000059cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60
Ahmed Bougacha36f70352016-12-21 23:26:20 +000061static cl::opt<bool> WarnOnSkippedPatterns(
62 "warn-on-skipped-patterns",
63 cl::desc("Explain why a pattern was skipped for inclusion "
64 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000065 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066
Daniel Sandersbdfebb82017-03-15 20:18:38 +000067namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000068//===- Helper functions ---------------------------------------------------===//
69
Daniel Sanders52b4ce72017-03-07 23:20:35 +000070/// This class stands in for LLT wherever we want to tablegen-erate an
71/// equivalent at compiler run-time.
72class LLTCodeGen {
73private:
74 LLT Ty;
75
76public:
77 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
78
Daniel Sanders7aac7cc2017-07-20 09:25:44 +000079 std::string getCxxEnumValue() const {
80 std::string Str;
81 raw_string_ostream OS(Str);
82
83 emitCxxEnumValue(OS);
84 return OS.str();
85 }
86
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000087 void emitCxxEnumValue(raw_ostream &OS) const {
88 if (Ty.isScalar()) {
89 OS << "GILLT_s" << Ty.getSizeInBits();
90 return;
91 }
92 if (Ty.isVector()) {
93 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
94 return;
95 }
96 llvm_unreachable("Unhandled LLT");
97 }
98
Daniel Sanders52b4ce72017-03-07 23:20:35 +000099 void emitCxxConstructorCall(raw_ostream &OS) const {
100 if (Ty.isScalar()) {
101 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
102 return;
103 }
104 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000105 OS << "LLT::vector(" << Ty.getNumElements() << ", "
106 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000107 return;
108 }
109 llvm_unreachable("Unhandled LLT");
110 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000111
112 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000113
114 /// This ordering is used for std::unique() and std::sort(). There's no
115 /// particular logic behind the order.
116 bool operator<(const LLTCodeGen &Other) const {
117 if (!Ty.isValid())
118 return Other.Ty.isValid();
119 if (Ty.isScalar()) {
120 if (!Other.Ty.isValid())
121 return false;
122 if (Other.Ty.isScalar())
123 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
124 return false;
125 }
126 if (Ty.isVector()) {
127 if (!Other.Ty.isValid() || Other.Ty.isScalar())
128 return false;
129 if (Other.Ty.isVector()) {
130 if (Ty.getNumElements() < Other.Ty.getNumElements())
131 return true;
132 if (Ty.getNumElements() > Other.Ty.getNumElements())
133 return false;
134 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
135 }
136 return false;
137 }
138 llvm_unreachable("Unhandled LLT");
139 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000140};
141
142class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000143/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
144/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000145static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000146 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000147 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000148 return LLTCodeGen(
149 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000150 if (VT.isInteger() || VT.isFloatingPoint())
151 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
152 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000153}
154
Daniel Sandersd0656a32017-04-13 09:45:37 +0000155static std::string explainPredicates(const TreePatternNode *N) {
156 std::string Explanation = "";
157 StringRef Separator = "";
158 for (const auto &P : N->getPredicateFns()) {
159 Explanation +=
160 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
161 if (P.isAlwaysTrue())
162 Explanation += " always-true";
163 if (P.isImmediatePattern())
164 Explanation += " immediate";
165 }
166 return Explanation;
167}
168
Daniel Sandersd0656a32017-04-13 09:45:37 +0000169std::string explainOperator(Record *Operator) {
170 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000171 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000172
173 if (Operator->isSubClassOf("Intrinsic"))
174 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
175
176 return " (Operator not understood)";
177}
178
179/// Helper function to let the emitter report skip reason error messages.
180static Error failedImport(const Twine &Reason) {
181 return make_error<StringError>(Reason, inconvertibleErrorCode());
182}
183
184static Error isTrivialOperatorNode(const TreePatternNode *N) {
185 std::string Explanation = "";
186 std::string Separator = "";
187 if (N->isLeaf()) {
Daniel Sanders3334cc02017-05-23 20:02:48 +0000188 if (isa<IntInit>(N->getLeafValue()))
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000189 return Error::success();
190
Daniel Sandersd0656a32017-04-13 09:45:37 +0000191 Explanation = "Is a leaf";
192 Separator = ", ";
193 }
194
195 if (N->hasAnyPredicate()) {
196 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
197 Separator = ", ";
198 }
199
200 if (N->getTransformFn()) {
201 Explanation += Separator + "Has a transform function";
202 Separator = ", ";
203 }
204
205 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
206 return Error::success();
207
208 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000209}
210
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000211static Record *getInitValueAsRegClass(Init *V) {
212 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
213 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
214 return VDefInit->getDef()->getValueAsDef("RegClass");
215 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
216 return VDefInit->getDef();
217 }
218 return nullptr;
219}
220
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000221std::string
222getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
223 std::string Name = "GIFBS";
224 for (const auto &Feature : FeatureBitset)
225 Name += ("_" + Feature->getName()).str();
226 return Name;
227}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000228
229//===- MatchTable Helpers -------------------------------------------------===//
230
231class MatchTable;
232
233/// A record to be stored in a MatchTable.
234///
235/// This class represents any and all output that may be required to emit the
236/// MatchTable. Instances are most often configured to represent an opcode or
237/// value that will be emitted to the table with some formatting but it can also
238/// represent commas, comments, and other formatting instructions.
239struct MatchTableRecord {
240 enum RecordFlagsBits {
241 MTRF_None = 0x0,
242 /// Causes EmitStr to be formatted as comment when emitted.
243 MTRF_Comment = 0x1,
244 /// Causes the record value to be followed by a comma when emitted.
245 MTRF_CommaFollows = 0x2,
246 /// Causes the record value to be followed by a line break when emitted.
247 MTRF_LineBreakFollows = 0x4,
248 /// Indicates that the record defines a label and causes an additional
249 /// comment to be emitted containing the index of the label.
250 MTRF_Label = 0x8,
251 /// Causes the record to be emitted as the index of the label specified by
252 /// LabelID along with a comment indicating where that label is.
253 MTRF_JumpTarget = 0x10,
254 /// Causes the formatter to add a level of indentation before emitting the
255 /// record.
256 MTRF_Indent = 0x20,
257 /// Causes the formatter to remove a level of indentation after emitting the
258 /// record.
259 MTRF_Outdent = 0x40,
260 };
261
262 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
263 /// reference or define.
264 unsigned LabelID;
265 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
266 /// value, a label name.
267 std::string EmitStr;
268
269private:
270 /// The number of MatchTable elements described by this record. Comments are 0
271 /// while values are typically 1. Values >1 may occur when we need to emit
272 /// values that exceed the size of a MatchTable element.
273 unsigned NumElements;
274
275public:
276 /// A bitfield of RecordFlagsBits flags.
277 unsigned Flags;
278
279 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
280 unsigned NumElements, unsigned Flags)
281 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
282 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
283 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
284 "This value is reserved for non-labels");
285 }
286
287 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
288 const MatchTable &Table) const;
289 unsigned size() const { return NumElements; }
290};
291
292/// Holds the contents of a generated MatchTable to enable formatting and the
293/// necessary index tracking needed to support GIM_Try.
294class MatchTable {
295 /// An unique identifier for the table. The generated table will be named
296 /// MatchTable${ID}.
297 unsigned ID;
298 /// The records that make up the table. Also includes comments describing the
299 /// values being emitted and line breaks to format it.
300 std::vector<MatchTableRecord> Contents;
301 /// The currently defined labels.
302 DenseMap<unsigned, unsigned> LabelMap;
303 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
304 unsigned CurrentSize;
305
306public:
307 static MatchTableRecord LineBreak;
308 static MatchTableRecord Comment(StringRef Comment) {
309 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
310 }
311 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
312 unsigned ExtraFlags = 0;
313 if (IndentAdjust > 0)
314 ExtraFlags |= MatchTableRecord::MTRF_Indent;
315 if (IndentAdjust < 0)
316 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
317
318 return MatchTableRecord(None, Opcode, 1,
319 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
320 }
321 static MatchTableRecord NamedValue(StringRef NamedValue) {
322 return MatchTableRecord(None, NamedValue, 1,
323 MatchTableRecord::MTRF_CommaFollows);
324 }
325 static MatchTableRecord NamedValue(StringRef Namespace,
326 StringRef NamedValue) {
327 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
328 MatchTableRecord::MTRF_CommaFollows);
329 }
330 static MatchTableRecord IntValue(int64_t IntValue) {
331 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
332 MatchTableRecord::MTRF_CommaFollows);
333 }
334 static MatchTableRecord Label(unsigned LabelID) {
335 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
336 MatchTableRecord::MTRF_Label |
337 MatchTableRecord::MTRF_Comment |
338 MatchTableRecord::MTRF_LineBreakFollows);
339 }
340 static MatchTableRecord JumpTarget(unsigned LabelID) {
341 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
342 MatchTableRecord::MTRF_JumpTarget |
343 MatchTableRecord::MTRF_Comment |
344 MatchTableRecord::MTRF_CommaFollows);
345 }
346
347 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
348
349 void push_back(const MatchTableRecord &Value) {
350 if (Value.Flags & MatchTableRecord::MTRF_Label)
351 defineLabel(Value.LabelID);
352 Contents.push_back(Value);
353 CurrentSize += Value.size();
354 }
355
356 void defineLabel(unsigned LabelID) {
357 LabelMap.insert(std::make_pair(LabelID, CurrentSize + 1));
358 }
359
360 unsigned getLabelIndex(unsigned LabelID) const {
361 const auto I = LabelMap.find(LabelID);
362 assert(I != LabelMap.end() && "Use of undeclared label");
363 return I->second;
364 }
365
366 void emit(raw_ostream &OS) const {
367 unsigned Indentation = 4;
368 OS << " const static int64_t MatchTable" << ID << "[] = {";
369 LineBreak.emit(OS, true, *this);
370 OS << std::string(Indentation, ' ');
371
372 for (auto I = Contents.begin(), E = Contents.end(); I != E;
373 ++I) {
374 bool LineBreakIsNext = false;
375 const auto &NextI = std::next(I);
376
377 if (NextI != E) {
378 if (NextI->EmitStr == "" &&
379 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
380 LineBreakIsNext = true;
381 }
382
383 if (I->Flags & MatchTableRecord::MTRF_Indent)
384 Indentation += 2;
385
386 I->emit(OS, LineBreakIsNext, *this);
387 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
388 OS << std::string(Indentation, ' ');
389
390 if (I->Flags & MatchTableRecord::MTRF_Outdent)
391 Indentation -= 2;
392 }
393 OS << "};\n";
394 }
395};
396
397MatchTableRecord MatchTable::LineBreak = {
398 None, "" /* Emit String */, 0 /* Elements */,
399 MatchTableRecord::MTRF_LineBreakFollows};
400
401void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
402 const MatchTable &Table) const {
403 bool UseLineComment =
404 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
405 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
406 UseLineComment = false;
407
408 if (Flags & MTRF_Comment)
409 OS << (UseLineComment ? "// " : "/*");
410
411 OS << EmitStr;
412 if (Flags & MTRF_Label)
413 OS << ": @" << Table.getLabelIndex(LabelID);
414
415 if (Flags & MTRF_Comment && !UseLineComment)
416 OS << "*/";
417
418 if (Flags & MTRF_JumpTarget) {
419 if (Flags & MTRF_Comment)
420 OS << " ";
421 OS << Table.getLabelIndex(LabelID);
422 }
423
424 if (Flags & MTRF_CommaFollows) {
425 OS << ",";
426 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
427 OS << " ";
428 }
429
430 if (Flags & MTRF_LineBreakFollows)
431 OS << "\n";
432}
433
434MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
435 Table.push_back(Value);
436 return Table;
437}
438
439raw_ostream &operator<<(raw_ostream &OS, const MatchTable &Table) {
440 Table.emit(OS);
441 return OS;
442}
443
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000444//===- Matchers -----------------------------------------------------------===//
445
Daniel Sandersbee57392017-04-04 13:25:23 +0000446class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000447class MatchAction;
448
449/// Generates code to check that a match rule matches.
450class RuleMatcher {
451 /// A list of matchers that all need to succeed for the current rule to match.
452 /// FIXME: This currently supports a single match position but could be
453 /// extended to support multiple positions to support div/rem fusion or
454 /// load-multiple instructions.
455 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
456
457 /// A list of actions that need to be taken when all predicates in this rule
458 /// have succeeded.
459 std::vector<std::unique_ptr<MatchAction>> Actions;
460
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000461 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000462 /// emitCaptureOpcodes().
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000463 std::map<const InstructionMatcher *, unsigned> InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000464
465 /// ID for the next instruction variable defined with defineInsnVar()
466 unsigned NextInsnVarID;
467
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000468 std::vector<Record *> RequiredFeatures;
469
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000470public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000471 RuleMatcher()
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000472 : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000473 RuleMatcher(RuleMatcher &&Other) = default;
474 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000475
476 InstructionMatcher &addInstructionMatcher();
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000477 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000478 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000479
480 template <class Kind, class... Args> Kind &addAction(Args &&... args);
481
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000482 /// Define an instruction without emitting any code to do so.
483 /// This is used for the root of the match.
484 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
485 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000486 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000487 unsigned InsnVarID, unsigned OpIdx);
488 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000489
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000490 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000491
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000492 void emit(raw_ostream &OS);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000493
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000494 /// Compare the priority of this object and B.
495 ///
496 /// Returns true if this object is more important than B.
497 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000498
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000499 /// Report the maximum number of temporary operands needed by the rule
500 /// matcher.
501 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000502
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000503 // FIXME: Remove this as soon as possible
504 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000505};
506
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000507template <class PredicateTy> class PredicateListMatcher {
508private:
509 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
510 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000511
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000512public:
513 /// Construct a new operand predicate and add it to the matcher.
514 template <class Kind, class... Args>
515 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000516 Predicates.emplace_back(
517 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000518 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000519 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000520
Daniel Sanders32291982017-06-28 13:50:04 +0000521 typename PredicateVec::const_iterator predicates_begin() const {
522 return Predicates.begin();
523 }
524 typename PredicateVec::const_iterator predicates_end() const {
525 return Predicates.end();
526 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000527 iterator_range<typename PredicateVec::const_iterator> predicates() const {
528 return make_range(predicates_begin(), predicates_end());
529 }
Daniel Sanders32291982017-06-28 13:50:04 +0000530 typename PredicateVec::size_type predicates_size() const {
531 return Predicates.size();
532 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000533
Daniel Sanders9d662d22017-07-06 10:06:12 +0000534 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000535 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000536 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000537 if (Predicates.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000538 Table << MatchTable::Comment("No predicates") << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000539 return;
540 }
541
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000542 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000543 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000544 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000545};
546
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000547/// Generates code to check a predicate of an operand.
548///
549/// Typical predicates include:
550/// * Operand is a particular register.
551/// * Operand is assigned a particular register bank.
552/// * Operand is an MBB.
553class OperandPredicateMatcher {
554public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000555 /// This enum is used for RTTI and also defines the priority that is given to
556 /// the predicate when generating the matcher code. Kinds with higher priority
557 /// must be tested first.
558 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000559 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
560 /// but OPM_Int must have priority over OPM_RegBank since constant integers
561 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000562 enum PredicateKind {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000563 OPM_ComplexPattern,
Daniel Sandersbee57392017-04-04 13:25:23 +0000564 OPM_Instruction,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000565 OPM_IntrinsicID,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000566 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000567 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000568 OPM_LLT,
569 OPM_RegBank,
570 OPM_MBB,
571 };
572
573protected:
574 PredicateKind Kind;
575
576public:
577 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000578 virtual ~OperandPredicateMatcher() {}
579
Daniel Sanders759ff412017-02-24 13:58:11 +0000580 PredicateKind getKind() const { return Kind; }
581
Daniel Sandersbee57392017-04-04 13:25:23 +0000582 /// Return the OperandMatcher for the specified operand or nullptr if there
583 /// isn't one by that name in this operand predicate matcher.
584 ///
585 /// InstructionOperandMatcher is the only subclass that can return non-null
586 /// for this.
587 virtual Optional<const OperandMatcher *>
Daniel Sandersdb7ed372017-04-04 13:52:00 +0000588 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000589 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
590 return None;
591 }
592
Daniel Sanders9d662d22017-07-06 10:06:12 +0000593 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000594 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000595 /// Only InstructionOperandMatcher needs to do anything for this method the
596 /// rest just walk the tree.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000597 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000598 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000599
Daniel Sanders9d662d22017-07-06 10:06:12 +0000600 /// Emit MatchTable opcodes that check the predicate for the given operand.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000601 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000602 unsigned InsnVarID,
603 unsigned OpIdx) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000604
605 /// Compare the priority of this object and B.
606 ///
607 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000608 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
609 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000610 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000611
612 /// Report the maximum number of temporary operands needed by the predicate
613 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000614 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000615};
616
617/// Generates code to check that an operand is a particular LLT.
618class LLTOperandMatcher : public OperandPredicateMatcher {
619protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000620 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000621
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000622public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000623 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders759ff412017-02-24 13:58:11 +0000624 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
625
626 static bool classof(const OperandPredicateMatcher *P) {
627 return P->getKind() == OPM_LLT;
628 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000629
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000630 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000631 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000632 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
633 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
634 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
635 << MatchTable::NamedValue(Ty.getCxxEnumValue())
636 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000637 }
638};
639
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000640/// Generates code to check that an operand is a particular target constant.
641class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
642protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000643 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000644 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000645
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000646 unsigned getAllocatedTemporariesBaseID() const;
647
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000648public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000649 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
650 const Record &TheDef)
651 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
652 TheDef(TheDef) {}
653
654 static bool classof(const OperandPredicateMatcher *P) {
655 return P->getKind() == OPM_ComplexPattern;
656 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000657
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000658 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000659 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000660 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000661 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
662 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
663 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
664 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
665 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
666 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000667 }
668
Daniel Sanders2deea182017-04-22 15:11:04 +0000669 unsigned countRendererFns() const override {
670 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000671 }
672};
673
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000674/// Generates code to check that an operand is in a particular register bank.
675class RegisterBankOperandMatcher : public OperandPredicateMatcher {
676protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000677 const CodeGenRegisterClass &RC;
678
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000679public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000680 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
681 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
682
683 static bool classof(const OperandPredicateMatcher *P) {
684 return P->getKind() == OPM_RegBank;
685 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000686
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000687 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000688 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000689 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
690 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
691 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
692 << MatchTable::Comment("RC")
693 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
694 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000695 }
696};
697
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000698/// Generates code to check that an operand is a basic block.
699class MBBOperandMatcher : public OperandPredicateMatcher {
700public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000701 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
702
703 static bool classof(const OperandPredicateMatcher *P) {
704 return P->getKind() == OPM_MBB;
705 }
706
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000707 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000708 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000709 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
710 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
711 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000712 }
713};
714
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000715/// Generates code to check that an operand is a G_CONSTANT with a particular
716/// int.
717class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000718protected:
719 int64_t Value;
720
721public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000722 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000723 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
724
725 static bool classof(const OperandPredicateMatcher *P) {
726 return P->getKind() == OPM_Int;
727 }
728
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000729 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000730 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000731 Table << MatchTable::Opcode("GIM_CheckConstantInt")
732 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
733 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
734 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000735 }
736};
737
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000738/// Generates code to check that an operand is a raw int (where MO.isImm() or
739/// MO.isCImm() is true).
740class LiteralIntOperandMatcher : public OperandPredicateMatcher {
741protected:
742 int64_t Value;
743
744public:
745 LiteralIntOperandMatcher(int64_t Value)
746 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
747
748 static bool classof(const OperandPredicateMatcher *P) {
749 return P->getKind() == OPM_LiteralInt;
750 }
751
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000752 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000753 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000754 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
755 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
756 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
757 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000758 }
759};
760
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000761/// Generates code to check that an operand is an intrinsic ID.
762class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
763protected:
764 const CodeGenIntrinsic *II;
765
766public:
767 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
768 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
769
770 static bool classof(const OperandPredicateMatcher *P) {
771 return P->getKind() == OPM_IntrinsicID;
772 }
773
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000774 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000775 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000776 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
777 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
778 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
779 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
780 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000781 }
782};
783
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000784/// Generates code to check that a set of predicates match for a particular
785/// operand.
786class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
787protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000788 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000789 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000790 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000791
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000792 /// The index of the first temporary variable allocated to this operand. The
793 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000794 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000795 unsigned AllocatedTemporariesBaseID;
796
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000797public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000798 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000799 const std::string &SymbolicName,
800 unsigned AllocatedTemporariesBaseID)
801 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
802 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000803
804 bool hasSymbolicName() const { return !SymbolicName.empty(); }
805 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000806 void setSymbolicName(StringRef Name) {
807 assert(SymbolicName.empty() && "Operand already has a symbolic name");
808 SymbolicName = Name;
809 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000810 unsigned getOperandIndex() const { return OpIdx; }
811
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000812 std::string getOperandExpr(unsigned InsnVarID) const {
813 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
814 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000815 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000816
Daniel Sandersbee57392017-04-04 13:25:23 +0000817 Optional<const OperandMatcher *>
818 getOptionalOperand(StringRef DesiredSymbolicName) const {
819 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
820 if (DesiredSymbolicName == SymbolicName)
821 return this;
822 for (const auto &OP : predicates()) {
823 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
824 if (MaybeOperand.hasValue())
825 return MaybeOperand.getValue();
826 }
827 return None;
828 }
829
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000830 InstructionMatcher &getInstructionMatcher() const { return Insn; }
831
Daniel Sanders9d662d22017-07-06 10:06:12 +0000832 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000833 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000834 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000835 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000836 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000837 }
838
Daniel Sanders9d662d22017-07-06 10:06:12 +0000839 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000840 /// InsnVarID matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000841 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000842 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000843 std::string Comment;
844 raw_string_ostream CommentOS(Comment);
845 CommentOS << "MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000846 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000847 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000848 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000849 CommentOS << SymbolicName;
850 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
851
852 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000853 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000854
855 /// Compare the priority of this object and B.
856 ///
857 /// Returns true if this object is more important than B.
858 bool isHigherPriorityThan(const OperandMatcher &B) const {
859 // Operand matchers involving more predicates have higher priority.
860 if (predicates_size() > B.predicates_size())
861 return true;
862 if (predicates_size() < B.predicates_size())
863 return false;
864
865 // This assumes that predicates are added in a consistent order.
866 for (const auto &Predicate : zip(predicates(), B.predicates())) {
867 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
868 return true;
869 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
870 return false;
871 }
872
873 return false;
874 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000875
876 /// Report the maximum number of temporary operands needed by the operand
877 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000878 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000879 return std::accumulate(
880 predicates().begin(), predicates().end(), 0,
881 [](unsigned A,
882 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000883 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000884 });
885 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000886
887 unsigned getAllocatedTemporariesBaseID() const {
888 return AllocatedTemporariesBaseID;
889 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000890};
891
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000892unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
893 return Operand.getAllocatedTemporariesBaseID();
894}
895
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000896/// Generates code to check a predicate on an instruction.
897///
898/// Typical predicates include:
899/// * The opcode of the instruction is a particular value.
900/// * The nsw/nuw flag is/isn't set.
901class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000902protected:
903 /// This enum is used for RTTI and also defines the priority that is given to
904 /// the predicate when generating the matcher code. Kinds with higher priority
905 /// must be tested first.
906 enum PredicateKind {
907 IPM_Opcode,
908 };
909
910 PredicateKind Kind;
911
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000912public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000913 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000914 virtual ~InstructionPredicateMatcher() {}
915
Daniel Sanders759ff412017-02-24 13:58:11 +0000916 PredicateKind getKind() const { return Kind; }
917
Daniel Sanders9d662d22017-07-06 10:06:12 +0000918 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000919 /// InsnVarID matches the predicate.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000920 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000921 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000922
923 /// Compare the priority of this object and B.
924 ///
925 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000926 virtual bool
927 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000928 return Kind < B.Kind;
929 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000930
931 /// Report the maximum number of temporary operands needed by the predicate
932 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000933 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000934};
935
936/// Generates code to check the opcode of an instruction.
937class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
938protected:
939 const CodeGenInstruction *I;
940
941public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000942 InstructionOpcodeMatcher(const CodeGenInstruction *I)
943 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000944
Daniel Sanders759ff412017-02-24 13:58:11 +0000945 static bool classof(const InstructionPredicateMatcher *P) {
946 return P->getKind() == IPM_Opcode;
947 }
948
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000949 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000950 unsigned InsnVarID) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000951 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
952 << MatchTable::IntValue(InsnVarID)
953 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
954 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000955 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000956
957 /// Compare the priority of this object and B.
958 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000959 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000960 bool
961 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000962 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
963 return true;
964 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
965 return false;
966
967 // Prioritize opcodes for cosmetic reasons in the generated source. Although
968 // this is cosmetic at the moment, we may want to drive a similar ordering
969 // using instruction frequency information to improve compile time.
970 if (const InstructionOpcodeMatcher *BO =
971 dyn_cast<InstructionOpcodeMatcher>(&B))
972 return I->TheDef->getName() < BO->I->TheDef->getName();
973
974 return false;
975 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000976};
977
978/// Generates code to check that a set of predicates and operands match for a
979/// particular instruction.
980///
981/// Typical predicates include:
982/// * Has a specific opcode.
983/// * Has an nsw/nuw flag or doesn't.
984class InstructionMatcher
985 : public PredicateListMatcher<InstructionPredicateMatcher> {
986protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000987 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000988
989 /// The operands to match. All rendered operands must be present even if the
990 /// condition is always true.
991 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000992
993public:
994 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000995 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
996 unsigned AllocatedTemporariesBaseID) {
997 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
998 AllocatedTemporariesBaseID));
999 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001000 }
1001
Daniel Sandersffc7d582017-03-29 15:37:18 +00001002 OperandMatcher &getOperand(unsigned OpIdx) {
1003 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001004 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1005 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001006 });
1007 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001008 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001009 llvm_unreachable("Failed to lookup operand");
1010 }
1011
Daniel Sandersbee57392017-04-04 13:25:23 +00001012 Optional<const OperandMatcher *>
1013 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001014 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
Daniel Sandersbee57392017-04-04 13:25:23 +00001015 for (const auto &Operand : Operands) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001016 const auto &OM = Operand->getOptionalOperand(SymbolicName);
Daniel Sandersbee57392017-04-04 13:25:23 +00001017 if (OM.hasValue())
1018 return OM.getValue();
1019 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001020 return None;
1021 }
1022
Daniel Sandersdb7ed372017-04-04 13:52:00 +00001023 const OperandMatcher &getOperand(StringRef SymbolicName) const {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001024 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
1025 if (OM.hasValue())
1026 return *OM.getValue();
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001027 llvm_unreachable("Failed to lookup operand");
1028 }
1029
1030 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001031 OperandVec::iterator operands_begin() { return Operands.begin(); }
1032 OperandVec::iterator operands_end() { return Operands.end(); }
1033 iterator_range<OperandVec::iterator> operands() {
1034 return make_range(operands_begin(), operands_end());
1035 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001036 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1037 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001038 iterator_range<OperandVec::const_iterator> operands() const {
1039 return make_range(operands_begin(), operands_end());
1040 }
1041
Daniel Sanders9d662d22017-07-06 10:06:12 +00001042 /// Emit MatchTable opcodes to check the shape of the match and capture
1043 /// instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001044 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001045 unsigned InsnID) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001046 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1047 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1048 << MatchTable::Comment("Expected")
1049 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001050 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001051 Operand->emitCaptureOpcodes(Table, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001052 }
1053
Daniel Sanders9d662d22017-07-06 10:06:12 +00001054 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001055 /// InsnVarName matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001056 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001057 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001058 emitPredicateListOpcodes(Table, Rule, InsnVarID);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001059 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001060 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001061 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001062
1063 /// Compare the priority of this object and B.
1064 ///
1065 /// Returns true if this object is more important than B.
1066 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1067 // Instruction matchers involving more operands have higher priority.
1068 if (Operands.size() > B.Operands.size())
1069 return true;
1070 if (Operands.size() < B.Operands.size())
1071 return false;
1072
1073 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1074 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1075 return true;
1076 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1077 return false;
1078 }
1079
1080 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001081 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001082 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001083 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001084 return false;
1085 }
1086
1087 return false;
1088 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001089
1090 /// Report the maximum number of temporary operands needed by the instruction
1091 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001092 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001093 return std::accumulate(predicates().begin(), predicates().end(), 0,
1094 [](unsigned A,
1095 const std::unique_ptr<InstructionPredicateMatcher>
1096 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001097 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001098 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001099 std::accumulate(
1100 Operands.begin(), Operands.end(), 0,
1101 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001102 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001103 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001104 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001105};
1106
Daniel Sandersbee57392017-04-04 13:25:23 +00001107/// Generates code to check that the operand is a register defined by an
1108/// instruction that matches the given instruction matcher.
1109///
1110/// For example, the pattern:
1111/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1112/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1113/// the:
1114/// (G_ADD $src1, $src2)
1115/// subpattern.
1116class InstructionOperandMatcher : public OperandPredicateMatcher {
1117protected:
1118 std::unique_ptr<InstructionMatcher> InsnMatcher;
1119
1120public:
1121 InstructionOperandMatcher()
1122 : OperandPredicateMatcher(OPM_Instruction),
1123 InsnMatcher(new InstructionMatcher()) {}
1124
1125 static bool classof(const OperandPredicateMatcher *P) {
1126 return P->getKind() == OPM_Instruction;
1127 }
1128
1129 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1130
1131 Optional<const OperandMatcher *>
1132 getOptionalOperand(StringRef SymbolicName) const override {
1133 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1134 return InsnMatcher->getOptionalOperand(SymbolicName);
1135 }
1136
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001137 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001138 unsigned InsnID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001139 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1140 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001141 }
1142
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001143 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001144 unsigned InsnVarID_,
1145 unsigned OpIdx_) const override {
1146 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001147 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001148 }
1149};
1150
Daniel Sanders43c882c2017-02-01 10:53:10 +00001151//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001152class OperandRenderer {
1153public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001154 enum RendererKind {
1155 OR_Copy,
1156 OR_CopySubReg,
1157 OR_Imm,
1158 OR_Register,
1159 OR_ComplexPattern
1160 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001161
1162protected:
1163 RendererKind Kind;
1164
1165public:
1166 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1167 virtual ~OperandRenderer() {}
1168
1169 RendererKind getKind() const { return Kind; }
1170
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001171 virtual void emitRenderOpcodes(MatchTable &Table,
1172 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001173};
1174
1175/// A CopyRenderer emits code to copy a single operand from an existing
1176/// instruction to the one being built.
1177class CopyRenderer : public OperandRenderer {
1178protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001179 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001180 /// The matcher for the instruction that this operand is copied from.
1181 /// This provides the facility for looking up an a operand by it's name so
1182 /// that it can be used as a source for the instruction being built.
1183 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001184 /// The name of the operand.
1185 const StringRef SymbolicName;
1186
1187public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001188 CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1189 StringRef SymbolicName)
1190 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
1191 SymbolicName(SymbolicName) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001192
1193 static bool classof(const OperandRenderer *R) {
1194 return R->getKind() == OR_Copy;
1195 }
1196
1197 const StringRef getSymbolicName() const { return SymbolicName; }
1198
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001199 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001200 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001201 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001202 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1203 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1204 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1205 << MatchTable::IntValue(Operand.getOperandIndex())
1206 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001207 }
1208};
1209
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001210/// A CopySubRegRenderer emits code to copy a single register operand from an
1211/// existing instruction to the one being built and indicate that only a
1212/// subregister should be copied.
1213class CopySubRegRenderer : public OperandRenderer {
1214protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001215 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001216 /// The matcher for the instruction that this operand is copied from.
1217 /// This provides the facility for looking up an a operand by it's name so
1218 /// that it can be used as a source for the instruction being built.
1219 const InstructionMatcher &Matched;
1220 /// The name of the operand.
1221 const StringRef SymbolicName;
1222 /// The subregister to extract.
1223 const CodeGenSubRegIndex *SubReg;
1224
1225public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001226 CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1227 StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1228 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001229 SymbolicName(SymbolicName), SubReg(SubReg) {}
1230
1231 static bool classof(const OperandRenderer *R) {
1232 return R->getKind() == OR_CopySubReg;
1233 }
1234
1235 const StringRef getSymbolicName() const { return SymbolicName; }
1236
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001237 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001238 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001239 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001240 Table << MatchTable::Opcode("GIR_CopySubReg")
1241 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1242 << MatchTable::Comment("OldInsnID")
1243 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1244 << MatchTable::IntValue(Operand.getOperandIndex())
1245 << MatchTable::Comment("SubRegIdx")
1246 << MatchTable::IntValue(SubReg->EnumValue)
1247 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001248 }
1249};
1250
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001251/// Adds a specific physical register to the instruction being built.
1252/// This is typically useful for WZR/XZR on AArch64.
1253class AddRegisterRenderer : public OperandRenderer {
1254protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001255 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001256 const Record *RegisterDef;
1257
1258public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001259 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1260 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1261 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001262
1263 static bool classof(const OperandRenderer *R) {
1264 return R->getKind() == OR_Register;
1265 }
1266
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001267 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1268 Table << MatchTable::Opcode("GIR_AddRegister")
1269 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1270 << MatchTable::NamedValue(
1271 (RegisterDef->getValue("Namespace")
1272 ? RegisterDef->getValueAsString("Namespace")
1273 : ""),
1274 RegisterDef->getName())
1275 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001276 }
1277};
1278
Daniel Sanders0ed28822017-04-12 08:23:08 +00001279/// Adds a specific immediate to the instruction being built.
1280class ImmRenderer : public OperandRenderer {
1281protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001282 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001283 int64_t Imm;
1284
1285public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001286 ImmRenderer(unsigned InsnID, int64_t Imm)
1287 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001288
1289 static bool classof(const OperandRenderer *R) {
1290 return R->getKind() == OR_Imm;
1291 }
1292
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001293 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1294 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1295 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1296 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001297 }
1298};
1299
Daniel Sanders2deea182017-04-22 15:11:04 +00001300/// Adds operands by calling a renderer function supplied by the ComplexPattern
1301/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001302class RenderComplexPatternOperand : public OperandRenderer {
1303private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001304 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001305 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001306 /// The name of the operand.
1307 const StringRef SymbolicName;
1308 /// The renderer number. This must be unique within a rule since it's used to
1309 /// identify a temporary variable to hold the renderer function.
1310 unsigned RendererID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001311
1312 unsigned getNumOperands() const {
1313 return TheDef.getValueAsDag("Operands")->getNumArgs();
1314 }
1315
1316public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001317 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1318 StringRef SymbolicName, unsigned RendererID)
1319 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sanders2deea182017-04-22 15:11:04 +00001320 SymbolicName(SymbolicName), RendererID(RendererID) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001321
1322 static bool classof(const OperandRenderer *R) {
1323 return R->getKind() == OR_ComplexPattern;
1324 }
1325
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001326 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1327 Table << MatchTable::Opcode("GIR_ComplexRenderer")
1328 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1329 << MatchTable::Comment("RendererID")
1330 << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001331 }
1332};
1333
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001334/// An action taken when all Matcher predicates succeeded for a parent rule.
1335///
1336/// Typical actions include:
1337/// * Changing the opcode of an instruction.
1338/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001339class MatchAction {
1340public:
1341 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001342
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001343 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001344 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001345 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1346 /// requirements on the instruction vary from action to
1347 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001348 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1349 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001350};
1351
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001352/// Generates a comment describing the matched rule being acted upon.
1353class DebugCommentAction : public MatchAction {
1354private:
1355 const PatternToMatch &P;
1356
1357public:
1358 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1359
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001360 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1361 unsigned RecycleInsnID) const override {
1362 Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + " => " +
1363 llvm::to_string(*P.getDstPattern()))
1364 << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001365 }
1366};
1367
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001368/// Generates code to build an instruction or mutate an existing instruction
1369/// into the desired instruction when this is possible.
1370class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001371private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001372 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001373 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001374 const InstructionMatcher &Matched;
1375 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1376
1377 /// True if the instruction can be built solely by mutating the opcode.
1378 bool canMutate() const {
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001379 if (OperandRenderers.size() != Matched.getNumOperands())
1380 return false;
1381
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001382 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001383 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001384 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1385 if (&Matched != &OM.getInstructionMatcher() ||
1386 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001387 return false;
1388 } else
1389 return false;
1390 }
1391
1392 return true;
1393 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001394
Daniel Sanders43c882c2017-02-01 10:53:10 +00001395public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001396 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001397 const InstructionMatcher &Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001398 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001399
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001400 template <class Kind, class... Args>
1401 Kind &addRenderer(Args&&... args) {
1402 OperandRenderers.emplace_back(
1403 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1404 return *static_cast<Kind *>(OperandRenderers.back().get());
1405 }
1406
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001407 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1408 unsigned RecycleInsnID) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001409 if (canMutate()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001410 Table << MatchTable::Opcode("GIR_MutateOpcode")
1411 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1412 << MatchTable::Comment("RecycleInsnID")
1413 << MatchTable::IntValue(RecycleInsnID)
1414 << MatchTable::Comment("Opcode")
1415 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1416 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001417
1418 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001419 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001420 auto Namespace = Def->getValue("Namespace")
1421 ? Def->getValueAsString("Namespace")
1422 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001423 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1424 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1425 << MatchTable::NamedValue(Namespace, Def->getName())
1426 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001427 }
1428 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001429 auto Namespace = Use->getValue("Namespace")
1430 ? Use->getValueAsString("Namespace")
1431 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001432 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1433 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1434 << MatchTable::NamedValue(Namespace, Use->getName())
1435 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001436 }
1437 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001438 return;
1439 }
1440
1441 // TODO: Simple permutation looks like it could be almost as common as
1442 // mutation due to commutative operations.
1443
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001444 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1445 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1446 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1447 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001448 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001449 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001450
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001451 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1452 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1453 << MatchTable::LineBreak << MatchTable::Opcode("GIR_EraseFromParent")
1454 << MatchTable::Comment("InsnID")
1455 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001456 }
1457};
1458
1459/// Generates code to constrain the operands of an output instruction to the
1460/// register classes specified by the definition of that instruction.
1461class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001462 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001463
1464public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001465 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001466
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001467 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1468 unsigned RecycleInsnID) const override {
1469 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1470 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1471 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001472 }
1473};
1474
1475/// Generates code to constrain the specified operand of an output instruction
1476/// to the specified register class.
1477class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001478 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001479 unsigned OpIdx;
1480 const CodeGenRegisterClass &RC;
1481
1482public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001483 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001484 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001485 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001486
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001487 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1488 unsigned RecycleInsnID) const override {
1489 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1490 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1491 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1492 << MatchTable::Comment("RC " + RC.getName())
1493 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001494 }
1495};
1496
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001497InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1498 Matchers.emplace_back(new InstructionMatcher());
1499 return *Matchers.back();
1500}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001501
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001502void RuleMatcher::addRequiredFeature(Record *Feature) {
1503 RequiredFeatures.push_back(Feature);
1504}
1505
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001506const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1507 return RequiredFeatures;
1508}
1509
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001510template <class Kind, class... Args>
1511Kind &RuleMatcher::addAction(Args &&... args) {
1512 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1513 return *static_cast<Kind *>(Actions.back().get());
1514}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001515
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001516unsigned
1517RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1518 unsigned NewInsnVarID = NextInsnVarID++;
1519 InsnVariableIDs[&Matcher] = NewInsnVarID;
1520 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001521}
1522
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001523unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001524 const InstructionMatcher &Matcher,
1525 unsigned InsnID, unsigned OpIdx) {
1526 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001527 Table << MatchTable::Opcode("GIM_RecordInsn")
1528 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1529 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1530 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1531 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1532 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001533 return NewInsnVarID;
1534}
1535
1536unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1537 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1538 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001539 return I->second;
1540 llvm_unreachable("Matched Insn was not captured in a local variable");
1541}
1542
Daniel Sanders9d662d22017-07-06 10:06:12 +00001543/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001544/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001545void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001546 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001547 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001548 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001549}
1550
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001551void RuleMatcher::emit(raw_ostream &OS) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001552 if (Matchers.empty())
1553 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001554
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001555 // The representation supports rules that require multiple roots such as:
1556 // %ptr(p0) = ...
1557 // %elt0(s32) = G_LOAD %ptr
1558 // %1(p0) = G_ADD %ptr, 4
1559 // %elt1(s32) = G_LOAD p0 %1
1560 // which could be usefully folded into:
1561 // %ptr(p0) = ...
1562 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1563 // on some targets but we don't need to make use of that yet.
1564 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001565
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001566 MatchTable Table(CurrentMatchTableID);
1567 Table << MatchTable::Opcode("GIM_Try", +1)
1568 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(0)
1569 << MatchTable::LineBreak;
1570
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001571 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001572 Table << MatchTable::Opcode("GIM_CheckFeatures")
1573 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1574 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001575 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001576
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001577 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001578
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001579 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001580 getInsnVarID(*Matchers.front()));
1581
Daniel Sandersbee57392017-04-04 13:25:23 +00001582 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001583 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00001584 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001585 SmallVector<unsigned, 2> InsnIDs;
1586 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001587 // Skip the root node since it isn't moving anywhere. Everything else is
1588 // sinking to meet it.
1589 if (Pair.first == Matchers.front().get())
1590 continue;
1591
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001592 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00001593 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001594 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00001595
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001596 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001597 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001598 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1599 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1600 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00001601
1602 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1603 // account for unsafe cases.
1604 //
1605 // Example:
1606 // MI1--> %0 = ...
1607 // %1 = ... %0
1608 // MI0--> %2 = ... %0
1609 // It's not safe to erase MI1. We currently handle this by not
1610 // erasing %0 (even when it's dead).
1611 //
1612 // Example:
1613 // MI1--> %0 = load volatile @a
1614 // %1 = load volatile @a
1615 // MI0--> %2 = ... %0
1616 // It's not safe to sink %0's def past %1. We currently handle
1617 // this by rejecting all loads.
1618 //
1619 // Example:
1620 // MI1--> %0 = load @a
1621 // %1 = store @a
1622 // MI0--> %2 = ... %0
1623 // It's not safe to sink %0's def past %1. We currently handle
1624 // this by rejecting all loads.
1625 //
1626 // Example:
1627 // G_CONDBR %cond, @BB1
1628 // BB0:
1629 // MI1--> %0 = load @a
1630 // G_BR @BB1
1631 // BB1:
1632 // MI0--> %2 = ... %0
1633 // It's not always safe to sink %0 across control flow. In this
1634 // case it may introduce a memory fault. We currentl handle this
1635 // by rejecting all loads.
1636 }
1637 }
1638
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001639 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001640 MA->emitActionOpcodes(Table, *this, 0);
1641 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
1642 << MatchTable::Label(0) << MatchTable::Opcode("GIM_Reject")
1643 << MatchTable::LineBreak;
1644 OS << Table
Daniel Sandersa6cfce62017-07-05 14:50:18 +00001645 << " State.MIs.resize(1);\n"
1646 << " DEBUG(dbgs() << \"Processing MatchTable" << CurrentMatchTableID
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001647 << "\\n\");\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00001648 << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, MatchTable"
1649 << CurrentMatchTableID << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
1650 << " return true;\n"
1651 << " }\n\n";
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001652}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001653
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001654bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1655 // Rules involving more match roots have higher priority.
1656 if (Matchers.size() > B.Matchers.size())
1657 return true;
1658 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00001659 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001660
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001661 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1662 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1663 return true;
1664 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1665 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001666 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001667
1668 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00001669}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001670
Daniel Sanders2deea182017-04-22 15:11:04 +00001671unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001672 return std::accumulate(
1673 Matchers.begin(), Matchers.end(), 0,
1674 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001675 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001676 });
1677}
1678
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001679//===- GlobalISelEmitter class --------------------------------------------===//
1680
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001681class GlobalISelEmitter {
1682public:
1683 explicit GlobalISelEmitter(RecordKeeper &RK);
1684 void run(raw_ostream &OS);
1685
1686private:
1687 const RecordKeeper &RK;
1688 const CodeGenDAGPatterns CGP;
1689 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001690 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001691
1692 /// Keep track of the equivalence between SDNodes and Instruction.
1693 /// This is defined using 'GINodeEquiv' in the target description.
1694 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1695
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001696 /// Keep track of the equivalence between ComplexPattern's and
1697 /// GIComplexOperandMatcher. Map entries are specified by subclassing
1698 /// GIComplexPatternEquiv.
1699 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1700
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001701 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001702 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001703
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001704 void gatherNodeEquivs();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001705 const CodeGenInstruction *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001706
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001707 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001708 Expected<InstructionMatcher &>
Daniel Sandersc270c502017-03-30 09:36:33 +00001709 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders57938df2017-07-11 10:40:18 +00001710 const TreePatternNode *Src,
1711 unsigned &TempOpIdx) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001712 Error importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001713 const TreePatternNode *SrcChild, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00001714 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001715 Expected<BuildMIAction &>
1716 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1717 const InstructionMatcher &InsnMatcher);
Daniel Sandersc270c502017-03-30 09:36:33 +00001718 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1719 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001720 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00001721 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1722 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001723 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001724 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1725 const std::vector<Record *> &ImplicitDefs) const;
1726
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001727 /// Analyze pattern \p P, returning a matcher for it if possible.
1728 /// Otherwise, return an Error explaining why we don't support it.
1729 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001730
1731 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001732};
1733
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001734void GlobalISelEmitter::gatherNodeEquivs() {
1735 assert(NodeEquivs.empty());
1736 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1737 NodeEquivs[Equiv->getValueAsDef("Node")] =
1738 &Target.getInstruction(Equiv->getValueAsDef("I"));
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001739
1740 assert(ComplexPatternEquivs.empty());
1741 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1742 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1743 if (!SelDAGEquiv)
1744 continue;
1745 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1746 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001747}
1748
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001749const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001750 return NodeEquivs.lookup(N);
1751}
1752
1753GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001754 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001755
1756//===- Emitter ------------------------------------------------------------===//
1757
Daniel Sandersc270c502017-03-30 09:36:33 +00001758Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001759GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001760 ArrayRef<Init *> Predicates) {
1761 for (const Init *Predicate : Predicates) {
1762 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1763 declareSubtargetFeature(PredicateDef->getDef());
1764 M.addRequiredFeature(PredicateDef->getDef());
1765 }
1766
Daniel Sandersc270c502017-03-30 09:36:33 +00001767 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001768}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001769
Daniel Sanders57938df2017-07-11 10:40:18 +00001770Expected<InstructionMatcher &>
1771GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1772 const TreePatternNode *Src,
1773 unsigned &TempOpIdx) const {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001774 const CodeGenInstruction *SrcGIOrNull = nullptr;
1775
Daniel Sandersffc7d582017-03-29 15:37:18 +00001776 // Start with the defined operands (i.e., the results of the root operator).
1777 if (Src->getExtTypes().size() > 1)
1778 return failedImport("Src pattern has multiple results");
1779
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001780 if (Src->isLeaf()) {
1781 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00001782 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001783 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1784 &Target.getInstruction(RK.getDef("G_CONSTANT")));
1785 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001786 return failedImport(
1787 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001788 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001789 SrcGIOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001790 if (!SrcGIOrNull)
1791 return failedImport("Pattern operator lacks an equivalent Instruction" +
1792 explainOperator(Src->getOperator()));
1793 auto &SrcGI = *SrcGIOrNull;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001794
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001795 // The operators look good: match the opcode
1796 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1797 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001798
1799 unsigned OpIdx = 0;
1800 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1801 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1802
1803 if (!OpTyOrNone)
1804 return failedImport(
1805 "Result of Src pattern operator has an unsupported type");
1806
1807 // Results don't have a name unless they are the root node. The caller will
1808 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001809 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001810 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1811 }
1812
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001813 if (Src->isLeaf()) {
1814 Init *SrcInit = Src->getLeafValue();
1815 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1816 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1817 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1818 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001819 return failedImport(
1820 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001821 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001822 assert(SrcGIOrNull &&
1823 "Expected to have already found an equivalent Instruction");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001824 // Match the used operands (i.e. the children of the operator).
1825 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001826 TreePatternNode *SrcChild = Src->getChild(i);
1827
1828 // For G_INTRINSIC, the operand immediately following the defs is an
1829 // intrinsic ID.
1830 if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001831 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001832 OperandMatcher &OM =
1833 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001834 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00001835 continue;
1836 }
1837
1838 return failedImport("Expected IntInit containing instrinsic ID)");
1839 }
1840
1841 if (auto Error =
1842 importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001843 return std::move(Error);
1844 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001845 }
1846
1847 return InsnMatcher;
1848}
1849
Daniel Sandersc270c502017-03-30 09:36:33 +00001850Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001851 const TreePatternNode *SrcChild,
Daniel Sandersc270c502017-03-30 09:36:33 +00001852 unsigned OpIdx,
1853 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001854 OperandMatcher &OM =
1855 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001856
1857 if (SrcChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001858 return failedImport("Src pattern child has predicate (" +
1859 explainPredicates(SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001860
1861 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1862 if (ChildTypes.size() != 1)
1863 return failedImport("Src pattern child has multiple results");
1864
1865 // Check MBB's before the type check since they are not a known type.
1866 if (!SrcChild->isLeaf()) {
1867 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1868 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1869 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1870 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00001871 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001872 }
1873 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001874 }
1875
1876 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1877 if (!OpTyOrNone)
Daniel Sanders85ffd362017-07-06 08:12:20 +00001878 return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001879 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1880
Daniel Sandersbee57392017-04-04 13:25:23 +00001881 // Check for nested instructions.
1882 if (!SrcChild->isLeaf()) {
1883 // Map the node to a gMIR instruction.
1884 InstructionOperandMatcher &InsnOperand =
1885 OM.addPredicate<InstructionOperandMatcher>();
Daniel Sanders57938df2017-07-11 10:40:18 +00001886 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
1887 InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00001888 if (auto Error = InsnMatcherOrError.takeError())
1889 return Error;
1890
1891 return Error::success();
1892 }
1893
Daniel Sandersffc7d582017-03-29 15:37:18 +00001894 // Check for constant immediates.
1895 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001896 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00001897 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001898 }
1899
1900 // Check for def's like register classes or ComplexPattern's.
1901 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1902 auto *ChildRec = ChildDefInit->getDef();
1903
1904 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001905 if (ChildRec->isSubClassOf("RegisterClass") ||
1906 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001907 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001908 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00001909 return Error::success();
1910 }
1911
Daniel Sandersffc7d582017-03-29 15:37:18 +00001912 // Check for ComplexPattern's.
1913 if (ChildRec->isSubClassOf("ComplexPattern")) {
1914 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1915 if (ComplexPattern == ComplexPatternEquivs.end())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001916 return failedImport("SelectionDAG ComplexPattern (" +
1917 ChildRec->getName() + ") not mapped to GlobalISel");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001918
Daniel Sanders2deea182017-04-22 15:11:04 +00001919 OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1920 *ComplexPattern->second);
1921 TempOpIdx++;
Daniel Sandersc270c502017-03-30 09:36:33 +00001922 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001923 }
1924
Daniel Sandersd0656a32017-04-13 09:45:37 +00001925 if (ChildRec->isSubClassOf("ImmLeaf")) {
1926 return failedImport(
1927 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1928 }
1929
Daniel Sandersffc7d582017-03-29 15:37:18 +00001930 return failedImport(
1931 "Src pattern child def is an unsupported tablegen class");
1932 }
1933
1934 return failedImport("Src pattern child is an unsupported kind");
1935}
1936
Daniel Sandersc270c502017-03-30 09:36:33 +00001937Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00001938 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001939 const InstructionMatcher &InsnMatcher) const {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001940 // The only non-leaf child we accept is 'bb': it's an operator because
1941 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1942 if (!DstChild->isLeaf()) {
1943 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1944 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1945 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001946 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
Daniel Sandersffc7d582017-03-29 15:37:18 +00001947 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001948 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001949 }
1950 }
1951 return failedImport("Dst pattern child isn't a leaf node or an MBB");
1952 }
1953
1954 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1955 if (DstChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001956 return failedImport("Dst pattern child has predicate (" +
1957 explainPredicates(DstChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001958
1959 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1960 auto *ChildRec = ChildDefInit->getDef();
1961
1962 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1963 if (ChildTypes.size() != 1)
1964 return failedImport("Dst pattern child has multiple results");
1965
1966 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1967 if (!OpTyOrNone)
1968 return failedImport("Dst operand has an unsupported type");
1969
1970 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001971 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00001972 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001973 }
1974
Daniel Sanders658541f2017-04-22 15:53:21 +00001975 if (ChildRec->isSubClassOf("RegisterClass") ||
1976 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001977 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
1978 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001979 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001980 }
1981
1982 if (ChildRec->isSubClassOf("ComplexPattern")) {
1983 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1984 if (ComplexPattern == ComplexPatternEquivs.end())
1985 return failedImport(
1986 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1987
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001988 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00001989 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001990 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00001991 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00001992 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001993 }
1994
Daniel Sandersd0656a32017-04-13 09:45:37 +00001995 if (ChildRec->isSubClassOf("SDNodeXForm"))
1996 return failedImport("Dst pattern child def is an unsupported tablegen "
1997 "class (SDNodeXForm)");
1998
Daniel Sandersffc7d582017-03-29 15:37:18 +00001999 return failedImport(
2000 "Dst pattern child def is an unsupported tablegen class");
2001 }
2002
2003 return failedImport("Dst pattern child is an unsupported kind");
2004}
2005
Daniel Sandersc270c502017-03-30 09:36:33 +00002006Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002007 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002008 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002009 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002010 if (!DstOp->isSubClassOf("Instruction")) {
2011 if (DstOp->isSubClassOf("ValueType"))
2012 return failedImport(
2013 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002014 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002015 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002016 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002017
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002018 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2019 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002020 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002021
2022 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002023 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002024 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2025 DstI = &Target.getInstruction(RK.getDef("COPY"));
2026 DstINumUses--; // Ignore the class constraint.
2027 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002028 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2029 DstI = &Target.getInstruction(RK.getDef("COPY"));
2030 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002031 }
2032
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002033 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002034
2035 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002036 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2037 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002038 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002039 }
2040
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002041 // EXTRACT_SUBREG needs to use a subregister COPY.
2042 if (IsExtractSubReg) {
2043 if (!Dst->getChild(0)->isLeaf())
2044 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2045
Daniel Sanders32291982017-06-28 13:50:04 +00002046 if (DefInit *SubRegInit =
2047 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002048 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2049 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2050 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2051
2052 const auto &SrcRCDstRCPair =
2053 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2054 if (SrcRCDstRCPair.hasValue()) {
2055 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2056 if (SrcRCDstRCPair->first != RC)
2057 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2058 }
2059
2060 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002061 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002062 return DstMIBuilder;
2063 }
2064
2065 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2066 }
2067
Daniel Sandersffc7d582017-03-29 15:37:18 +00002068 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002069 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002070 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002071 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002072 const CGIOperandList::OperandInfo &DstIOperand =
2073 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002074
Diana Picus382602f2017-05-17 08:57:28 +00002075 // If the operand has default values, introduce them now.
2076 // FIXME: Until we have a decent test case that dictates we should do
2077 // otherwise, we're going to assume that operands with default values cannot
2078 // be specified in the patterns. Therefore, adding them will not cause us to
2079 // end up with too many rendered operands.
2080 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002081 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002082 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2083 return std::move(Error);
2084 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002085 continue;
2086 }
2087
2088 if (auto Error = importExplicitUseRenderer(
2089 DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002090 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002091 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002092 }
2093
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002094 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002095 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002096 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002097 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002098 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002099 " default ones");
2100
Daniel Sandersffc7d582017-03-29 15:37:18 +00002101 return DstMIBuilder;
2102}
2103
Diana Picus382602f2017-05-17 08:57:28 +00002104Error GlobalISelEmitter::importDefaultOperandRenderers(
2105 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002106 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002107 // Look through ValueType operators.
2108 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2109 if (const DefInit *DefaultDagOperator =
2110 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2111 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2112 DefaultOp = DefaultDagOp->getArg(0);
2113 }
2114 }
2115
2116 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002117 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002118 continue;
2119 }
2120
2121 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002122 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002123 continue;
2124 }
2125
2126 return failedImport("Could not add default op");
2127 }
2128
2129 return Error::success();
2130}
2131
Daniel Sandersc270c502017-03-30 09:36:33 +00002132Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002133 BuildMIAction &DstMIBuilder,
2134 const std::vector<Record *> &ImplicitDefs) const {
2135 if (!ImplicitDefs.empty())
2136 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002137 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002138}
2139
2140Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002141 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002142 RuleMatcher M;
2143 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002144
Daniel Sandersc270c502017-03-30 09:36:33 +00002145 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002146 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002147
2148 // Next, analyze the pattern operators.
2149 TreePatternNode *Src = P.getSrcPattern();
2150 TreePatternNode *Dst = P.getDstPattern();
2151
2152 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002153 if (auto Err = isTrivialOperatorNode(Dst))
2154 return failedImport("Dst pattern root isn't a trivial operator (" +
2155 toString(std::move(Err)) + ")");
2156 if (auto Err = isTrivialOperatorNode(Src))
2157 return failedImport("Src pattern root isn't a trivial operator (" +
2158 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002159
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002160 if (Dst->isLeaf())
2161 return failedImport("Dst pattern root isn't a known leaf");
2162
Daniel Sandersbee57392017-04-04 13:25:23 +00002163 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002164 Record *DstOp = Dst->getOperator();
2165 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002166 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002167
2168 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002169 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002170 return failedImport("Src pattern results and dst MI defs are different (" +
2171 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2172 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002173
Daniel Sandersffc7d582017-03-29 15:37:18 +00002174 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
Daniel Sanders57938df2017-07-11 10:40:18 +00002175 unsigned TempOpIdx = 0;
2176 auto InsnMatcherOrError =
2177 createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002178 if (auto Error = InsnMatcherOrError.takeError())
2179 return std::move(Error);
2180 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2181
2182 // The root of the match also has constraints on the register bank so that it
2183 // matches the result instruction.
2184 unsigned OpIdx = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002185 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002186 (void)Ty;
2187
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002188 const auto &DstIOperand = DstI.Operands[OpIdx];
2189 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002190 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2191 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2192
2193 if (DstIOpRec == nullptr)
2194 return failedImport(
2195 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002196 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2197 if (!Dst->getChild(0)->isLeaf())
2198 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2199
Daniel Sanders32291982017-06-28 13:50:04 +00002200 // We can assume that a subregister is in the same bank as it's super
2201 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002202 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2203
2204 if (DstIOpRec == nullptr)
2205 return failedImport(
2206 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002207 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002208 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002209 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002210 return failedImport("Dst MI def isn't a register class" +
2211 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002212
Daniel Sandersffc7d582017-03-29 15:37:18 +00002213 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2214 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002215 OM.addPredicate<RegisterBankOperandMatcher>(
2216 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002217 ++OpIdx;
2218 }
2219
Daniel Sandersc270c502017-03-30 09:36:33 +00002220 auto DstMIBuilderOrError =
2221 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002222 if (auto Error = DstMIBuilderOrError.takeError())
2223 return std::move(Error);
2224 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002225
Daniel Sandersffc7d582017-03-29 15:37:18 +00002226 // Render the implicit defs.
2227 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002228 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002229 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002230
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002231 // Constrain the registers to classes. This is normally derived from the
2232 // emitted instruction but a few instructions require special handling.
2233 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2234 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2235 // result is constrained to the class given by the second child.
2236 Record *DstIOpRec =
2237 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2238
2239 if (DstIOpRec == nullptr)
2240 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2241
2242 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002243 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002244
2245 // We're done with this pattern! It's eligible for GISel emission; return
2246 // it.
2247 ++NumPatternImported;
2248 return std::move(M);
2249 }
2250
2251 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2252 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2253 // instructions, the result register class is controlled by the
2254 // subregisters of the operand. As a result, we must constrain the result
2255 // class rather than check that it's already the right one.
2256 if (!Dst->getChild(0)->isLeaf())
2257 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2258
Daniel Sanders320390b2017-06-28 15:16:03 +00002259 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2260 if (!SubRegInit)
2261 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002262
Daniel Sanders320390b2017-06-28 15:16:03 +00002263 // Constrain the result to the same register bank as the operand.
2264 Record *DstIOpRec =
2265 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002266
Daniel Sanders320390b2017-06-28 15:16:03 +00002267 if (DstIOpRec == nullptr)
2268 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002269
Daniel Sanders320390b2017-06-28 15:16:03 +00002270 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002271 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002272
Daniel Sanders320390b2017-06-28 15:16:03 +00002273 // It would be nice to leave this constraint implicit but we're required
2274 // to pick a register class so constrain the result to a register class
2275 // that can hold the correct MVT.
2276 //
2277 // FIXME: This may introduce an extra copy if the chosen class doesn't
2278 // actually contain the subregisters.
2279 assert(Src->getExtTypes().size() == 1 &&
2280 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002281
Daniel Sanders320390b2017-06-28 15:16:03 +00002282 const auto &SrcRCDstRCPair =
2283 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2284 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002285 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2286 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2287
2288 // We're done with this pattern! It's eligible for GISel emission; return
2289 // it.
2290 ++NumPatternImported;
2291 return std::move(M);
2292 }
2293
2294 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002295
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002296 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002297 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002298 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002299}
2300
2301void GlobalISelEmitter::run(raw_ostream &OS) {
2302 // Track the GINodeEquiv definitions.
2303 gatherNodeEquivs();
2304
2305 emitSourceFileHeader(("Global Instruction Selector for the " +
2306 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002307 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002308 // Look through the SelectionDAG patterns we found, possibly emitting some.
2309 for (const PatternToMatch &Pat : CGP.ptms()) {
2310 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002311 auto MatcherOrErr = runOnPattern(Pat);
2312
2313 // The pattern analysis can fail, indicating an unsupported pattern.
2314 // Report that if we've been asked to do so.
2315 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002316 if (WarnOnSkippedPatterns) {
2317 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002318 "Skipped pattern: " + toString(std::move(Err)));
2319 } else {
2320 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002321 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002322 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002323 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002324 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002325
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002326 Rules.push_back(std::move(MatcherOrErr.get()));
2327 }
2328
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002329 std::stable_sort(Rules.begin(), Rules.end(),
2330 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002331 if (A.isHigherPriorityThan(B)) {
2332 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2333 "and less important at "
2334 "the same time");
2335 return true;
2336 }
2337 return false;
2338 });
2339
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002340 std::vector<Record *> ComplexPredicates =
2341 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2342 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2343 [](const Record *A, const Record *B) {
2344 if (A->getName() < B->getName())
2345 return true;
2346 return false;
2347 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002348 unsigned MaxTemporaries = 0;
2349 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00002350 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002351
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002352 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2353 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2354 << ";\n"
2355 << "using PredicateBitset = "
2356 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2357 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2358
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002359 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2360 << " mutable MatcherState State;\n"
2361 << " typedef "
2362 "ComplexRendererFn("
2363 << Target.getName()
2364 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2365 << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2366 "MatcherInfo;\n"
2367 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002368
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002369 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2370 << ", State(" << MaxTemporaries << "),\n"
2371 << "MatcherInfo({TypeObjects, FeatureBitsets, {\n"
2372 << " nullptr, // GICP_Invalid\n";
2373 for (const auto &Record : ComplexPredicates)
2374 OS << " &" << Target.getName()
2375 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2376 << ", // " << Record->getName() << "\n";
2377 OS << "}})\n"
2378 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002379
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002380 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2381 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2382 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002383
2384 // Separate subtarget features by how often they must be recomputed.
2385 SubtargetFeatureInfoMap ModuleFeatures;
2386 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2387 std::inserter(ModuleFeatures, ModuleFeatures.end()),
2388 [](const SubtargetFeatureInfoMap::value_type &X) {
2389 return !X.second.mustRecomputePerFunction();
2390 });
2391 SubtargetFeatureInfoMap FunctionFeatures;
2392 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2393 std::inserter(FunctionFeatures, FunctionFeatures.end()),
2394 [](const SubtargetFeatureInfoMap::value_type &X) {
2395 return X.second.mustRecomputePerFunction();
2396 });
2397
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002398 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002399 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2400 ModuleFeatures, OS);
2401 SubtargetFeatureInfo::emitComputeAvailableFeatures(
2402 Target.getName(), "InstructionSelector",
2403 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2404 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002405
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002406 // Emit a table containing the LLT objects needed by the matcher and an enum
2407 // for the matcher to reference them with.
2408 std::vector<LLTCodeGen> TypeObjects = {
2409 LLT::scalar(8), LLT::scalar(16), LLT::scalar(32),
2410 LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1),
2411 LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1),
2412 LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8),
2413 LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16),
2414 LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32),
2415 LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32),
2416 LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64),
2417 };
2418 std::sort(TypeObjects.begin(), TypeObjects.end());
2419 OS << "enum {\n";
2420 for (const auto &TypeObject : TypeObjects) {
2421 OS << " ";
2422 TypeObject.emitCxxEnumValue(OS);
2423 OS << ",\n";
2424 }
2425 OS << "};\n"
2426 << "const static LLT TypeObjects[] = {\n";
2427 for (const auto &TypeObject : TypeObjects) {
2428 OS << " ";
2429 TypeObject.emitCxxConstructorCall(OS);
2430 OS << ",\n";
2431 }
2432 OS << "};\n\n";
2433
2434 // Emit a table containing the PredicateBitsets objects needed by the matcher
2435 // and an enum for the matcher to reference them with.
2436 std::vector<std::vector<Record *>> FeatureBitsets;
2437 for (auto &Rule : Rules)
2438 FeatureBitsets.push_back(Rule.getRequiredFeatures());
2439 std::sort(
2440 FeatureBitsets.begin(), FeatureBitsets.end(),
2441 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2442 if (A.size() < B.size())
2443 return true;
2444 if (A.size() > B.size())
2445 return false;
2446 for (const auto &Pair : zip(A, B)) {
2447 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2448 return true;
2449 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2450 return false;
2451 }
2452 return false;
2453 });
2454 FeatureBitsets.erase(
2455 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2456 FeatureBitsets.end());
2457 OS << "enum {\n"
2458 << " GIFBS_Invalid,\n";
2459 for (const auto &FeatureBitset : FeatureBitsets) {
2460 if (FeatureBitset.empty())
2461 continue;
2462 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2463 }
2464 OS << "};\n"
2465 << "const static PredicateBitset FeatureBitsets[] {\n"
2466 << " {}, // GIFBS_Invalid\n";
2467 for (const auto &FeatureBitset : FeatureBitsets) {
2468 if (FeatureBitset.empty())
2469 continue;
2470 OS << " {";
2471 for (const auto &Feature : FeatureBitset) {
2472 const auto &I = SubtargetFeatures.find(Feature);
2473 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2474 OS << I->second.getEnumBitName() << ", ";
2475 }
2476 OS << "},\n";
2477 }
2478 OS << "};\n\n";
2479
2480 // Emit complex predicate table and an enum to reference them with.
2481 OS << "enum {\n"
2482 << " GICP_Invalid,\n";
2483 for (const auto &Record : ComplexPredicates)
2484 OS << " GICP_" << Record->getName() << ",\n";
2485 OS << "};\n"
2486 << "// See constructor for table contents\n\n";
2487
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002488 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002489 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2490 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002491 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00002492 << " // FIXME: This should be computed on a per-function basis rather "
2493 "than per-insn.\n"
2494 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2495 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00002496 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2497 << " NewMIVector OutMIs;\n"
2498 << " State.MIs.clear();\n"
2499 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002500
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002501 for (auto &Rule : Rules) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002502 Rule.emit(OS);
Daniel Sandersc60abe32017-07-04 15:31:50 +00002503 ++CurrentMatchTableID;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002504 ++NumPatternEmitted;
Daniel Sandersc60abe32017-07-04 15:31:50 +00002505 assert(CurrentMatchTableID == NumPatternEmitted &&
2506 "Statistic deviates from number of emitted tables");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002507 }
2508
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002509 OS << " return false;\n"
2510 << "}\n"
2511 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002512
2513 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2514 << "PredicateBitset AvailableModuleFeatures;\n"
2515 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2516 << "PredicateBitset getAvailableFeatures() const {\n"
2517 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2518 << "}\n"
2519 << "PredicateBitset\n"
2520 << "computeAvailableModuleFeatures(const " << Target.getName()
2521 << "Subtarget *Subtarget) const;\n"
2522 << "PredicateBitset\n"
2523 << "computeAvailableFunctionFeatures(const " << Target.getName()
2524 << "Subtarget *Subtarget,\n"
2525 << " const MachineFunction *MF) const;\n"
2526 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2527
2528 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2529 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2530 << "AvailableFunctionFeatures()\n"
2531 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002532}
2533
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002534void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2535 if (SubtargetFeatures.count(Predicate) == 0)
2536 SubtargetFeatures.emplace(
2537 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2538}
2539
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002540} // end anonymous namespace
2541
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002542//===----------------------------------------------------------------------===//
2543
2544namespace llvm {
2545void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2546 GlobalISelEmitter(RK).run(OS);
2547}
2548} // End llvm namespace