blob: 855397fcec9287ff3531b6b04c8c7fc2a7f3be07 [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"
Daniel Sandersf76f3152017-11-16 00:46:35 +000038#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000039#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"
David Blaikie13e77db2018-03-23 23:58:25 +000042#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000043#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000044#include "llvm/TableGen/Error.h"
45#include "llvm/TableGen/Record.h"
46#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000047#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000048#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000049using namespace llvm;
50
51#define DEBUG_TYPE "gisel-emitter"
52
53STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000054STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
55STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000056STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000057STATISTIC(NumPatternEmitted, "Number of patterns emitted");
58
Daniel Sanders0848b232017-03-27 13:15:13 +000059cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60
Ahmed Bougacha36f70352016-12-21 23:26:20 +000061static cl::opt<bool> WarnOnSkippedPatterns(
62 "warn-on-skipped-patterns",
63 cl::desc("Explain why a pattern was skipped for inclusion "
64 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000065 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066
Daniel Sandersf76f3152017-11-16 00:46:35 +000067static cl::opt<bool> GenerateCoverage(
68 "instrument-gisel-coverage",
69 cl::desc("Generate coverage instrumentation for GlobalISel"),
70 cl::init(false), cl::cat(GlobalISelEmitterCat));
71
72static cl::opt<std::string> UseCoverageFile(
73 "gisel-coverage-file", cl::init(""),
74 cl::desc("Specify file to retrieve coverage information from"),
75 cl::cat(GlobalISelEmitterCat));
76
Quentin Colombetec76d9c2017-12-18 19:47:41 +000077static cl::opt<bool> OptimizeMatchTable(
78 "optimize-match-table",
79 cl::desc("Generate an optimized version of the match table"),
80 cl::init(true), cl::cat(GlobalISelEmitterCat));
81
Daniel Sandersbdfebb82017-03-15 20:18:38 +000082namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000083//===- Helper functions ---------------------------------------------------===//
84
Daniel Sanders11300ce2017-10-13 21:28:03 +000085/// Get the name of the enum value used to number the predicate function.
86std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000087 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000088 Predicate.getFnName();
89}
90
91/// Get the opcode used to check this predicate.
92std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000093 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000094}
95
Daniel Sanders52b4ce72017-03-07 23:20:35 +000096/// This class stands in for LLT wherever we want to tablegen-erate an
97/// equivalent at compiler run-time.
98class LLTCodeGen {
99private:
100 LLT Ty;
101
102public:
103 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
104
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000105 std::string getCxxEnumValue() const {
106 std::string Str;
107 raw_string_ostream OS(Str);
108
109 emitCxxEnumValue(OS);
110 return OS.str();
111 }
112
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000113 void emitCxxEnumValue(raw_ostream &OS) const {
114 if (Ty.isScalar()) {
115 OS << "GILLT_s" << Ty.getSizeInBits();
116 return;
117 }
118 if (Ty.isVector()) {
119 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
120 return;
121 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000122 if (Ty.isPointer()) {
123 OS << "GILLT_p" << Ty.getAddressSpace();
124 if (Ty.getSizeInBits() > 0)
125 OS << "s" << Ty.getSizeInBits();
126 return;
127 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000128 llvm_unreachable("Unhandled LLT");
129 }
130
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000131 void emitCxxConstructorCall(raw_ostream &OS) const {
132 if (Ty.isScalar()) {
133 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
134 return;
135 }
136 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000137 OS << "LLT::vector(" << Ty.getNumElements() << ", "
138 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000139 return;
140 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000141 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
142 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
143 << Ty.getSizeInBits() << ")";
144 return;
145 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000146 llvm_unreachable("Unhandled LLT");
147 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000148
149 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000150
151 /// This ordering is used for std::unique() and std::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000152 /// particular logic behind the order but either A < B or B < A must be
153 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000154 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000155 if (Ty.isValid() != Other.Ty.isValid())
156 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000157 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000158 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000159
160 if (Ty.isVector() != Other.Ty.isVector())
161 return Ty.isVector() < Other.Ty.isVector();
162 if (Ty.isScalar() != Other.Ty.isScalar())
163 return Ty.isScalar() < Other.Ty.isScalar();
164 if (Ty.isPointer() != Other.Ty.isPointer())
165 return Ty.isPointer() < Other.Ty.isPointer();
166
167 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
168 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
169
170 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
171 return Ty.getNumElements() < Other.Ty.getNumElements();
172
173 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000174 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000175
176 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000177};
178
179class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000180/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
181/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000182static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000183 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000184
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000185 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000186 return LLTCodeGen(
187 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000188
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000189 if (VT.isInteger() || VT.isFloatingPoint())
190 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
191 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000192}
193
Daniel Sandersd0656a32017-04-13 09:45:37 +0000194static std::string explainPredicates(const TreePatternNode *N) {
195 std::string Explanation = "";
196 StringRef Separator = "";
197 for (const auto &P : N->getPredicateFns()) {
198 Explanation +=
199 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000200 Separator = ", ";
201
Daniel Sandersd0656a32017-04-13 09:45:37 +0000202 if (P.isAlwaysTrue())
203 Explanation += " always-true";
204 if (P.isImmediatePattern())
205 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000206
207 if (P.isUnindexed())
208 Explanation += " unindexed";
209
210 if (P.isNonExtLoad())
211 Explanation += " non-extload";
212 if (P.isAnyExtLoad())
213 Explanation += " extload";
214 if (P.isSignExtLoad())
215 Explanation += " sextload";
216 if (P.isZeroExtLoad())
217 Explanation += " zextload";
218
219 if (P.isNonTruncStore())
220 Explanation += " non-truncstore";
221 if (P.isTruncStore())
222 Explanation += " truncstore";
223
224 if (Record *VT = P.getMemoryVT())
225 Explanation += (" MemVT=" + VT->getName()).str();
226 if (Record *VT = P.getScalarMemoryVT())
227 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000228
229 if (P.isAtomicOrderingMonotonic())
230 Explanation += " monotonic";
231 if (P.isAtomicOrderingAcquire())
232 Explanation += " acquire";
233 if (P.isAtomicOrderingRelease())
234 Explanation += " release";
235 if (P.isAtomicOrderingAcquireRelease())
236 Explanation += " acq_rel";
237 if (P.isAtomicOrderingSequentiallyConsistent())
238 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000239 if (P.isAtomicOrderingAcquireOrStronger())
240 Explanation += " >=acquire";
241 if (P.isAtomicOrderingWeakerThanAcquire())
242 Explanation += " <acquire";
243 if (P.isAtomicOrderingReleaseOrStronger())
244 Explanation += " >=release";
245 if (P.isAtomicOrderingWeakerThanRelease())
246 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000247 }
248 return Explanation;
249}
250
Daniel Sandersd0656a32017-04-13 09:45:37 +0000251std::string explainOperator(Record *Operator) {
252 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000253 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000254
255 if (Operator->isSubClassOf("Intrinsic"))
256 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
257
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000258 if (Operator->isSubClassOf("ComplexPattern"))
259 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
260 ")")
261 .str();
262
Volkan Kelesf7f25682018-01-16 18:44:05 +0000263 if (Operator->isSubClassOf("SDNodeXForm"))
264 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
265 ")")
266 .str();
267
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000268 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000269}
270
271/// Helper function to let the emitter report skip reason error messages.
272static Error failedImport(const Twine &Reason) {
273 return make_error<StringError>(Reason, inconvertibleErrorCode());
274}
275
276static Error isTrivialOperatorNode(const TreePatternNode *N) {
277 std::string Explanation = "";
278 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000279
280 bool HasUnsupportedPredicate = false;
281 for (const auto &Predicate : N->getPredicateFns()) {
282 if (Predicate.isAlwaysTrue())
283 continue;
284
285 if (Predicate.isImmediatePattern())
286 continue;
287
Daniel Sandersa71f4542017-10-16 00:56:30 +0000288 if (Predicate.isNonExtLoad())
289 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000290
Daniel Sanders76664652017-11-28 22:07:05 +0000291 if (Predicate.isNonTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000292 continue;
293
Daniel Sanders76664652017-11-28 22:07:05 +0000294 if (Predicate.isLoad() || Predicate.isStore()) {
295 if (Predicate.isUnindexed())
296 continue;
297 }
298
299 if (Predicate.isAtomic() && Predicate.getMemoryVT())
300 continue;
301
302 if (Predicate.isAtomic() &&
303 (Predicate.isAtomicOrderingMonotonic() ||
304 Predicate.isAtomicOrderingAcquire() ||
305 Predicate.isAtomicOrderingRelease() ||
306 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000307 Predicate.isAtomicOrderingSequentiallyConsistent() ||
308 Predicate.isAtomicOrderingAcquireOrStronger() ||
309 Predicate.isAtomicOrderingWeakerThanAcquire() ||
310 Predicate.isAtomicOrderingReleaseOrStronger() ||
311 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000312 continue;
313
Daniel Sanders2c269f62017-08-24 09:11:20 +0000314 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000315 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
316 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000317 Explanation += (Separator + "first-failing:" +
318 Predicate.getOrigPatFragRecord()->getRecord()->getName())
319 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000320 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000321 }
322
Volkan Kelesf7f25682018-01-16 18:44:05 +0000323 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000324 return Error::success();
325
326 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000327}
328
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000329static Record *getInitValueAsRegClass(Init *V) {
330 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
331 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
332 return VDefInit->getDef()->getValueAsDef("RegClass");
333 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
334 return VDefInit->getDef();
335 }
336 return nullptr;
337}
338
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000339std::string
340getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
341 std::string Name = "GIFBS";
342 for (const auto &Feature : FeatureBitset)
343 Name += ("_" + Feature->getName()).str();
344 return Name;
345}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000346
347//===- MatchTable Helpers -------------------------------------------------===//
348
349class MatchTable;
350
351/// A record to be stored in a MatchTable.
352///
353/// This class represents any and all output that may be required to emit the
354/// MatchTable. Instances are most often configured to represent an opcode or
355/// value that will be emitted to the table with some formatting but it can also
356/// represent commas, comments, and other formatting instructions.
357struct MatchTableRecord {
358 enum RecordFlagsBits {
359 MTRF_None = 0x0,
360 /// Causes EmitStr to be formatted as comment when emitted.
361 MTRF_Comment = 0x1,
362 /// Causes the record value to be followed by a comma when emitted.
363 MTRF_CommaFollows = 0x2,
364 /// Causes the record value to be followed by a line break when emitted.
365 MTRF_LineBreakFollows = 0x4,
366 /// Indicates that the record defines a label and causes an additional
367 /// comment to be emitted containing the index of the label.
368 MTRF_Label = 0x8,
369 /// Causes the record to be emitted as the index of the label specified by
370 /// LabelID along with a comment indicating where that label is.
371 MTRF_JumpTarget = 0x10,
372 /// Causes the formatter to add a level of indentation before emitting the
373 /// record.
374 MTRF_Indent = 0x20,
375 /// Causes the formatter to remove a level of indentation after emitting the
376 /// record.
377 MTRF_Outdent = 0x40,
378 };
379
380 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
381 /// reference or define.
382 unsigned LabelID;
383 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
384 /// value, a label name.
385 std::string EmitStr;
386
387private:
388 /// The number of MatchTable elements described by this record. Comments are 0
389 /// while values are typically 1. Values >1 may occur when we need to emit
390 /// values that exceed the size of a MatchTable element.
391 unsigned NumElements;
392
393public:
394 /// A bitfield of RecordFlagsBits flags.
395 unsigned Flags;
396
397 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
398 unsigned NumElements, unsigned Flags)
399 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
400 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
401 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
402 "This value is reserved for non-labels");
403 }
404
405 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
406 const MatchTable &Table) const;
407 unsigned size() const { return NumElements; }
408};
409
410/// Holds the contents of a generated MatchTable to enable formatting and the
411/// necessary index tracking needed to support GIM_Try.
412class MatchTable {
413 /// An unique identifier for the table. The generated table will be named
414 /// MatchTable${ID}.
415 unsigned ID;
416 /// The records that make up the table. Also includes comments describing the
417 /// values being emitted and line breaks to format it.
418 std::vector<MatchTableRecord> Contents;
419 /// The currently defined labels.
420 DenseMap<unsigned, unsigned> LabelMap;
421 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
422 unsigned CurrentSize;
423
Daniel Sanders8e82af22017-07-27 11:03:45 +0000424 /// A unique identifier for a MatchTable label.
425 static unsigned CurrentLabelID;
426
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000427public:
428 static MatchTableRecord LineBreak;
429 static MatchTableRecord Comment(StringRef Comment) {
430 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
431 }
432 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
433 unsigned ExtraFlags = 0;
434 if (IndentAdjust > 0)
435 ExtraFlags |= MatchTableRecord::MTRF_Indent;
436 if (IndentAdjust < 0)
437 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
438
439 return MatchTableRecord(None, Opcode, 1,
440 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
441 }
442 static MatchTableRecord NamedValue(StringRef NamedValue) {
443 return MatchTableRecord(None, NamedValue, 1,
444 MatchTableRecord::MTRF_CommaFollows);
445 }
446 static MatchTableRecord NamedValue(StringRef Namespace,
447 StringRef NamedValue) {
448 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
449 MatchTableRecord::MTRF_CommaFollows);
450 }
451 static MatchTableRecord IntValue(int64_t IntValue) {
452 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
453 MatchTableRecord::MTRF_CommaFollows);
454 }
455 static MatchTableRecord Label(unsigned LabelID) {
456 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
457 MatchTableRecord::MTRF_Label |
458 MatchTableRecord::MTRF_Comment |
459 MatchTableRecord::MTRF_LineBreakFollows);
460 }
461 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000462 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000463 MatchTableRecord::MTRF_JumpTarget |
464 MatchTableRecord::MTRF_Comment |
465 MatchTableRecord::MTRF_CommaFollows);
466 }
467
468 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
469
470 void push_back(const MatchTableRecord &Value) {
471 if (Value.Flags & MatchTableRecord::MTRF_Label)
472 defineLabel(Value.LabelID);
473 Contents.push_back(Value);
474 CurrentSize += Value.size();
475 }
476
Daniel Sanders8e82af22017-07-27 11:03:45 +0000477 unsigned allocateLabelID() const { return CurrentLabelID++; }
478
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000479 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000480 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000481 }
482
483 unsigned getLabelIndex(unsigned LabelID) const {
484 const auto I = LabelMap.find(LabelID);
485 assert(I != LabelMap.end() && "Use of undeclared label");
486 return I->second;
487 }
488
Daniel Sanders8e82af22017-07-27 11:03:45 +0000489 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
490
491 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000492 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000493 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000494 LineBreak.emit(OS, true, *this);
495 OS << std::string(Indentation, ' ');
496
497 for (auto I = Contents.begin(), E = Contents.end(); I != E;
498 ++I) {
499 bool LineBreakIsNext = false;
500 const auto &NextI = std::next(I);
501
502 if (NextI != E) {
503 if (NextI->EmitStr == "" &&
504 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
505 LineBreakIsNext = true;
506 }
507
508 if (I->Flags & MatchTableRecord::MTRF_Indent)
509 Indentation += 2;
510
511 I->emit(OS, LineBreakIsNext, *this);
512 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
513 OS << std::string(Indentation, ' ');
514
515 if (I->Flags & MatchTableRecord::MTRF_Outdent)
516 Indentation -= 2;
517 }
518 OS << "};\n";
519 }
520};
521
Daniel Sanders8e82af22017-07-27 11:03:45 +0000522unsigned MatchTable::CurrentLabelID = 0;
523
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000524MatchTableRecord MatchTable::LineBreak = {
525 None, "" /* Emit String */, 0 /* Elements */,
526 MatchTableRecord::MTRF_LineBreakFollows};
527
528void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
529 const MatchTable &Table) const {
530 bool UseLineComment =
531 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
532 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
533 UseLineComment = false;
534
535 if (Flags & MTRF_Comment)
536 OS << (UseLineComment ? "// " : "/*");
537
538 OS << EmitStr;
539 if (Flags & MTRF_Label)
540 OS << ": @" << Table.getLabelIndex(LabelID);
541
542 if (Flags & MTRF_Comment && !UseLineComment)
543 OS << "*/";
544
545 if (Flags & MTRF_JumpTarget) {
546 if (Flags & MTRF_Comment)
547 OS << " ";
548 OS << Table.getLabelIndex(LabelID);
549 }
550
551 if (Flags & MTRF_CommaFollows) {
552 OS << ",";
553 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
554 OS << " ";
555 }
556
557 if (Flags & MTRF_LineBreakFollows)
558 OS << "\n";
559}
560
561MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
562 Table.push_back(Value);
563 return Table;
564}
565
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000566//===- Matchers -----------------------------------------------------------===//
567
Daniel Sandersbee57392017-04-04 13:25:23 +0000568class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000569class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000570class PredicateMatcher;
571class RuleMatcher;
572
573class Matcher {
574public:
575 virtual ~Matcher() = default;
576 virtual void emit(MatchTable &Table) = 0;
Quentin Colombet34688b92017-12-18 21:25:53 +0000577 virtual std::unique_ptr<PredicateMatcher> forgetFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000578};
579
580class GroupMatcher : public Matcher {
581 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Conditions;
582 SmallVector<Matcher *, 8> Rules;
583
584public:
585 void addCondition(std::unique_ptr<PredicateMatcher> &&Predicate) {
586 Conditions.emplace_back(std::move(Predicate));
587 }
588 void addRule(Matcher &Rule) { Rules.push_back(&Rule); }
589 const std::unique_ptr<PredicateMatcher> &conditions_back() const {
590 return Conditions.back();
591 }
592 bool lastConditionMatches(const PredicateMatcher &Predicate) const;
593 bool conditions_empty() const { return Conditions.empty(); }
594 void clear() {
595 Conditions.clear();
596 Rules.clear();
597 }
598 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000599
600 std::unique_ptr<PredicateMatcher> forgetFirstCondition() override {
601 // We shouldn't need to mess up with groups, since we
602 // should have merged everything shareable upfront.
603 // If we start to look into reordering predicates,
604 // we may want to reconsider this.
605 assert(0 && "Groups should be formed maximal for now");
606 llvm_unreachable("No need for this for now");
607 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000608};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000609
610/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000611class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000612public:
Daniel Sanders08464522018-01-29 21:09:12 +0000613 using ActionList = std::list<std::unique_ptr<MatchAction>>;
614 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000615
616protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000617 /// A list of matchers that all need to succeed for the current rule to match.
618 /// FIXME: This currently supports a single match position but could be
619 /// extended to support multiple positions to support div/rem fusion or
620 /// load-multiple instructions.
621 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
622
623 /// A list of actions that need to be taken when all predicates in this rule
624 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000625 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000626
Daniel Sandersa7b75262017-10-31 18:50:24 +0000627 using DefinedInsnVariablesMap =
628 std::map<const InstructionMatcher *, unsigned>;
629
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000630 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000631 /// emitCaptureOpcodes().
Daniel Sanders078572b2017-08-02 11:03:36 +0000632 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000633
Daniel Sandersa7b75262017-10-31 18:50:24 +0000634 using MutatableInsnSet = SmallPtrSet<const InstructionMatcher *, 4>;
635
636 // The set of instruction matchers that have not yet been claimed for mutation
637 // by a BuildMI.
638 MutatableInsnSet MutatableInsns;
639
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000640 /// A map of named operands defined by the matchers that may be referenced by
641 /// the renderers.
642 StringMap<OperandMatcher *> DefinedOperands;
643
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000644 /// ID for the next instruction variable defined with defineInsnVar()
645 unsigned NextInsnVarID;
646
Daniel Sanders198447a2017-11-01 00:29:47 +0000647 /// ID for the next output instruction allocated with allocateOutputInsnID()
648 unsigned NextOutputInsnID;
649
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000650 /// ID for the next temporary register ID allocated with allocateTempRegID()
651 unsigned NextTempRegID;
652
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000653 std::vector<Record *> RequiredFeatures;
654
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000655 ArrayRef<SMLoc> SrcLoc;
656
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000657 typedef std::tuple<Record *, unsigned, unsigned>
658 DefinedComplexPatternSubOperand;
659 typedef StringMap<DefinedComplexPatternSubOperand>
660 DefinedComplexPatternSubOperandMap;
661 /// A map of Symbolic Names to ComplexPattern sub-operands.
662 DefinedComplexPatternSubOperandMap ComplexSubOperands;
663
Daniel Sandersf76f3152017-11-16 00:46:35 +0000664 uint64_t RuleID;
665 static uint64_t NextRuleID;
666
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000667public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000668 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000669 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000670 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000671 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
672 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000673 RuleMatcher(RuleMatcher &&Other) = default;
674 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000675
Daniel Sandersf76f3152017-11-16 00:46:35 +0000676 uint64_t getRuleID() const { return RuleID; }
677
Daniel Sanders05540042017-08-08 10:44:31 +0000678 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000679 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000680 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000681
682 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000683 template <class Kind, class... Args>
684 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000685
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000686 /// Define an instruction without emitting any code to do so.
687 /// This is used for the root of the match.
688 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
Quentin Colombetaad20be2017-12-15 23:07:42 +0000689 void clearImplicitMap() {
690 NextInsnVarID = 0;
691 InsnVariableIDs.clear();
692 };
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000693 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000694 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000695 unsigned InsnVarID, unsigned OpIdx);
696 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000697 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
698 return InsnVariableIDs.begin();
699 }
700 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
701 return InsnVariableIDs.end();
702 }
703 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
704 defined_insn_vars() const {
705 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
706 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000707
Daniel Sandersa7b75262017-10-31 18:50:24 +0000708 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
709 return MutatableInsns.begin();
710 }
711 MutatableInsnSet::const_iterator mutatable_insns_end() const {
712 return MutatableInsns.end();
713 }
714 iterator_range<typename MutatableInsnSet::const_iterator>
715 mutatable_insns() const {
716 return make_range(mutatable_insns_begin(), mutatable_insns_end());
717 }
718 void reserveInsnMatcherForMutation(const InstructionMatcher *InsnMatcher) {
719 bool R = MutatableInsns.erase(InsnMatcher);
720 assert(R && "Reserving a mutatable insn that isn't available");
721 (void)R;
722 }
723
Daniel Sanders7438b262017-10-31 23:03:18 +0000724 action_iterator actions_begin() { return Actions.begin(); }
725 action_iterator actions_end() { return Actions.end(); }
726 iterator_range<action_iterator> actions() {
727 return make_range(actions_begin(), actions_end());
728 }
729
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000730 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
731
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000732 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
733 unsigned RendererID, unsigned SubOperandID) {
734 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
735 ComplexSubOperands[SymbolicName] =
736 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
737 }
738 Optional<DefinedComplexPatternSubOperand>
739 getComplexSubOperand(StringRef SymbolicName) const {
740 const auto &I = ComplexSubOperands.find(SymbolicName);
741 if (I == ComplexSubOperands.end())
742 return None;
743 return I->second;
744 }
745
Daniel Sanders05540042017-08-08 10:44:31 +0000746 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000747 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000748
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000749 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000750
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000751 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000752
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000753 /// Compare the priority of this object and B.
754 ///
755 /// Returns true if this object is more important than B.
756 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000757
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000758 /// Report the maximum number of temporary operands needed by the rule
759 /// matcher.
760 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000761
Quentin Colombet34688b92017-12-18 21:25:53 +0000762 std::unique_ptr<PredicateMatcher> forgetFirstCondition() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000763
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000764 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000765 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000766
767 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000768 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000769
770 bool insnmatchers_empty() const { return Matchers.empty(); }
771 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000772};
773
Daniel Sandersf76f3152017-11-16 00:46:35 +0000774uint64_t RuleMatcher::NextRuleID = 0;
775
Daniel Sanders7438b262017-10-31 23:03:18 +0000776using action_iterator = RuleMatcher::action_iterator;
777
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000778template <class PredicateTy> class PredicateListMatcher {
779private:
780 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
781 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000782
Daniel Sanders2c269f62017-08-24 09:11:20 +0000783 /// Template instantiations should specialize this to return a string to use
784 /// for the comment emitted when there are no predicates.
785 std::string getNoPredicateComment() const;
786
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000787public:
788 /// Construct a new operand predicate and add it to the matcher.
789 template <class Kind, class... Args>
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000790 Optional<Kind *> addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000791 Predicates.emplace_back(
792 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000793 return static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000794 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000795
Daniel Sanders32291982017-06-28 13:50:04 +0000796 typename PredicateVec::const_iterator predicates_begin() const {
797 return Predicates.begin();
798 }
799 typename PredicateVec::const_iterator predicates_end() const {
800 return Predicates.end();
801 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000802 iterator_range<typename PredicateVec::const_iterator> predicates() const {
803 return make_range(predicates_begin(), predicates_end());
804 }
Daniel Sanders32291982017-06-28 13:50:04 +0000805 typename PredicateVec::size_type predicates_size() const {
806 return Predicates.size();
807 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000808 bool predicates_empty() const { return Predicates.empty(); }
809
810 std::unique_ptr<PredicateTy> predicates_pop_front() {
811 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
812 Predicates.erase(Predicates.begin());
813 return Front;
814 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000815
Daniel Sanders9d662d22017-07-06 10:06:12 +0000816 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000817 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000818 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000819 if (Predicates.empty()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000820 Table << MatchTable::Comment(getNoPredicateComment())
821 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000822 return;
823 }
824
Quentin Colombetaad20be2017-12-15 23:07:42 +0000825 unsigned OpIdx = (*predicates_begin())->getOpIdx();
826 (void)OpIdx;
827 for (const auto &Predicate : predicates()) {
828 assert(Predicate->getOpIdx() == OpIdx &&
829 "Checks touch different operands?");
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000830 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Quentin Colombetaad20be2017-12-15 23:07:42 +0000831 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000832 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000833};
834
Quentin Colombet063d7982017-12-14 23:44:07 +0000835class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000836public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000837 /// This enum is used for RTTI and also defines the priority that is given to
838 /// the predicate when generating the matcher code. Kinds with higher priority
839 /// must be tested first.
840 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000841 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
842 /// but OPM_Int must have priority over OPM_RegBank since constant integers
843 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +0000844 ///
845 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
846 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +0000847 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +0000848 IPM_Opcode,
849 IPM_ImmPredicate,
850 IPM_AtomicOrderingMMO,
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000851 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000852 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000853 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +0000854 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000855 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000856 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000857 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +0000858 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +0000859 OPM_RegBank,
860 OPM_MBB,
861 };
862
863protected:
864 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +0000865 unsigned InsnVarID;
866 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +0000867
868public:
Quentin Colombetaad20be2017-12-15 23:07:42 +0000869 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
870 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +0000871
Quentin Colombetaad20be2017-12-15 23:07:42 +0000872 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombet063d7982017-12-14 23:44:07 +0000873 virtual ~PredicateMatcher() = default;
874 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +0000875 virtual void emitPredicateOpcodes(MatchTable &Table,
876 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000877
Daniel Sanders759ff412017-02-24 13:58:11 +0000878 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000879
880 virtual bool isIdentical(const PredicateMatcher &B) const {
881 if (InsnVarID != 0 || OpIdx != (unsigned)~0) {
882 // We currently don't hoist the record of instruction properly.
883 // Therefore we can only work on the orig instruction (InsnVarID
884 // == 0).
885 DEBUG(dbgs() << "Non-zero instr ID not supported yet\n");
886 return false;
887 }
888 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
889 OpIdx == B.OpIdx;
890 }
Quentin Colombet063d7982017-12-14 23:44:07 +0000891};
892
893/// Generates code to check a predicate of an operand.
894///
895/// Typical predicates include:
896/// * Operand is a particular register.
897/// * Operand is assigned a particular register bank.
898/// * Operand is an MBB.
899class OperandPredicateMatcher : public PredicateMatcher {
900public:
Quentin Colombetaad20be2017-12-15 23:07:42 +0000901 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
902 unsigned OpIdx)
903 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +0000904 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +0000905
Daniel Sanders9d662d22017-07-06 10:06:12 +0000906 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000907 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000908 /// Only InstructionOperandMatcher needs to do anything for this method the
909 /// rest just walk the tree.
Quentin Colombetaad20be2017-12-15 23:07:42 +0000910 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000911
Daniel Sanders759ff412017-02-24 13:58:11 +0000912 /// Compare the priority of this object and B.
913 ///
914 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +0000915 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000916
917 /// Report the maximum number of temporary operands needed by the predicate
918 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000919 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000920};
921
Daniel Sanders2c269f62017-08-24 09:11:20 +0000922template <>
923std::string
924PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
925 return "No operand predicates";
926}
927
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000928/// Generates code to check that a register operand is defined by the same exact
929/// one as another.
930class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000931 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000932
933public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +0000934 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +0000935 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
936 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000937
938 static bool classof(const OperandPredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000939 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000940 }
941
Quentin Colombetaad20be2017-12-15 23:07:42 +0000942 void emitPredicateOpcodes(MatchTable &Table,
943 RuleMatcher &Rule) const override;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000944};
945
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000946/// Generates code to check that an operand is a particular LLT.
947class LLTOperandMatcher : public OperandPredicateMatcher {
948protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000949 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000950
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000951public:
Daniel Sanders032e7f22017-08-17 13:18:35 +0000952 static std::set<LLTCodeGen> KnownTypes;
953
Quentin Colombeteba10cb2017-12-18 22:12:13 +0000954 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +0000955 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000956 KnownTypes.insert(Ty);
957 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000958
Quentin Colombet063d7982017-12-14 23:44:07 +0000959 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +0000960 return P->getKind() == OPM_LLT;
961 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000962 bool isIdentical(const PredicateMatcher &B) const override {
963 return OperandPredicateMatcher::isIdentical(B) &&
964 Ty == cast<LLTOperandMatcher>(&B)->Ty;
965 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000966
Quentin Colombetaad20be2017-12-15 23:07:42 +0000967 void emitPredicateOpcodes(MatchTable &Table,
968 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000969 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
970 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
971 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
972 << MatchTable::NamedValue(Ty.getCxxEnumValue())
973 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000974 }
975};
976
Daniel Sanders032e7f22017-08-17 13:18:35 +0000977std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
978
Daniel Sandersa71f4542017-10-16 00:56:30 +0000979/// Generates code to check that an operand is a pointer to any address space.
980///
981/// In SelectionDAG, the types did not describe pointers or address spaces. As a
982/// result, iN is used to describe a pointer of N bits to any address space and
983/// PatFrag predicates are typically used to constrain the address space. There's
984/// no reliable means to derive the missing type information from the pattern so
985/// imported rules must test the components of a pointer separately.
986///
Daniel Sandersea8711b2017-10-16 03:36:29 +0000987/// If SizeInBits is zero, then the pointer size will be obtained from the
988/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +0000989class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
990protected:
991 unsigned SizeInBits;
992
993public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +0000994 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
995 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +0000996 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
997 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +0000998
999 static bool classof(const OperandPredicateMatcher *P) {
1000 return P->getKind() == OPM_PointerToAny;
1001 }
1002
Quentin Colombetaad20be2017-12-15 23:07:42 +00001003 void emitPredicateOpcodes(MatchTable &Table,
1004 RuleMatcher &Rule) const override {
1005 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1006 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1007 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1008 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001009 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1010 }
1011};
1012
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001013/// Generates code to check that an operand is a particular target constant.
1014class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1015protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001016 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001017 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001018
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001019 unsigned getAllocatedTemporariesBaseID() const;
1020
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001021public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001022 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1023
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001024 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1025 const OperandMatcher &Operand,
1026 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001027 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1028 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001029
Quentin Colombet063d7982017-12-14 23:44:07 +00001030 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001031 return P->getKind() == OPM_ComplexPattern;
1032 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001033
Quentin Colombetaad20be2017-12-15 23:07:42 +00001034 void emitPredicateOpcodes(MatchTable &Table,
1035 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001036 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001037 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1038 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1039 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1040 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1041 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1042 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001043 }
1044
Daniel Sanders2deea182017-04-22 15:11:04 +00001045 unsigned countRendererFns() const override {
1046 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001047 }
1048};
1049
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001050/// Generates code to check that an operand is in a particular register bank.
1051class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1052protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001053 const CodeGenRegisterClass &RC;
1054
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001055public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001056 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1057 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001058 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001059
Quentin Colombet893e0f12017-12-15 23:24:39 +00001060 bool isIdentical(const PredicateMatcher &B) const override {
1061 return OperandPredicateMatcher::isIdentical(B) &&
1062 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1063 }
1064
Quentin Colombet063d7982017-12-14 23:44:07 +00001065 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001066 return P->getKind() == OPM_RegBank;
1067 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001068
Quentin Colombetaad20be2017-12-15 23:07:42 +00001069 void emitPredicateOpcodes(MatchTable &Table,
1070 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001071 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1072 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1073 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1074 << MatchTable::Comment("RC")
1075 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1076 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001077 }
1078};
1079
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001080/// Generates code to check that an operand is a basic block.
1081class MBBOperandMatcher : public OperandPredicateMatcher {
1082public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001083 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1084 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001085
Quentin Colombet063d7982017-12-14 23:44:07 +00001086 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001087 return P->getKind() == OPM_MBB;
1088 }
1089
Quentin Colombetaad20be2017-12-15 23:07:42 +00001090 void emitPredicateOpcodes(MatchTable &Table,
1091 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001092 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1093 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1094 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001095 }
1096};
1097
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001098/// Generates code to check that an operand is a G_CONSTANT with a particular
1099/// int.
1100class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001101protected:
1102 int64_t Value;
1103
1104public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001105 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001106 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001107
Quentin Colombet893e0f12017-12-15 23:24:39 +00001108 bool isIdentical(const PredicateMatcher &B) const override {
1109 return OperandPredicateMatcher::isIdentical(B) &&
1110 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1111 }
1112
Quentin Colombet063d7982017-12-14 23:44:07 +00001113 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001114 return P->getKind() == OPM_Int;
1115 }
1116
Quentin Colombetaad20be2017-12-15 23:07:42 +00001117 void emitPredicateOpcodes(MatchTable &Table,
1118 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001119 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1120 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1121 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1122 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001123 }
1124};
1125
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001126/// Generates code to check that an operand is a raw int (where MO.isImm() or
1127/// MO.isCImm() is true).
1128class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1129protected:
1130 int64_t Value;
1131
1132public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001133 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001134 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1135 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001136
Quentin Colombet893e0f12017-12-15 23:24:39 +00001137 bool isIdentical(const PredicateMatcher &B) const override {
1138 return OperandPredicateMatcher::isIdentical(B) &&
1139 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1140 }
1141
Quentin Colombet063d7982017-12-14 23:44:07 +00001142 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001143 return P->getKind() == OPM_LiteralInt;
1144 }
1145
Quentin Colombetaad20be2017-12-15 23:07:42 +00001146 void emitPredicateOpcodes(MatchTable &Table,
1147 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001148 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1149 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1150 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1151 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001152 }
1153};
1154
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001155/// Generates code to check that an operand is an intrinsic ID.
1156class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1157protected:
1158 const CodeGenIntrinsic *II;
1159
1160public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001161 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1162 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001163 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001164
Quentin Colombet893e0f12017-12-15 23:24:39 +00001165 bool isIdentical(const PredicateMatcher &B) const override {
1166 return OperandPredicateMatcher::isIdentical(B) &&
1167 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1168 }
1169
Quentin Colombet063d7982017-12-14 23:44:07 +00001170 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001171 return P->getKind() == OPM_IntrinsicID;
1172 }
1173
Quentin Colombetaad20be2017-12-15 23:07:42 +00001174 void emitPredicateOpcodes(MatchTable &Table,
1175 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001176 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1177 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1178 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1179 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1180 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001181 }
1182};
1183
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001184/// Generates code to check that a set of predicates match for a particular
1185/// operand.
1186class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1187protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001188 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001189 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001190 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001191
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001192 /// The index of the first temporary variable allocated to this operand. The
1193 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001194 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001195 unsigned AllocatedTemporariesBaseID;
1196
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001197public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001198 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001199 const std::string &SymbolicName,
1200 unsigned AllocatedTemporariesBaseID)
1201 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1202 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001203
1204 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1205 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001206 void setSymbolicName(StringRef Name) {
1207 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1208 SymbolicName = Name;
1209 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001210 unsigned getOperandIndex() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001211 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001212
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001213 std::string getOperandExpr(unsigned InsnVarID) const {
1214 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1215 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001216 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001217
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001218 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1219
Daniel Sandersa71f4542017-10-16 00:56:30 +00001220 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001221 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001222
Daniel Sanders9d662d22017-07-06 10:06:12 +00001223 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001224 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
Daniel Sandersbee57392017-04-04 13:25:23 +00001225 for (const auto &Predicate : predicates())
Quentin Colombetaad20be2017-12-15 23:07:42 +00001226 Predicate->emitCaptureOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001227 }
1228
Daniel Sanders9d662d22017-07-06 10:06:12 +00001229 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001230 /// InsnVarID matches all the predicates and all the operands.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001231 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001232 std::string Comment;
1233 raw_string_ostream CommentOS(Comment);
Quentin Colombetaad20be2017-12-15 23:07:42 +00001234 CommentOS << "MIs[" << getInsnVarID() << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001235 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001236 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001237 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001238 CommentOS << SymbolicName;
1239 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1240
Quentin Colombetaad20be2017-12-15 23:07:42 +00001241 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001242 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001243
1244 /// Compare the priority of this object and B.
1245 ///
1246 /// Returns true if this object is more important than B.
1247 bool isHigherPriorityThan(const OperandMatcher &B) const {
1248 // Operand matchers involving more predicates have higher priority.
1249 if (predicates_size() > B.predicates_size())
1250 return true;
1251 if (predicates_size() < B.predicates_size())
1252 return false;
1253
1254 // This assumes that predicates are added in a consistent order.
1255 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1256 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1257 return true;
1258 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1259 return false;
1260 }
1261
1262 return false;
1263 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001264
1265 /// Report the maximum number of temporary operands needed by the operand
1266 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001267 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001268 return std::accumulate(
1269 predicates().begin(), predicates().end(), 0,
1270 [](unsigned A,
1271 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001272 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001273 });
1274 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001275
1276 unsigned getAllocatedTemporariesBaseID() const {
1277 return AllocatedTemporariesBaseID;
1278 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001279
1280 bool isSameAsAnotherOperand() const {
1281 for (const auto &Predicate : predicates())
1282 if (isa<SameOperandMatcher>(Predicate))
1283 return true;
1284 return false;
1285 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001286};
1287
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001288// Specialize OperandMatcher::addPredicate() to refrain from adding redundant
1289// predicates.
1290template <>
1291template <class Kind, class... Args>
1292Optional<Kind *>
1293PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
Quentin Colombetaad20be2017-12-15 23:07:42 +00001294 auto *OpMatcher = static_cast<OperandMatcher *>(this);
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001295 if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
1296 return None;
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001297 Predicates.emplace_back(llvm::make_unique<Kind>(OpMatcher->getInsnVarID(),
1298 OpMatcher->getOperandIndex(),
1299 std::forward<Args>(args)...));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001300 return static_cast<Kind *>(Predicates.back().get());
1301}
1302
1303Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001304 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001305 if (!VTy.isMachineValueType())
1306 return failedImport("unsupported typeset");
1307
1308 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1309 addPredicate<PointerToAnyOperandMatcher>(0);
1310 return Error::success();
1311 }
1312
1313 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1314 if (!OpTyOrNone)
1315 return failedImport("unsupported type");
1316
1317 if (OperandIsAPointer)
1318 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1319 else
1320 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1321 return Error::success();
1322}
1323
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001324unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1325 return Operand.getAllocatedTemporariesBaseID();
1326}
1327
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001328/// Generates code to check a predicate on an instruction.
1329///
1330/// Typical predicates include:
1331/// * The opcode of the instruction is a particular value.
1332/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001333class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001334public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001335 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1336 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001337 virtual ~InstructionPredicateMatcher() {}
1338
Daniel Sanders759ff412017-02-24 13:58:11 +00001339 /// Compare the priority of this object and B.
1340 ///
1341 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001342 virtual bool
1343 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001344 return Kind < B.Kind;
1345 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001346
1347 /// Report the maximum number of temporary operands needed by the predicate
1348 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001349 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001350};
1351
Daniel Sanders2c269f62017-08-24 09:11:20 +00001352template <>
1353std::string
1354PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1355 return "No instruction predicates";
1356}
1357
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001358/// Generates code to check the opcode of an instruction.
1359class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1360protected:
1361 const CodeGenInstruction *I;
1362
1363public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001364 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1365 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001366
Quentin Colombet063d7982017-12-14 23:44:07 +00001367 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001368 return P->getKind() == IPM_Opcode;
1369 }
1370
Quentin Colombet893e0f12017-12-15 23:24:39 +00001371 bool isIdentical(const PredicateMatcher &B) const override {
1372 return InstructionPredicateMatcher::isIdentical(B) &&
1373 I == cast<InstructionOpcodeMatcher>(&B)->I;
1374 }
1375
Quentin Colombetaad20be2017-12-15 23:07:42 +00001376 void emitPredicateOpcodes(MatchTable &Table,
1377 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001378 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1379 << MatchTable::IntValue(InsnVarID)
1380 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1381 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001382 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001383
1384 /// Compare the priority of this object and B.
1385 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001386 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001387 bool
1388 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001389 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1390 return true;
1391 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1392 return false;
1393
1394 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1395 // this is cosmetic at the moment, we may want to drive a similar ordering
1396 // using instruction frequency information to improve compile time.
1397 if (const InstructionOpcodeMatcher *BO =
1398 dyn_cast<InstructionOpcodeMatcher>(&B))
1399 return I->TheDef->getName() < BO->I->TheDef->getName();
1400
1401 return false;
1402 };
Daniel Sanders05540042017-08-08 10:44:31 +00001403
1404 bool isConstantInstruction() const {
1405 return I->TheDef->getName() == "G_CONSTANT";
1406 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001407};
1408
Daniel Sanders2c269f62017-08-24 09:11:20 +00001409/// Generates code to check that this instruction is a constant whose value
1410/// meets an immediate predicate.
1411///
1412/// Immediates are slightly odd since they are typically used like an operand
1413/// but are represented as an operator internally. We typically write simm8:$src
1414/// in a tablegen pattern, but this is just syntactic sugar for
1415/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1416/// that will be matched and the predicate (which is attached to the imm
1417/// operator) that will be tested. In SelectionDAG this describes a
1418/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1419///
1420/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1421/// this representation, the immediate could be tested with an
1422/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1423/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1424/// there are two implementation issues with producing that matcher
1425/// configuration from the SelectionDAG pattern:
1426/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1427/// were we to sink the immediate predicate to the operand we would have to
1428/// have two partial implementations of PatFrag support, one for immediates
1429/// and one for non-immediates.
1430/// * At the point we handle the predicate, the OperandMatcher hasn't been
1431/// created yet. If we were to sink the predicate to the OperandMatcher we
1432/// would also have to complicate (or duplicate) the code that descends and
1433/// creates matchers for the subtree.
1434/// Overall, it's simpler to handle it in the place it was found.
1435class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1436protected:
1437 TreePredicateFn Predicate;
1438
1439public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001440 InstructionImmPredicateMatcher(unsigned InsnVarID,
1441 const TreePredicateFn &Predicate)
1442 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1443 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001444
Quentin Colombet893e0f12017-12-15 23:24:39 +00001445 bool isIdentical(const PredicateMatcher &B) const override {
1446 return InstructionPredicateMatcher::isIdentical(B) &&
1447 Predicate.getOrigPatFragRecord() ==
1448 cast<InstructionImmPredicateMatcher>(&B)
1449 ->Predicate.getOrigPatFragRecord();
1450 }
1451
Quentin Colombet063d7982017-12-14 23:44:07 +00001452 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001453 return P->getKind() == IPM_ImmPredicate;
1454 }
1455
Quentin Colombetaad20be2017-12-15 23:07:42 +00001456 void emitPredicateOpcodes(MatchTable &Table,
1457 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001458 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001459 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1460 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001461 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001462 << MatchTable::LineBreak;
1463 }
1464};
1465
Daniel Sanders76664652017-11-28 22:07:05 +00001466/// Generates code to check that a memory instruction has a atomic ordering
1467/// MachineMemoryOperand.
1468class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001469public:
1470 enum AOComparator {
1471 AO_Exactly,
1472 AO_OrStronger,
1473 AO_WeakerThan,
1474 };
1475
1476protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001477 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001478 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001479
Daniel Sanders39690bd2017-10-15 02:41:12 +00001480public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001481 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001482 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001483 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1484 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001485
1486 static bool classof(const InstructionPredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001487 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001488 }
1489
Quentin Colombetaad20be2017-12-15 23:07:42 +00001490 void emitPredicateOpcodes(MatchTable &Table,
1491 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001492 StringRef Opcode = "GIM_CheckAtomicOrdering";
1493
1494 if (Comparator == AO_OrStronger)
1495 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1496 if (Comparator == AO_WeakerThan)
1497 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1498
1499 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1500 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001501 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001502 << MatchTable::LineBreak;
1503 }
1504};
1505
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001506/// Generates code to check that a set of predicates and operands match for a
1507/// particular instruction.
1508///
1509/// Typical predicates include:
1510/// * Has a specific opcode.
1511/// * Has an nsw/nuw flag or doesn't.
1512class InstructionMatcher
1513 : public PredicateListMatcher<InstructionPredicateMatcher> {
1514protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001515 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001516
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001517 RuleMatcher &Rule;
1518
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001519 /// The operands to match. All rendered operands must be present even if the
1520 /// condition is always true.
1521 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001522
Daniel Sanders05540042017-08-08 10:44:31 +00001523 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001524 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001525
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001526public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001527 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001528 : Rule(Rule), SymbolicName(SymbolicName) {
1529 // We create a new instruction matcher.
1530 // Get a new ID for that instruction.
1531 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1532 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001533
1534 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001535
Quentin Colombetaad20be2017-12-15 23:07:42 +00001536 unsigned getVarID() const { return InsnVarID; }
1537
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001538 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001539 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1540 unsigned AllocatedTemporariesBaseID) {
1541 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1542 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001543 if (!SymbolicName.empty())
1544 Rule.defineOperand(SymbolicName, *Operands.back());
1545
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001546 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001547 }
1548
Daniel Sandersffc7d582017-03-29 15:37:18 +00001549 OperandMatcher &getOperand(unsigned OpIdx) {
1550 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001551 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1552 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001553 });
1554 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001555 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001556 llvm_unreachable("Failed to lookup operand");
1557 }
1558
Daniel Sanders05540042017-08-08 10:44:31 +00001559 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001560 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001561 OperandVec::iterator operands_begin() { return Operands.begin(); }
1562 OperandVec::iterator operands_end() { return Operands.end(); }
1563 iterator_range<OperandVec::iterator> operands() {
1564 return make_range(operands_begin(), operands_end());
1565 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001566 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1567 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001568 iterator_range<OperandVec::const_iterator> operands() const {
1569 return make_range(operands_begin(), operands_end());
1570 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001571 bool operands_empty() const { return Operands.empty(); }
1572
1573 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001574
Daniel Sanders9d662d22017-07-06 10:06:12 +00001575 /// Emit MatchTable opcodes to check the shape of the match and capture
1576 /// instructions into the MIs table.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001577 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001578 Table << MatchTable::Opcode("GIM_CheckNumOperands")
Quentin Colombetaad20be2017-12-15 23:07:42 +00001579 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001580 << MatchTable::Comment("Expected")
1581 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001582 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001583 Operand->emitCaptureOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001584 }
1585
Daniel Sanders9d662d22017-07-06 10:06:12 +00001586 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001587 /// InsnVarName matches all the predicates and all the operands.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001588 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
1589 emitPredicateListOpcodes(Table, Rule);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001590 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001591 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001592 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001593
1594 /// Compare the priority of this object and B.
1595 ///
1596 /// Returns true if this object is more important than B.
1597 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1598 // Instruction matchers involving more operands have higher priority.
1599 if (Operands.size() > B.Operands.size())
1600 return true;
1601 if (Operands.size() < B.Operands.size())
1602 return false;
1603
1604 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1605 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1606 return true;
1607 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1608 return false;
1609 }
1610
1611 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001612 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001613 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001614 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001615 return false;
1616 }
1617
1618 return false;
1619 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001620
1621 /// Report the maximum number of temporary operands needed by the instruction
1622 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001623 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001624 return std::accumulate(predicates().begin(), predicates().end(), 0,
1625 [](unsigned A,
1626 const std::unique_ptr<InstructionPredicateMatcher>
1627 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001628 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001629 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001630 std::accumulate(
1631 Operands.begin(), Operands.end(), 0,
1632 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001633 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001634 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001635 }
Daniel Sanders05540042017-08-08 10:44:31 +00001636
1637 bool isConstantInstruction() const {
1638 for (const auto &P : predicates())
1639 if (const InstructionOpcodeMatcher *Opcode =
1640 dyn_cast<InstructionOpcodeMatcher>(P.get()))
1641 return Opcode->isConstantInstruction();
1642 return false;
1643 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001644};
1645
Quentin Colombetaad20be2017-12-15 23:07:42 +00001646template <>
1647template <class Kind, class... Args>
1648Optional<Kind *>
1649PredicateListMatcher<InstructionPredicateMatcher>::addPredicate(
1650 Args &&... args) {
1651 InstructionMatcher *InstMatcher = static_cast<InstructionMatcher *>(this);
1652 Predicates.emplace_back(llvm::make_unique<Kind>(InstMatcher->getVarID(),
1653 std::forward<Args>(args)...));
1654 return static_cast<Kind *>(Predicates.back().get());
1655}
1656
Daniel Sandersbee57392017-04-04 13:25:23 +00001657/// Generates code to check that the operand is a register defined by an
1658/// instruction that matches the given instruction matcher.
1659///
1660/// For example, the pattern:
1661/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1662/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1663/// the:
1664/// (G_ADD $src1, $src2)
1665/// subpattern.
1666class InstructionOperandMatcher : public OperandPredicateMatcher {
1667protected:
1668 std::unique_ptr<InstructionMatcher> InsnMatcher;
1669
1670public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001671 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1672 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001673 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001674 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00001675
Quentin Colombet063d7982017-12-14 23:44:07 +00001676 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001677 return P->getKind() == OPM_Instruction;
1678 }
1679
1680 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1681
Quentin Colombetaad20be2017-12-15 23:07:42 +00001682 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1683 unsigned InsnID =
1684 Rule.defineInsnVar(Table, *InsnMatcher, InsnVarID, getOpIdx());
1685 (void)InsnID;
1686 assert(InsnMatcher->getVarID() == InsnID &&
1687 "Mismatch between build and emit");
1688 InsnMatcher->emitCaptureOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001689 }
1690
Quentin Colombetaad20be2017-12-15 23:07:42 +00001691 void emitPredicateOpcodes(MatchTable &Table,
1692 RuleMatcher &Rule) const override {
1693 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001694 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00001695
1696 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
1697 if (OperandPredicateMatcher::isHigherPriorityThan(B))
1698 return true;
1699 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
1700 return false;
1701
1702 if (const InstructionOperandMatcher *BP =
1703 dyn_cast<InstructionOperandMatcher>(&B))
1704 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
1705 return true;
1706 return false;
1707 }
Daniel Sandersbee57392017-04-04 13:25:23 +00001708};
1709
Daniel Sanders43c882c2017-02-01 10:53:10 +00001710//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001711class OperandRenderer {
1712public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001713 enum RendererKind {
1714 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001715 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001716 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00001717 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00001718 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001719 OR_Imm,
1720 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00001721 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00001722 OR_ComplexPattern,
1723 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001724 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001725
1726protected:
1727 RendererKind Kind;
1728
1729public:
1730 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1731 virtual ~OperandRenderer() {}
1732
1733 RendererKind getKind() const { return Kind; }
1734
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001735 virtual void emitRenderOpcodes(MatchTable &Table,
1736 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001737};
1738
1739/// A CopyRenderer emits code to copy a single operand from an existing
1740/// instruction to the one being built.
1741class CopyRenderer : public OperandRenderer {
1742protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001743 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001744 /// The name of the operand.
1745 const StringRef SymbolicName;
1746
1747public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001748 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
1749 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00001750 SymbolicName(SymbolicName) {
1751 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1752 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001753
1754 static bool classof(const OperandRenderer *R) {
1755 return R->getKind() == OR_Copy;
1756 }
1757
1758 const StringRef getSymbolicName() const { return SymbolicName; }
1759
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001760 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001761 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001762 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001763 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1764 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1765 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1766 << MatchTable::IntValue(Operand.getOperandIndex())
1767 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001768 }
1769};
1770
Daniel Sandersd66e0902017-10-23 18:19:24 +00001771/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1772/// existing instruction to the one being built. If the operand turns out to be
1773/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1774class CopyOrAddZeroRegRenderer : public OperandRenderer {
1775protected:
1776 unsigned NewInsnID;
1777 /// The name of the operand.
1778 const StringRef SymbolicName;
1779 const Record *ZeroRegisterDef;
1780
1781public:
1782 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001783 StringRef SymbolicName, Record *ZeroRegisterDef)
1784 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1785 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1786 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1787 }
1788
1789 static bool classof(const OperandRenderer *R) {
1790 return R->getKind() == OR_CopyOrAddZeroReg;
1791 }
1792
1793 const StringRef getSymbolicName() const { return SymbolicName; }
1794
1795 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1796 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1797 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1798 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1799 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1800 << MatchTable::Comment("OldInsnID")
1801 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1802 << MatchTable::IntValue(Operand.getOperandIndex())
1803 << MatchTable::NamedValue(
1804 (ZeroRegisterDef->getValue("Namespace")
1805 ? ZeroRegisterDef->getValueAsString("Namespace")
1806 : ""),
1807 ZeroRegisterDef->getName())
1808 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1809 }
1810};
1811
Daniel Sanders05540042017-08-08 10:44:31 +00001812/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1813/// an extended immediate operand.
1814class CopyConstantAsImmRenderer : public OperandRenderer {
1815protected:
1816 unsigned NewInsnID;
1817 /// The name of the operand.
1818 const std::string SymbolicName;
1819 bool Signed;
1820
1821public:
1822 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1823 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1824 SymbolicName(SymbolicName), Signed(true) {}
1825
1826 static bool classof(const OperandRenderer *R) {
1827 return R->getKind() == OR_CopyConstantAsImm;
1828 }
1829
1830 const StringRef getSymbolicName() const { return SymbolicName; }
1831
1832 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1833 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1834 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1835 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1836 : "GIR_CopyConstantAsUImm")
1837 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1838 << MatchTable::Comment("OldInsnID")
1839 << MatchTable::IntValue(OldInsnVarID)
1840 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1841 }
1842};
1843
Daniel Sanders11300ce2017-10-13 21:28:03 +00001844/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1845/// instruction to an extended immediate operand.
1846class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1847protected:
1848 unsigned NewInsnID;
1849 /// The name of the operand.
1850 const std::string SymbolicName;
1851
1852public:
1853 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1854 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1855 SymbolicName(SymbolicName) {}
1856
1857 static bool classof(const OperandRenderer *R) {
1858 return R->getKind() == OR_CopyFConstantAsFPImm;
1859 }
1860
1861 const StringRef getSymbolicName() const { return SymbolicName; }
1862
1863 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1864 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1865 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1866 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1867 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1868 << MatchTable::Comment("OldInsnID")
1869 << MatchTable::IntValue(OldInsnVarID)
1870 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1871 }
1872};
1873
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001874/// A CopySubRegRenderer emits code to copy a single register operand from an
1875/// existing instruction to the one being built and indicate that only a
1876/// subregister should be copied.
1877class CopySubRegRenderer : public OperandRenderer {
1878protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001879 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001880 /// The name of the operand.
1881 const StringRef SymbolicName;
1882 /// The subregister to extract.
1883 const CodeGenSubRegIndex *SubReg;
1884
1885public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001886 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
1887 const CodeGenSubRegIndex *SubReg)
1888 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001889 SymbolicName(SymbolicName), SubReg(SubReg) {}
1890
1891 static bool classof(const OperandRenderer *R) {
1892 return R->getKind() == OR_CopySubReg;
1893 }
1894
1895 const StringRef getSymbolicName() const { return SymbolicName; }
1896
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001897 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001898 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001899 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001900 Table << MatchTable::Opcode("GIR_CopySubReg")
1901 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1902 << MatchTable::Comment("OldInsnID")
1903 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1904 << MatchTable::IntValue(Operand.getOperandIndex())
1905 << MatchTable::Comment("SubRegIdx")
1906 << MatchTable::IntValue(SubReg->EnumValue)
1907 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001908 }
1909};
1910
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001911/// Adds a specific physical register to the instruction being built.
1912/// This is typically useful for WZR/XZR on AArch64.
1913class AddRegisterRenderer : public OperandRenderer {
1914protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001915 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001916 const Record *RegisterDef;
1917
1918public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001919 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1920 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1921 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001922
1923 static bool classof(const OperandRenderer *R) {
1924 return R->getKind() == OR_Register;
1925 }
1926
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001927 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1928 Table << MatchTable::Opcode("GIR_AddRegister")
1929 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1930 << MatchTable::NamedValue(
1931 (RegisterDef->getValue("Namespace")
1932 ? RegisterDef->getValueAsString("Namespace")
1933 : ""),
1934 RegisterDef->getName())
1935 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001936 }
1937};
1938
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00001939/// Adds a specific temporary virtual register to the instruction being built.
1940/// This is used to chain instructions together when emitting multiple
1941/// instructions.
1942class TempRegRenderer : public OperandRenderer {
1943protected:
1944 unsigned InsnID;
1945 unsigned TempRegID;
1946 bool IsDef;
1947
1948public:
1949 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
1950 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
1951 IsDef(IsDef) {}
1952
1953 static bool classof(const OperandRenderer *R) {
1954 return R->getKind() == OR_TempRegister;
1955 }
1956
1957 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1958 Table << MatchTable::Opcode("GIR_AddTempRegister")
1959 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1960 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
1961 << MatchTable::Comment("TempRegFlags");
1962 if (IsDef)
1963 Table << MatchTable::NamedValue("RegState::Define");
1964 else
1965 Table << MatchTable::IntValue(0);
1966 Table << MatchTable::LineBreak;
1967 }
1968};
1969
Daniel Sanders0ed28822017-04-12 08:23:08 +00001970/// Adds a specific immediate to the instruction being built.
1971class ImmRenderer : public OperandRenderer {
1972protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001973 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001974 int64_t Imm;
1975
1976public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001977 ImmRenderer(unsigned InsnID, int64_t Imm)
1978 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001979
1980 static bool classof(const OperandRenderer *R) {
1981 return R->getKind() == OR_Imm;
1982 }
1983
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001984 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1985 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1986 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1987 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001988 }
1989};
1990
Daniel Sanders2deea182017-04-22 15:11:04 +00001991/// Adds operands by calling a renderer function supplied by the ComplexPattern
1992/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001993class RenderComplexPatternOperand : public OperandRenderer {
1994private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001995 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001996 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001997 /// The name of the operand.
1998 const StringRef SymbolicName;
1999 /// The renderer number. This must be unique within a rule since it's used to
2000 /// identify a temporary variable to hold the renderer function.
2001 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002002 /// When provided, this is the suboperand of the ComplexPattern operand to
2003 /// render. Otherwise all the suboperands will be rendered.
2004 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002005
2006 unsigned getNumOperands() const {
2007 return TheDef.getValueAsDag("Operands")->getNumArgs();
2008 }
2009
2010public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002011 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002012 StringRef SymbolicName, unsigned RendererID,
2013 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002014 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002015 SymbolicName(SymbolicName), RendererID(RendererID),
2016 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002017
2018 static bool classof(const OperandRenderer *R) {
2019 return R->getKind() == OR_ComplexPattern;
2020 }
2021
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002022 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002023 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2024 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002025 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2026 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002027 << MatchTable::IntValue(RendererID);
2028 if (SubOperand.hasValue())
2029 Table << MatchTable::Comment("SubOperand")
2030 << MatchTable::IntValue(SubOperand.getValue());
2031 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002032 }
2033};
2034
Volkan Kelesf7f25682018-01-16 18:44:05 +00002035class CustomRenderer : public OperandRenderer {
2036protected:
2037 unsigned InsnID;
2038 const Record &Renderer;
2039 /// The name of the operand.
2040 const std::string SymbolicName;
2041
2042public:
2043 CustomRenderer(unsigned InsnID, const Record &Renderer,
2044 StringRef SymbolicName)
2045 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2046 SymbolicName(SymbolicName) {}
2047
2048 static bool classof(const OperandRenderer *R) {
2049 return R->getKind() == OR_Custom;
2050 }
2051
2052 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2053 const InstructionMatcher &InsnMatcher =
2054 Rule.getInstructionMatcher(SymbolicName);
2055 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2056 Table << MatchTable::Opcode("GIR_CustomRenderer")
2057 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2058 << MatchTable::Comment("OldInsnID")
2059 << MatchTable::IntValue(OldInsnVarID)
2060 << MatchTable::Comment("Renderer")
2061 << MatchTable::NamedValue(
2062 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2063 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2064 }
2065};
2066
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002067/// An action taken when all Matcher predicates succeeded for a parent rule.
2068///
2069/// Typical actions include:
2070/// * Changing the opcode of an instruction.
2071/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002072class MatchAction {
2073public:
2074 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002075
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002076 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002077 virtual void emitActionOpcodes(MatchTable &Table,
2078 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002079};
2080
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002081/// Generates a comment describing the matched rule being acted upon.
2082class DebugCommentAction : public MatchAction {
2083private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002084 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002085
2086public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002087 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002088
Daniel Sandersa7b75262017-10-31 18:50:24 +00002089 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002090 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002091 }
2092};
2093
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002094/// Generates code to build an instruction or mutate an existing instruction
2095/// into the desired instruction when this is possible.
2096class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002097private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002098 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002099 const CodeGenInstruction *I;
Daniel Sanders64f745c2017-10-24 17:08:43 +00002100 const InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002101 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2102
2103 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002104 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2105 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002106 return false;
2107
Daniel Sandersa7b75262017-10-31 18:50:24 +00002108 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002109 return false;
2110
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002111 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002112 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002113 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002114 if (Insn != &OM.getInstructionMatcher() ||
Daniel Sanders3016d3c2017-04-22 14:31:28 +00002115 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002116 return false;
2117 } else
2118 return false;
2119 }
2120
2121 return true;
2122 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002123
Daniel Sanders43c882c2017-02-01 10:53:10 +00002124public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002125 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2126 : InsnID(InsnID), I(I), Matched(nullptr) {}
2127
Daniel Sanders08464522018-01-29 21:09:12 +00002128 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002129 const CodeGenInstruction *getCGI() const { return I; }
2130
Daniel Sandersa7b75262017-10-31 18:50:24 +00002131 void chooseInsnToMutate(RuleMatcher &Rule) {
2132 for (const auto *MutateCandidate : Rule.mutatable_insns()) {
2133 if (canMutate(Rule, MutateCandidate)) {
2134 // Take the first one we're offered that we're able to mutate.
2135 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2136 Matched = MutateCandidate;
2137 return;
2138 }
2139 }
2140 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002141
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002142 template <class Kind, class... Args>
2143 Kind &addRenderer(Args&&... args) {
2144 OperandRenderers.emplace_back(
Daniel Sanders198447a2017-11-01 00:29:47 +00002145 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002146 return *static_cast<Kind *>(OperandRenderers.back().get());
2147 }
2148
Daniel Sandersa7b75262017-10-31 18:50:24 +00002149 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2150 if (Matched) {
2151 assert(canMutate(Rule, Matched) &&
2152 "Arranged to mutate an insn that isn't mutatable");
2153
2154 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002155 Table << MatchTable::Opcode("GIR_MutateOpcode")
2156 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2157 << MatchTable::Comment("RecycleInsnID")
2158 << MatchTable::IntValue(RecycleInsnID)
2159 << MatchTable::Comment("Opcode")
2160 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2161 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002162
2163 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002164 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002165 auto Namespace = Def->getValue("Namespace")
2166 ? Def->getValueAsString("Namespace")
2167 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002168 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2169 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2170 << MatchTable::NamedValue(Namespace, Def->getName())
2171 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002172 }
2173 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002174 auto Namespace = Use->getValue("Namespace")
2175 ? Use->getValueAsString("Namespace")
2176 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002177 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2178 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2179 << MatchTable::NamedValue(Namespace, Use->getName())
2180 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002181 }
2182 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002183 return;
2184 }
2185
2186 // TODO: Simple permutation looks like it could be almost as common as
2187 // mutation due to commutative operations.
2188
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002189 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2190 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2191 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2192 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002193 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002194 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002195
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002196 if (I->mayLoad || I->mayStore) {
2197 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2198 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2199 << MatchTable::Comment("MergeInsnID's");
2200 // Emit the ID's for all the instructions that are matched by this rule.
2201 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2202 // some other means of having a memoperand. Also limit this to
2203 // emitted instructions that expect to have a memoperand too. For
2204 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2205 // sign-extend instructions shouldn't put the memoperand on the
2206 // sign-extend since it has no effect there.
2207 std::vector<unsigned> MergeInsnIDs;
2208 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2209 MergeInsnIDs.push_back(IDMatcherPair.second);
2210 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
2211 for (const auto &MergeInsnID : MergeInsnIDs)
2212 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002213 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2214 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002215 }
2216
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002217 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2218 // better for combines. Particularly when there are multiple match
2219 // roots.
2220 if (InsnID == 0)
2221 Table << MatchTable::Opcode("GIR_EraseFromParent")
2222 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2223 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002224 }
2225};
2226
2227/// Generates code to constrain the operands of an output instruction to the
2228/// register classes specified by the definition of that instruction.
2229class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002230 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002231
2232public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002233 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002234
Daniel Sandersa7b75262017-10-31 18:50:24 +00002235 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002236 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2237 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2238 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002239 }
2240};
2241
2242/// Generates code to constrain the specified operand of an output instruction
2243/// to the specified register class.
2244class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002245 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002246 unsigned OpIdx;
2247 const CodeGenRegisterClass &RC;
2248
2249public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002250 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002251 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002252 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002253
Daniel Sandersa7b75262017-10-31 18:50:24 +00002254 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002255 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2256 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2257 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2258 << MatchTable::Comment("RC " + RC.getName())
2259 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002260 }
2261};
2262
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002263/// Generates code to create a temporary register which can be used to chain
2264/// instructions together.
2265class MakeTempRegisterAction : public MatchAction {
2266private:
2267 LLTCodeGen Ty;
2268 unsigned TempRegID;
2269
2270public:
2271 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2272 : Ty(Ty), TempRegID(TempRegID) {}
2273
2274 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2275 Table << MatchTable::Opcode("GIR_MakeTempReg")
2276 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2277 << MatchTable::Comment("TypeID")
2278 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2279 << MatchTable::LineBreak;
2280 }
2281};
2282
Daniel Sanders05540042017-08-08 10:44:31 +00002283InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002284 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002285 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002286 return *Matchers.back();
2287}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002288
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002289void RuleMatcher::addRequiredFeature(Record *Feature) {
2290 RequiredFeatures.push_back(Feature);
2291}
2292
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002293const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2294 return RequiredFeatures;
2295}
2296
Daniel Sanders7438b262017-10-31 23:03:18 +00002297// Emplaces an action of the specified Kind at the end of the action list.
2298//
2299// Returns a reference to the newly created action.
2300//
2301// Like std::vector::emplace_back(), may invalidate all iterators if the new
2302// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2303// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002304template <class Kind, class... Args>
2305Kind &RuleMatcher::addAction(Args &&... args) {
2306 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2307 return *static_cast<Kind *>(Actions.back().get());
2308}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002309
Daniel Sanders7438b262017-10-31 23:03:18 +00002310// Emplaces an action of the specified Kind before the given insertion point.
2311//
2312// Returns an iterator pointing at the newly created instruction.
2313//
2314// Like std::vector::insert(), may invalidate all iterators if the new size
2315// exceeds the capacity. Otherwise, only invalidates the iterators from the
2316// insertion point onwards.
2317template <class Kind, class... Args>
2318action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2319 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002320 return Actions.emplace(InsertPt,
2321 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002322}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002323
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002324unsigned
2325RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
2326 unsigned NewInsnVarID = NextInsnVarID++;
2327 InsnVariableIDs[&Matcher] = NewInsnVarID;
2328 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002329}
2330
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002331unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002332 const InstructionMatcher &Matcher,
2333 unsigned InsnID, unsigned OpIdx) {
2334 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002335 Table << MatchTable::Opcode("GIM_RecordInsn")
2336 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
2337 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
2338 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2339 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2340 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002341 return NewInsnVarID;
2342}
2343
2344unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
2345 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2346 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002347 return I->second;
2348 llvm_unreachable("Matched Insn was not captured in a local variable");
2349}
2350
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002351void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2352 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2353 DefinedOperands[SymbolicName] = &OM;
2354 return;
2355 }
2356
2357 // If the operand is already defined, then we must ensure both references in
2358 // the matcher have the exact same node.
2359 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2360}
2361
Daniel Sanders05540042017-08-08 10:44:31 +00002362const InstructionMatcher &
2363RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2364 for (const auto &I : InsnVariableIDs)
2365 if (I.first->getSymbolicName() == SymbolicName)
2366 return *I.first;
2367 llvm_unreachable(
2368 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2369}
2370
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002371const OperandMatcher &
2372RuleMatcher::getOperandMatcher(StringRef Name) const {
2373 const auto &I = DefinedOperands.find(Name);
2374
2375 if (I == DefinedOperands.end())
2376 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2377
2378 return *I->second;
2379}
2380
Daniel Sanders9d662d22017-07-06 10:06:12 +00002381/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002382/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002383void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002384 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002385 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Quentin Colombeta646ef02017-12-15 23:24:36 +00002386 (void)InsnVarID;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002387 assert(Matchers.front()->getVarID() == InsnVarID &&
2388 "IDs differ between build and emit");
2389 Matchers.front()->emitCaptureOpcodes(Table, *this);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002390}
2391
Daniel Sanders8e82af22017-07-27 11:03:45 +00002392void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002393 if (Matchers.empty())
2394 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002395
Quentin Colombet63a328c2017-12-19 02:57:23 +00002396 // Reset the ID generation so that the emitted IDs match the ones
2397 // we set while building the InstructionMatcher and such.
2398 clearImplicitMap();
2399
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002400 // The representation supports rules that require multiple roots such as:
2401 // %ptr(p0) = ...
2402 // %elt0(s32) = G_LOAD %ptr
2403 // %1(p0) = G_ADD %ptr, 4
2404 // %elt1(s32) = G_LOAD p0 %1
2405 // which could be usefully folded into:
2406 // %ptr(p0) = ...
2407 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2408 // on some targets but we don't need to make use of that yet.
2409 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002410
Daniel Sanders8e82af22017-07-27 11:03:45 +00002411 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002412 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00002413 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002414 << MatchTable::LineBreak;
2415
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002416 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002417 Table << MatchTable::Opcode("GIM_CheckFeatures")
2418 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2419 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002420 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002421
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002422 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002423
Quentin Colombetaad20be2017-12-15 23:07:42 +00002424 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002425
Daniel Sandersbee57392017-04-04 13:25:23 +00002426 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002427 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002428 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002429 SmallVector<unsigned, 2> InsnIDs;
2430 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002431 // Skip the root node since it isn't moving anywhere. Everything else is
2432 // sinking to meet it.
2433 if (Pair.first == Matchers.front().get())
2434 continue;
2435
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002436 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002437 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002438 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002439
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002440 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002441 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002442 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2443 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2444 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002445
2446 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2447 // account for unsafe cases.
2448 //
2449 // Example:
2450 // MI1--> %0 = ...
2451 // %1 = ... %0
2452 // MI0--> %2 = ... %0
2453 // It's not safe to erase MI1. We currently handle this by not
2454 // erasing %0 (even when it's dead).
2455 //
2456 // Example:
2457 // MI1--> %0 = load volatile @a
2458 // %1 = load volatile @a
2459 // MI0--> %2 = ... %0
2460 // It's not safe to sink %0's def past %1. We currently handle
2461 // this by rejecting all loads.
2462 //
2463 // Example:
2464 // MI1--> %0 = load @a
2465 // %1 = store @a
2466 // MI0--> %2 = ... %0
2467 // It's not safe to sink %0's def past %1. We currently handle
2468 // this by rejecting all loads.
2469 //
2470 // Example:
2471 // G_CONDBR %cond, @BB1
2472 // BB0:
2473 // MI1--> %0 = load @a
2474 // G_BR @BB1
2475 // BB1:
2476 // MI0--> %2 = ... %0
2477 // It's not always safe to sink %0 across control flow. In this
2478 // case it may introduce a memory fault. We currentl handle this
2479 // by rejecting all loads.
2480 }
2481 }
2482
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002483 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002484 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002485
2486 if (GenerateCoverage)
2487 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2488 << MatchTable::LineBreak;
2489
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002490 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002491 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002492 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002493}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002494
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002495bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2496 // Rules involving more match roots have higher priority.
2497 if (Matchers.size() > B.Matchers.size())
2498 return true;
2499 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002500 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002501
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002502 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2503 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2504 return true;
2505 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2506 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002507 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002508
2509 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002510}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002511
Daniel Sanders2deea182017-04-22 15:11:04 +00002512unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002513 return std::accumulate(
2514 Matchers.begin(), Matchers.end(), 0,
2515 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002516 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002517 });
2518}
2519
Daniel Sanders05540042017-08-08 10:44:31 +00002520bool OperandPredicateMatcher::isHigherPriorityThan(
2521 const OperandPredicateMatcher &B) const {
2522 // Generally speaking, an instruction is more important than an Int or a
2523 // LiteralInt because it can cover more nodes but theres an exception to
2524 // this. G_CONSTANT's are less important than either of those two because they
2525 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002526
2527 const InstructionOperandMatcher *AOM =
2528 dyn_cast<InstructionOperandMatcher>(this);
2529 const InstructionOperandMatcher *BOM =
2530 dyn_cast<InstructionOperandMatcher>(&B);
2531 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2532 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2533
2534 if (AOM && BOM) {
2535 // The relative priorities between a G_CONSTANT and any other instruction
2536 // don't actually matter but this code is needed to ensure a strict weak
2537 // ordering. This is particularly important on Windows where the rules will
2538 // be incorrectly sorted without it.
2539 if (AIsConstantInsn != BIsConstantInsn)
2540 return AIsConstantInsn < BIsConstantInsn;
2541 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002542 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002543
2544 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2545 return false;
2546 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2547 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002548
2549 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002550}
Daniel Sanders05540042017-08-08 10:44:31 +00002551
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002552void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00002553 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002554 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002555 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Quentin Colombetaad20be2017-12-15 23:07:42 +00002556 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002557
2558 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2559 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2560 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2561 << MatchTable::Comment("OtherMI")
2562 << MatchTable::IntValue(OtherInsnVarID)
2563 << MatchTable::Comment("OtherOpIdx")
2564 << MatchTable::IntValue(OtherOM.getOperandIndex())
2565 << MatchTable::LineBreak;
2566}
2567
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002568//===- GlobalISelEmitter class --------------------------------------------===//
2569
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002570class GlobalISelEmitter {
2571public:
2572 explicit GlobalISelEmitter(RecordKeeper &RK);
2573 void run(raw_ostream &OS);
2574
2575private:
2576 const RecordKeeper &RK;
2577 const CodeGenDAGPatterns CGP;
2578 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002579 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002580
Daniel Sanders39690bd2017-10-15 02:41:12 +00002581 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002582 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2583 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002584 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002585 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002586
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002587 /// Keep track of the equivalence between ComplexPattern's and
2588 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2589 /// GIComplexPatternEquiv.
2590 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2591
Volkan Kelesf7f25682018-01-16 18:44:05 +00002592 /// Keep track of the equivalence between SDNodeXForm's and
2593 /// GICustomOperandRenderer. Map entries are specified by subclassing
2594 /// GISDNodeXFormEquiv.
2595 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
2596
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00002597 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
2598 /// This adds compatibility for RuleMatchers to use this for ordering rules.
2599 DenseMap<uint64_t, int> RuleMatcherScores;
2600
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002601 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002602 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002603
Daniel Sandersf76f3152017-11-16 00:46:35 +00002604 // Rule coverage information.
2605 Optional<CodeGenCoverage> RuleCoverage;
2606
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002607 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002608 Record *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002609
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002610 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002611 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2612 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2613 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2614 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2615 unsigned &TempOpIdx) const;
2616 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002617 const TreePatternNode *SrcChild,
2618 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002619 unsigned &TempOpIdx) const;
Daniel Sandersdf258e32017-10-31 19:09:29 +00002620
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002621 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00002622 createAndImportInstructionRenderer(RuleMatcher &M,
2623 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002624 Expected<action_iterator> createAndImportSubInstructionRenderer(
2625 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
2626 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00002627 Expected<action_iterator>
2628 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
2629 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00002630 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00002631 Expected<action_iterator>
2632 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
2633 BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00002634 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00002635 Expected<action_iterator>
2636 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
2637 BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002638 TreePatternNode *DstChild);
Diana Picus382602f2017-05-17 08:57:28 +00002639 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2640 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002641 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002642 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2643 const std::vector<Record *> &ImplicitDefs) const;
2644
Daniel Sanders11300ce2017-10-13 21:28:03 +00002645 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2646 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002647 std::function<bool(const Record *R)> Filter);
2648
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002649 /// Analyze pattern \p P, returning a matcher for it if possible.
2650 /// Otherwise, return an Error explaining why we don't support it.
2651 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002652
2653 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00002654
2655 TreePatternNode *fixupPatternNode(TreePatternNode *N);
2656 void fixupPatternTrees(TreePattern *P);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002657
2658 /// Takes a sequence of \p Rules and group them based on the predicates
2659 /// they share. \p StorageGroupMatcher is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00002660 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002661 /// The optimization process does not change the relative order of
2662 /// the rules. In particular, we don't try to share predicates if
2663 /// that means reordering the rules (e.g., we won't group R1 and R3
2664 /// in the following example as it would imply reordering R2 and R3
2665 /// => R1 p1, R2 p2, R3 p1).
2666 ///
2667 /// What this optimization does looks like:
2668 /// Output without optimization:
2669 /// \verbatim
2670 /// # R1
2671 /// # predicate A
2672 /// # predicate B
2673 /// ...
2674 /// # R2
2675 /// # predicate A // <-- effectively this is going to be checked twice.
2676 /// // Once in R1 and once in R2.
2677 /// # predicate C
2678 /// \endverbatim
2679 /// Output with optimization:
2680 /// \verbatim
2681 /// # Group1_2
2682 /// # predicate A // <-- Check is now shared.
2683 /// # R1
2684 /// # predicate B
2685 /// # R2
2686 /// # predicate C
2687 /// \endverbatim
2688 std::vector<Matcher *> optimizeRules(
Quentin Colombet34688b92017-12-18 21:25:53 +00002689 const std::vector<Matcher *> &Rules,
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002690 std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002691};
2692
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002693void GlobalISelEmitter::gatherNodeEquivs() {
2694 assert(NodeEquivs.empty());
2695 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002696 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002697
2698 assert(ComplexPatternEquivs.empty());
2699 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2700 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2701 if (!SelDAGEquiv)
2702 continue;
2703 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2704 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00002705
2706 assert(SDNodeXFormEquivs.empty());
2707 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
2708 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2709 if (!SelDAGEquiv)
2710 continue;
2711 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
2712 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002713}
2714
Daniel Sanders39690bd2017-10-15 02:41:12 +00002715Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002716 return NodeEquivs.lookup(N);
2717}
2718
2719GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sanders7e523672017-11-11 03:23:44 +00002720 : RK(RK), CGP(RK, [&](TreePattern *P) { fixupPatternTrees(P); }),
2721 Target(CGP.getTargetInfo()), CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002722
2723//===- Emitter ------------------------------------------------------------===//
2724
Daniel Sandersc270c502017-03-30 09:36:33 +00002725Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002726GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002727 ArrayRef<Predicate> Predicates) {
2728 for (const Predicate &P : Predicates) {
2729 if (!P.Def)
2730 continue;
2731 declareSubtargetFeature(P.Def);
2732 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002733 }
2734
Daniel Sandersc270c502017-03-30 09:36:33 +00002735 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002736}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002737
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002738Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2739 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2740 const TreePatternNode *Src, unsigned &TempOpIdx) const {
2741 Record *SrcGIEquivOrNull = nullptr;
2742 const CodeGenInstruction *SrcGIOrNull = nullptr;
2743
2744 // Start with the defined operands (i.e., the results of the root operator).
2745 if (Src->getExtTypes().size() > 1)
2746 return failedImport("Src pattern has multiple results");
2747
2748 if (Src->isLeaf()) {
2749 Init *SrcInit = Src->getLeafValue();
2750 if (isa<IntInit>(SrcInit)) {
2751 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2752 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2753 } else
2754 return failedImport(
2755 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2756 } else {
2757 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2758 if (!SrcGIEquivOrNull)
2759 return failedImport("Pattern operator lacks an equivalent Instruction" +
2760 explainOperator(Src->getOperator()));
2761 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
2762
2763 // The operators look good: match the opcode
2764 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
2765 }
2766
2767 unsigned OpIdx = 0;
2768 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2769 // Results don't have a name unless they are the root node. The caller will
2770 // set the name if appropriate.
2771 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2772 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2773 return failedImport(toString(std::move(Error)) +
2774 " for result of Src pattern operator");
2775 }
2776
Daniel Sanders2c269f62017-08-24 09:11:20 +00002777 for (const auto &Predicate : Src->getPredicateFns()) {
2778 if (Predicate.isAlwaysTrue())
2779 continue;
2780
2781 if (Predicate.isImmediatePattern()) {
2782 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2783 continue;
2784 }
2785
Daniel Sandersa71f4542017-10-16 00:56:30 +00002786 // No check required. G_LOAD by itself is a non-extending load.
2787 if (Predicate.isNonExtLoad())
2788 continue;
2789
Daniel Sandersd66e0902017-10-23 18:19:24 +00002790 // No check required. G_STORE by itself is a non-extending store.
2791 if (Predicate.isNonTruncStore())
2792 continue;
2793
Daniel Sanders76664652017-11-28 22:07:05 +00002794 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
2795 if (Predicate.getMemoryVT() != nullptr) {
2796 Optional<LLTCodeGen> MemTyOrNone =
2797 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00002798
Daniel Sanders76664652017-11-28 22:07:05 +00002799 if (!MemTyOrNone)
2800 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00002801
Quentin Colombetaad20be2017-12-15 23:07:42 +00002802 OperandMatcher &OM = InsnMatcher.getOperand(0);
2803 OM.addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
Daniel Sanders76664652017-11-28 22:07:05 +00002804 continue;
2805 }
2806 }
2807
2808 if (Predicate.isLoad() || Predicate.isStore()) {
2809 // No check required. A G_LOAD/G_STORE is an unindexed load.
2810 if (Predicate.isUnindexed())
2811 continue;
2812 }
2813
2814 if (Predicate.isAtomic()) {
2815 if (Predicate.isAtomicOrderingMonotonic()) {
2816 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2817 "Monotonic");
2818 continue;
2819 }
2820 if (Predicate.isAtomicOrderingAcquire()) {
2821 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
2822 continue;
2823 }
2824 if (Predicate.isAtomicOrderingRelease()) {
2825 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
2826 continue;
2827 }
2828 if (Predicate.isAtomicOrderingAcquireRelease()) {
2829 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2830 "AcquireRelease");
2831 continue;
2832 }
2833 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
2834 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2835 "SequentiallyConsistent");
2836 continue;
2837 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00002838
2839 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
2840 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2841 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2842 continue;
2843 }
2844 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
2845 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2846 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2847 continue;
2848 }
2849
2850 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
2851 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2852 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2853 continue;
2854 }
2855 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
2856 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2857 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2858 continue;
2859 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00002860 }
2861
Daniel Sanders2c269f62017-08-24 09:11:20 +00002862 return failedImport("Src pattern child has predicate (" +
2863 explainPredicates(Src) + ")");
2864 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002865 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2866 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00002867
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002868 if (Src->isLeaf()) {
2869 Init *SrcInit = Src->getLeafValue();
2870 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002871 OperandMatcher &OM =
2872 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002873 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2874 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002875 return failedImport(
2876 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002877 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002878 assert(SrcGIOrNull &&
2879 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00002880 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2881 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2882 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00002883 // here since we don't support ImmLeaf predicates yet. However, we still
2884 // need to note the hidden operand to get GIM_CheckNumOperands correct.
2885 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2886 return InsnMatcher;
2887 }
2888
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002889 // Match the used operands (i.e. the children of the operator).
2890 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002891 TreePatternNode *SrcChild = Src->getChild(i);
2892
Daniel Sandersa71f4542017-10-16 00:56:30 +00002893 // SelectionDAG allows pointers to be represented with iN since it doesn't
2894 // distinguish between pointers and integers but they are different types in GlobalISel.
2895 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00002896 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002897
Daniel Sanders28887fe2017-09-19 12:56:36 +00002898 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2899 // following the defs is an intrinsic ID.
2900 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2901 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2902 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002903 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002904 OperandMatcher &OM =
2905 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002906 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00002907 continue;
2908 }
2909
2910 return failedImport("Expected IntInit containing instrinsic ID)");
2911 }
2912
Daniel Sandersa71f4542017-10-16 00:56:30 +00002913 if (auto Error =
2914 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2915 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002916 return std::move(Error);
2917 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002918 }
2919
2920 return InsnMatcher;
2921}
2922
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002923Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2924 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2925 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2926 if (ComplexPattern == ComplexPatternEquivs.end())
2927 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2928 ") not mapped to GlobalISel");
2929
2930 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2931 TempOpIdx++;
2932 return Error::success();
2933}
2934
2935Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2936 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002937 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002938 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00002939 unsigned OpIdx,
2940 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002941 OperandMatcher &OM =
2942 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002943 if (OM.isSameAsAnotherOperand())
2944 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002945
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002946 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002947 if (ChildTypes.size() != 1)
2948 return failedImport("Src pattern child has multiple results");
2949
2950 // Check MBB's before the type check since they are not a known type.
2951 if (!SrcChild->isLeaf()) {
2952 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2953 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2954 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2955 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00002956 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002957 }
2958 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002959 }
2960
Daniel Sandersa71f4542017-10-16 00:56:30 +00002961 if (auto Error =
2962 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2963 return failedImport(toString(std::move(Error)) + " for Src operand (" +
2964 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002965
Daniel Sandersbee57392017-04-04 13:25:23 +00002966 // Check for nested instructions.
2967 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002968 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2969 // When a ComplexPattern is used as an operator, it should do the same
2970 // thing as when used as a leaf. However, the children of the operator
2971 // name the sub-operands that make up the complex operand and we must
2972 // prepare to reference them in the renderer too.
2973 unsigned RendererID = TempOpIdx;
2974 if (auto Error = importComplexPatternOperandMatcher(
2975 OM, SrcChild->getOperator(), TempOpIdx))
2976 return Error;
2977
2978 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2979 auto *SubOperand = SrcChild->getChild(i);
2980 if (!SubOperand->getName().empty())
2981 Rule.defineComplexSubOperand(SubOperand->getName(),
2982 SrcChild->getOperator(), RendererID, i);
2983 }
2984
2985 return Error::success();
2986 }
2987
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002988 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2989 InsnMatcher.getRuleMatcher(), SrcChild->getName());
2990 if (!MaybeInsnOperand.hasValue()) {
2991 // This isn't strictly true. If the user were to provide exactly the same
2992 // matchers as the original operand then we could allow it. However, it's
2993 // simpler to not permit the redundant specification.
2994 return failedImport("Nested instruction cannot be the same as another operand");
2995 }
2996
Daniel Sandersbee57392017-04-04 13:25:23 +00002997 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002998 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00002999 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003000 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003001 if (auto Error = InsnMatcherOrError.takeError())
3002 return Error;
3003
3004 return Error::success();
3005 }
3006
Diana Picusd1b61812017-11-03 10:30:19 +00003007 if (SrcChild->hasAnyPredicate())
3008 return failedImport("Src pattern child has unsupported predicate");
3009
Daniel Sandersffc7d582017-03-29 15:37:18 +00003010 // Check for constant immediates.
3011 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003012 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003013 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003014 }
3015
3016 // Check for def's like register classes or ComplexPattern's.
3017 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3018 auto *ChildRec = ChildDefInit->getDef();
3019
3020 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003021 if (ChildRec->isSubClassOf("RegisterClass") ||
3022 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003023 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003024 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003025 return Error::success();
3026 }
3027
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003028 // Check for ValueType.
3029 if (ChildRec->isSubClassOf("ValueType")) {
3030 // We already added a type check as standard practice so this doesn't need
3031 // to do anything.
3032 return Error::success();
3033 }
3034
Daniel Sandersffc7d582017-03-29 15:37:18 +00003035 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003036 if (ChildRec->isSubClassOf("ComplexPattern"))
3037 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003038
Daniel Sandersd0656a32017-04-13 09:45:37 +00003039 if (ChildRec->isSubClassOf("ImmLeaf")) {
3040 return failedImport(
3041 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3042 }
3043
Daniel Sandersffc7d582017-03-29 15:37:18 +00003044 return failedImport(
3045 "Src pattern child def is an unsupported tablegen class");
3046 }
3047
3048 return failedImport("Src pattern child is an unsupported kind");
3049}
3050
Daniel Sanders7438b262017-10-31 23:03:18 +00003051Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3052 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003053 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003054
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003055 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
3056 if (SubOperand.hasValue()) {
3057 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003058 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003059 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003060 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003061 }
3062
Daniel Sandersffc7d582017-03-29 15:37:18 +00003063 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003064
3065 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3066 auto Child = DstChild->getChild(0);
3067 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
3068 if (I != SDNodeXFormEquivs.end()) {
3069 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
3070 return InsertPt;
3071 }
3072 return failedImport("SDNodeXForm " + Child->getName() +
3073 " has no custom renderer");
3074 }
3075
Daniel Sanders05540042017-08-08 10:44:31 +00003076 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3077 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003078 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3079 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
3080 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003081 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003082 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003083 }
3084 }
Daniel Sanders05540042017-08-08 10:44:31 +00003085
3086 // Similarly, imm is an operator in TreePatternNode's view but must be
3087 // rendered as operands.
3088 // FIXME: The target should be able to choose sign-extended when appropriate
3089 // (e.g. on Mips).
3090 if (DstChild->getOperator()->getName() == "imm") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003091 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003092 return InsertPt;
Daniel Sanders11300ce2017-10-13 21:28:03 +00003093 } else if (DstChild->getOperator()->getName() == "fpimm") {
3094 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003095 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003096 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003097 }
3098
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003099 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3100 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3101 if (ChildTypes.size() != 1)
3102 return failedImport("Dst pattern child has multiple results");
3103
3104 Optional<LLTCodeGen> OpTyOrNone = None;
3105 if (ChildTypes.front().isMachineValueType())
3106 OpTyOrNone =
3107 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3108 if (!OpTyOrNone)
3109 return failedImport("Dst operand has an unsupported type");
3110
3111 unsigned TempRegID = Rule.allocateTempRegID();
3112 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3113 InsertPt, OpTyOrNone.getValue(), TempRegID);
3114 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3115
3116 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3117 ++InsertPt, Rule, DstChild, TempRegID);
3118 if (auto Error = InsertPtOrError.takeError())
3119 return std::move(Error);
3120 return InsertPtOrError.get();
3121 }
3122
Daniel Sanders2c269f62017-08-24 09:11:20 +00003123 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003124 }
3125
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003126 // It could be a specific immediate in which case we should just check for
3127 // that immediate.
3128 if (const IntInit *ChildIntInit =
3129 dyn_cast<IntInit>(DstChild->getLeafValue())) {
3130 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3131 return InsertPt;
3132 }
3133
Daniel Sandersffc7d582017-03-29 15:37:18 +00003134 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003135 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
3136 auto *ChildRec = ChildDefInit->getDef();
3137
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003138 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003139 if (ChildTypes.size() != 1)
3140 return failedImport("Dst pattern child has multiple results");
3141
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003142 Optional<LLTCodeGen> OpTyOrNone = None;
3143 if (ChildTypes.front().isMachineValueType())
3144 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003145 if (!OpTyOrNone)
3146 return failedImport("Dst operand has an unsupported type");
3147
3148 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003149 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003150 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003151 }
3152
Daniel Sanders658541f2017-04-22 15:53:21 +00003153 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003154 ChildRec->isSubClassOf("RegisterOperand") ||
3155 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003156 if (ChildRec->isSubClassOf("RegisterOperand") &&
3157 !ChildRec->isValueUnset("GIZeroRegister")) {
3158 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003159 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003160 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003161 }
3162
Daniel Sanders198447a2017-11-01 00:29:47 +00003163 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003164 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003165 }
3166
3167 if (ChildRec->isSubClassOf("ComplexPattern")) {
3168 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3169 if (ComplexPattern == ComplexPatternEquivs.end())
3170 return failedImport(
3171 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3172
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003173 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003174 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003175 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003176 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003177 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003178 }
3179
3180 return failedImport(
3181 "Dst pattern child def is an unsupported tablegen class");
3182 }
3183
3184 return failedImport("Dst pattern child is an unsupported kind");
3185}
3186
Daniel Sandersc270c502017-03-30 09:36:33 +00003187Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersa7b75262017-10-31 18:50:24 +00003188 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003189 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3190 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003191 return std::move(Error);
3192
Daniel Sanders7438b262017-10-31 23:03:18 +00003193 action_iterator InsertPt = InsertPtOrError.get();
3194 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003195
3196 importExplicitDefRenderers(DstMIBuilder);
3197
Daniel Sanders7438b262017-10-31 23:03:18 +00003198 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3199 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003200 return std::move(Error);
3201
3202 return DstMIBuilder;
3203}
3204
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003205Expected<action_iterator>
3206GlobalISelEmitter::createAndImportSubInstructionRenderer(
Daniel Sanders08464522018-01-29 21:09:12 +00003207 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003208 unsigned TempRegID) {
3209 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3210
3211 // TODO: Assert there's exactly one result.
3212
3213 if (auto Error = InsertPtOrError.takeError())
3214 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003215
3216 BuildMIAction &DstMIBuilder =
3217 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3218
3219 // Assign the result to TempReg.
3220 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3221
Daniel Sanders08464522018-01-29 21:09:12 +00003222 InsertPtOrError =
3223 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003224 if (auto Error = InsertPtOrError.takeError())
3225 return std::move(Error);
3226
Daniel Sanders08464522018-01-29 21:09:12 +00003227 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3228 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003229 return InsertPtOrError.get();
3230}
3231
Daniel Sanders7438b262017-10-31 23:03:18 +00003232Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
3233 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003234 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003235 if (!DstOp->isSubClassOf("Instruction")) {
3236 if (DstOp->isSubClassOf("ValueType"))
3237 return failedImport(
3238 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003239 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003240 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003241 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003242
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003243 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003244 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003245 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003246 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003247 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003248 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003249 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3250 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003251
Daniel Sanders198447a2017-11-01 00:29:47 +00003252 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3253 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003254}
3255
3256void GlobalISelEmitter::importExplicitDefRenderers(
3257 BuildMIAction &DstMIBuilder) {
3258 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003259 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3260 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003261 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003262 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003263}
3264
Daniel Sanders7438b262017-10-31 23:03:18 +00003265Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3266 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00003267 const llvm::TreePatternNode *Dst) {
3268 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3269 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003270
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003271 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003272 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003273 if (!Dst->getChild(0)->isLeaf())
3274 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3275
Daniel Sanders32291982017-06-28 13:50:04 +00003276 if (DefInit *SubRegInit =
3277 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003278 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3279 if (!RCDef)
3280 return failedImport("EXTRACT_SUBREG child #0 could not "
3281 "be coerced to a register class");
3282
3283 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003284 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3285
3286 const auto &SrcRCDstRCPair =
3287 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3288 if (SrcRCDstRCPair.hasValue()) {
3289 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3290 if (SrcRCDstRCPair->first != RC)
3291 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3292 }
3293
Daniel Sanders198447a2017-11-01 00:29:47 +00003294 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
3295 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003296 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003297 }
3298
3299 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3300 }
3301
Daniel Sandersffc7d582017-03-29 15:37:18 +00003302 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003303 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
3304 unsigned ExpectedDstINumUses = Dst->getNumChildren();
3305 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3306 DstINumUses--; // Ignore the class constraint.
3307 ExpectedDstINumUses--;
3308 }
3309
Daniel Sanders0ed28822017-04-12 08:23:08 +00003310 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003311 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003312 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003313 const CGIOperandList::OperandInfo &DstIOperand =
3314 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003315
Diana Picus382602f2017-05-17 08:57:28 +00003316 // If the operand has default values, introduce them now.
3317 // FIXME: Until we have a decent test case that dictates we should do
3318 // otherwise, we're going to assume that operands with default values cannot
3319 // be specified in the patterns. Therefore, adding them will not cause us to
3320 // end up with too many rendered operands.
3321 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003322 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00003323 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3324 return std::move(Error);
3325 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003326 continue;
3327 }
3328
Daniel Sanders7438b262017-10-31 23:03:18 +00003329 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
3330 Dst->getChild(Child));
3331 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003332 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003333 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003334 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003335 }
3336
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003337 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003338 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003339 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003340 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003341 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003342 " default ones");
3343
Daniel Sanders7438b262017-10-31 23:03:18 +00003344 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003345}
3346
Diana Picus382602f2017-05-17 08:57:28 +00003347Error GlobalISelEmitter::importDefaultOperandRenderers(
3348 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00003349 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00003350 // Look through ValueType operators.
3351 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3352 if (const DefInit *DefaultDagOperator =
3353 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3354 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3355 DefaultOp = DefaultDagOp->getArg(0);
3356 }
3357 }
3358
3359 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003360 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00003361 continue;
3362 }
3363
3364 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003365 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00003366 continue;
3367 }
3368
3369 return failedImport("Could not add default op");
3370 }
3371
3372 return Error::success();
3373}
3374
Daniel Sandersc270c502017-03-30 09:36:33 +00003375Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00003376 BuildMIAction &DstMIBuilder,
3377 const std::vector<Record *> &ImplicitDefs) const {
3378 if (!ImplicitDefs.empty())
3379 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00003380 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003381}
3382
3383Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003384 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003385 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003386 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003387 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00003388 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3389 " => " +
3390 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003391
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003392 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003393 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003394
3395 // Next, analyze the pattern operators.
3396 TreePatternNode *Src = P.getSrcPattern();
3397 TreePatternNode *Dst = P.getDstPattern();
3398
3399 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00003400 if (auto Err = isTrivialOperatorNode(Dst))
3401 return failedImport("Dst pattern root isn't a trivial operator (" +
3402 toString(std::move(Err)) + ")");
3403 if (auto Err = isTrivialOperatorNode(Src))
3404 return failedImport("Src pattern root isn't a trivial operator (" +
3405 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003406
Quentin Colombetaad20be2017-12-15 23:07:42 +00003407 // The different predicates and matchers created during
3408 // addInstructionMatcher use the RuleMatcher M to set up their
3409 // instruction ID (InsnVarID) that are going to be used when
3410 // M is going to be emitted.
3411 // However, the code doing the emission still relies on the IDs
3412 // returned during that process by the RuleMatcher when issuing
3413 // the recordInsn opcodes.
3414 // Because of that:
3415 // 1. The order in which we created the predicates
3416 // and such must be the same as the order in which we emit them,
3417 // and
3418 // 2. We need to reset the generation of the IDs in M somewhere between
3419 // addInstructionMatcher and emit
3420 //
3421 // FIXME: Long term, we don't want to have to rely on this implicit
3422 // naming being the same. One possible solution would be to have
3423 // explicit operator for operation capture and reference those.
3424 // The plus side is that it would expose opportunities to share
3425 // the capture accross rules. The downside is that it would
3426 // introduce a dependency between predicates (captures must happen
3427 // before their first use.)
Daniel Sandersedd07842017-08-17 09:26:14 +00003428 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
3429 unsigned TempOpIdx = 0;
3430 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003431 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00003432 if (auto Error = InsnMatcherOrError.takeError())
3433 return std::move(Error);
3434 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3435
3436 if (Dst->isLeaf()) {
3437 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
3438
3439 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3440 if (RCDef) {
3441 // We need to replace the def and all its uses with the specified
3442 // operand. However, we must also insert COPY's wherever needed.
3443 // For now, emit a copy and let the register allocator clean up.
3444 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3445 const auto &DstIOperand = DstI.Operands[0];
3446
3447 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3448 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003449 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00003450 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3451
Daniel Sanders198447a2017-11-01 00:29:47 +00003452 auto &DstMIBuilder =
3453 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3454 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3455 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003456 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3457
3458 // We're done with this pattern! It's eligible for GISel emission; return
3459 // it.
3460 ++NumPatternImported;
3461 return std::move(M);
3462 }
3463
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003464 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00003465 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003466
Daniel Sandersbee57392017-04-04 13:25:23 +00003467 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003468 Record *DstOp = Dst->getOperator();
3469 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003470 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003471
3472 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003473 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00003474 return failedImport("Src pattern results and dst MI defs are different (" +
3475 to_string(Src->getExtTypes().size()) + " def(s) vs " +
3476 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003477
Daniel Sandersffc7d582017-03-29 15:37:18 +00003478 // The root of the match also has constraints on the register bank so that it
3479 // matches the result instruction.
3480 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003481 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3482 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003483
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003484 const auto &DstIOperand = DstI.Operands[OpIdx];
3485 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003486 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3487 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3488
3489 if (DstIOpRec == nullptr)
3490 return failedImport(
3491 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003492 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3493 if (!Dst->getChild(0)->isLeaf())
3494 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3495
Daniel Sanders32291982017-06-28 13:50:04 +00003496 // We can assume that a subregister is in the same bank as it's super
3497 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003498 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3499
3500 if (DstIOpRec == nullptr)
3501 return failedImport(
3502 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003503 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00003504 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003505 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00003506 return failedImport("Dst MI def isn't a register class" +
3507 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003508
Daniel Sandersffc7d582017-03-29 15:37:18 +00003509 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3510 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003511 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003512 OM.addPredicate<RegisterBankOperandMatcher>(
3513 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003514 ++OpIdx;
3515 }
3516
Daniel Sandersa7b75262017-10-31 18:50:24 +00003517 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003518 if (auto Error = DstMIBuilderOrError.takeError())
3519 return std::move(Error);
3520 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003521
Daniel Sandersffc7d582017-03-29 15:37:18 +00003522 // Render the implicit defs.
3523 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00003524 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003525 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003526
Daniel Sandersa7b75262017-10-31 18:50:24 +00003527 DstMIBuilder.chooseInsnToMutate(M);
3528
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003529 // Constrain the registers to classes. This is normally derived from the
3530 // emitted instruction but a few instructions require special handling.
3531 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3532 // COPY_TO_REGCLASS does not provide operand constraints itself but the
3533 // result is constrained to the class given by the second child.
3534 Record *DstIOpRec =
3535 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3536
3537 if (DstIOpRec == nullptr)
3538 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3539
3540 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003541 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003542
3543 // We're done with this pattern! It's eligible for GISel emission; return
3544 // it.
3545 ++NumPatternImported;
3546 return std::move(M);
3547 }
3548
3549 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3550 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
3551 // instructions, the result register class is controlled by the
3552 // subregisters of the operand. As a result, we must constrain the result
3553 // class rather than check that it's already the right one.
3554 if (!Dst->getChild(0)->isLeaf())
3555 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3556
Daniel Sanders320390b2017-06-28 15:16:03 +00003557 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
3558 if (!SubRegInit)
3559 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003560
Daniel Sanders320390b2017-06-28 15:16:03 +00003561 // Constrain the result to the same register bank as the operand.
3562 Record *DstIOpRec =
3563 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003564
Daniel Sanders320390b2017-06-28 15:16:03 +00003565 if (DstIOpRec == nullptr)
3566 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003567
Daniel Sanders320390b2017-06-28 15:16:03 +00003568 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003569 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003570
Daniel Sanders320390b2017-06-28 15:16:03 +00003571 // It would be nice to leave this constraint implicit but we're required
3572 // to pick a register class so constrain the result to a register class
3573 // that can hold the correct MVT.
3574 //
3575 // FIXME: This may introduce an extra copy if the chosen class doesn't
3576 // actually contain the subregisters.
3577 assert(Src->getExtTypes().size() == 1 &&
3578 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003579
Daniel Sanders320390b2017-06-28 15:16:03 +00003580 const auto &SrcRCDstRCPair =
3581 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3582 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003583 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
3584 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
3585
3586 // We're done with this pattern! It's eligible for GISel emission; return
3587 // it.
3588 ++NumPatternImported;
3589 return std::move(M);
3590 }
3591
3592 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003593
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003594 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003595 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003596 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003597}
3598
Daniel Sanders649c5852017-10-13 20:42:18 +00003599// Emit imm predicate table and an enum to reference them with.
3600// The 'Predicate_' part of the name is redundant but eliminating it is more
3601// trouble than it's worth.
3602void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00003603 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
3604 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003605 std::vector<const Record *> MatchedRecords;
3606 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
3607 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
3608 [&](Record *Record) {
3609 return !Record->getValueAsString("ImmediateCode").empty() &&
3610 Filter(Record);
3611 });
3612
Daniel Sanders11300ce2017-10-13 21:28:03 +00003613 if (!MatchedRecords.empty()) {
3614 OS << "// PatFrag predicates.\n"
3615 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00003616 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00003617 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
3618 for (const auto *Record : MatchedRecords) {
3619 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
3620 << EnumeratorSeparator;
3621 EnumeratorSeparator = ",\n";
3622 }
3623 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00003624 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00003625
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003626 OS << "bool " << Target.getName() << "InstructionSelector::testImmPredicate_"
Aaron Ballman82e17f52017-12-20 20:09:30 +00003627 << TypeIdentifier << "(unsigned PredicateID, " << Type
3628 << " Imm) const {\n";
3629 if (!MatchedRecords.empty())
3630 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003631 for (const auto *Record : MatchedRecords) {
3632 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
3633 << Record->getName() << ": {\n"
3634 << " " << Record->getValueAsString("ImmediateCode") << "\n"
3635 << " llvm_unreachable(\"ImmediateCode should have returned\");\n"
3636 << " return false;\n"
3637 << " }\n";
3638 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00003639 if (!MatchedRecords.empty())
3640 OS << " }\n";
3641 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003642 << " return false;\n"
3643 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00003644}
3645
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003646std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Quentin Colombet34688b92017-12-18 21:25:53 +00003647 const std::vector<Matcher *> &Rules,
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003648 std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher) {
3649 std::vector<Matcher *> OptRules;
3650 // Start with a stupid grouping for now.
3651 std::unique_ptr<GroupMatcher> CurrentGroup = make_unique<GroupMatcher>();
3652 assert(CurrentGroup->conditions_empty());
3653 unsigned NbGroup = 0;
Quentin Colombet34688b92017-12-18 21:25:53 +00003654 for (Matcher *Rule : Rules) {
3655 std::unique_ptr<PredicateMatcher> Predicate = Rule->forgetFirstCondition();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003656 if (!CurrentGroup->conditions_empty() &&
3657 !CurrentGroup->lastConditionMatches(*Predicate)) {
3658 // Start a new group.
3659 ++NbGroup;
3660 OptRules.push_back(CurrentGroup.get());
3661 StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3662 CurrentGroup = make_unique<GroupMatcher>();
3663 assert(CurrentGroup->conditions_empty());
3664 }
3665 if (CurrentGroup->conditions_empty())
3666 CurrentGroup->addCondition(std::move(Predicate));
Quentin Colombet34688b92017-12-18 21:25:53 +00003667 CurrentGroup->addRule(*Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003668 }
3669 if (!CurrentGroup->conditions_empty()) {
3670 ++NbGroup;
3671 OptRules.push_back(CurrentGroup.get());
3672 StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3673 }
3674 DEBUG(dbgs() << "NbGroup: " << NbGroup << "\n");
3675 return OptRules;
3676}
3677
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003678void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00003679 if (!UseCoverageFile.empty()) {
3680 RuleCoverage = CodeGenCoverage();
3681 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
3682 if (!RuleCoverageBufOrErr) {
3683 PrintWarning(SMLoc(), "Missing rule coverage data");
3684 RuleCoverage = None;
3685 } else {
3686 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
3687 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
3688 RuleCoverage = None;
3689 }
3690 }
3691 }
3692
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003693 // Track the GINodeEquiv definitions.
3694 gatherNodeEquivs();
3695
3696 emitSourceFileHeader(("Global Instruction Selector for the " +
3697 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003698 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003699 // Look through the SelectionDAG patterns we found, possibly emitting some.
3700 for (const PatternToMatch &Pat : CGP.ptms()) {
3701 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00003702
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003703 auto MatcherOrErr = runOnPattern(Pat);
3704
3705 // The pattern analysis can fail, indicating an unsupported pattern.
3706 // Report that if we've been asked to do so.
3707 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003708 if (WarnOnSkippedPatterns) {
3709 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003710 "Skipped pattern: " + toString(std::move(Err)));
3711 } else {
3712 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003713 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003714 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003715 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003716 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003717
Daniel Sandersf76f3152017-11-16 00:46:35 +00003718 if (RuleCoverage) {
3719 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
3720 ++NumPatternsTested;
3721 else
3722 PrintWarning(Pat.getSrcRecord()->getLoc(),
3723 "Pattern is not covered by a test");
3724 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003725 Rules.push_back(std::move(MatcherOrErr.get()));
3726 }
3727
Volkan Kelesf7f25682018-01-16 18:44:05 +00003728 // Comparison function to order records by name.
3729 auto orderByName = [](const Record *A, const Record *B) {
3730 return A->getName() < B->getName();
3731 };
3732
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003733 std::vector<Record *> ComplexPredicates =
3734 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Volkan Kelesf7f25682018-01-16 18:44:05 +00003735 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(), orderByName);
3736
3737 std::vector<Record *> CustomRendererFns =
3738 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
3739 std::sort(CustomRendererFns.begin(), CustomRendererFns.end(), orderByName);
3740
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003741 unsigned MaxTemporaries = 0;
3742 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003743 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003744
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003745 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3746 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3747 << ";\n"
3748 << "using PredicateBitset = "
3749 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3750 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3751
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003752 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3753 << " mutable MatcherState State;\n"
3754 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003755 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003756 << Target.getName()
3757 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003758
3759 << " typedef void(" << Target.getName()
3760 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
3761 "MachineInstr&) "
3762 "const;\n"
3763 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
3764 "CustomRendererFn> "
3765 "ISelInfo;\n";
3766 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00003767 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003768 << " static " << Target.getName()
3769 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003770 << "bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
3771 "override;\n"
3772 << "bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
3773 "const override;\n"
3774 << "bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
3775 "&Imm) const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003776 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003777
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003778 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3779 << ", State(" << MaxTemporaries << "),\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003780 << "ISelInfo({TypeObjects, FeatureBitsets, ComplexPredicateFns, "
3781 "CustomRenderers})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003782 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003783
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003784 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3785 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3786 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003787
3788 // Separate subtarget features by how often they must be recomputed.
3789 SubtargetFeatureInfoMap ModuleFeatures;
3790 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3791 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3792 [](const SubtargetFeatureInfoMap::value_type &X) {
3793 return !X.second.mustRecomputePerFunction();
3794 });
3795 SubtargetFeatureInfoMap FunctionFeatures;
3796 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3797 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3798 [](const SubtargetFeatureInfoMap::value_type &X) {
3799 return X.second.mustRecomputePerFunction();
3800 });
3801
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003802 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003803 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3804 ModuleFeatures, OS);
3805 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3806 Target.getName(), "InstructionSelector",
3807 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3808 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003809
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003810 // Emit a table containing the LLT objects needed by the matcher and an enum
3811 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003812 std::vector<LLTCodeGen> TypeObjects;
3813 for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3814 TypeObjects.push_back(Ty);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003815 std::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003816 OS << "// LLT Objects.\n"
3817 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003818 for (const auto &TypeObject : TypeObjects) {
3819 OS << " ";
3820 TypeObject.emitCxxEnumValue(OS);
3821 OS << ",\n";
3822 }
3823 OS << "};\n"
3824 << "const static LLT TypeObjects[] = {\n";
3825 for (const auto &TypeObject : TypeObjects) {
3826 OS << " ";
3827 TypeObject.emitCxxConstructorCall(OS);
3828 OS << ",\n";
3829 }
3830 OS << "};\n\n";
3831
3832 // Emit a table containing the PredicateBitsets objects needed by the matcher
3833 // and an enum for the matcher to reference them with.
3834 std::vector<std::vector<Record *>> FeatureBitsets;
3835 for (auto &Rule : Rules)
3836 FeatureBitsets.push_back(Rule.getRequiredFeatures());
3837 std::sort(
3838 FeatureBitsets.begin(), FeatureBitsets.end(),
3839 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3840 if (A.size() < B.size())
3841 return true;
3842 if (A.size() > B.size())
3843 return false;
3844 for (const auto &Pair : zip(A, B)) {
3845 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3846 return true;
3847 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3848 return false;
3849 }
3850 return false;
3851 });
3852 FeatureBitsets.erase(
3853 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3854 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003855 OS << "// Feature bitsets.\n"
3856 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003857 << " GIFBS_Invalid,\n";
3858 for (const auto &FeatureBitset : FeatureBitsets) {
3859 if (FeatureBitset.empty())
3860 continue;
3861 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3862 }
3863 OS << "};\n"
3864 << "const static PredicateBitset FeatureBitsets[] {\n"
3865 << " {}, // GIFBS_Invalid\n";
3866 for (const auto &FeatureBitset : FeatureBitsets) {
3867 if (FeatureBitset.empty())
3868 continue;
3869 OS << " {";
3870 for (const auto &Feature : FeatureBitset) {
3871 const auto &I = SubtargetFeatures.find(Feature);
3872 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3873 OS << I->second.getEnumBitName() << ", ";
3874 }
3875 OS << "},\n";
3876 }
3877 OS << "};\n\n";
3878
3879 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00003880 OS << "// ComplexPattern predicates.\n"
3881 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003882 << " GICP_Invalid,\n";
3883 for (const auto &Record : ComplexPredicates)
3884 OS << " GICP_" << Record->getName() << ",\n";
3885 OS << "};\n"
3886 << "// See constructor for table contents\n\n";
3887
Daniel Sanders11300ce2017-10-13 21:28:03 +00003888 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003889 bool Unset;
3890 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3891 !R->getValueAsBit("IsAPInt");
3892 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00003893 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3894 bool Unset;
3895 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3896 });
3897 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3898 return R->getValueAsBit("IsAPInt");
3899 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00003900 OS << "\n";
3901
3902 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3903 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3904 << " nullptr, // GICP_Invalid\n";
3905 for (const auto &Record : ComplexPredicates)
3906 OS << " &" << Target.getName()
3907 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3908 << ", // " << Record->getName() << "\n";
3909 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00003910
Volkan Kelesf7f25682018-01-16 18:44:05 +00003911 OS << "// Custom renderers.\n"
3912 << "enum {\n"
3913 << " GICR_Invalid,\n";
3914 for (const auto &Record : CustomRendererFns)
3915 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
3916 OS << "};\n";
3917
3918 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
3919 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
3920 << " nullptr, // GICP_Invalid\n";
3921 for (const auto &Record : CustomRendererFns)
3922 OS << " &" << Target.getName()
3923 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
3924 << ", // " << Record->getName() << "\n";
3925 OS << "};\n\n";
3926
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003927 OS << "bool " << Target.getName()
Daniel Sandersf76f3152017-11-16 00:46:35 +00003928 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
3929 "&CoverageInfo) const {\n"
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003930 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003931 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00003932 << " // FIXME: This should be computed on a per-function basis rather "
3933 "than per-insn.\n"
3934 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3935 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00003936 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3937 << " NewMIVector OutMIs;\n"
3938 << " State.MIs.clear();\n"
3939 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003940
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003941 std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
3942 const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003943 int ScoreA = RuleMatcherScores[A.getRuleID()];
3944 int ScoreB = RuleMatcherScores[B.getRuleID()];
3945 if (ScoreA > ScoreB)
3946 return true;
3947 if (ScoreB > ScoreA)
3948 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003949 if (A.isHigherPriorityThan(B)) {
3950 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3951 "and less important at "
3952 "the same time");
3953 return true;
3954 }
3955 return false;
3956 });
3957 std::vector<std::unique_ptr<GroupMatcher>> StorageGroupMatcher;
3958
Quentin Colombet34688b92017-12-18 21:25:53 +00003959 std::vector<Matcher *> InputRules;
3960 for (Matcher &Rule : Rules)
3961 InputRules.push_back(&Rule);
3962
3963 std::vector<Matcher *> OptRules =
3964 OptimizeMatchTable ? optimizeRules(InputRules, StorageGroupMatcher)
3965 : InputRules;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003966
Daniel Sanders8e82af22017-07-27 11:03:45 +00003967 MatchTable Table(0);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003968 for (Matcher *Rule : OptRules)
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003969 Rule->emit(Table);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003970
Daniel Sanders8e82af22017-07-27 11:03:45 +00003971 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3972 Table.emitDeclaration(OS);
Volkan Kelesf7f25682018-01-16 18:44:05 +00003973 OS << " if (executeMatchTable(*this, OutMIs, State, ISelInfo, ";
Daniel Sanders8e82af22017-07-27 11:03:45 +00003974 Table.emitUse(OS);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003975 OS << ", TII, MRI, TRI, RBI, AvailableFeatures, CoverageInfo)) {\n"
Daniel Sanders8e82af22017-07-27 11:03:45 +00003976 << " return true;\n"
3977 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003978
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003979 OS << " return false;\n"
3980 << "}\n"
3981 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003982
3983 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3984 << "PredicateBitset AvailableModuleFeatures;\n"
3985 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3986 << "PredicateBitset getAvailableFeatures() const {\n"
3987 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3988 << "}\n"
3989 << "PredicateBitset\n"
3990 << "computeAvailableModuleFeatures(const " << Target.getName()
3991 << "Subtarget *Subtarget) const;\n"
3992 << "PredicateBitset\n"
3993 << "computeAvailableFunctionFeatures(const " << Target.getName()
3994 << "Subtarget *Subtarget,\n"
3995 << " const MachineFunction *MF) const;\n"
3996 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3997
3998 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3999 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4000 << "AvailableFunctionFeatures()\n"
4001 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004002}
4003
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004004void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4005 if (SubtargetFeatures.count(Predicate) == 0)
4006 SubtargetFeatures.emplace(
4007 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4008}
4009
Daniel Sanders7e523672017-11-11 03:23:44 +00004010TreePatternNode *GlobalISelEmitter::fixupPatternNode(TreePatternNode *N) {
4011 if (!N->isLeaf()) {
4012 for (unsigned I = 0, E = N->getNumChildren(); I < E; ++I) {
4013 TreePatternNode *OrigChild = N->getChild(I);
4014 TreePatternNode *NewChild = fixupPatternNode(OrigChild);
4015 if (OrigChild != NewChild)
4016 N->setChild(I, NewChild);
4017 }
4018
4019 if (N->getOperator()->getName() == "ld") {
4020 // If it's a signext-load we need to adapt the pattern slightly. We need
4021 // to split the node into (sext (ld ...)), remove the <<signext>> predicate,
4022 // and then apply the <<signextTY>> predicate by updating the result type
4023 // of the load.
4024 //
4025 // For example:
4026 // (ld:[i32] [iPTR])<<unindexed>><<signext>><<signexti16>>
4027 // must be transformed into:
4028 // (sext:[i32] (ld:[i16] [iPTR])<<unindexed>>)
4029 //
Daniel Sandersb78ac6e2017-11-13 18:30:23 +00004030 // Likewise for zeroext-load and anyext-load.
Daniel Sanders7e523672017-11-11 03:23:44 +00004031
4032 std::vector<TreePredicateFn> Predicates;
4033 bool IsSignExtLoad = false;
4034 bool IsZeroExtLoad = false;
Daniel Sandersb78ac6e2017-11-13 18:30:23 +00004035 bool IsAnyExtLoad = false;
Daniel Sanders7e523672017-11-11 03:23:44 +00004036 Record *MemVT = nullptr;
4037 for (const auto &P : N->getPredicateFns()) {
4038 if (P.isLoad() && P.isSignExtLoad()) {
4039 IsSignExtLoad = true;
4040 continue;
4041 }
4042 if (P.isLoad() && P.isZeroExtLoad()) {
4043 IsZeroExtLoad = true;
4044 continue;
4045 }
Daniel Sandersb78ac6e2017-11-13 18:30:23 +00004046 if (P.isLoad() && P.isAnyExtLoad()) {
4047 IsAnyExtLoad = true;
4048 continue;
4049 }
Daniel Sanders7e523672017-11-11 03:23:44 +00004050 if (P.isLoad() && P.getMemoryVT()) {
4051 MemVT = P.getMemoryVT();
4052 continue;
4053 }
4054 Predicates.push_back(P);
4055 }
4056
Daniel Sandersb78ac6e2017-11-13 18:30:23 +00004057 if ((IsSignExtLoad || IsZeroExtLoad || IsAnyExtLoad) && MemVT) {
4058 assert((IsSignExtLoad + IsZeroExtLoad + IsAnyExtLoad) == 1 &&
4059 "IsSignExtLoad, IsZeroExtLoad, IsAnyExtLoad are mutually exclusive");
Daniel Sanders7e523672017-11-11 03:23:44 +00004060 TreePatternNode *Ext = new TreePatternNode(
Daniel Sandersb78ac6e2017-11-13 18:30:23 +00004061 RK.getDef(IsSignExtLoad ? "sext"
4062 : IsZeroExtLoad ? "zext" : "anyext"),
4063 {N}, 1);
Daniel Sanders7e523672017-11-11 03:23:44 +00004064 Ext->setType(0, N->getType(0));
4065 N->clearPredicateFns();
4066 N->setPredicateFns(Predicates);
4067 N->setType(0, getValueType(MemVT));
4068 return Ext;
4069 }
4070 }
4071 }
4072
4073 return N;
4074}
4075
4076void GlobalISelEmitter::fixupPatternTrees(TreePattern *P) {
4077 for (unsigned I = 0, E = P->getNumTrees(); I < E; ++I) {
4078 TreePatternNode *OrigTree = P->getTree(I);
4079 TreePatternNode *NewTree = fixupPatternNode(OrigTree);
4080 if (OrigTree != NewTree)
4081 P->setTree(I, NewTree);
4082 }
4083}
4084
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004085std::unique_ptr<PredicateMatcher> RuleMatcher::forgetFirstCondition() {
4086 assert(!insnmatchers_empty() &&
4087 "Trying to forget something that does not exist");
4088
4089 InstructionMatcher &Matcher = insnmatchers_front();
4090 std::unique_ptr<PredicateMatcher> Condition;
4091 if (!Matcher.predicates_empty())
4092 Condition = Matcher.predicates_pop_front();
4093 if (!Condition) {
4094 // If there is no more predicate on the instruction itself, look at its
4095 // operands.
4096 assert(!Matcher.operands_empty() &&
4097 "Empty instruction should have been discarded");
4098 OperandMatcher &OpMatcher = **Matcher.operands_begin();
4099 assert(!OpMatcher.predicates_empty() && "no operand constraint");
4100 Condition = OpMatcher.predicates_pop_front();
4101 // If this operand is free of constraints, rip it off.
4102 if (OpMatcher.predicates_empty())
4103 Matcher.pop_front();
4104 }
4105 // Rip the instruction off when it is empty.
4106 if (Matcher.operands_empty() && Matcher.predicates_empty())
4107 insnmatchers_pop_front();
4108 return Condition;
4109}
4110
4111bool GroupMatcher::lastConditionMatches(
4112 const PredicateMatcher &Predicate) const {
4113 const auto &LastCondition = conditions_back();
4114 return Predicate.isIdentical(*LastCondition);
4115}
4116
4117void GroupMatcher::emit(MatchTable &Table) {
4118 unsigned LabelID = Table.allocateLabelID();
4119 if (!conditions_empty()) {
4120 Table << MatchTable::Opcode("GIM_Try", +1)
4121 << MatchTable::Comment("On fail goto")
4122 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
4123 for (auto &Condition : Conditions)
4124 Condition->emitPredicateOpcodes(
4125 Table, *static_cast<RuleMatcher *>(*Rules.begin()));
4126 }
4127 // Emit the conditions.
4128 // Then checks apply the rules.
4129 for (const auto &Rule : Rules)
4130 Rule->emit(Table);
4131 // If we don't succeeded for that block, that means we are not going to select
4132 // this instruction.
4133 if (!conditions_empty()) {
4134 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4135 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
4136 << MatchTable::Label(LabelID);
4137 }
4138}
4139
Quentin Colombetaad20be2017-12-15 23:07:42 +00004140unsigned OperandMatcher::getInsnVarID() const { return Insn.getVarID(); }
4141
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004142} // end anonymous namespace
4143
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004144//===----------------------------------------------------------------------===//
4145
4146namespace llvm {
4147void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4148 GlobalISelEmitter(RK).run(OS);
4149}
4150} // End llvm namespace