blob: 85739bbab4ae221284b55d652b3b66cee3185ba7 [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");
56
Daniel Sanders0848b232017-03-27 13:15:13 +000057cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58
Ahmed Bougacha36f70352016-12-21 23:26:20 +000059static cl::opt<bool> WarnOnSkippedPatterns(
60 "warn-on-skipped-patterns",
61 cl::desc("Explain why a pattern was skipped for inclusion "
62 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000063 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000064
Daniel Sandersbdfebb82017-03-15 20:18:38 +000065namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066//===- Helper functions ---------------------------------------------------===//
67
Daniel Sanders11300ce2017-10-13 21:28:03 +000068
69/// Get the name of the enum value used to number the predicate function.
70std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000071 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000072 Predicate.getFnName();
73}
74
75/// Get the opcode used to check this predicate.
76std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000077 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000078}
79
Daniel Sanders52b4ce72017-03-07 23:20:35 +000080/// This class stands in for LLT wherever we want to tablegen-erate an
81/// equivalent at compiler run-time.
82class LLTCodeGen {
83private:
84 LLT Ty;
85
86public:
87 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
88
Daniel Sanders7aac7cc2017-07-20 09:25:44 +000089 std::string getCxxEnumValue() const {
90 std::string Str;
91 raw_string_ostream OS(Str);
92
93 emitCxxEnumValue(OS);
94 return OS.str();
95 }
96
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000097 void emitCxxEnumValue(raw_ostream &OS) const {
98 if (Ty.isScalar()) {
99 OS << "GILLT_s" << Ty.getSizeInBits();
100 return;
101 }
102 if (Ty.isVector()) {
103 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
104 return;
105 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000106 if (Ty.isPointer()) {
107 OS << "GILLT_p" << Ty.getAddressSpace();
108 if (Ty.getSizeInBits() > 0)
109 OS << "s" << Ty.getSizeInBits();
110 return;
111 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000112 llvm_unreachable("Unhandled LLT");
113 }
114
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000115 void emitCxxConstructorCall(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
118 return;
119 }
120 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000121 OS << "LLT::vector(" << Ty.getNumElements() << ", "
122 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000123 return;
124 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000125 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
126 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
127 << Ty.getSizeInBits() << ")";
128 return;
129 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000130 llvm_unreachable("Unhandled LLT");
131 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000132
133 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000134
135 /// This ordering is used for std::unique() and std::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000136 /// particular logic behind the order but either A < B or B < A must be
137 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000138 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000139 if (Ty.isValid() != Other.Ty.isValid())
140 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000141 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000142 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000143
144 if (Ty.isVector() != Other.Ty.isVector())
145 return Ty.isVector() < Other.Ty.isVector();
146 if (Ty.isScalar() != Other.Ty.isScalar())
147 return Ty.isScalar() < Other.Ty.isScalar();
148 if (Ty.isPointer() != Other.Ty.isPointer())
149 return Ty.isPointer() < Other.Ty.isPointer();
150
151 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
152 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
153
154 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
155 return Ty.getNumElements() < Other.Ty.getNumElements();
156
157 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000158 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000159};
160
161class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000162/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
163/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000164static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000165 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000166
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000167 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000168 return LLTCodeGen(
169 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000170
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000171 if (VT.isInteger() || VT.isFloatingPoint())
172 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
173 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000174}
175
Daniel Sandersd0656a32017-04-13 09:45:37 +0000176static std::string explainPredicates(const TreePatternNode *N) {
177 std::string Explanation = "";
178 StringRef Separator = "";
179 for (const auto &P : N->getPredicateFns()) {
180 Explanation +=
181 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
182 if (P.isAlwaysTrue())
183 Explanation += " always-true";
184 if (P.isImmediatePattern())
185 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000186
187 if (P.isUnindexed())
188 Explanation += " unindexed";
189
190 if (P.isNonExtLoad())
191 Explanation += " non-extload";
192 if (P.isAnyExtLoad())
193 Explanation += " extload";
194 if (P.isSignExtLoad())
195 Explanation += " sextload";
196 if (P.isZeroExtLoad())
197 Explanation += " zextload";
198
199 if (P.isNonTruncStore())
200 Explanation += " non-truncstore";
201 if (P.isTruncStore())
202 Explanation += " truncstore";
203
204 if (Record *VT = P.getMemoryVT())
205 Explanation += (" MemVT=" + VT->getName()).str();
206 if (Record *VT = P.getScalarMemoryVT())
207 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 }
209 return Explanation;
210}
211
Daniel Sandersd0656a32017-04-13 09:45:37 +0000212std::string explainOperator(Record *Operator) {
213 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000214 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000215
216 if (Operator->isSubClassOf("Intrinsic"))
217 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
218
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000219 if (Operator->isSubClassOf("ComplexPattern"))
220 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
221 ")")
222 .str();
223
224 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000225}
226
227/// Helper function to let the emitter report skip reason error messages.
228static Error failedImport(const Twine &Reason) {
229 return make_error<StringError>(Reason, inconvertibleErrorCode());
230}
231
232static Error isTrivialOperatorNode(const TreePatternNode *N) {
233 std::string Explanation = "";
234 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000235
236 bool HasUnsupportedPredicate = false;
237 for (const auto &Predicate : N->getPredicateFns()) {
238 if (Predicate.isAlwaysTrue())
239 continue;
240
241 if (Predicate.isImmediatePattern())
242 continue;
243
Daniel Sandersa71f4542017-10-16 00:56:30 +0000244 if (Predicate.isLoad() && Predicate.isUnindexed())
245 continue;
246
247 if (Predicate.isNonExtLoad())
248 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000249
250 if (Predicate.isStore() && Predicate.isUnindexed())
251 continue;
252
253 if (Predicate.isNonTruncStore())
254 continue;
255
Daniel Sanders2c269f62017-08-24 09:11:20 +0000256 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000257 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
258 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000259 Explanation += (Separator + "first-failing:" +
260 Predicate.getOrigPatFragRecord()->getRecord()->getName())
261 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000262 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000263 }
264
265 if (N->getTransformFn()) {
266 Explanation += Separator + "Has a transform function";
267 Separator = ", ";
268 }
269
Daniel Sanders2c269f62017-08-24 09:11:20 +0000270 if (!HasUnsupportedPredicate && !N->getTransformFn())
Daniel Sandersd0656a32017-04-13 09:45:37 +0000271 return Error::success();
272
273 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000274}
275
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000276static Record *getInitValueAsRegClass(Init *V) {
277 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
278 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
279 return VDefInit->getDef()->getValueAsDef("RegClass");
280 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
281 return VDefInit->getDef();
282 }
283 return nullptr;
284}
285
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000286std::string
287getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
288 std::string Name = "GIFBS";
289 for (const auto &Feature : FeatureBitset)
290 Name += ("_" + Feature->getName()).str();
291 return Name;
292}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000293
294//===- MatchTable Helpers -------------------------------------------------===//
295
296class MatchTable;
297
298/// A record to be stored in a MatchTable.
299///
300/// This class represents any and all output that may be required to emit the
301/// MatchTable. Instances are most often configured to represent an opcode or
302/// value that will be emitted to the table with some formatting but it can also
303/// represent commas, comments, and other formatting instructions.
304struct MatchTableRecord {
305 enum RecordFlagsBits {
306 MTRF_None = 0x0,
307 /// Causes EmitStr to be formatted as comment when emitted.
308 MTRF_Comment = 0x1,
309 /// Causes the record value to be followed by a comma when emitted.
310 MTRF_CommaFollows = 0x2,
311 /// Causes the record value to be followed by a line break when emitted.
312 MTRF_LineBreakFollows = 0x4,
313 /// Indicates that the record defines a label and causes an additional
314 /// comment to be emitted containing the index of the label.
315 MTRF_Label = 0x8,
316 /// Causes the record to be emitted as the index of the label specified by
317 /// LabelID along with a comment indicating where that label is.
318 MTRF_JumpTarget = 0x10,
319 /// Causes the formatter to add a level of indentation before emitting the
320 /// record.
321 MTRF_Indent = 0x20,
322 /// Causes the formatter to remove a level of indentation after emitting the
323 /// record.
324 MTRF_Outdent = 0x40,
325 };
326
327 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
328 /// reference or define.
329 unsigned LabelID;
330 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
331 /// value, a label name.
332 std::string EmitStr;
333
334private:
335 /// The number of MatchTable elements described by this record. Comments are 0
336 /// while values are typically 1. Values >1 may occur when we need to emit
337 /// values that exceed the size of a MatchTable element.
338 unsigned NumElements;
339
340public:
341 /// A bitfield of RecordFlagsBits flags.
342 unsigned Flags;
343
344 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
345 unsigned NumElements, unsigned Flags)
346 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
347 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
348 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
349 "This value is reserved for non-labels");
350 }
351
352 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
353 const MatchTable &Table) const;
354 unsigned size() const { return NumElements; }
355};
356
357/// Holds the contents of a generated MatchTable to enable formatting and the
358/// necessary index tracking needed to support GIM_Try.
359class MatchTable {
360 /// An unique identifier for the table. The generated table will be named
361 /// MatchTable${ID}.
362 unsigned ID;
363 /// The records that make up the table. Also includes comments describing the
364 /// values being emitted and line breaks to format it.
365 std::vector<MatchTableRecord> Contents;
366 /// The currently defined labels.
367 DenseMap<unsigned, unsigned> LabelMap;
368 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
369 unsigned CurrentSize;
370
Daniel Sanders8e82af22017-07-27 11:03:45 +0000371 /// A unique identifier for a MatchTable label.
372 static unsigned CurrentLabelID;
373
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000374public:
375 static MatchTableRecord LineBreak;
376 static MatchTableRecord Comment(StringRef Comment) {
377 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
378 }
379 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
380 unsigned ExtraFlags = 0;
381 if (IndentAdjust > 0)
382 ExtraFlags |= MatchTableRecord::MTRF_Indent;
383 if (IndentAdjust < 0)
384 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
385
386 return MatchTableRecord(None, Opcode, 1,
387 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
388 }
389 static MatchTableRecord NamedValue(StringRef NamedValue) {
390 return MatchTableRecord(None, NamedValue, 1,
391 MatchTableRecord::MTRF_CommaFollows);
392 }
393 static MatchTableRecord NamedValue(StringRef Namespace,
394 StringRef NamedValue) {
395 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
396 MatchTableRecord::MTRF_CommaFollows);
397 }
398 static MatchTableRecord IntValue(int64_t IntValue) {
399 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
400 MatchTableRecord::MTRF_CommaFollows);
401 }
402 static MatchTableRecord Label(unsigned LabelID) {
403 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
404 MatchTableRecord::MTRF_Label |
405 MatchTableRecord::MTRF_Comment |
406 MatchTableRecord::MTRF_LineBreakFollows);
407 }
408 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000409 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000410 MatchTableRecord::MTRF_JumpTarget |
411 MatchTableRecord::MTRF_Comment |
412 MatchTableRecord::MTRF_CommaFollows);
413 }
414
415 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
416
417 void push_back(const MatchTableRecord &Value) {
418 if (Value.Flags & MatchTableRecord::MTRF_Label)
419 defineLabel(Value.LabelID);
420 Contents.push_back(Value);
421 CurrentSize += Value.size();
422 }
423
Daniel Sanders8e82af22017-07-27 11:03:45 +0000424 unsigned allocateLabelID() const { return CurrentLabelID++; }
425
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000426 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000427 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000428 }
429
430 unsigned getLabelIndex(unsigned LabelID) const {
431 const auto I = LabelMap.find(LabelID);
432 assert(I != LabelMap.end() && "Use of undeclared label");
433 return I->second;
434 }
435
Daniel Sanders8e82af22017-07-27 11:03:45 +0000436 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
437
438 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000439 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000440 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000441 LineBreak.emit(OS, true, *this);
442 OS << std::string(Indentation, ' ');
443
444 for (auto I = Contents.begin(), E = Contents.end(); I != E;
445 ++I) {
446 bool LineBreakIsNext = false;
447 const auto &NextI = std::next(I);
448
449 if (NextI != E) {
450 if (NextI->EmitStr == "" &&
451 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
452 LineBreakIsNext = true;
453 }
454
455 if (I->Flags & MatchTableRecord::MTRF_Indent)
456 Indentation += 2;
457
458 I->emit(OS, LineBreakIsNext, *this);
459 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
460 OS << std::string(Indentation, ' ');
461
462 if (I->Flags & MatchTableRecord::MTRF_Outdent)
463 Indentation -= 2;
464 }
465 OS << "};\n";
466 }
467};
468
Daniel Sanders8e82af22017-07-27 11:03:45 +0000469unsigned MatchTable::CurrentLabelID = 0;
470
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000471MatchTableRecord MatchTable::LineBreak = {
472 None, "" /* Emit String */, 0 /* Elements */,
473 MatchTableRecord::MTRF_LineBreakFollows};
474
475void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
476 const MatchTable &Table) const {
477 bool UseLineComment =
478 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
479 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
480 UseLineComment = false;
481
482 if (Flags & MTRF_Comment)
483 OS << (UseLineComment ? "// " : "/*");
484
485 OS << EmitStr;
486 if (Flags & MTRF_Label)
487 OS << ": @" << Table.getLabelIndex(LabelID);
488
489 if (Flags & MTRF_Comment && !UseLineComment)
490 OS << "*/";
491
492 if (Flags & MTRF_JumpTarget) {
493 if (Flags & MTRF_Comment)
494 OS << " ";
495 OS << Table.getLabelIndex(LabelID);
496 }
497
498 if (Flags & MTRF_CommaFollows) {
499 OS << ",";
500 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
501 OS << " ";
502 }
503
504 if (Flags & MTRF_LineBreakFollows)
505 OS << "\n";
506}
507
508MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
509 Table.push_back(Value);
510 return Table;
511}
512
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000513//===- Matchers -----------------------------------------------------------===//
514
Daniel Sandersbee57392017-04-04 13:25:23 +0000515class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000516class MatchAction;
517
518/// Generates code to check that a match rule matches.
519class RuleMatcher {
520 /// A list of matchers that all need to succeed for the current rule to match.
521 /// FIXME: This currently supports a single match position but could be
522 /// extended to support multiple positions to support div/rem fusion or
523 /// load-multiple instructions.
524 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
525
526 /// A list of actions that need to be taken when all predicates in this rule
527 /// have succeeded.
528 std::vector<std::unique_ptr<MatchAction>> Actions;
529
Daniel Sanders078572b2017-08-02 11:03:36 +0000530 typedef std::map<const InstructionMatcher *, unsigned>
531 DefinedInsnVariablesMap;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000532 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000533 /// emitCaptureOpcodes().
Daniel Sanders078572b2017-08-02 11:03:36 +0000534 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000535
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000536 /// A map of named operands defined by the matchers that may be referenced by
537 /// the renderers.
538 StringMap<OperandMatcher *> DefinedOperands;
539
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000540 /// ID for the next instruction variable defined with defineInsnVar()
541 unsigned NextInsnVarID;
542
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000543 std::vector<Record *> RequiredFeatures;
544
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000545 ArrayRef<SMLoc> SrcLoc;
546
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000547 typedef std::tuple<Record *, unsigned, unsigned>
548 DefinedComplexPatternSubOperand;
549 typedef StringMap<DefinedComplexPatternSubOperand>
550 DefinedComplexPatternSubOperandMap;
551 /// A map of Symbolic Names to ComplexPattern sub-operands.
552 DefinedComplexPatternSubOperandMap ComplexSubOperands;
553
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000554public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000555 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
556 : Matchers(), Actions(), InsnVariableIDs(), DefinedOperands(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000557 NextInsnVarID(0), SrcLoc(SrcLoc), ComplexSubOperands() {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000558 RuleMatcher(RuleMatcher &&Other) = default;
559 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000560
Daniel Sanders05540042017-08-08 10:44:31 +0000561 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000562 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000563 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000564
565 template <class Kind, class... Args> Kind &addAction(Args &&... args);
566
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000567 /// Define an instruction without emitting any code to do so.
568 /// This is used for the root of the match.
569 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
570 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000571 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000572 unsigned InsnVarID, unsigned OpIdx);
573 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000574 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
575 return InsnVariableIDs.begin();
576 }
577 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
578 return InsnVariableIDs.end();
579 }
580 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
581 defined_insn_vars() const {
582 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
583 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000584
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000585 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
586
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000587 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
588 unsigned RendererID, unsigned SubOperandID) {
589 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
590 ComplexSubOperands[SymbolicName] =
591 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
592 }
593 Optional<DefinedComplexPatternSubOperand>
594 getComplexSubOperand(StringRef SymbolicName) const {
595 const auto &I = ComplexSubOperands.find(SymbolicName);
596 if (I == ComplexSubOperands.end())
597 return None;
598 return I->second;
599 }
600
Daniel Sanders05540042017-08-08 10:44:31 +0000601 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000602 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000603
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000604 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000605
Daniel Sanders8e82af22017-07-27 11:03:45 +0000606 void emit(MatchTable &Table);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000607
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000608 /// Compare the priority of this object and B.
609 ///
610 /// Returns true if this object is more important than B.
611 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000612
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000613 /// Report the maximum number of temporary operands needed by the rule
614 /// matcher.
615 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000616
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000617 // FIXME: Remove this as soon as possible
618 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000619};
620
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000621template <class PredicateTy> class PredicateListMatcher {
622private:
623 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
624 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000625
Daniel Sanders2c269f62017-08-24 09:11:20 +0000626 /// Template instantiations should specialize this to return a string to use
627 /// for the comment emitted when there are no predicates.
628 std::string getNoPredicateComment() const;
629
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000630public:
631 /// Construct a new operand predicate and add it to the matcher.
632 template <class Kind, class... Args>
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000633 Optional<Kind *> addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000634 Predicates.emplace_back(
635 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000636 return static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000637 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000638
Daniel Sanders32291982017-06-28 13:50:04 +0000639 typename PredicateVec::const_iterator predicates_begin() const {
640 return Predicates.begin();
641 }
642 typename PredicateVec::const_iterator predicates_end() const {
643 return Predicates.end();
644 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000645 iterator_range<typename PredicateVec::const_iterator> predicates() const {
646 return make_range(predicates_begin(), predicates_end());
647 }
Daniel Sanders32291982017-06-28 13:50:04 +0000648 typename PredicateVec::size_type predicates_size() const {
649 return Predicates.size();
650 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000651
Daniel Sanders9d662d22017-07-06 10:06:12 +0000652 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000653 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000654 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000655 if (Predicates.empty()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000656 Table << MatchTable::Comment(getNoPredicateComment())
657 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000658 return;
659 }
660
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000661 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000662 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000663 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000664};
665
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000666/// Generates code to check a predicate of an operand.
667///
668/// Typical predicates include:
669/// * Operand is a particular register.
670/// * Operand is assigned a particular register bank.
671/// * Operand is an MBB.
672class OperandPredicateMatcher {
673public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000674 /// This enum is used for RTTI and also defines the priority that is given to
675 /// the predicate when generating the matcher code. Kinds with higher priority
676 /// must be tested first.
677 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000678 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
679 /// but OPM_Int must have priority over OPM_RegBank since constant integers
680 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000681 enum PredicateKind {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000682 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000683 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000684 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +0000685 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000686 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000687 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000688 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +0000689 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +0000690 OPM_RegBank,
691 OPM_MBB,
692 };
693
694protected:
695 PredicateKind Kind;
696
697public:
698 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000699 virtual ~OperandPredicateMatcher() {}
700
Daniel Sanders759ff412017-02-24 13:58:11 +0000701 PredicateKind getKind() const { return Kind; }
702
Daniel Sanders9d662d22017-07-06 10:06:12 +0000703 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000704 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000705 /// Only InstructionOperandMatcher needs to do anything for this method the
706 /// rest just walk the tree.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000707 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000708 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000709
Daniel Sanders9d662d22017-07-06 10:06:12 +0000710 /// Emit MatchTable opcodes that check the predicate for the given operand.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000711 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000712 unsigned InsnVarID,
713 unsigned OpIdx) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000714
715 /// Compare the priority of this object and B.
716 ///
717 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +0000718 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000719
720 /// Report the maximum number of temporary operands needed by the predicate
721 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000722 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000723};
724
Daniel Sanders2c269f62017-08-24 09:11:20 +0000725template <>
726std::string
727PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
728 return "No operand predicates";
729}
730
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000731/// Generates code to check that a register operand is defined by the same exact
732/// one as another.
733class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000734 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000735
736public:
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000737 SameOperandMatcher(StringRef MatchingName)
738 : OperandPredicateMatcher(OPM_SameOperand), MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000739
740 static bool classof(const OperandPredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000741 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000742 }
743
744 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
745 unsigned InsnVarID, unsigned OpIdx) const override;
746};
747
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000748/// Generates code to check that an operand is a particular LLT.
749class LLTOperandMatcher : public OperandPredicateMatcher {
750protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000751 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000752
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000753public:
Daniel Sanders032e7f22017-08-17 13:18:35 +0000754 static std::set<LLTCodeGen> KnownTypes;
755
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000756 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders032e7f22017-08-17 13:18:35 +0000757 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {
758 KnownTypes.insert(Ty);
759 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000760
761 static bool classof(const OperandPredicateMatcher *P) {
762 return P->getKind() == OPM_LLT;
763 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000764
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000765 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000766 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000767 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
768 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
769 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
770 << MatchTable::NamedValue(Ty.getCxxEnumValue())
771 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000772 }
773};
774
Daniel Sanders032e7f22017-08-17 13:18:35 +0000775std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
776
Daniel Sandersa71f4542017-10-16 00:56:30 +0000777/// Generates code to check that an operand is a pointer to any address space.
778///
779/// In SelectionDAG, the types did not describe pointers or address spaces. As a
780/// result, iN is used to describe a pointer of N bits to any address space and
781/// PatFrag predicates are typically used to constrain the address space. There's
782/// no reliable means to derive the missing type information from the pattern so
783/// imported rules must test the components of a pointer separately.
784///
Daniel Sandersea8711b2017-10-16 03:36:29 +0000785/// If SizeInBits is zero, then the pointer size will be obtained from the
786/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +0000787class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
788protected:
789 unsigned SizeInBits;
790
791public:
792 PointerToAnyOperandMatcher(unsigned SizeInBits)
793 : OperandPredicateMatcher(OPM_PointerToAny), SizeInBits(SizeInBits) {}
794
795 static bool classof(const OperandPredicateMatcher *P) {
796 return P->getKind() == OPM_PointerToAny;
797 }
798
799 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
800 unsigned InsnVarID, unsigned OpIdx) const override {
801 Table << MatchTable::Opcode("GIM_CheckPointerToAny") << MatchTable::Comment("MI")
802 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
803 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("SizeInBits")
804 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
805 }
806};
807
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000808/// Generates code to check that an operand is a particular target constant.
809class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
810protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000811 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000812 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000813
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000814 unsigned getAllocatedTemporariesBaseID() const;
815
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000816public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000817 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
818 const Record &TheDef)
819 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
820 TheDef(TheDef) {}
821
822 static bool classof(const OperandPredicateMatcher *P) {
823 return P->getKind() == OPM_ComplexPattern;
824 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000825
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000826 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000827 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000828 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000829 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
830 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
831 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
832 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
833 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
834 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000835 }
836
Daniel Sanders2deea182017-04-22 15:11:04 +0000837 unsigned countRendererFns() const override {
838 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000839 }
840};
841
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000842/// Generates code to check that an operand is in a particular register bank.
843class RegisterBankOperandMatcher : public OperandPredicateMatcher {
844protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000845 const CodeGenRegisterClass &RC;
846
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000847public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000848 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
849 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
850
851 static bool classof(const OperandPredicateMatcher *P) {
852 return P->getKind() == OPM_RegBank;
853 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000854
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000855 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000856 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000857 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
858 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
859 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
860 << MatchTable::Comment("RC")
861 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
862 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000863 }
864};
865
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000866/// Generates code to check that an operand is a basic block.
867class MBBOperandMatcher : public OperandPredicateMatcher {
868public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000869 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
870
871 static bool classof(const OperandPredicateMatcher *P) {
872 return P->getKind() == OPM_MBB;
873 }
874
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000875 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000876 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000877 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
878 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
879 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000880 }
881};
882
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000883/// Generates code to check that an operand is a G_CONSTANT with a particular
884/// int.
885class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000886protected:
887 int64_t Value;
888
889public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000890 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000891 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
892
893 static bool classof(const OperandPredicateMatcher *P) {
894 return P->getKind() == OPM_Int;
895 }
896
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000897 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000898 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000899 Table << MatchTable::Opcode("GIM_CheckConstantInt")
900 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
901 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
902 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000903 }
904};
905
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000906/// Generates code to check that an operand is a raw int (where MO.isImm() or
907/// MO.isCImm() is true).
908class LiteralIntOperandMatcher : public OperandPredicateMatcher {
909protected:
910 int64_t Value;
911
912public:
913 LiteralIntOperandMatcher(int64_t Value)
914 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
915
916 static bool classof(const OperandPredicateMatcher *P) {
917 return P->getKind() == OPM_LiteralInt;
918 }
919
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000920 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000921 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000922 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
923 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
924 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
925 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000926 }
927};
928
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000929/// Generates code to check that an operand is an intrinsic ID.
930class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
931protected:
932 const CodeGenIntrinsic *II;
933
934public:
935 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
936 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
937
938 static bool classof(const OperandPredicateMatcher *P) {
939 return P->getKind() == OPM_IntrinsicID;
940 }
941
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000942 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000943 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000944 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
945 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
946 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
947 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
948 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000949 }
950};
951
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000952/// Generates code to check that a set of predicates match for a particular
953/// operand.
954class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
955protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000956 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000957 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000958 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000959
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000960 /// The index of the first temporary variable allocated to this operand. The
961 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000962 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000963 unsigned AllocatedTemporariesBaseID;
964
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000965public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000966 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000967 const std::string &SymbolicName,
968 unsigned AllocatedTemporariesBaseID)
969 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
970 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000971
972 bool hasSymbolicName() const { return !SymbolicName.empty(); }
973 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000974 void setSymbolicName(StringRef Name) {
975 assert(SymbolicName.empty() && "Operand already has a symbolic name");
976 SymbolicName = Name;
977 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000978 unsigned getOperandIndex() const { return OpIdx; }
979
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000980 std::string getOperandExpr(unsigned InsnVarID) const {
981 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
982 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000983 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000984
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000985 InstructionMatcher &getInstructionMatcher() const { return Insn; }
986
Daniel Sandersa71f4542017-10-16 00:56:30 +0000987 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +0000988 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000989
Daniel Sanders9d662d22017-07-06 10:06:12 +0000990 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000991 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000992 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000993 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000994 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000995 }
996
Daniel Sanders9d662d22017-07-06 10:06:12 +0000997 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000998 /// InsnVarID matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000999 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001000 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001001 std::string Comment;
1002 raw_string_ostream CommentOS(Comment);
1003 CommentOS << "MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001004 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001005 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001006 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001007 CommentOS << SymbolicName;
1008 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1009
1010 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001011 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001012
1013 /// Compare the priority of this object and B.
1014 ///
1015 /// Returns true if this object is more important than B.
1016 bool isHigherPriorityThan(const OperandMatcher &B) const {
1017 // Operand matchers involving more predicates have higher priority.
1018 if (predicates_size() > B.predicates_size())
1019 return true;
1020 if (predicates_size() < B.predicates_size())
1021 return false;
1022
1023 // This assumes that predicates are added in a consistent order.
1024 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1025 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1026 return true;
1027 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1028 return false;
1029 }
1030
1031 return false;
1032 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001033
1034 /// Report the maximum number of temporary operands needed by the operand
1035 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001036 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001037 return std::accumulate(
1038 predicates().begin(), predicates().end(), 0,
1039 [](unsigned A,
1040 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001041 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001042 });
1043 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001044
1045 unsigned getAllocatedTemporariesBaseID() const {
1046 return AllocatedTemporariesBaseID;
1047 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001048
1049 bool isSameAsAnotherOperand() const {
1050 for (const auto &Predicate : predicates())
1051 if (isa<SameOperandMatcher>(Predicate))
1052 return true;
1053 return false;
1054 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001055};
1056
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001057// Specialize OperandMatcher::addPredicate() to refrain from adding redundant
1058// predicates.
1059template <>
1060template <class Kind, class... Args>
1061Optional<Kind *>
1062PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
1063 if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
1064 return None;
1065 Predicates.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1066 return static_cast<Kind *>(Predicates.back().get());
1067}
1068
1069Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1070 bool OperandIsAPointer) {
1071 if (!VTy.isMachineValueType())
1072 return failedImport("unsupported typeset");
1073
1074 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1075 addPredicate<PointerToAnyOperandMatcher>(0);
1076 return Error::success();
1077 }
1078
1079 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1080 if (!OpTyOrNone)
1081 return failedImport("unsupported type");
1082
1083 if (OperandIsAPointer)
1084 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1085 else
1086 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1087 return Error::success();
1088}
1089
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001090unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1091 return Operand.getAllocatedTemporariesBaseID();
1092}
1093
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001094/// Generates code to check a predicate on an instruction.
1095///
1096/// Typical predicates include:
1097/// * The opcode of the instruction is a particular value.
1098/// * The nsw/nuw flag is/isn't set.
1099class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +00001100protected:
1101 /// This enum is used for RTTI and also defines the priority that is given to
1102 /// the predicate when generating the matcher code. Kinds with higher priority
1103 /// must be tested first.
1104 enum PredicateKind {
1105 IPM_Opcode,
Daniel Sanders2c269f62017-08-24 09:11:20 +00001106 IPM_ImmPredicate,
Daniel Sanders39690bd2017-10-15 02:41:12 +00001107 IPM_NonAtomicMMO,
Daniel Sanders759ff412017-02-24 13:58:11 +00001108 };
1109
1110 PredicateKind Kind;
1111
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001112public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +00001113 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001114 virtual ~InstructionPredicateMatcher() {}
1115
Daniel Sanders759ff412017-02-24 13:58:11 +00001116 PredicateKind getKind() const { return Kind; }
1117
Daniel Sanders9d662d22017-07-06 10:06:12 +00001118 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001119 /// InsnVarID matches the predicate.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001120 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001121 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +00001122
1123 /// Compare the priority of this object and B.
1124 ///
1125 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001126 virtual bool
1127 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001128 return Kind < B.Kind;
1129 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001130
1131 /// Report the maximum number of temporary operands needed by the predicate
1132 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001133 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001134};
1135
Daniel Sanders2c269f62017-08-24 09:11:20 +00001136template <>
1137std::string
1138PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1139 return "No instruction predicates";
1140}
1141
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001142/// Generates code to check the opcode of an instruction.
1143class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1144protected:
1145 const CodeGenInstruction *I;
1146
1147public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +00001148 InstructionOpcodeMatcher(const CodeGenInstruction *I)
1149 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001150
Daniel Sanders759ff412017-02-24 13:58:11 +00001151 static bool classof(const InstructionPredicateMatcher *P) {
1152 return P->getKind() == IPM_Opcode;
1153 }
1154
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001155 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001156 unsigned InsnVarID) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001157 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1158 << MatchTable::IntValue(InsnVarID)
1159 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1160 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001161 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001162
1163 /// Compare the priority of this object and B.
1164 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001165 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001166 bool
1167 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001168 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1169 return true;
1170 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1171 return false;
1172
1173 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1174 // this is cosmetic at the moment, we may want to drive a similar ordering
1175 // using instruction frequency information to improve compile time.
1176 if (const InstructionOpcodeMatcher *BO =
1177 dyn_cast<InstructionOpcodeMatcher>(&B))
1178 return I->TheDef->getName() < BO->I->TheDef->getName();
1179
1180 return false;
1181 };
Daniel Sanders05540042017-08-08 10:44:31 +00001182
1183 bool isConstantInstruction() const {
1184 return I->TheDef->getName() == "G_CONSTANT";
1185 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001186};
1187
Daniel Sanders2c269f62017-08-24 09:11:20 +00001188/// Generates code to check that this instruction is a constant whose value
1189/// meets an immediate predicate.
1190///
1191/// Immediates are slightly odd since they are typically used like an operand
1192/// but are represented as an operator internally. We typically write simm8:$src
1193/// in a tablegen pattern, but this is just syntactic sugar for
1194/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1195/// that will be matched and the predicate (which is attached to the imm
1196/// operator) that will be tested. In SelectionDAG this describes a
1197/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1198///
1199/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1200/// this representation, the immediate could be tested with an
1201/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1202/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1203/// there are two implementation issues with producing that matcher
1204/// configuration from the SelectionDAG pattern:
1205/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1206/// were we to sink the immediate predicate to the operand we would have to
1207/// have two partial implementations of PatFrag support, one for immediates
1208/// and one for non-immediates.
1209/// * At the point we handle the predicate, the OperandMatcher hasn't been
1210/// created yet. If we were to sink the predicate to the OperandMatcher we
1211/// would also have to complicate (or duplicate) the code that descends and
1212/// creates matchers for the subtree.
1213/// Overall, it's simpler to handle it in the place it was found.
1214class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1215protected:
1216 TreePredicateFn Predicate;
1217
1218public:
1219 InstructionImmPredicateMatcher(const TreePredicateFn &Predicate)
1220 : InstructionPredicateMatcher(IPM_ImmPredicate), Predicate(Predicate) {}
1221
1222 static bool classof(const InstructionPredicateMatcher *P) {
1223 return P->getKind() == IPM_ImmPredicate;
1224 }
1225
1226 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1227 unsigned InsnVarID) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001228 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001229 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1230 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001231 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001232 << MatchTable::LineBreak;
1233 }
1234};
1235
Daniel Sanders39690bd2017-10-15 02:41:12 +00001236/// Generates code to check that a memory instruction has a non-atomic MachineMemoryOperand.
1237class NonAtomicMMOPredicateMatcher : public InstructionPredicateMatcher {
1238public:
1239 NonAtomicMMOPredicateMatcher()
1240 : InstructionPredicateMatcher(IPM_NonAtomicMMO) {}
1241
1242 static bool classof(const InstructionPredicateMatcher *P) {
1243 return P->getKind() == IPM_NonAtomicMMO;
1244 }
1245
1246 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1247 unsigned InsnVarID) const override {
1248 Table << MatchTable::Opcode("GIM_CheckNonAtomic")
1249 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1250 << MatchTable::LineBreak;
1251 }
1252};
1253
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001254/// Generates code to check that a set of predicates and operands match for a
1255/// particular instruction.
1256///
1257/// Typical predicates include:
1258/// * Has a specific opcode.
1259/// * Has an nsw/nuw flag or doesn't.
1260class InstructionMatcher
1261 : public PredicateListMatcher<InstructionPredicateMatcher> {
1262protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001263 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001264
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001265 RuleMatcher &Rule;
1266
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001267 /// The operands to match. All rendered operands must be present even if the
1268 /// condition is always true.
1269 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001270
Daniel Sanders05540042017-08-08 10:44:31 +00001271 std::string SymbolicName;
1272
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001273public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001274 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1275 : Rule(Rule), SymbolicName(SymbolicName) {}
1276
1277 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001278
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001279 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001280 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1281 unsigned AllocatedTemporariesBaseID) {
1282 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1283 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001284 if (!SymbolicName.empty())
1285 Rule.defineOperand(SymbolicName, *Operands.back());
1286
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001287 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001288 }
1289
Daniel Sandersffc7d582017-03-29 15:37:18 +00001290 OperandMatcher &getOperand(unsigned OpIdx) {
1291 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001292 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1293 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001294 });
1295 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001296 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001297 llvm_unreachable("Failed to lookup operand");
1298 }
1299
Daniel Sanders05540042017-08-08 10:44:31 +00001300 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001301 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001302 OperandVec::iterator operands_begin() { return Operands.begin(); }
1303 OperandVec::iterator operands_end() { return Operands.end(); }
1304 iterator_range<OperandVec::iterator> operands() {
1305 return make_range(operands_begin(), operands_end());
1306 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001307 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1308 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001309 iterator_range<OperandVec::const_iterator> operands() const {
1310 return make_range(operands_begin(), operands_end());
1311 }
1312
Daniel Sanders9d662d22017-07-06 10:06:12 +00001313 /// Emit MatchTable opcodes to check the shape of the match and capture
1314 /// instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001315 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001316 unsigned InsnID) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001317 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1318 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1319 << MatchTable::Comment("Expected")
1320 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001321 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001322 Operand->emitCaptureOpcodes(Table, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001323 }
1324
Daniel Sanders9d662d22017-07-06 10:06:12 +00001325 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001326 /// InsnVarName matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001327 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001328 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001329 emitPredicateListOpcodes(Table, Rule, InsnVarID);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001330 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001331 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001332 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001333
1334 /// Compare the priority of this object and B.
1335 ///
1336 /// Returns true if this object is more important than B.
1337 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1338 // Instruction matchers involving more operands have higher priority.
1339 if (Operands.size() > B.Operands.size())
1340 return true;
1341 if (Operands.size() < B.Operands.size())
1342 return false;
1343
1344 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1345 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1346 return true;
1347 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1348 return false;
1349 }
1350
1351 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001352 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001353 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001354 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001355 return false;
1356 }
1357
1358 return false;
1359 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001360
1361 /// Report the maximum number of temporary operands needed by the instruction
1362 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001363 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001364 return std::accumulate(predicates().begin(), predicates().end(), 0,
1365 [](unsigned A,
1366 const std::unique_ptr<InstructionPredicateMatcher>
1367 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001368 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001369 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001370 std::accumulate(
1371 Operands.begin(), Operands.end(), 0,
1372 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001373 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001374 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001375 }
Daniel Sanders05540042017-08-08 10:44:31 +00001376
1377 bool isConstantInstruction() const {
1378 for (const auto &P : predicates())
1379 if (const InstructionOpcodeMatcher *Opcode =
1380 dyn_cast<InstructionOpcodeMatcher>(P.get()))
1381 return Opcode->isConstantInstruction();
1382 return false;
1383 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001384};
1385
Daniel Sandersbee57392017-04-04 13:25:23 +00001386/// Generates code to check that the operand is a register defined by an
1387/// instruction that matches the given instruction matcher.
1388///
1389/// For example, the pattern:
1390/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1391/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1392/// the:
1393/// (G_ADD $src1, $src2)
1394/// subpattern.
1395class InstructionOperandMatcher : public OperandPredicateMatcher {
1396protected:
1397 std::unique_ptr<InstructionMatcher> InsnMatcher;
1398
1399public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001400 InstructionOperandMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Daniel Sandersbee57392017-04-04 13:25:23 +00001401 : OperandPredicateMatcher(OPM_Instruction),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001402 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00001403
1404 static bool classof(const OperandPredicateMatcher *P) {
1405 return P->getKind() == OPM_Instruction;
1406 }
1407
1408 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1409
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001410 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001411 unsigned InsnID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001412 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1413 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001414 }
1415
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001416 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001417 unsigned InsnVarID_,
1418 unsigned OpIdx_) const override {
1419 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001420 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001421 }
1422};
1423
Daniel Sanders43c882c2017-02-01 10:53:10 +00001424//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001425class OperandRenderer {
1426public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001427 enum RendererKind {
1428 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001429 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001430 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00001431 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00001432 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001433 OR_Imm,
1434 OR_Register,
1435 OR_ComplexPattern
1436 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001437
1438protected:
1439 RendererKind Kind;
1440
1441public:
1442 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1443 virtual ~OperandRenderer() {}
1444
1445 RendererKind getKind() const { return Kind; }
1446
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001447 virtual void emitRenderOpcodes(MatchTable &Table,
1448 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001449};
1450
1451/// A CopyRenderer emits code to copy a single operand from an existing
1452/// instruction to the one being built.
1453class CopyRenderer : public OperandRenderer {
1454protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001455 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001456 /// The name of the operand.
1457 const StringRef SymbolicName;
1458
1459public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001460 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
1461 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00001462 SymbolicName(SymbolicName) {
1463 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1464 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001465
1466 static bool classof(const OperandRenderer *R) {
1467 return R->getKind() == OR_Copy;
1468 }
1469
1470 const StringRef getSymbolicName() const { return SymbolicName; }
1471
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001472 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001473 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001474 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001475 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1476 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1477 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1478 << MatchTable::IntValue(Operand.getOperandIndex())
1479 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001480 }
1481};
1482
Daniel Sandersd66e0902017-10-23 18:19:24 +00001483/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1484/// existing instruction to the one being built. If the operand turns out to be
1485/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1486class CopyOrAddZeroRegRenderer : public OperandRenderer {
1487protected:
1488 unsigned NewInsnID;
1489 /// The name of the operand.
1490 const StringRef SymbolicName;
1491 const Record *ZeroRegisterDef;
1492
1493public:
1494 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001495 StringRef SymbolicName, Record *ZeroRegisterDef)
1496 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1497 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1498 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1499 }
1500
1501 static bool classof(const OperandRenderer *R) {
1502 return R->getKind() == OR_CopyOrAddZeroReg;
1503 }
1504
1505 const StringRef getSymbolicName() const { return SymbolicName; }
1506
1507 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1508 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1509 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1510 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1511 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1512 << MatchTable::Comment("OldInsnID")
1513 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1514 << MatchTable::IntValue(Operand.getOperandIndex())
1515 << MatchTable::NamedValue(
1516 (ZeroRegisterDef->getValue("Namespace")
1517 ? ZeroRegisterDef->getValueAsString("Namespace")
1518 : ""),
1519 ZeroRegisterDef->getName())
1520 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1521 }
1522};
1523
Daniel Sanders05540042017-08-08 10:44:31 +00001524/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1525/// an extended immediate operand.
1526class CopyConstantAsImmRenderer : public OperandRenderer {
1527protected:
1528 unsigned NewInsnID;
1529 /// The name of the operand.
1530 const std::string SymbolicName;
1531 bool Signed;
1532
1533public:
1534 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1535 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1536 SymbolicName(SymbolicName), Signed(true) {}
1537
1538 static bool classof(const OperandRenderer *R) {
1539 return R->getKind() == OR_CopyConstantAsImm;
1540 }
1541
1542 const StringRef getSymbolicName() const { return SymbolicName; }
1543
1544 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1545 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1546 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1547 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1548 : "GIR_CopyConstantAsUImm")
1549 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1550 << MatchTable::Comment("OldInsnID")
1551 << MatchTable::IntValue(OldInsnVarID)
1552 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1553 }
1554};
1555
Daniel Sanders11300ce2017-10-13 21:28:03 +00001556/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1557/// instruction to an extended immediate operand.
1558class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1559protected:
1560 unsigned NewInsnID;
1561 /// The name of the operand.
1562 const std::string SymbolicName;
1563
1564public:
1565 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1566 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1567 SymbolicName(SymbolicName) {}
1568
1569 static bool classof(const OperandRenderer *R) {
1570 return R->getKind() == OR_CopyFConstantAsFPImm;
1571 }
1572
1573 const StringRef getSymbolicName() const { return SymbolicName; }
1574
1575 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1576 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1577 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1578 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1579 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1580 << MatchTable::Comment("OldInsnID")
1581 << MatchTable::IntValue(OldInsnVarID)
1582 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1583 }
1584};
1585
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001586/// A CopySubRegRenderer emits code to copy a single register operand from an
1587/// existing instruction to the one being built and indicate that only a
1588/// subregister should be copied.
1589class CopySubRegRenderer : public OperandRenderer {
1590protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001591 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001592 /// The name of the operand.
1593 const StringRef SymbolicName;
1594 /// The subregister to extract.
1595 const CodeGenSubRegIndex *SubReg;
1596
1597public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001598 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
1599 const CodeGenSubRegIndex *SubReg)
1600 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001601 SymbolicName(SymbolicName), SubReg(SubReg) {}
1602
1603 static bool classof(const OperandRenderer *R) {
1604 return R->getKind() == OR_CopySubReg;
1605 }
1606
1607 const StringRef getSymbolicName() const { return SymbolicName; }
1608
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001609 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001610 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001611 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001612 Table << MatchTable::Opcode("GIR_CopySubReg")
1613 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1614 << MatchTable::Comment("OldInsnID")
1615 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1616 << MatchTable::IntValue(Operand.getOperandIndex())
1617 << MatchTable::Comment("SubRegIdx")
1618 << MatchTable::IntValue(SubReg->EnumValue)
1619 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001620 }
1621};
1622
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001623/// Adds a specific physical register to the instruction being built.
1624/// This is typically useful for WZR/XZR on AArch64.
1625class AddRegisterRenderer : public OperandRenderer {
1626protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001627 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001628 const Record *RegisterDef;
1629
1630public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001631 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1632 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1633 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001634
1635 static bool classof(const OperandRenderer *R) {
1636 return R->getKind() == OR_Register;
1637 }
1638
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001639 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1640 Table << MatchTable::Opcode("GIR_AddRegister")
1641 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1642 << MatchTable::NamedValue(
1643 (RegisterDef->getValue("Namespace")
1644 ? RegisterDef->getValueAsString("Namespace")
1645 : ""),
1646 RegisterDef->getName())
1647 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001648 }
1649};
1650
Daniel Sanders0ed28822017-04-12 08:23:08 +00001651/// Adds a specific immediate to the instruction being built.
1652class ImmRenderer : public OperandRenderer {
1653protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001654 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001655 int64_t Imm;
1656
1657public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001658 ImmRenderer(unsigned InsnID, int64_t Imm)
1659 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001660
1661 static bool classof(const OperandRenderer *R) {
1662 return R->getKind() == OR_Imm;
1663 }
1664
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001665 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1666 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1667 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1668 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001669 }
1670};
1671
Daniel Sanders2deea182017-04-22 15:11:04 +00001672/// Adds operands by calling a renderer function supplied by the ComplexPattern
1673/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001674class RenderComplexPatternOperand : public OperandRenderer {
1675private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001676 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001677 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001678 /// The name of the operand.
1679 const StringRef SymbolicName;
1680 /// The renderer number. This must be unique within a rule since it's used to
1681 /// identify a temporary variable to hold the renderer function.
1682 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001683 /// When provided, this is the suboperand of the ComplexPattern operand to
1684 /// render. Otherwise all the suboperands will be rendered.
1685 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001686
1687 unsigned getNumOperands() const {
1688 return TheDef.getValueAsDag("Operands")->getNumArgs();
1689 }
1690
1691public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001692 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001693 StringRef SymbolicName, unsigned RendererID,
1694 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001695 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001696 SymbolicName(SymbolicName), RendererID(RendererID),
1697 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001698
1699 static bool classof(const OperandRenderer *R) {
1700 return R->getKind() == OR_ComplexPattern;
1701 }
1702
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001703 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001704 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
1705 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001706 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1707 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001708 << MatchTable::IntValue(RendererID);
1709 if (SubOperand.hasValue())
1710 Table << MatchTable::Comment("SubOperand")
1711 << MatchTable::IntValue(SubOperand.getValue());
1712 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001713 }
1714};
1715
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001716/// An action taken when all Matcher predicates succeeded for a parent rule.
1717///
1718/// Typical actions include:
1719/// * Changing the opcode of an instruction.
1720/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001721class MatchAction {
1722public:
1723 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001724
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001725 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001726 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001727 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1728 /// requirements on the instruction vary from action to
1729 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001730 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1731 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001732};
1733
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001734/// Generates a comment describing the matched rule being acted upon.
1735class DebugCommentAction : public MatchAction {
1736private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00001737 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001738
1739public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00001740 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001741
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001742 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1743 unsigned RecycleInsnID) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00001744 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001745 }
1746};
1747
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001748/// Generates code to build an instruction or mutate an existing instruction
1749/// into the desired instruction when this is possible.
1750class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001751private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001752 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001753 const CodeGenInstruction *I;
Daniel Sanders64f745c2017-10-24 17:08:43 +00001754 const InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001755 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1756
1757 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001758 bool canMutate(RuleMatcher &Rule) const {
Daniel Sandersab1d1192017-10-24 18:11:54 +00001759 if (!Matched)
1760 return false;
1761
Daniel Sanders64f745c2017-10-24 17:08:43 +00001762 if (OperandRenderers.size() != Matched->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001763 return false;
1764
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001765 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001766 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001767 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersab1d1192017-10-24 18:11:54 +00001768 if (Matched != &OM.getInstructionMatcher() ||
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001769 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001770 return false;
1771 } else
1772 return false;
1773 }
1774
1775 return true;
1776 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001777
Daniel Sanders43c882c2017-02-01 10:53:10 +00001778public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001779 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sanders64f745c2017-10-24 17:08:43 +00001780 const InstructionMatcher *Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001781 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001782
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001783 template <class Kind, class... Args>
1784 Kind &addRenderer(Args&&... args) {
1785 OperandRenderers.emplace_back(
1786 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1787 return *static_cast<Kind *>(OperandRenderers.back().get());
1788 }
1789
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001790 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1791 unsigned RecycleInsnID) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001792 if (canMutate(Rule)) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001793 Table << MatchTable::Opcode("GIR_MutateOpcode")
1794 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1795 << MatchTable::Comment("RecycleInsnID")
1796 << MatchTable::IntValue(RecycleInsnID)
1797 << MatchTable::Comment("Opcode")
1798 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1799 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001800
1801 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001802 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001803 auto Namespace = Def->getValue("Namespace")
1804 ? Def->getValueAsString("Namespace")
1805 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001806 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1807 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1808 << MatchTable::NamedValue(Namespace, Def->getName())
1809 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001810 }
1811 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001812 auto Namespace = Use->getValue("Namespace")
1813 ? Use->getValueAsString("Namespace")
1814 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001815 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1816 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1817 << MatchTable::NamedValue(Namespace, Use->getName())
1818 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001819 }
1820 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001821 return;
1822 }
1823
1824 // TODO: Simple permutation looks like it could be almost as common as
1825 // mutation due to commutative operations.
1826
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001827 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1828 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1829 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1830 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001831 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001832 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001833
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001834 if (I->mayLoad || I->mayStore) {
1835 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1836 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1837 << MatchTable::Comment("MergeInsnID's");
1838 // Emit the ID's for all the instructions that are matched by this rule.
1839 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1840 // some other means of having a memoperand. Also limit this to
1841 // emitted instructions that expect to have a memoperand too. For
1842 // example, (G_SEXT (G_LOAD x)) that results in separate load and
1843 // sign-extend instructions shouldn't put the memoperand on the
1844 // sign-extend since it has no effect there.
1845 std::vector<unsigned> MergeInsnIDs;
1846 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1847 MergeInsnIDs.push_back(IDMatcherPair.second);
1848 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1849 for (const auto &MergeInsnID : MergeInsnIDs)
1850 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00001851 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1852 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001853 }
1854
1855 Table << MatchTable::Opcode("GIR_EraseFromParent")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001856 << MatchTable::Comment("InsnID")
1857 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001858 }
1859};
1860
1861/// Generates code to constrain the operands of an output instruction to the
1862/// register classes specified by the definition of that instruction.
1863class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001864 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001865
1866public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001867 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001868
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001869 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1870 unsigned RecycleInsnID) const override {
1871 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1872 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1873 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001874 }
1875};
1876
1877/// Generates code to constrain the specified operand of an output instruction
1878/// to the specified register class.
1879class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001880 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001881 unsigned OpIdx;
1882 const CodeGenRegisterClass &RC;
1883
1884public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001885 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001886 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001887 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001888
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001889 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1890 unsigned RecycleInsnID) const override {
1891 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1892 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1893 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1894 << MatchTable::Comment("RC " + RC.getName())
1895 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001896 }
1897};
1898
Daniel Sanders05540042017-08-08 10:44:31 +00001899InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001900 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001901 return *Matchers.back();
1902}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001903
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001904void RuleMatcher::addRequiredFeature(Record *Feature) {
1905 RequiredFeatures.push_back(Feature);
1906}
1907
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001908const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1909 return RequiredFeatures;
1910}
1911
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001912template <class Kind, class... Args>
1913Kind &RuleMatcher::addAction(Args &&... args) {
1914 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1915 return *static_cast<Kind *>(Actions.back().get());
1916}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001917
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001918unsigned
1919RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1920 unsigned NewInsnVarID = NextInsnVarID++;
1921 InsnVariableIDs[&Matcher] = NewInsnVarID;
1922 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001923}
1924
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001925unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001926 const InstructionMatcher &Matcher,
1927 unsigned InsnID, unsigned OpIdx) {
1928 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001929 Table << MatchTable::Opcode("GIM_RecordInsn")
1930 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1931 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1932 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1933 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1934 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001935 return NewInsnVarID;
1936}
1937
1938unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1939 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1940 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001941 return I->second;
1942 llvm_unreachable("Matched Insn was not captured in a local variable");
1943}
1944
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001945void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
1946 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
1947 DefinedOperands[SymbolicName] = &OM;
1948 return;
1949 }
1950
1951 // If the operand is already defined, then we must ensure both references in
1952 // the matcher have the exact same node.
1953 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
1954}
1955
Daniel Sanders05540042017-08-08 10:44:31 +00001956const InstructionMatcher &
1957RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1958 for (const auto &I : InsnVariableIDs)
1959 if (I.first->getSymbolicName() == SymbolicName)
1960 return *I.first;
1961 llvm_unreachable(
1962 ("Failed to lookup instruction " + SymbolicName).str().c_str());
1963}
1964
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001965const OperandMatcher &
1966RuleMatcher::getOperandMatcher(StringRef Name) const {
1967 const auto &I = DefinedOperands.find(Name);
1968
1969 if (I == DefinedOperands.end())
1970 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
1971
1972 return *I->second;
1973}
1974
Daniel Sanders9d662d22017-07-06 10:06:12 +00001975/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001976/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001977void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001978 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001979 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001980 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001981}
1982
Daniel Sanders8e82af22017-07-27 11:03:45 +00001983void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001984 if (Matchers.empty())
1985 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001986
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001987 // The representation supports rules that require multiple roots such as:
1988 // %ptr(p0) = ...
1989 // %elt0(s32) = G_LOAD %ptr
1990 // %1(p0) = G_ADD %ptr, 4
1991 // %elt1(s32) = G_LOAD p0 %1
1992 // which could be usefully folded into:
1993 // %ptr(p0) = ...
1994 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1995 // on some targets but we don't need to make use of that yet.
1996 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001997
Daniel Sanders8e82af22017-07-27 11:03:45 +00001998 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001999 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00002000 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002001 << MatchTable::LineBreak;
2002
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002003 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002004 Table << MatchTable::Opcode("GIM_CheckFeatures")
2005 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2006 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002007 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002008
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002009 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002010
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002011 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002012 getInsnVarID(*Matchers.front()));
2013
Daniel Sandersbee57392017-04-04 13:25:23 +00002014 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002015 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002016 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002017 SmallVector<unsigned, 2> InsnIDs;
2018 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002019 // Skip the root node since it isn't moving anywhere. Everything else is
2020 // sinking to meet it.
2021 if (Pair.first == Matchers.front().get())
2022 continue;
2023
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002024 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002025 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002026 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002027
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002028 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002029 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002030 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2031 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2032 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002033
2034 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2035 // account for unsafe cases.
2036 //
2037 // Example:
2038 // MI1--> %0 = ...
2039 // %1 = ... %0
2040 // MI0--> %2 = ... %0
2041 // It's not safe to erase MI1. We currently handle this by not
2042 // erasing %0 (even when it's dead).
2043 //
2044 // Example:
2045 // MI1--> %0 = load volatile @a
2046 // %1 = load volatile @a
2047 // MI0--> %2 = ... %0
2048 // It's not safe to sink %0's def past %1. We currently handle
2049 // this by rejecting all loads.
2050 //
2051 // Example:
2052 // MI1--> %0 = load @a
2053 // %1 = store @a
2054 // MI0--> %2 = ... %0
2055 // It's not safe to sink %0's def past %1. We currently handle
2056 // this by rejecting all loads.
2057 //
2058 // Example:
2059 // G_CONDBR %cond, @BB1
2060 // BB0:
2061 // MI1--> %0 = load @a
2062 // G_BR @BB1
2063 // BB1:
2064 // MI0--> %2 = ... %0
2065 // It's not always safe to sink %0 across control flow. In this
2066 // case it may introduce a memory fault. We currentl handle this
2067 // by rejecting all loads.
2068 }
2069 }
2070
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002071 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002072 MA->emitActionOpcodes(Table, *this, 0);
2073 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002074 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002075}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002076
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002077bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2078 // Rules involving more match roots have higher priority.
2079 if (Matchers.size() > B.Matchers.size())
2080 return true;
2081 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002082 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002083
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002084 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2085 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2086 return true;
2087 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2088 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002089 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002090
2091 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002092}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002093
Daniel Sanders2deea182017-04-22 15:11:04 +00002094unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002095 return std::accumulate(
2096 Matchers.begin(), Matchers.end(), 0,
2097 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002098 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002099 });
2100}
2101
Daniel Sanders05540042017-08-08 10:44:31 +00002102bool OperandPredicateMatcher::isHigherPriorityThan(
2103 const OperandPredicateMatcher &B) const {
2104 // Generally speaking, an instruction is more important than an Int or a
2105 // LiteralInt because it can cover more nodes but theres an exception to
2106 // this. G_CONSTANT's are less important than either of those two because they
2107 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002108
2109 const InstructionOperandMatcher *AOM =
2110 dyn_cast<InstructionOperandMatcher>(this);
2111 const InstructionOperandMatcher *BOM =
2112 dyn_cast<InstructionOperandMatcher>(&B);
2113 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2114 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2115
2116 if (AOM && BOM) {
2117 // The relative priorities between a G_CONSTANT and any other instruction
2118 // don't actually matter but this code is needed to ensure a strict weak
2119 // ordering. This is particularly important on Windows where the rules will
2120 // be incorrectly sorted without it.
2121 if (AIsConstantInsn != BIsConstantInsn)
2122 return AIsConstantInsn < BIsConstantInsn;
2123 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002124 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002125
2126 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2127 return false;
2128 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2129 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002130
2131 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002132}
Daniel Sanders05540042017-08-08 10:44:31 +00002133
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002134void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
2135 RuleMatcher &Rule,
2136 unsigned InsnVarID,
2137 unsigned OpIdx) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002138 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002139 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
2140
2141 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2142 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2143 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2144 << MatchTable::Comment("OtherMI")
2145 << MatchTable::IntValue(OtherInsnVarID)
2146 << MatchTable::Comment("OtherOpIdx")
2147 << MatchTable::IntValue(OtherOM.getOperandIndex())
2148 << MatchTable::LineBreak;
2149}
2150
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002151//===- GlobalISelEmitter class --------------------------------------------===//
2152
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002153class GlobalISelEmitter {
2154public:
2155 explicit GlobalISelEmitter(RecordKeeper &RK);
2156 void run(raw_ostream &OS);
2157
2158private:
2159 const RecordKeeper &RK;
2160 const CodeGenDAGPatterns CGP;
2161 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002162 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002163
Daniel Sanders39690bd2017-10-15 02:41:12 +00002164 /// Keep track of the equivalence between SDNodes and Instruction by mapping
2165 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2166 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002167 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002168 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002169
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002170 /// Keep track of the equivalence between ComplexPattern's and
2171 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2172 /// GIComplexPatternEquiv.
2173 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2174
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002175 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002176 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002177
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002178 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002179 Record *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002180
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002181 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002182 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2183 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2184 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2185 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2186 unsigned &TempOpIdx) const;
2187 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002188 const TreePatternNode *SrcChild,
2189 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002190 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002191 Expected<BuildMIAction &>
2192 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
2193 const InstructionMatcher &InsnMatcher);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002194 Error importExplicitUseRenderer(RuleMatcher &Rule,
2195 BuildMIAction &DstMIBuilder,
Daniel Sandersc270c502017-03-30 09:36:33 +00002196 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002197 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00002198 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2199 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002200 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002201 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2202 const std::vector<Record *> &ImplicitDefs) const;
2203
Daniel Sanders11300ce2017-10-13 21:28:03 +00002204 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2205 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002206 std::function<bool(const Record *R)> Filter);
2207
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002208 /// Analyze pattern \p P, returning a matcher for it if possible.
2209 /// Otherwise, return an Error explaining why we don't support it.
2210 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002211
2212 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002213};
2214
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002215void GlobalISelEmitter::gatherNodeEquivs() {
2216 assert(NodeEquivs.empty());
2217 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002218 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002219
2220 assert(ComplexPatternEquivs.empty());
2221 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2222 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2223 if (!SelDAGEquiv)
2224 continue;
2225 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2226 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002227}
2228
Daniel Sanders39690bd2017-10-15 02:41:12 +00002229Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002230 return NodeEquivs.lookup(N);
2231}
2232
2233GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002234 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2235 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002236
2237//===- Emitter ------------------------------------------------------------===//
2238
Daniel Sandersc270c502017-03-30 09:36:33 +00002239Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002240GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002241 ArrayRef<Predicate> Predicates) {
2242 for (const Predicate &P : Predicates) {
2243 if (!P.Def)
2244 continue;
2245 declareSubtargetFeature(P.Def);
2246 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002247 }
2248
Daniel Sandersc270c502017-03-30 09:36:33 +00002249 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002250}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002251
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002252Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2253 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2254 const TreePatternNode *Src, unsigned &TempOpIdx) const {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002255 Record *SrcGIEquivOrNull = nullptr;
Daniel Sanders85ffd362017-07-06 08:12:20 +00002256 const CodeGenInstruction *SrcGIOrNull = nullptr;
2257
Daniel Sandersffc7d582017-03-29 15:37:18 +00002258 // Start with the defined operands (i.e., the results of the root operator).
2259 if (Src->getExtTypes().size() > 1)
2260 return failedImport("Src pattern has multiple results");
2261
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002262 if (Src->isLeaf()) {
2263 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00002264 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002265 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2266 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2267 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002268 return failedImport(
2269 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002270 } else {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002271 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2272 if (!SrcGIEquivOrNull)
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002273 return failedImport("Pattern operator lacks an equivalent Instruction" +
2274 explainOperator(Src->getOperator()));
Daniel Sanders39690bd2017-10-15 02:41:12 +00002275 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002276
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002277 // The operators look good: match the opcode
Daniel Sanders39690bd2017-10-15 02:41:12 +00002278 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002279 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002280
2281 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002282 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002283 // Results don't have a name unless they are the root node. The caller will
2284 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002285 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002286 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2287 return failedImport(toString(std::move(Error)) +
2288 " for result of Src pattern operator");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002289 }
2290
Daniel Sanders2c269f62017-08-24 09:11:20 +00002291 for (const auto &Predicate : Src->getPredicateFns()) {
2292 if (Predicate.isAlwaysTrue())
2293 continue;
2294
2295 if (Predicate.isImmediatePattern()) {
2296 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2297 continue;
2298 }
2299
Daniel Sandersa71f4542017-10-16 00:56:30 +00002300 // No check required. A G_LOAD is an unindexed load.
2301 if (Predicate.isLoad() && Predicate.isUnindexed())
2302 continue;
2303
2304 // No check required. G_LOAD by itself is a non-extending load.
2305 if (Predicate.isNonExtLoad())
2306 continue;
2307
2308 if (Predicate.isLoad() && Predicate.getMemoryVT() != nullptr) {
2309 Optional<LLTCodeGen> MemTyOrNone =
2310 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2311
2312 if (!MemTyOrNone)
2313 return failedImport("MemVT could not be converted to LLT");
2314
2315 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2316 continue;
2317 }
2318
Daniel Sandersd66e0902017-10-23 18:19:24 +00002319 // No check required. A G_STORE is an unindexed store.
2320 if (Predicate.isStore() && Predicate.isUnindexed())
2321 continue;
2322
2323 // No check required. G_STORE by itself is a non-extending store.
2324 if (Predicate.isNonTruncStore())
2325 continue;
2326
2327 if (Predicate.isStore() && Predicate.getMemoryVT() != nullptr) {
2328 Optional<LLTCodeGen> MemTyOrNone =
2329 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2330
2331 if (!MemTyOrNone)
2332 return failedImport("MemVT could not be converted to LLT");
2333
2334 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2335 continue;
2336 }
2337
Daniel Sanders2c269f62017-08-24 09:11:20 +00002338 return failedImport("Src pattern child has predicate (" +
2339 explainPredicates(Src) + ")");
2340 }
Daniel Sanders39690bd2017-10-15 02:41:12 +00002341 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2342 InsnMatcher.addPredicate<NonAtomicMMOPredicateMatcher>();
Daniel Sanders2c269f62017-08-24 09:11:20 +00002343
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002344 if (Src->isLeaf()) {
2345 Init *SrcInit = Src->getLeafValue();
2346 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002347 OperandMatcher &OM =
2348 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002349 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2350 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002351 return failedImport(
2352 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002353 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002354 assert(SrcGIOrNull &&
2355 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00002356 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2357 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2358 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00002359 // here since we don't support ImmLeaf predicates yet. However, we still
2360 // need to note the hidden operand to get GIM_CheckNumOperands correct.
2361 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2362 return InsnMatcher;
2363 }
2364
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002365 // Match the used operands (i.e. the children of the operator).
2366 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002367 TreePatternNode *SrcChild = Src->getChild(i);
2368
Daniel Sandersa71f4542017-10-16 00:56:30 +00002369 // SelectionDAG allows pointers to be represented with iN since it doesn't
2370 // distinguish between pointers and integers but they are different types in GlobalISel.
2371 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
2372 // TODO: Find a better way to do this, SDTCisPtrTy?
2373 bool OperandIsAPointer =
Daniel Sandersd66e0902017-10-23 18:19:24 +00002374 (SrcGIOrNull->TheDef->getName() == "G_LOAD" && i == 0) ||
2375 (SrcGIOrNull->TheDef->getName() == "G_STORE" && i == 1);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002376
Daniel Sanders28887fe2017-09-19 12:56:36 +00002377 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2378 // following the defs is an intrinsic ID.
2379 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2380 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2381 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002382 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002383 OperandMatcher &OM =
2384 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002385 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00002386 continue;
2387 }
2388
2389 return failedImport("Expected IntInit containing instrinsic ID)");
2390 }
2391
Daniel Sandersa71f4542017-10-16 00:56:30 +00002392 if (auto Error =
2393 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2394 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002395 return std::move(Error);
2396 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002397 }
2398
2399 return InsnMatcher;
2400}
2401
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002402Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2403 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2404 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2405 if (ComplexPattern == ComplexPatternEquivs.end())
2406 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2407 ") not mapped to GlobalISel");
2408
2409 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2410 TempOpIdx++;
2411 return Error::success();
2412}
2413
2414Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2415 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002416 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002417 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00002418 unsigned OpIdx,
2419 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002420 OperandMatcher &OM =
2421 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002422 if (OM.isSameAsAnotherOperand())
2423 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002424
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002425 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002426 if (ChildTypes.size() != 1)
2427 return failedImport("Src pattern child has multiple results");
2428
2429 // Check MBB's before the type check since they are not a known type.
2430 if (!SrcChild->isLeaf()) {
2431 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2432 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2433 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2434 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00002435 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002436 }
2437 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002438 }
2439
Daniel Sandersa71f4542017-10-16 00:56:30 +00002440 if (auto Error =
2441 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2442 return failedImport(toString(std::move(Error)) + " for Src operand (" +
2443 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002444
Daniel Sandersbee57392017-04-04 13:25:23 +00002445 // Check for nested instructions.
2446 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002447 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2448 // When a ComplexPattern is used as an operator, it should do the same
2449 // thing as when used as a leaf. However, the children of the operator
2450 // name the sub-operands that make up the complex operand and we must
2451 // prepare to reference them in the renderer too.
2452 unsigned RendererID = TempOpIdx;
2453 if (auto Error = importComplexPatternOperandMatcher(
2454 OM, SrcChild->getOperator(), TempOpIdx))
2455 return Error;
2456
2457 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2458 auto *SubOperand = SrcChild->getChild(i);
2459 if (!SubOperand->getName().empty())
2460 Rule.defineComplexSubOperand(SubOperand->getName(),
2461 SrcChild->getOperator(), RendererID, i);
2462 }
2463
2464 return Error::success();
2465 }
2466
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002467 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2468 InsnMatcher.getRuleMatcher(), SrcChild->getName());
2469 if (!MaybeInsnOperand.hasValue()) {
2470 // This isn't strictly true. If the user were to provide exactly the same
2471 // matchers as the original operand then we could allow it. However, it's
2472 // simpler to not permit the redundant specification.
2473 return failedImport("Nested instruction cannot be the same as another operand");
2474 }
2475
Daniel Sandersbee57392017-04-04 13:25:23 +00002476 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002477 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00002478 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002479 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00002480 if (auto Error = InsnMatcherOrError.takeError())
2481 return Error;
2482
2483 return Error::success();
2484 }
2485
Daniel Sandersffc7d582017-03-29 15:37:18 +00002486 // Check for constant immediates.
2487 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002488 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00002489 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002490 }
2491
2492 // Check for def's like register classes or ComplexPattern's.
2493 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2494 auto *ChildRec = ChildDefInit->getDef();
2495
2496 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002497 if (ChildRec->isSubClassOf("RegisterClass") ||
2498 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002499 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002500 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00002501 return Error::success();
2502 }
2503
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002504 // Check for ValueType.
2505 if (ChildRec->isSubClassOf("ValueType")) {
2506 // We already added a type check as standard practice so this doesn't need
2507 // to do anything.
2508 return Error::success();
2509 }
2510
Daniel Sandersffc7d582017-03-29 15:37:18 +00002511 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002512 if (ChildRec->isSubClassOf("ComplexPattern"))
2513 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002514
Daniel Sandersd0656a32017-04-13 09:45:37 +00002515 if (ChildRec->isSubClassOf("ImmLeaf")) {
2516 return failedImport(
2517 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2518 }
2519
Daniel Sandersffc7d582017-03-29 15:37:18 +00002520 return failedImport(
2521 "Src pattern child def is an unsupported tablegen class");
2522 }
2523
2524 return failedImport("Src pattern child is an unsupported kind");
2525}
2526
Daniel Sandersc270c502017-03-30 09:36:33 +00002527Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002528 RuleMatcher &Rule, BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002529 const InstructionMatcher &InsnMatcher) const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00002530 if (DstChild->getTransformFn() != nullptr) {
2531 return failedImport("Dst pattern child has transform fn " +
2532 DstChild->getTransformFn()->getName());
2533 }
2534
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002535 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
2536 if (SubOperand.hasValue()) {
2537 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2538 0, *std::get<0>(*SubOperand), DstChild->getName(),
2539 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
2540 return Error::success();
2541 }
2542
Daniel Sandersffc7d582017-03-29 15:37:18 +00002543 if (!DstChild->isLeaf()) {
Daniel Sanders05540042017-08-08 10:44:31 +00002544 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2545 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002546 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2547 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2548 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002549 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002550 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002551 }
2552 }
Daniel Sanders05540042017-08-08 10:44:31 +00002553
2554 // Similarly, imm is an operator in TreePatternNode's view but must be
2555 // rendered as operands.
2556 // FIXME: The target should be able to choose sign-extended when appropriate
2557 // (e.g. on Mips).
2558 if (DstChild->getOperator()->getName() == "imm") {
2559 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2560 DstChild->getName());
2561 return Error::success();
Daniel Sanders11300ce2017-10-13 21:28:03 +00002562 } else if (DstChild->getOperator()->getName() == "fpimm") {
2563 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
2564 0, DstChild->getName());
2565 return Error::success();
Daniel Sanders05540042017-08-08 10:44:31 +00002566 }
2567
Daniel Sanders2c269f62017-08-24 09:11:20 +00002568 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002569 }
2570
2571 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002572 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2573 auto *ChildRec = ChildDefInit->getDef();
2574
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002575 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002576 if (ChildTypes.size() != 1)
2577 return failedImport("Dst pattern child has multiple results");
2578
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002579 Optional<LLTCodeGen> OpTyOrNone = None;
2580 if (ChildTypes.front().isMachineValueType())
2581 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002582 if (!OpTyOrNone)
2583 return failedImport("Dst operand has an unsupported type");
2584
2585 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002586 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00002587 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002588 }
2589
Daniel Sanders658541f2017-04-22 15:53:21 +00002590 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002591 ChildRec->isSubClassOf("RegisterOperand") ||
2592 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00002593 if (ChildRec->isSubClassOf("RegisterOperand") &&
2594 !ChildRec->isValueUnset("GIZeroRegister")) {
2595 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002596 0, DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sandersd66e0902017-10-23 18:19:24 +00002597 return Error::success();
2598 }
2599
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002600 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002601 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002602 }
2603
2604 if (ChildRec->isSubClassOf("ComplexPattern")) {
2605 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2606 if (ComplexPattern == ComplexPatternEquivs.end())
2607 return failedImport(
2608 "SelectionDAG ComplexPattern not mapped to GlobalISel");
2609
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002610 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00002611 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002612 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00002613 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00002614 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002615 }
2616
Daniel Sandersd0656a32017-04-13 09:45:37 +00002617 if (ChildRec->isSubClassOf("SDNodeXForm"))
2618 return failedImport("Dst pattern child def is an unsupported tablegen "
2619 "class (SDNodeXForm)");
2620
Daniel Sandersffc7d582017-03-29 15:37:18 +00002621 return failedImport(
2622 "Dst pattern child def is an unsupported tablegen class");
2623 }
2624
2625 return failedImport("Dst pattern child is an unsupported kind");
2626}
2627
Daniel Sandersc270c502017-03-30 09:36:33 +00002628Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002629 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002630 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002631 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002632 if (!DstOp->isSubClassOf("Instruction")) {
2633 if (DstOp->isSubClassOf("ValueType"))
2634 return failedImport(
2635 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002636 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002637 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002638 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002639
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002640 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2641 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002642 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002643
2644 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002645 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002646 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2647 DstI = &Target.getInstruction(RK.getDef("COPY"));
2648 DstINumUses--; // Ignore the class constraint.
2649 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002650 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2651 DstI = &Target.getInstruction(RK.getDef("COPY"));
2652 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002653 }
2654
Daniel Sanders64f745c2017-10-24 17:08:43 +00002655 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, &InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002656
2657 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002658 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2659 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002660 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002661 }
2662
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002663 // EXTRACT_SUBREG needs to use a subregister COPY.
2664 if (IsExtractSubReg) {
2665 if (!Dst->getChild(0)->isLeaf())
2666 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2667
Daniel Sanders32291982017-06-28 13:50:04 +00002668 if (DefInit *SubRegInit =
2669 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002670 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2671 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2672 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2673
2674 const auto &SrcRCDstRCPair =
2675 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2676 if (SrcRCDstRCPair.hasValue()) {
2677 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2678 if (SrcRCDstRCPair->first != RC)
2679 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2680 }
2681
2682 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002683 0, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002684 return DstMIBuilder;
2685 }
2686
2687 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2688 }
2689
Daniel Sandersffc7d582017-03-29 15:37:18 +00002690 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002691 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002692 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002693 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002694 const CGIOperandList::OperandInfo &DstIOperand =
2695 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002696
Diana Picus382602f2017-05-17 08:57:28 +00002697 // If the operand has default values, introduce them now.
2698 // FIXME: Until we have a decent test case that dictates we should do
2699 // otherwise, we're going to assume that operands with default values cannot
2700 // be specified in the patterns. Therefore, adding them will not cause us to
2701 // end up with too many rendered operands.
2702 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002703 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002704 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2705 return std::move(Error);
2706 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002707 continue;
2708 }
2709
2710 if (auto Error = importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002711 M, DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002712 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002713 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002714 }
2715
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002716 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002717 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002718 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002719 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002720 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002721 " default ones");
2722
Daniel Sandersffc7d582017-03-29 15:37:18 +00002723 return DstMIBuilder;
2724}
2725
Diana Picus382602f2017-05-17 08:57:28 +00002726Error GlobalISelEmitter::importDefaultOperandRenderers(
2727 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002728 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002729 // Look through ValueType operators.
2730 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2731 if (const DefInit *DefaultDagOperator =
2732 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2733 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2734 DefaultOp = DefaultDagOp->getArg(0);
2735 }
2736 }
2737
2738 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002739 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002740 continue;
2741 }
2742
2743 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002744 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002745 continue;
2746 }
2747
2748 return failedImport("Could not add default op");
2749 }
2750
2751 return Error::success();
2752}
2753
Daniel Sandersc270c502017-03-30 09:36:33 +00002754Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002755 BuildMIAction &DstMIBuilder,
2756 const std::vector<Record *> &ImplicitDefs) const {
2757 if (!ImplicitDefs.empty())
2758 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002759 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002760}
2761
2762Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002763 // Keep track of the matchers and actions to emit.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002764 RuleMatcher M(P.getSrcRecord()->getLoc());
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002765 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
2766 " => " +
2767 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002768
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002769 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002770 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002771
2772 // Next, analyze the pattern operators.
2773 TreePatternNode *Src = P.getSrcPattern();
2774 TreePatternNode *Dst = P.getDstPattern();
2775
2776 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002777 if (auto Err = isTrivialOperatorNode(Dst))
2778 return failedImport("Dst pattern root isn't a trivial operator (" +
2779 toString(std::move(Err)) + ")");
2780 if (auto Err = isTrivialOperatorNode(Src))
2781 return failedImport("Src pattern root isn't a trivial operator (" +
2782 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002783
Daniel Sandersedd07842017-08-17 09:26:14 +00002784 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2785 unsigned TempOpIdx = 0;
2786 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002787 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00002788 if (auto Error = InsnMatcherOrError.takeError())
2789 return std::move(Error);
2790 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2791
2792 if (Dst->isLeaf()) {
2793 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2794
2795 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2796 if (RCDef) {
2797 // We need to replace the def and all its uses with the specified
2798 // operand. However, we must also insert COPY's wherever needed.
2799 // For now, emit a copy and let the register allocator clean up.
2800 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2801 const auto &DstIOperand = DstI.Operands[0];
2802
2803 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2804 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002805 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00002806 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2807
Daniel Sanders64f745c2017-10-24 17:08:43 +00002808 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, &InsnMatcher);
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002809 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
2810 DstMIBuilder.addRenderer<CopyRenderer>(0, Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00002811 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2812
2813 // We're done with this pattern! It's eligible for GISel emission; return
2814 // it.
2815 ++NumPatternImported;
2816 return std::move(M);
2817 }
2818
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002819 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00002820 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002821
Daniel Sandersbee57392017-04-04 13:25:23 +00002822 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002823 Record *DstOp = Dst->getOperator();
2824 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002825 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002826
2827 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002828 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002829 return failedImport("Src pattern results and dst MI defs are different (" +
2830 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2831 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002832
Daniel Sandersffc7d582017-03-29 15:37:18 +00002833 // The root of the match also has constraints on the register bank so that it
2834 // matches the result instruction.
2835 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002836 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2837 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002838
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002839 const auto &DstIOperand = DstI.Operands[OpIdx];
2840 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002841 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2842 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2843
2844 if (DstIOpRec == nullptr)
2845 return failedImport(
2846 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002847 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2848 if (!Dst->getChild(0)->isLeaf())
2849 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2850
Daniel Sanders32291982017-06-28 13:50:04 +00002851 // We can assume that a subregister is in the same bank as it's super
2852 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002853 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2854
2855 if (DstIOpRec == nullptr)
2856 return failedImport(
2857 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002858 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002859 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002860 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002861 return failedImport("Dst MI def isn't a register class" +
2862 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002863
Daniel Sandersffc7d582017-03-29 15:37:18 +00002864 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2865 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002866 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002867 OM.addPredicate<RegisterBankOperandMatcher>(
2868 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002869 ++OpIdx;
2870 }
2871
Daniel Sandersc270c502017-03-30 09:36:33 +00002872 auto DstMIBuilderOrError =
2873 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002874 if (auto Error = DstMIBuilderOrError.takeError())
2875 return std::move(Error);
2876 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002877
Daniel Sandersffc7d582017-03-29 15:37:18 +00002878 // Render the implicit defs.
2879 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002880 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002881 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002882
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002883 // Constrain the registers to classes. This is normally derived from the
2884 // emitted instruction but a few instructions require special handling.
2885 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2886 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2887 // result is constrained to the class given by the second child.
2888 Record *DstIOpRec =
2889 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2890
2891 if (DstIOpRec == nullptr)
2892 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2893
2894 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002895 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002896
2897 // We're done with this pattern! It's eligible for GISel emission; return
2898 // it.
2899 ++NumPatternImported;
2900 return std::move(M);
2901 }
2902
2903 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2904 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2905 // instructions, the result register class is controlled by the
2906 // subregisters of the operand. As a result, we must constrain the result
2907 // class rather than check that it's already the right one.
2908 if (!Dst->getChild(0)->isLeaf())
2909 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2910
Daniel Sanders320390b2017-06-28 15:16:03 +00002911 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2912 if (!SubRegInit)
2913 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002914
Daniel Sanders320390b2017-06-28 15:16:03 +00002915 // Constrain the result to the same register bank as the operand.
2916 Record *DstIOpRec =
2917 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002918
Daniel Sanders320390b2017-06-28 15:16:03 +00002919 if (DstIOpRec == nullptr)
2920 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002921
Daniel Sanders320390b2017-06-28 15:16:03 +00002922 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002923 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002924
Daniel Sanders320390b2017-06-28 15:16:03 +00002925 // It would be nice to leave this constraint implicit but we're required
2926 // to pick a register class so constrain the result to a register class
2927 // that can hold the correct MVT.
2928 //
2929 // FIXME: This may introduce an extra copy if the chosen class doesn't
2930 // actually contain the subregisters.
2931 assert(Src->getExtTypes().size() == 1 &&
2932 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002933
Daniel Sanders320390b2017-06-28 15:16:03 +00002934 const auto &SrcRCDstRCPair =
2935 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2936 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002937 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2938 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2939
2940 // We're done with this pattern! It's eligible for GISel emission; return
2941 // it.
2942 ++NumPatternImported;
2943 return std::move(M);
2944 }
2945
2946 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002947
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002948 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002949 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002950 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002951}
2952
Daniel Sanders649c5852017-10-13 20:42:18 +00002953// Emit imm predicate table and an enum to reference them with.
2954// The 'Predicate_' part of the name is redundant but eliminating it is more
2955// trouble than it's worth.
2956void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00002957 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
2958 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00002959 std::vector<const Record *> MatchedRecords;
2960 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
2961 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
2962 [&](Record *Record) {
2963 return !Record->getValueAsString("ImmediateCode").empty() &&
2964 Filter(Record);
2965 });
2966
Daniel Sanders11300ce2017-10-13 21:28:03 +00002967 if (!MatchedRecords.empty()) {
2968 OS << "// PatFrag predicates.\n"
2969 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00002970 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00002971 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
2972 for (const auto *Record : MatchedRecords) {
2973 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
2974 << EnumeratorSeparator;
2975 EnumeratorSeparator = ",\n";
2976 }
2977 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00002978 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00002979
Daniel Sanders649c5852017-10-13 20:42:18 +00002980 for (const auto *Record : MatchedRecords)
Daniel Sanders11300ce2017-10-13 21:28:03 +00002981 OS << "static bool Predicate_" << Record->getName() << "(" << Type
2982 << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
2983
2984 OS << "static InstructionSelector::" << TypeIdentifier
2985 << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
Daniel Sanders649c5852017-10-13 20:42:18 +00002986 << " nullptr,\n";
2987 for (const auto *Record : MatchedRecords)
2988 OS << " Predicate_" << Record->getName() << ",\n";
2989 OS << "};\n";
2990}
2991
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002992void GlobalISelEmitter::run(raw_ostream &OS) {
2993 // Track the GINodeEquiv definitions.
2994 gatherNodeEquivs();
2995
2996 emitSourceFileHeader(("Global Instruction Selector for the " +
2997 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002998 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002999 // Look through the SelectionDAG patterns we found, possibly emitting some.
3000 for (const PatternToMatch &Pat : CGP.ptms()) {
3001 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003002 auto MatcherOrErr = runOnPattern(Pat);
3003
3004 // The pattern analysis can fail, indicating an unsupported pattern.
3005 // Report that if we've been asked to do so.
3006 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003007 if (WarnOnSkippedPatterns) {
3008 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003009 "Skipped pattern: " + toString(std::move(Err)));
3010 } else {
3011 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003012 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003013 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003014 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003015 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003016
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003017 Rules.push_back(std::move(MatcherOrErr.get()));
3018 }
3019
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00003020 std::stable_sort(Rules.begin(), Rules.end(),
3021 [&](const RuleMatcher &A, const RuleMatcher &B) {
3022 if (A.isHigherPriorityThan(B)) {
3023 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3024 "and less important at "
3025 "the same time");
3026 return true;
3027 }
3028 return false;
3029 });
Daniel Sanders759ff412017-02-24 13:58:11 +00003030
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003031 std::vector<Record *> ComplexPredicates =
3032 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
3033 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
3034 [](const Record *A, const Record *B) {
3035 if (A->getName() < B->getName())
3036 return true;
3037 return false;
3038 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003039 unsigned MaxTemporaries = 0;
3040 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003041 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003042
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003043 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3044 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3045 << ";\n"
3046 << "using PredicateBitset = "
3047 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3048 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3049
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003050 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3051 << " mutable MatcherState State;\n"
3052 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003053 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003054 << Target.getName()
3055 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003056 << " const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003057 "MatcherInfo;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003058 << " static " << Target.getName()
3059 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003060 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003061
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003062 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3063 << ", State(" << MaxTemporaries << "),\n"
Daniel Sanders11300ce2017-10-13 21:28:03 +00003064 << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
Daniel Sandersea8711b2017-10-16 03:36:29 +00003065 "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003066 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003067
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003068 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3069 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3070 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003071
3072 // Separate subtarget features by how often they must be recomputed.
3073 SubtargetFeatureInfoMap ModuleFeatures;
3074 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3075 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3076 [](const SubtargetFeatureInfoMap::value_type &X) {
3077 return !X.second.mustRecomputePerFunction();
3078 });
3079 SubtargetFeatureInfoMap FunctionFeatures;
3080 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3081 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3082 [](const SubtargetFeatureInfoMap::value_type &X) {
3083 return X.second.mustRecomputePerFunction();
3084 });
3085
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003086 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003087 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3088 ModuleFeatures, OS);
3089 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3090 Target.getName(), "InstructionSelector",
3091 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3092 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003093
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003094 // Emit a table containing the LLT objects needed by the matcher and an enum
3095 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003096 std::vector<LLTCodeGen> TypeObjects;
3097 for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3098 TypeObjects.push_back(Ty);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003099 std::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003100 OS << "// LLT Objects.\n"
3101 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003102 for (const auto &TypeObject : TypeObjects) {
3103 OS << " ";
3104 TypeObject.emitCxxEnumValue(OS);
3105 OS << ",\n";
3106 }
3107 OS << "};\n"
3108 << "const static LLT TypeObjects[] = {\n";
3109 for (const auto &TypeObject : TypeObjects) {
3110 OS << " ";
3111 TypeObject.emitCxxConstructorCall(OS);
3112 OS << ",\n";
3113 }
3114 OS << "};\n\n";
3115
3116 // Emit a table containing the PredicateBitsets objects needed by the matcher
3117 // and an enum for the matcher to reference them with.
3118 std::vector<std::vector<Record *>> FeatureBitsets;
3119 for (auto &Rule : Rules)
3120 FeatureBitsets.push_back(Rule.getRequiredFeatures());
3121 std::sort(
3122 FeatureBitsets.begin(), FeatureBitsets.end(),
3123 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3124 if (A.size() < B.size())
3125 return true;
3126 if (A.size() > B.size())
3127 return false;
3128 for (const auto &Pair : zip(A, B)) {
3129 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3130 return true;
3131 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3132 return false;
3133 }
3134 return false;
3135 });
3136 FeatureBitsets.erase(
3137 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3138 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003139 OS << "// Feature bitsets.\n"
3140 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003141 << " GIFBS_Invalid,\n";
3142 for (const auto &FeatureBitset : FeatureBitsets) {
3143 if (FeatureBitset.empty())
3144 continue;
3145 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3146 }
3147 OS << "};\n"
3148 << "const static PredicateBitset FeatureBitsets[] {\n"
3149 << " {}, // GIFBS_Invalid\n";
3150 for (const auto &FeatureBitset : FeatureBitsets) {
3151 if (FeatureBitset.empty())
3152 continue;
3153 OS << " {";
3154 for (const auto &Feature : FeatureBitset) {
3155 const auto &I = SubtargetFeatures.find(Feature);
3156 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3157 OS << I->second.getEnumBitName() << ", ";
3158 }
3159 OS << "},\n";
3160 }
3161 OS << "};\n\n";
3162
3163 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00003164 OS << "// ComplexPattern predicates.\n"
3165 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003166 << " GICP_Invalid,\n";
3167 for (const auto &Record : ComplexPredicates)
3168 OS << " GICP_" << Record->getName() << ",\n";
3169 OS << "};\n"
3170 << "// See constructor for table contents\n\n";
3171
Daniel Sanders11300ce2017-10-13 21:28:03 +00003172 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003173 bool Unset;
3174 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3175 !R->getValueAsBit("IsAPInt");
3176 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00003177 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3178 bool Unset;
3179 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3180 });
3181 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3182 return R->getValueAsBit("IsAPInt");
3183 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00003184 OS << "\n";
3185
3186 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3187 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3188 << " nullptr, // GICP_Invalid\n";
3189 for (const auto &Record : ComplexPredicates)
3190 OS << " &" << Target.getName()
3191 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3192 << ", // " << Record->getName() << "\n";
3193 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00003194
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003195 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003196 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
3197 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003198 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00003199 << " // FIXME: This should be computed on a per-function basis rather "
3200 "than per-insn.\n"
3201 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3202 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00003203 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3204 << " NewMIVector OutMIs;\n"
3205 << " State.MIs.clear();\n"
3206 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003207
Daniel Sanders8e82af22017-07-27 11:03:45 +00003208 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003209 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00003210 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003211 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003212 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00003213 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3214 Table.emitDeclaration(OS);
3215 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
3216 Table.emitUse(OS);
3217 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
3218 << " return true;\n"
3219 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003220
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003221 OS << " return false;\n"
3222 << "}\n"
3223 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003224
3225 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3226 << "PredicateBitset AvailableModuleFeatures;\n"
3227 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3228 << "PredicateBitset getAvailableFeatures() const {\n"
3229 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3230 << "}\n"
3231 << "PredicateBitset\n"
3232 << "computeAvailableModuleFeatures(const " << Target.getName()
3233 << "Subtarget *Subtarget) const;\n"
3234 << "PredicateBitset\n"
3235 << "computeAvailableFunctionFeatures(const " << Target.getName()
3236 << "Subtarget *Subtarget,\n"
3237 << " const MachineFunction *MF) const;\n"
3238 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3239
3240 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3241 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
3242 << "AvailableFunctionFeatures()\n"
3243 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003244}
3245
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003246void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
3247 if (SubtargetFeatures.count(Predicate) == 0)
3248 SubtargetFeatures.emplace(
3249 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
3250}
3251
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003252} // end anonymous namespace
3253
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003254//===----------------------------------------------------------------------===//
3255
3256namespace llvm {
3257void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
3258 GlobalISelEmitter(RK).run(OS);
3259}
3260} // End llvm namespace