blob: 842711bf04808ca073abf62ae1c5e8201c57b451 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This tablegen backend emits code for use by the GlobalISel instruction
11/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12///
13/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14/// backend, filters out the ones that are unsupported, maps
15/// SelectionDAG-specific constructs to their GlobalISel counterpart
16/// (when applicable: MVT to LLT; SDNode to generic Instruction).
17///
18/// Not all patterns are supported: pass the tablegen invocation
19/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20/// as well as why.
21///
22/// The generated file defines a single method:
23/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24/// intended to be used in InstructionSelector::select as the first-step
25/// selector for the patterns that don't require complex C++.
26///
27/// FIXME: We'll probably want to eventually define a base
28/// "TargetGenInstructionSelector" class.
29///
30//===----------------------------------------------------------------------===//
31
32#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000033#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000034#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000035#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000036#include "llvm/ADT/Statistic.h"
Daniel Sandersf76f3152017-11-16 00:46:35 +000037#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000038#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000039#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000040#include "llvm/Support/LowLevelTypeImpl.h"
David Blaikie13e77db2018-03-23 23:58:25 +000041#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000046#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000047#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000055STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000056STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57
Daniel Sanders0848b232017-03-27 13:15:13 +000058cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060static cl::opt<bool> WarnOnSkippedPatterns(
61 "warn-on-skipped-patterns",
62 cl::desc("Explain why a pattern was skipped for inclusion "
63 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000064 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000065
Daniel Sandersf76f3152017-11-16 00:46:35 +000066static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
70
71static cl::opt<std::string> UseCoverageFile(
72 "gisel-coverage-file", cl::init(""),
73 cl::desc("Specify file to retrieve coverage information from"),
74 cl::cat(GlobalISelEmitterCat));
75
Quentin Colombetec76d9c2017-12-18 19:47:41 +000076static cl::opt<bool> OptimizeMatchTable(
77 "optimize-match-table",
78 cl::desc("Generate an optimized version of the match table"),
79 cl::init(true), cl::cat(GlobalISelEmitterCat));
80
Daniel Sandersbdfebb82017-03-15 20:18:38 +000081namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000082//===- Helper functions ---------------------------------------------------===//
83
Daniel Sanders11300ce2017-10-13 21:28:03 +000084/// Get the name of the enum value used to number the predicate function.
85std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000086 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000088 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000089 Predicate.getFnName();
90}
91
92/// Get the opcode used to check this predicate.
93std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000094 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000095}
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097/// This class stands in for LLT wherever we want to tablegen-erate an
98/// equivalent at compiler run-time.
99class LLTCodeGen {
100private:
101 LLT Ty;
102
103public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000104 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
110
111 emitCxxEnumValue(OS);
112 return OS.str();
113 }
114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
119 }
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
123 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
129 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000130 llvm_unreachable("Unhandled LLT");
131 }
132
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
137 }
138 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000141 return;
142 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
147 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 llvm_unreachable("Unhandled LLT");
149 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000150
151 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000152
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000153 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000156 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000161
162 if (Ty.isVector() != Other.Ty.isVector())
163 return Ty.isVector() < Other.Ty.isVector();
164 if (Ty.isScalar() != Other.Ty.isScalar())
165 return Ty.isScalar() < Other.Ty.isScalar();
166 if (Ty.isPointer() != Other.Ty.isPointer())
167 return Ty.isPointer() < Other.Ty.isPointer();
168
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
174
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000176 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000177
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000179};
180
Daniel Sandersf84bc372018-05-05 20:53:24 +0000181// Track all types that are used so we can emit the corresponding enum.
182std::set<LLTCodeGen> KnownTypes;
183
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000184class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000185/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000189
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000193
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000197}
198
Florian Hahn6b1db822018-06-14 20:32:58 +0000199static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000200 std::string Explanation = "";
201 StringRef Separator = "";
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
238
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
244
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
247 }
248
249 OS << ']';
250 }
251
Matt Arsenault52c26242019-07-31 00:14:43 +0000252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
255
Daniel Sanders76664652017-11-28 22:07:05 +0000256 if (P.isAtomicOrderingMonotonic())
257 Explanation += " monotonic";
258 if (P.isAtomicOrderingAcquire())
259 Explanation += " acquire";
260 if (P.isAtomicOrderingRelease())
261 Explanation += " release";
262 if (P.isAtomicOrderingAcquireRelease())
263 Explanation += " acq_rel";
264 if (P.isAtomicOrderingSequentiallyConsistent())
265 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000266 if (P.isAtomicOrderingAcquireOrStronger())
267 Explanation += " >=acquire";
268 if (P.isAtomicOrderingWeakerThanAcquire())
269 Explanation += " <acquire";
270 if (P.isAtomicOrderingReleaseOrStronger())
271 Explanation += " >=release";
272 if (P.isAtomicOrderingWeakerThanRelease())
273 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000274 }
275 return Explanation;
276}
277
Daniel Sandersd0656a32017-04-13 09:45:37 +0000278std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000281
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
289
Volkan Kelesf7f25682018-01-16 18:44:05 +0000290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
294
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000295 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000296}
297
298/// Helper function to let the emitter report skip reason error messages.
299static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
301}
302
Florian Hahn6b1db822018-06-14 20:32:58 +0000303static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000304 std::string Explanation = "";
305 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000306
307 bool HasUnsupportedPredicate = false;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
310
Daniel Sanders2c269f62017-08-24 09:11:20 +0000311 if (Predicate.isAlwaysTrue())
312 continue;
313
314 if (Predicate.isImmediatePattern())
315 continue;
316
Daniel Sandersf84bc372018-05-05 20:53:24 +0000317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000319 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320
Matt Arsenault02772492019-07-15 21:15:20 +0000321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sandersf84bc372018-05-05 20:53:24 +0000324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
326
Daniel Sanders76664652017-11-28 22:07:05 +0000327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
330 }
331
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
Matt Arsenault52c26242019-07-31 00:14:43 +0000336
337 if (Predicate.getMinAlignment() > 0)
338 continue;
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000339 }
340
Daniel Sanders76664652017-11-28 22:07:05 +0000341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
343
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000354 continue;
355
Daniel Sanders8ead1292018-06-15 23:13:43 +0000356 if (Predicate.hasGISelPredicateCode())
357 continue;
358
Daniel Sanders2c269f62017-08-24 09:11:20 +0000359 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000365 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000366 }
367
Volkan Kelesf7f25682018-01-16 18:44:05 +0000368 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000369 return Error::success();
370
371 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000372}
373
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000374static Record *getInitValueAsRegClass(Init *V) {
375 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377 return VDefInit->getDef()->getValueAsDef("RegClass");
378 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379 return VDefInit->getDef();
380 }
381 return nullptr;
382}
383
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000384std::string
385getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
390}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000391
392//===- MatchTable Helpers -------------------------------------------------===//
393
394class MatchTable;
395
396/// A record to be stored in a MatchTable.
397///
398/// This class represents any and all output that may be required to emit the
399/// MatchTable. Instances are most often configured to represent an opcode or
400/// value that will be emitted to the table with some formatting but it can also
401/// represent commas, comments, and other formatting instructions.
402struct MatchTableRecord {
403 enum RecordFlagsBits {
404 MTRF_None = 0x0,
405 /// Causes EmitStr to be formatted as comment when emitted.
406 MTRF_Comment = 0x1,
407 /// Causes the record value to be followed by a comma when emitted.
408 MTRF_CommaFollows = 0x2,
409 /// Causes the record value to be followed by a line break when emitted.
410 MTRF_LineBreakFollows = 0x4,
411 /// Indicates that the record defines a label and causes an additional
412 /// comment to be emitted containing the index of the label.
413 MTRF_Label = 0x8,
414 /// Causes the record to be emitted as the index of the label specified by
415 /// LabelID along with a comment indicating where that label is.
416 MTRF_JumpTarget = 0x10,
417 /// Causes the formatter to add a level of indentation before emitting the
418 /// record.
419 MTRF_Indent = 0x20,
420 /// Causes the formatter to remove a level of indentation after emitting the
421 /// record.
422 MTRF_Outdent = 0x40,
423 };
424
425 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426 /// reference or define.
427 unsigned LabelID;
428 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429 /// value, a label name.
430 std::string EmitStr;
431
432private:
433 /// The number of MatchTable elements described by this record. Comments are 0
434 /// while values are typically 1. Values >1 may occur when we need to emit
435 /// values that exceed the size of a MatchTable element.
436 unsigned NumElements;
437
438public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
441
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000442 /// The actual run-time value, if known
443 int64_t RawValue;
444
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
451
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000452 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
453 "This value is reserved for non-labels");
454 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000455 MatchTableRecord(const MatchTableRecord &Other) = default;
456 MatchTableRecord(MatchTableRecord &&Other) = default;
457
458 /// Useful if a Match Table Record gets optimized out
459 void turnIntoComment() {
460 Flags |= MTRF_Comment;
461 Flags &= ~MTRF_CommaFollows;
462 NumElements = 0;
463 }
464
465 /// For Jump Table generation purposes
466 bool operator<(const MatchTableRecord &Other) const {
467 return RawValue < Other.RawValue;
468 }
469 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000470
471 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
472 const MatchTable &Table) const;
473 unsigned size() const { return NumElements; }
474};
475
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000476class Matcher;
477
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000478/// Holds the contents of a generated MatchTable to enable formatting and the
479/// necessary index tracking needed to support GIM_Try.
480class MatchTable {
481 /// An unique identifier for the table. The generated table will be named
482 /// MatchTable${ID}.
483 unsigned ID;
484 /// The records that make up the table. Also includes comments describing the
485 /// values being emitted and line breaks to format it.
486 std::vector<MatchTableRecord> Contents;
487 /// The currently defined labels.
488 DenseMap<unsigned, unsigned> LabelMap;
489 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000490 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000491 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000492 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000493 /// Determines if the table should be instrumented for rule coverage tracking.
494 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000495
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000496public:
497 static MatchTableRecord LineBreak;
498 static MatchTableRecord Comment(StringRef Comment) {
499 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
500 }
501 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
502 unsigned ExtraFlags = 0;
503 if (IndentAdjust > 0)
504 ExtraFlags |= MatchTableRecord::MTRF_Indent;
505 if (IndentAdjust < 0)
506 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
507
508 return MatchTableRecord(None, Opcode, 1,
509 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
510 }
511 static MatchTableRecord NamedValue(StringRef NamedValue) {
512 return MatchTableRecord(None, NamedValue, 1,
513 MatchTableRecord::MTRF_CommaFollows);
514 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000515 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
516 return MatchTableRecord(None, NamedValue, 1,
517 MatchTableRecord::MTRF_CommaFollows, RawValue);
518 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000519 static MatchTableRecord NamedValue(StringRef Namespace,
520 StringRef NamedValue) {
521 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
522 MatchTableRecord::MTRF_CommaFollows);
523 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000524 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
525 int64_t RawValue) {
526 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
527 MatchTableRecord::MTRF_CommaFollows, RawValue);
528 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000529 static MatchTableRecord IntValue(int64_t IntValue) {
530 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
531 MatchTableRecord::MTRF_CommaFollows);
532 }
533 static MatchTableRecord Label(unsigned LabelID) {
534 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
535 MatchTableRecord::MTRF_Label |
536 MatchTableRecord::MTRF_Comment |
537 MatchTableRecord::MTRF_LineBreakFollows);
538 }
539 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000540 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000541 MatchTableRecord::MTRF_JumpTarget |
542 MatchTableRecord::MTRF_Comment |
543 MatchTableRecord::MTRF_CommaFollows);
544 }
545
Roman Tereshinbeb39312018-05-02 20:15:11 +0000546 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000547
Roman Tereshinbeb39312018-05-02 20:15:11 +0000548 MatchTable(bool WithCoverage, unsigned ID = 0)
549 : ID(ID), IsWithCoverage(WithCoverage) {}
550
551 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000552
553 void push_back(const MatchTableRecord &Value) {
554 if (Value.Flags & MatchTableRecord::MTRF_Label)
555 defineLabel(Value.LabelID);
556 Contents.push_back(Value);
557 CurrentSize += Value.size();
558 }
559
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000560 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000561
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000562 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000563 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000564 }
565
566 unsigned getLabelIndex(unsigned LabelID) const {
567 const auto I = LabelMap.find(LabelID);
568 assert(I != LabelMap.end() && "Use of undeclared label");
569 return I->second;
570 }
571
Daniel Sanders8e82af22017-07-27 11:03:45 +0000572 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
573
574 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000575 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000576 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000577 LineBreak.emit(OS, true, *this);
578 OS << std::string(Indentation, ' ');
579
580 for (auto I = Contents.begin(), E = Contents.end(); I != E;
581 ++I) {
582 bool LineBreakIsNext = false;
583 const auto &NextI = std::next(I);
584
585 if (NextI != E) {
586 if (NextI->EmitStr == "" &&
587 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
588 LineBreakIsNext = true;
589 }
590
591 if (I->Flags & MatchTableRecord::MTRF_Indent)
592 Indentation += 2;
593
594 I->emit(OS, LineBreakIsNext, *this);
595 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
596 OS << std::string(Indentation, ' ');
597
598 if (I->Flags & MatchTableRecord::MTRF_Outdent)
599 Indentation -= 2;
600 }
601 OS << "};\n";
602 }
603};
604
605MatchTableRecord MatchTable::LineBreak = {
606 None, "" /* Emit String */, 0 /* Elements */,
607 MatchTableRecord::MTRF_LineBreakFollows};
608
609void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
610 const MatchTable &Table) const {
611 bool UseLineComment =
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000612 LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000613 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
614 UseLineComment = false;
615
616 if (Flags & MTRF_Comment)
617 OS << (UseLineComment ? "// " : "/*");
618
619 OS << EmitStr;
620 if (Flags & MTRF_Label)
621 OS << ": @" << Table.getLabelIndex(LabelID);
622
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000623 if ((Flags & MTRF_Comment) && !UseLineComment)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000624 OS << "*/";
625
626 if (Flags & MTRF_JumpTarget) {
627 if (Flags & MTRF_Comment)
628 OS << " ";
629 OS << Table.getLabelIndex(LabelID);
630 }
631
632 if (Flags & MTRF_CommaFollows) {
633 OS << ",";
634 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
635 OS << " ";
636 }
637
638 if (Flags & MTRF_LineBreakFollows)
639 OS << "\n";
640}
641
642MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
643 Table.push_back(Value);
644 return Table;
645}
646
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000647//===- Matchers -----------------------------------------------------------===//
648
Daniel Sandersbee57392017-04-04 13:25:23 +0000649class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000650class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000651class PredicateMatcher;
652class RuleMatcher;
653
654class Matcher {
655public:
656 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000657 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000658 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000659
660 virtual bool hasFirstCondition() const = 0;
661 virtual const PredicateMatcher &getFirstCondition() const = 0;
662 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000663};
664
Roman Tereshinbeb39312018-05-02 20:15:11 +0000665MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
666 bool WithCoverage) {
667 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000668 for (Matcher *Rule : Rules)
669 Rule->emit(Table);
670
671 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
672}
673
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000674class GroupMatcher final : public Matcher {
675 /// Conditions that form a common prefix of all the matchers contained.
676 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
677
678 /// All the nested matchers, sharing a common prefix.
679 std::vector<Matcher *> Matchers;
680
681 /// An owning collection for any auxiliary matchers created while optimizing
682 /// nested matchers contained.
683 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000684
685public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000686 /// Add a matcher to the collection of nested matchers if it meets the
687 /// requirements, and return true. If it doesn't, do nothing and return false.
688 ///
689 /// Expected to preserve its argument, so it could be moved out later on.
690 bool addMatcher(Matcher &Candidate);
691
692 /// Mark the matcher as fully-built and ensure any invariants expected by both
693 /// optimize() and emit(...) methods. Generally, both sequences of calls
694 /// are expected to lead to a sensible result:
695 ///
696 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
697 /// addMatcher(...)*; finalize(); emit(...);
698 ///
699 /// or generally
700 ///
701 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
702 ///
703 /// Multiple calls to optimize() are expected to be handled gracefully, though
704 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
705 /// aren't generally supported. emit(...) is expected to be non-mutating and
706 /// producing the exact same results upon repeated calls.
707 ///
708 /// addMatcher() calls after the finalize() call are not supported.
709 ///
710 /// finalize() and optimize() are both allowed to mutate the contained
711 /// matchers, so moving them out after finalize() is not supported.
712 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000713 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000714 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000715
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000716 /// Could be used to move out the matchers added previously, unless finalize()
717 /// has been already called. If any of the matchers are moved out, the group
718 /// becomes safe to destroy, but not safe to re-use for anything else.
719 iterator_range<std::vector<Matcher *>::iterator> matchers() {
720 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000721 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000722 size_t size() const { return Matchers.size(); }
723 bool empty() const { return Matchers.empty(); }
724
725 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
726 assert(!Conditions.empty() &&
727 "Trying to pop a condition from a condition-less group");
728 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
729 Conditions.erase(Conditions.begin());
730 return P;
731 }
732 const PredicateMatcher &getFirstCondition() const override {
733 assert(!Conditions.empty() &&
734 "Trying to get a condition from a condition-less group");
735 return *Conditions.front();
736 }
737 bool hasFirstCondition() const override { return !Conditions.empty(); }
738
739private:
740 /// See if a candidate matcher could be added to this group solely by
741 /// analyzing its first condition.
742 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000743};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000744
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000745class SwitchMatcher : public Matcher {
746 /// All the nested matchers, representing distinct switch-cases. The first
747 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
748 /// matchers must share the same type and path to a value they check, in other
749 /// words, be isIdenticalDownToValue, but have different values they check
750 /// against.
751 std::vector<Matcher *> Matchers;
752
753 /// The representative condition, with a type and a path (InsnVarID and OpIdx
754 /// in most cases) shared by all the matchers contained.
755 std::unique_ptr<PredicateMatcher> Condition = nullptr;
756
757 /// Temporary set used to check that the case values don't repeat within the
758 /// same switch.
759 std::set<MatchTableRecord> Values;
760
761 /// An owning collection for any auxiliary matchers created while optimizing
762 /// nested matchers contained.
763 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
764
765public:
766 bool addMatcher(Matcher &Candidate);
767
768 void finalize();
769 void emit(MatchTable &Table) override;
770
771 iterator_range<std::vector<Matcher *>::iterator> matchers() {
772 return make_range(Matchers.begin(), Matchers.end());
773 }
774 size_t size() const { return Matchers.size(); }
775 bool empty() const { return Matchers.empty(); }
776
777 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
778 // SwitchMatcher doesn't have a common first condition for its cases, as all
779 // the cases only share a kind of a value (a type and a path to it) they
780 // match, but deliberately differ in the actual value they match.
781 llvm_unreachable("Trying to pop a condition from a condition-less group");
782 }
783 const PredicateMatcher &getFirstCondition() const override {
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
785 }
786 bool hasFirstCondition() const override { return false; }
787
788private:
789 /// See if the predicate type has a Switch-implementation for it.
790 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
791
792 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
793
794 /// emit()-helper
795 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
796 MatchTable &Table);
797};
798
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000799/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000800class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000801public:
Daniel Sanders08464522018-01-29 21:09:12 +0000802 using ActionList = std::list<std::unique_ptr<MatchAction>>;
803 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000804
805protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000806 /// A list of matchers that all need to succeed for the current rule to match.
807 /// FIXME: This currently supports a single match position but could be
808 /// extended to support multiple positions to support div/rem fusion or
809 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000810 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
811 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000812
813 /// A list of actions that need to be taken when all predicates in this rule
814 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000815 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000816
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000817 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000818
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000819 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000820 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000821
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000822 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000823
824 // The set of instruction matchers that have not yet been claimed for mutation
825 // by a BuildMI.
826 MutatableInsnSet MutatableInsns;
827
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000828 /// A map of named operands defined by the matchers that may be referenced by
829 /// the renderers.
830 StringMap<OperandMatcher *> DefinedOperands;
831
Matt Arsenault3e45c702019-09-06 20:32:37 +0000832 /// A map of anonymous physical register operands defined by the matchers that
833 /// may be referenced by the renderers.
834 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
835
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000836 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000837 unsigned NextInsnVarID;
838
Daniel Sanders198447a2017-11-01 00:29:47 +0000839 /// ID for the next output instruction allocated with allocateOutputInsnID()
840 unsigned NextOutputInsnID;
841
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000842 /// ID for the next temporary register ID allocated with allocateTempRegID()
843 unsigned NextTempRegID;
844
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000845 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000846 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000847
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000848 ArrayRef<SMLoc> SrcLoc;
849
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000850 typedef std::tuple<Record *, unsigned, unsigned>
851 DefinedComplexPatternSubOperand;
852 typedef StringMap<DefinedComplexPatternSubOperand>
853 DefinedComplexPatternSubOperandMap;
854 /// A map of Symbolic Names to ComplexPattern sub-operands.
855 DefinedComplexPatternSubOperandMap ComplexSubOperands;
856
Daniel Sandersf76f3152017-11-16 00:46:35 +0000857 uint64_t RuleID;
858 static uint64_t NextRuleID;
859
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000860public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000861 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000862 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000863 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000864 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
865 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000866 RuleMatcher(RuleMatcher &&Other) = default;
867 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000868
Daniel Sandersf76f3152017-11-16 00:46:35 +0000869 uint64_t getRuleID() const { return RuleID; }
870
Daniel Sanders05540042017-08-08 10:44:31 +0000871 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000872 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000873 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000874
875 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000876 template <class Kind, class... Args>
877 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000878
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000879 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000880 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
881
882 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000883 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
884 return InsnVariableIDs.begin();
885 }
886 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
887 return InsnVariableIDs.end();
888 }
889 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
890 defined_insn_vars() const {
891 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
892 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000893
Daniel Sandersa7b75262017-10-31 18:50:24 +0000894 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
895 return MutatableInsns.begin();
896 }
897 MutatableInsnSet::const_iterator mutatable_insns_end() const {
898 return MutatableInsns.end();
899 }
900 iterator_range<typename MutatableInsnSet::const_iterator>
901 mutatable_insns() const {
902 return make_range(mutatable_insns_begin(), mutatable_insns_end());
903 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000904 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000905 bool R = MutatableInsns.erase(InsnMatcher);
906 assert(R && "Reserving a mutatable insn that isn't available");
907 (void)R;
908 }
909
Daniel Sanders7438b262017-10-31 23:03:18 +0000910 action_iterator actions_begin() { return Actions.begin(); }
911 action_iterator actions_end() { return Actions.end(); }
912 iterator_range<action_iterator> actions() {
913 return make_range(actions_begin(), actions_end());
914 }
915
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000916 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
917
Matt Arsenault3e45c702019-09-06 20:32:37 +0000918 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
919
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000920 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
921 unsigned RendererID, unsigned SubOperandID) {
922 if (ComplexSubOperands.count(SymbolicName))
923 return failedImport(
924 "Complex suboperand referenced more than once (Operand: " +
925 SymbolicName + ")");
926
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000927 ComplexSubOperands[SymbolicName] =
928 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000929
930 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000931 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000932
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000933 Optional<DefinedComplexPatternSubOperand>
934 getComplexSubOperand(StringRef SymbolicName) const {
935 const auto &I = ComplexSubOperands.find(SymbolicName);
936 if (I == ComplexSubOperands.end())
937 return None;
938 return I->second;
939 }
940
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000941 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000942 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000943 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000944
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000945 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000946 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000947
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000948 /// Compare the priority of this object and B.
949 ///
950 /// Returns true if this object is more important than B.
951 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000952
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000953 /// Report the maximum number of temporary operands needed by the rule
954 /// matcher.
955 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000956
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000957 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
958 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000959 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000960 bool hasFirstCondition() const override;
961 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000962 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000963
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000964 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000965 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000966
967 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000968 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000969
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000970 iterator_range<MatchersTy::iterator> insnmatchers() {
971 return make_range(Matchers.begin(), Matchers.end());
972 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000973 bool insnmatchers_empty() const { return Matchers.empty(); }
974 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000975};
976
Daniel Sandersf76f3152017-11-16 00:46:35 +0000977uint64_t RuleMatcher::NextRuleID = 0;
978
Daniel Sanders7438b262017-10-31 23:03:18 +0000979using action_iterator = RuleMatcher::action_iterator;
980
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000981template <class PredicateTy> class PredicateListMatcher {
982private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000983 /// Template instantiations should specialize this to return a string to use
984 /// for the comment emitted when there are no predicates.
985 std::string getNoPredicateComment() const;
986
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000987protected:
988 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
989 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000990
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000991 /// Track if the list of predicates was manipulated by one of the optimization
992 /// methods.
993 bool Optimized = false;
994
995public:
996 /// Construct a new predicate and add it to the matcher.
997 template <class Kind, class... Args>
998 Optional<Kind *> addPredicate(Args &&... args);
999
1000 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001001 return Predicates.begin();
1002 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001003 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001004 return Predicates.end();
1005 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001006 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001007 return make_range(predicates_begin(), predicates_end());
1008 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001009 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001010 return Predicates.size();
1011 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001012 bool predicates_empty() const { return Predicates.empty(); }
1013
1014 std::unique_ptr<PredicateTy> predicates_pop_front() {
1015 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001016 Predicates.pop_front();
1017 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001018 return Front;
1019 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001020
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001021 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1022 Predicates.push_front(std::move(Predicate));
1023 }
1024
1025 void eraseNullPredicates() {
1026 const auto NewEnd =
1027 std::stable_partition(Predicates.begin(), Predicates.end(),
1028 std::logical_not<std::unique_ptr<PredicateTy>>());
1029 if (NewEnd != Predicates.begin()) {
1030 Predicates.erase(Predicates.begin(), NewEnd);
1031 Optimized = true;
1032 }
1033 }
1034
Daniel Sanders9d662d22017-07-06 10:06:12 +00001035 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001036 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001037 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1038 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001039 Table << MatchTable::Comment(getNoPredicateComment())
1040 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001041 return;
1042 }
1043
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001044 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001045 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001046 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001047};
1048
Quentin Colombet063d7982017-12-14 23:44:07 +00001049class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001050public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001051 /// This enum is used for RTTI and also defines the priority that is given to
1052 /// the predicate when generating the matcher code. Kinds with higher priority
1053 /// must be tested first.
1054 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001055 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1056 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1057 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001058 ///
1059 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1060 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001061 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001062 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001063 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001064 IPM_ImmPredicate,
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001065 IPM_Imm,
Quentin Colombet063d7982017-12-14 23:44:07 +00001066 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001067 IPM_MemoryLLTSize,
1068 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001069 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001070 IPM_MemoryAlignment,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001071 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001072 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001073 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001074 OPM_IntrinsicID,
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001075 OPM_CmpPredicate,
Daniel Sanders05540042017-08-08 10:44:31 +00001076 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001077 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001078 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001079 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001080 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001081 OPM_RegBank,
1082 OPM_MBB,
1083 };
1084
1085protected:
1086 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001087 unsigned InsnVarID;
1088 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001089
1090public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001091 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1092 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001093
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001094 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001095 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001096
Quentin Colombet063d7982017-12-14 23:44:07 +00001097 virtual ~PredicateMatcher() = default;
1098 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001099 virtual void emitPredicateOpcodes(MatchTable &Table,
1100 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001101
Daniel Sanders759ff412017-02-24 13:58:11 +00001102 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001103
1104 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001105 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1106 OpIdx == B.OpIdx;
1107 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001108
1109 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1110 return hasValue() && PredicateMatcher::isIdentical(B);
1111 }
1112
1113 virtual MatchTableRecord getValue() const {
1114 assert(hasValue() && "Can not get a value of a value-less predicate!");
1115 llvm_unreachable("Not implemented yet");
1116 }
1117 virtual bool hasValue() const { return false; }
1118
1119 /// Report the maximum number of temporary operands needed by the predicate
1120 /// matcher.
1121 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001122};
1123
1124/// Generates code to check a predicate of an operand.
1125///
1126/// Typical predicates include:
1127/// * Operand is a particular register.
1128/// * Operand is assigned a particular register bank.
1129/// * Operand is an MBB.
1130class OperandPredicateMatcher : public PredicateMatcher {
1131public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001132 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1133 unsigned OpIdx)
1134 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001135 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001136
Daniel Sanders759ff412017-02-24 13:58:11 +00001137 /// Compare the priority of this object and B.
1138 ///
1139 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001140 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001141};
1142
Daniel Sanders2c269f62017-08-24 09:11:20 +00001143template <>
1144std::string
1145PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1146 return "No operand predicates";
1147}
1148
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001149/// Generates code to check that a register operand is defined by the same exact
1150/// one as another.
1151class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001152 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001153
1154public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001155 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001156 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1157 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001158
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001159 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001160 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001161 }
1162
Quentin Colombetaad20be2017-12-15 23:07:42 +00001163 void emitPredicateOpcodes(MatchTable &Table,
1164 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001165
1166 bool isIdentical(const PredicateMatcher &B) const override {
1167 return OperandPredicateMatcher::isIdentical(B) &&
1168 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1169 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001170};
1171
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001172/// Generates code to check that an operand is a particular LLT.
1173class LLTOperandMatcher : public OperandPredicateMatcher {
1174protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001175 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001176
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001177public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001178 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1179
1180 static void initTypeIDValuesMap() {
1181 TypeIDValues.clear();
1182
1183 unsigned ID = 0;
Mark de Wevere8d448e2019-12-22 18:58:32 +01001184 for (const LLTCodeGen &LLTy : KnownTypes)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001185 TypeIDValues[LLTy] = ID++;
1186 }
1187
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001188 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001189 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001190 KnownTypes.insert(Ty);
1191 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001192
Quentin Colombet063d7982017-12-14 23:44:07 +00001193 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001194 return P->getKind() == OPM_LLT;
1195 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001196 bool isIdentical(const PredicateMatcher &B) const override {
1197 return OperandPredicateMatcher::isIdentical(B) &&
1198 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1199 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001200 MatchTableRecord getValue() const override {
1201 const auto VI = TypeIDValues.find(Ty);
1202 if (VI == TypeIDValues.end())
1203 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1204 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1205 }
1206 bool hasValue() const override {
1207 if (TypeIDValues.size() != KnownTypes.size())
1208 initTypeIDValuesMap();
1209 return TypeIDValues.count(Ty);
1210 }
1211
1212 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001213
Quentin Colombetaad20be2017-12-15 23:07:42 +00001214 void emitPredicateOpcodes(MatchTable &Table,
1215 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001216 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1217 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1218 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001219 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001220 }
1221};
1222
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001223std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1224
Daniel Sandersa71f4542017-10-16 00:56:30 +00001225/// Generates code to check that an operand is a pointer to any address space.
1226///
1227/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1228/// result, iN is used to describe a pointer of N bits to any address space and
1229/// PatFrag predicates are typically used to constrain the address space. There's
1230/// no reliable means to derive the missing type information from the pattern so
1231/// imported rules must test the components of a pointer separately.
1232///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001233/// If SizeInBits is zero, then the pointer size will be obtained from the
1234/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001235class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1236protected:
1237 unsigned SizeInBits;
1238
1239public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001240 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1241 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001242 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1243 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001244
1245 static bool classof(const OperandPredicateMatcher *P) {
1246 return P->getKind() == OPM_PointerToAny;
1247 }
1248
Quentin Colombetaad20be2017-12-15 23:07:42 +00001249 void emitPredicateOpcodes(MatchTable &Table,
1250 RuleMatcher &Rule) const override {
1251 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1252 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1253 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1254 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001255 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1256 }
1257};
1258
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001259/// Generates code to check that an operand is a particular target constant.
1260class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1261protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001262 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001263 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001264
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001265 unsigned getAllocatedTemporariesBaseID() const;
1266
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001267public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001268 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1269
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001270 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1271 const OperandMatcher &Operand,
1272 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001273 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1274 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001275
Quentin Colombet063d7982017-12-14 23:44:07 +00001276 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001277 return P->getKind() == OPM_ComplexPattern;
1278 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001279
Quentin Colombetaad20be2017-12-15 23:07:42 +00001280 void emitPredicateOpcodes(MatchTable &Table,
1281 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001282 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001283 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1284 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1285 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1286 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1287 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1288 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001289 }
1290
Daniel Sanders2deea182017-04-22 15:11:04 +00001291 unsigned countRendererFns() const override {
1292 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001293 }
1294};
1295
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001296/// Generates code to check that an operand is in a particular register bank.
1297class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1298protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001299 const CodeGenRegisterClass &RC;
1300
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001301public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001302 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1303 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001304 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001305
Quentin Colombet893e0f12017-12-15 23:24:39 +00001306 bool isIdentical(const PredicateMatcher &B) const override {
1307 return OperandPredicateMatcher::isIdentical(B) &&
1308 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1309 }
1310
Quentin Colombet063d7982017-12-14 23:44:07 +00001311 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001312 return P->getKind() == OPM_RegBank;
1313 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001314
Quentin Colombetaad20be2017-12-15 23:07:42 +00001315 void emitPredicateOpcodes(MatchTable &Table,
1316 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001317 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1318 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1319 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1320 << MatchTable::Comment("RC")
1321 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1322 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001323 }
1324};
1325
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001326/// Generates code to check that an operand is a basic block.
1327class MBBOperandMatcher : public OperandPredicateMatcher {
1328public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001329 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1330 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001331
Quentin Colombet063d7982017-12-14 23:44:07 +00001332 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001333 return P->getKind() == OPM_MBB;
1334 }
1335
Quentin Colombetaad20be2017-12-15 23:07:42 +00001336 void emitPredicateOpcodes(MatchTable &Table,
1337 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001338 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1339 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1340 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001341 }
1342};
1343
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001344class ImmOperandMatcher : public OperandPredicateMatcher {
1345public:
1346 ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1347 : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1348
1349 static bool classof(const PredicateMatcher *P) {
1350 return P->getKind() == IPM_Imm;
1351 }
1352
1353 void emitPredicateOpcodes(MatchTable &Table,
1354 RuleMatcher &Rule) const override {
1355 Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1356 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1357 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1358 }
1359};
1360
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001361/// Generates code to check that an operand is a G_CONSTANT with a particular
1362/// int.
1363class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001364protected:
1365 int64_t Value;
1366
1367public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001368 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001369 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001370
Quentin Colombet893e0f12017-12-15 23:24:39 +00001371 bool isIdentical(const PredicateMatcher &B) const override {
1372 return OperandPredicateMatcher::isIdentical(B) &&
1373 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1374 }
1375
Quentin Colombet063d7982017-12-14 23:44:07 +00001376 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001377 return P->getKind() == OPM_Int;
1378 }
1379
Quentin Colombetaad20be2017-12-15 23:07:42 +00001380 void emitPredicateOpcodes(MatchTable &Table,
1381 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001382 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1383 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1384 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1385 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001386 }
1387};
1388
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001389/// Generates code to check that an operand is a raw int (where MO.isImm() or
1390/// MO.isCImm() is true).
1391class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1392protected:
1393 int64_t Value;
1394
1395public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001396 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001397 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1398 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001399
Quentin Colombet893e0f12017-12-15 23:24:39 +00001400 bool isIdentical(const PredicateMatcher &B) const override {
1401 return OperandPredicateMatcher::isIdentical(B) &&
1402 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1403 }
1404
Quentin Colombet063d7982017-12-14 23:44:07 +00001405 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001406 return P->getKind() == OPM_LiteralInt;
1407 }
1408
Quentin Colombetaad20be2017-12-15 23:07:42 +00001409 void emitPredicateOpcodes(MatchTable &Table,
1410 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001411 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1412 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1413 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1414 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001415 }
1416};
1417
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001418/// Generates code to check that an operand is an CmpInst predicate
1419class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1420protected:
1421 std::string PredName;
1422
1423public:
1424 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1425 std::string P)
1426 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1427
1428 bool isIdentical(const PredicateMatcher &B) const override {
1429 return OperandPredicateMatcher::isIdentical(B) &&
1430 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1431 }
1432
1433 static bool classof(const PredicateMatcher *P) {
1434 return P->getKind() == OPM_CmpPredicate;
1435 }
1436
1437 void emitPredicateOpcodes(MatchTable &Table,
1438 RuleMatcher &Rule) const override {
1439 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1440 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1441 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1442 << MatchTable::Comment("Predicate")
1443 << MatchTable::NamedValue("CmpInst", PredName)
1444 << MatchTable::LineBreak;
1445 }
1446};
1447
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001448/// Generates code to check that an operand is an intrinsic ID.
1449class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1450protected:
1451 const CodeGenIntrinsic *II;
1452
1453public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001454 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1455 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001456 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001457
Quentin Colombet893e0f12017-12-15 23:24:39 +00001458 bool isIdentical(const PredicateMatcher &B) const override {
1459 return OperandPredicateMatcher::isIdentical(B) &&
1460 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1461 }
1462
Quentin Colombet063d7982017-12-14 23:44:07 +00001463 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001464 return P->getKind() == OPM_IntrinsicID;
1465 }
1466
Quentin Colombetaad20be2017-12-15 23:07:42 +00001467 void emitPredicateOpcodes(MatchTable &Table,
1468 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001469 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1470 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1471 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1472 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1473 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001474 }
1475};
1476
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001477/// Generates code to check that a set of predicates match for a particular
1478/// operand.
1479class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1480protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001481 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001482 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001483 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001484
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001485 /// The index of the first temporary variable allocated to this operand. The
1486 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001487 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001488 unsigned AllocatedTemporariesBaseID;
1489
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001490public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001491 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001492 const std::string &SymbolicName,
1493 unsigned AllocatedTemporariesBaseID)
1494 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1495 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001496
1497 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1498 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001499 void setSymbolicName(StringRef Name) {
1500 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1501 SymbolicName = Name;
1502 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001503
1504 /// Construct a new operand predicate and add it to the matcher.
1505 template <class Kind, class... Args>
1506 Optional<Kind *> addPredicate(Args &&... args) {
1507 if (isSameAsAnotherOperand())
1508 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001509 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001510 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1511 return static_cast<Kind *>(Predicates.back().get());
1512 }
1513
1514 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001515 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001516
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001517 std::string getOperandExpr(unsigned InsnVarID) const {
1518 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1519 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001520 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001521
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001522 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1523
Daniel Sandersa71f4542017-10-16 00:56:30 +00001524 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001525 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001526
Daniel Sanders9d662d22017-07-06 10:06:12 +00001527 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001528 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001529 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1530 if (!Optimized) {
1531 std::string Comment;
1532 raw_string_ostream CommentOS(Comment);
1533 CommentOS << "MIs[" << getInsnVarID() << "] ";
1534 if (SymbolicName.empty())
1535 CommentOS << "Operand " << OpIdx;
1536 else
1537 CommentOS << SymbolicName;
1538 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1539 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001540
Quentin Colombetaad20be2017-12-15 23:07:42 +00001541 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001542 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001543
1544 /// Compare the priority of this object and B.
1545 ///
1546 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001547 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001548 // Operand matchers involving more predicates have higher priority.
1549 if (predicates_size() > B.predicates_size())
1550 return true;
1551 if (predicates_size() < B.predicates_size())
1552 return false;
1553
1554 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001555 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001556 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1557 return true;
1558 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1559 return false;
1560 }
1561
1562 return false;
1563 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001564
1565 /// Report the maximum number of temporary operands needed by the operand
1566 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001567 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001568 return std::accumulate(
1569 predicates().begin(), predicates().end(), 0,
1570 [](unsigned A,
1571 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001572 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001573 });
1574 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001575
1576 unsigned getAllocatedTemporariesBaseID() const {
1577 return AllocatedTemporariesBaseID;
1578 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001579
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001580 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001581 for (const auto &Predicate : predicates())
1582 if (isa<SameOperandMatcher>(Predicate))
1583 return true;
1584 return false;
1585 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001586};
1587
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001588Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001589 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001590 if (!VTy.isMachineValueType())
1591 return failedImport("unsupported typeset");
1592
1593 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1594 addPredicate<PointerToAnyOperandMatcher>(0);
1595 return Error::success();
1596 }
1597
1598 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1599 if (!OpTyOrNone)
1600 return failedImport("unsupported type");
1601
1602 if (OperandIsAPointer)
1603 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001604 else if (VTy.isPointer())
1605 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1606 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001607 else
1608 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1609 return Error::success();
1610}
1611
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001612unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1613 return Operand.getAllocatedTemporariesBaseID();
1614}
1615
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001616/// Generates code to check a predicate on an instruction.
1617///
1618/// Typical predicates include:
1619/// * The opcode of the instruction is a particular value.
1620/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001621class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001622public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001623 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1624 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001625 virtual ~InstructionPredicateMatcher() {}
1626
Daniel Sanders759ff412017-02-24 13:58:11 +00001627 /// Compare the priority of this object and B.
1628 ///
1629 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001630 virtual bool
1631 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001632 return Kind < B.Kind;
1633 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001634};
1635
Daniel Sanders2c269f62017-08-24 09:11:20 +00001636template <>
1637std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001638PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001639 return "No instruction predicates";
1640}
1641
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001642/// Generates code to check the opcode of an instruction.
1643class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1644protected:
1645 const CodeGenInstruction *I;
1646
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001647 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1648
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001649public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001650 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1651 OpcodeValues.clear();
1652
1653 unsigned OpcodeValue = 0;
1654 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1655 OpcodeValues[I] = OpcodeValue++;
1656 }
1657
Quentin Colombetaad20be2017-12-15 23:07:42 +00001658 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1659 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001660
Quentin Colombet063d7982017-12-14 23:44:07 +00001661 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001662 return P->getKind() == IPM_Opcode;
1663 }
1664
Quentin Colombet893e0f12017-12-15 23:24:39 +00001665 bool isIdentical(const PredicateMatcher &B) const override {
1666 return InstructionPredicateMatcher::isIdentical(B) &&
1667 I == cast<InstructionOpcodeMatcher>(&B)->I;
1668 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001669 MatchTableRecord getValue() const override {
1670 const auto VI = OpcodeValues.find(I);
1671 if (VI != OpcodeValues.end())
1672 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1673 VI->second);
1674 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1675 }
1676 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001677
Quentin Colombetaad20be2017-12-15 23:07:42 +00001678 void emitPredicateOpcodes(MatchTable &Table,
1679 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001680 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001681 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001682 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001683 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001684
1685 /// Compare the priority of this object and B.
1686 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001687 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001688 bool
1689 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001690 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1691 return true;
1692 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1693 return false;
1694
1695 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1696 // this is cosmetic at the moment, we may want to drive a similar ordering
1697 // using instruction frequency information to improve compile time.
1698 if (const InstructionOpcodeMatcher *BO =
1699 dyn_cast<InstructionOpcodeMatcher>(&B))
1700 return I->TheDef->getName() < BO->I->TheDef->getName();
1701
1702 return false;
1703 };
Daniel Sanders05540042017-08-08 10:44:31 +00001704
1705 bool isConstantInstruction() const {
1706 return I->TheDef->getName() == "G_CONSTANT";
1707 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001708
Roman Tereshin19da6672018-05-22 04:31:50 +00001709 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshin6082a062019-10-30 20:58:46 -07001710 bool isVariadicNumOperands() const { return I->Operands.isVariadic; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001711
1712 StringRef getOperandType(unsigned OpIdx) const {
1713 return I->Operands[OpIdx].OperandType;
1714 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001715};
1716
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001717DenseMap<const CodeGenInstruction *, unsigned>
1718 InstructionOpcodeMatcher::OpcodeValues;
1719
Roman Tereshin19da6672018-05-22 04:31:50 +00001720class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1721 unsigned NumOperands = 0;
1722
1723public:
1724 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1725 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1726 NumOperands(NumOperands) {}
1727
1728 static bool classof(const PredicateMatcher *P) {
1729 return P->getKind() == IPM_NumOperands;
1730 }
1731
1732 bool isIdentical(const PredicateMatcher &B) const override {
1733 return InstructionPredicateMatcher::isIdentical(B) &&
1734 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1735 }
1736
1737 void emitPredicateOpcodes(MatchTable &Table,
1738 RuleMatcher &Rule) const override {
1739 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1740 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1741 << MatchTable::Comment("Expected")
1742 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1743 }
1744};
1745
Daniel Sanders2c269f62017-08-24 09:11:20 +00001746/// Generates code to check that this instruction is a constant whose value
1747/// meets an immediate predicate.
1748///
1749/// Immediates are slightly odd since they are typically used like an operand
1750/// but are represented as an operator internally. We typically write simm8:$src
1751/// in a tablegen pattern, but this is just syntactic sugar for
1752/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1753/// that will be matched and the predicate (which is attached to the imm
1754/// operator) that will be tested. In SelectionDAG this describes a
1755/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1756///
1757/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1758/// this representation, the immediate could be tested with an
1759/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1760/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1761/// there are two implementation issues with producing that matcher
1762/// configuration from the SelectionDAG pattern:
1763/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1764/// were we to sink the immediate predicate to the operand we would have to
1765/// have two partial implementations of PatFrag support, one for immediates
1766/// and one for non-immediates.
1767/// * At the point we handle the predicate, the OperandMatcher hasn't been
1768/// created yet. If we were to sink the predicate to the OperandMatcher we
1769/// would also have to complicate (or duplicate) the code that descends and
1770/// creates matchers for the subtree.
1771/// Overall, it's simpler to handle it in the place it was found.
1772class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1773protected:
1774 TreePredicateFn Predicate;
1775
1776public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001777 InstructionImmPredicateMatcher(unsigned InsnVarID,
1778 const TreePredicateFn &Predicate)
1779 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1780 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001781
Quentin Colombet893e0f12017-12-15 23:24:39 +00001782 bool isIdentical(const PredicateMatcher &B) const override {
1783 return InstructionPredicateMatcher::isIdentical(B) &&
1784 Predicate.getOrigPatFragRecord() ==
1785 cast<InstructionImmPredicateMatcher>(&B)
1786 ->Predicate.getOrigPatFragRecord();
1787 }
1788
Quentin Colombet063d7982017-12-14 23:44:07 +00001789 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001790 return P->getKind() == IPM_ImmPredicate;
1791 }
1792
Quentin Colombetaad20be2017-12-15 23:07:42 +00001793 void emitPredicateOpcodes(MatchTable &Table,
1794 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001795 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001796 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1797 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001798 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001799 << MatchTable::LineBreak;
1800 }
1801};
1802
Daniel Sanders76664652017-11-28 22:07:05 +00001803/// Generates code to check that a memory instruction has a atomic ordering
1804/// MachineMemoryOperand.
1805class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001806public:
1807 enum AOComparator {
1808 AO_Exactly,
1809 AO_OrStronger,
1810 AO_WeakerThan,
1811 };
1812
1813protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001814 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001815 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001816
Daniel Sanders39690bd2017-10-15 02:41:12 +00001817public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001818 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001819 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001820 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1821 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001822
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001823 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001824 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001825 }
1826
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001827 bool isIdentical(const PredicateMatcher &B) const override {
1828 if (!InstructionPredicateMatcher::isIdentical(B))
1829 return false;
1830 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1831 return Order == R.Order && Comparator == R.Comparator;
1832 }
1833
Quentin Colombetaad20be2017-12-15 23:07:42 +00001834 void emitPredicateOpcodes(MatchTable &Table,
1835 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001836 StringRef Opcode = "GIM_CheckAtomicOrdering";
1837
1838 if (Comparator == AO_OrStronger)
1839 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1840 if (Comparator == AO_WeakerThan)
1841 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1842
1843 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1844 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001845 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001846 << MatchTable::LineBreak;
1847 }
1848};
1849
Daniel Sandersf84bc372018-05-05 20:53:24 +00001850/// Generates code to check that the size of an MMO is exactly N bytes.
1851class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1852protected:
1853 unsigned MMOIdx;
1854 uint64_t Size;
1855
1856public:
1857 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1858 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1859 MMOIdx(MMOIdx), Size(Size) {}
1860
1861 static bool classof(const PredicateMatcher *P) {
1862 return P->getKind() == IPM_MemoryLLTSize;
1863 }
1864 bool isIdentical(const PredicateMatcher &B) const override {
1865 return InstructionPredicateMatcher::isIdentical(B) &&
1866 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1867 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1868 }
1869
1870 void emitPredicateOpcodes(MatchTable &Table,
1871 RuleMatcher &Rule) const override {
1872 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1873 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1874 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1875 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1876 << MatchTable::LineBreak;
1877 }
1878};
1879
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001880class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1881protected:
1882 unsigned MMOIdx;
1883 SmallVector<unsigned, 4> AddrSpaces;
1884
1885public:
1886 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1887 ArrayRef<unsigned> AddrSpaces)
1888 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1889 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1890
1891 static bool classof(const PredicateMatcher *P) {
1892 return P->getKind() == IPM_MemoryAddressSpace;
1893 }
1894 bool isIdentical(const PredicateMatcher &B) const override {
1895 if (!InstructionPredicateMatcher::isIdentical(B))
1896 return false;
1897 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1898 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1899 }
1900
1901 void emitPredicateOpcodes(MatchTable &Table,
1902 RuleMatcher &Rule) const override {
1903 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1904 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1905 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1906 // Encode number of address spaces to expect.
1907 << MatchTable::Comment("NumAddrSpace")
1908 << MatchTable::IntValue(AddrSpaces.size());
1909 for (unsigned AS : AddrSpaces)
1910 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1911
1912 Table << MatchTable::LineBreak;
1913 }
1914};
1915
Matt Arsenault52c26242019-07-31 00:14:43 +00001916class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1917protected:
1918 unsigned MMOIdx;
1919 int MinAlign;
1920
1921public:
1922 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1923 int MinAlign)
1924 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1925 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1926 assert(MinAlign > 0);
1927 }
1928
1929 static bool classof(const PredicateMatcher *P) {
1930 return P->getKind() == IPM_MemoryAlignment;
1931 }
1932
1933 bool isIdentical(const PredicateMatcher &B) const override {
1934 if (!InstructionPredicateMatcher::isIdentical(B))
1935 return false;
1936 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1937 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1938 }
1939
1940 void emitPredicateOpcodes(MatchTable &Table,
1941 RuleMatcher &Rule) const override {
1942 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1943 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1944 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1945 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1946 << MatchTable::LineBreak;
1947 }
1948};
1949
Daniel Sandersf84bc372018-05-05 20:53:24 +00001950/// Generates code to check that the size of an MMO is less-than, equal-to, or
1951/// greater than a given LLT.
1952class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1953public:
1954 enum RelationKind {
1955 GreaterThan,
1956 EqualTo,
1957 LessThan,
1958 };
1959
1960protected:
1961 unsigned MMOIdx;
1962 RelationKind Relation;
1963 unsigned OpIdx;
1964
1965public:
1966 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1967 enum RelationKind Relation,
1968 unsigned OpIdx)
1969 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1970 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1971
1972 static bool classof(const PredicateMatcher *P) {
1973 return P->getKind() == IPM_MemoryVsLLTSize;
1974 }
1975 bool isIdentical(const PredicateMatcher &B) const override {
1976 return InstructionPredicateMatcher::isIdentical(B) &&
1977 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1978 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1979 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1980 }
1981
1982 void emitPredicateOpcodes(MatchTable &Table,
1983 RuleMatcher &Rule) const override {
1984 Table << MatchTable::Opcode(Relation == EqualTo
1985 ? "GIM_CheckMemorySizeEqualToLLT"
1986 : Relation == GreaterThan
1987 ? "GIM_CheckMemorySizeGreaterThanLLT"
1988 : "GIM_CheckMemorySizeLessThanLLT")
1989 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1990 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1991 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1992 << MatchTable::LineBreak;
1993 }
1994};
1995
Daniel Sanders8ead1292018-06-15 23:13:43 +00001996/// Generates code to check an arbitrary C++ instruction predicate.
1997class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1998protected:
1999 TreePredicateFn Predicate;
2000
2001public:
2002 GenericInstructionPredicateMatcher(unsigned InsnVarID,
2003 TreePredicateFn Predicate)
2004 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2005 Predicate(Predicate) {}
2006
2007 static bool classof(const InstructionPredicateMatcher *P) {
2008 return P->getKind() == IPM_GenericPredicate;
2009 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00002010 bool isIdentical(const PredicateMatcher &B) const override {
2011 return InstructionPredicateMatcher::isIdentical(B) &&
2012 Predicate ==
2013 static_cast<const GenericInstructionPredicateMatcher &>(B)
2014 .Predicate;
2015 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00002016 void emitPredicateOpcodes(MatchTable &Table,
2017 RuleMatcher &Rule) const override {
2018 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2019 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2020 << MatchTable::Comment("FnId")
2021 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2022 << MatchTable::LineBreak;
2023 }
2024};
2025
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002026/// Generates code to check that a set of predicates and operands match for a
2027/// particular instruction.
2028///
2029/// Typical predicates include:
2030/// * Has a specific opcode.
2031/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002032class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002033protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002034 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002035
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002036 RuleMatcher &Rule;
2037
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002038 /// The operands to match. All rendered operands must be present even if the
2039 /// condition is always true.
2040 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002041 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002042
Daniel Sanders05540042017-08-08 10:44:31 +00002043 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002044 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002045
Matt Arsenault3e45c702019-09-06 20:32:37 +00002046 /// PhysRegInputs - List list has an entry for each explicitly specified
2047 /// physreg input to the pattern. The first elt is the Register node, the
2048 /// second is the recorded slot number the input pattern match saved it in.
2049 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2050
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002051public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002052 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002053 : Rule(Rule), SymbolicName(SymbolicName) {
2054 // We create a new instruction matcher.
2055 // Get a new ID for that instruction.
2056 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2057 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002058
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002059 /// Construct a new instruction predicate and add it to the matcher.
2060 template <class Kind, class... Args>
2061 Optional<Kind *> addPredicate(Args &&... args) {
2062 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002063 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002064 return static_cast<Kind *>(Predicates.back().get());
2065 }
2066
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002067 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002068
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002069 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002070
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002071 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002072 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2073 unsigned AllocatedTemporariesBaseID) {
2074 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2075 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002076 if (!SymbolicName.empty())
2077 Rule.defineOperand(SymbolicName, *Operands.back());
2078
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002079 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002080 }
2081
Daniel Sandersffc7d582017-03-29 15:37:18 +00002082 OperandMatcher &getOperand(unsigned OpIdx) {
2083 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002084 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002085 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002086 });
2087 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002088 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002089 llvm_unreachable("Failed to lookup operand");
2090 }
2091
Matt Arsenault3e45c702019-09-06 20:32:37 +00002092 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2093 unsigned TempOpIdx) {
2094 assert(SymbolicName.empty());
2095 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2096 Operands.emplace_back(OM);
2097 Rule.definePhysRegOperand(Reg, *OM);
2098 PhysRegInputs.emplace_back(Reg, OpIdx);
2099 return *OM;
2100 }
2101
2102 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2103 return PhysRegInputs;
2104 }
2105
Daniel Sanders05540042017-08-08 10:44:31 +00002106 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002107 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002108 OperandVec::iterator operands_begin() { return Operands.begin(); }
2109 OperandVec::iterator operands_end() { return Operands.end(); }
2110 iterator_range<OperandVec::iterator> operands() {
2111 return make_range(operands_begin(), operands_end());
2112 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002113 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2114 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002115 iterator_range<OperandVec::const_iterator> operands() const {
2116 return make_range(operands_begin(), operands_end());
2117 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002118 bool operands_empty() const { return Operands.empty(); }
2119
2120 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002121
Roman Tereshin19da6672018-05-22 04:31:50 +00002122 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002123
2124 /// Emit MatchTable opcodes that test whether the instruction named in
2125 /// InsnVarName matches all the predicates and all the operands.
2126 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002127 if (NumOperandsCheck)
2128 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2129 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002130
Quentin Colombetaad20be2017-12-15 23:07:42 +00002131 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002132
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002133 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002134 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002135 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002136
2137 /// Compare the priority of this object and B.
2138 ///
2139 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002140 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002141 // Instruction matchers involving more operands have higher priority.
2142 if (Operands.size() > B.Operands.size())
2143 return true;
2144 if (Operands.size() < B.Operands.size())
2145 return false;
2146
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002147 for (auto &&P : zip(predicates(), B.predicates())) {
2148 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2149 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2150 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002151 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002152 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002153 return false;
2154 }
2155
Mark de Wevere8d448e2019-12-22 18:58:32 +01002156 for (auto Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002157 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002158 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002159 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002160 return false;
2161 }
2162
2163 return false;
2164 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002165
2166 /// Report the maximum number of temporary operands needed by the instruction
2167 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002168 unsigned countRendererFns() {
2169 return std::accumulate(
2170 predicates().begin(), predicates().end(), 0,
2171 [](unsigned A,
2172 const std::unique_ptr<PredicateMatcher> &Predicate) {
2173 return A + Predicate->countRendererFns();
2174 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002175 std::accumulate(
2176 Operands.begin(), Operands.end(), 0,
2177 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002178 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002179 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002180 }
Daniel Sanders05540042017-08-08 10:44:31 +00002181
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002182 InstructionOpcodeMatcher &getOpcodeMatcher() {
2183 for (auto &P : predicates())
2184 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2185 return *OpMatcher;
2186 llvm_unreachable("Didn't find an opcode matcher");
2187 }
2188
2189 bool isConstantInstruction() {
2190 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002191 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002192
2193 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002194};
2195
Roman Tereshin19da6672018-05-22 04:31:50 +00002196StringRef RuleMatcher::getOpcode() const {
2197 return Matchers.front()->getOpcode();
2198}
2199
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002200unsigned RuleMatcher::getNumOperands() const {
2201 return Matchers.front()->getNumOperands();
2202}
2203
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002204LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2205 InstructionMatcher &InsnMatcher = *Matchers.front();
2206 if (!InsnMatcher.predicates_empty())
2207 if (const auto *TM =
2208 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2209 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2210 return TM->getTy();
2211 return {};
2212}
2213
Daniel Sandersbee57392017-04-04 13:25:23 +00002214/// Generates code to check that the operand is a register defined by an
2215/// instruction that matches the given instruction matcher.
2216///
2217/// For example, the pattern:
2218/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2219/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2220/// the:
2221/// (G_ADD $src1, $src2)
2222/// subpattern.
2223class InstructionOperandMatcher : public OperandPredicateMatcher {
2224protected:
2225 std::unique_ptr<InstructionMatcher> InsnMatcher;
2226
2227public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002228 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2229 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002230 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002231 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002232
Quentin Colombet063d7982017-12-14 23:44:07 +00002233 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002234 return P->getKind() == OPM_Instruction;
2235 }
2236
2237 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2238
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002239 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2240 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2241 Table << MatchTable::Opcode("GIM_RecordInsn")
2242 << MatchTable::Comment("DefineMI")
2243 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2244 << MatchTable::IntValue(getInsnVarID())
2245 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2246 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2247 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002248 }
2249
Quentin Colombetaad20be2017-12-15 23:07:42 +00002250 void emitPredicateOpcodes(MatchTable &Table,
2251 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002252 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002253 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002254 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002255
2256 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2257 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2258 return true;
2259 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2260 return false;
2261
2262 if (const InstructionOperandMatcher *BP =
2263 dyn_cast<InstructionOperandMatcher>(&B))
2264 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2265 return true;
2266 return false;
2267 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002268};
2269
Roman Tereshin19da6672018-05-22 04:31:50 +00002270void InstructionMatcher::optimize() {
2271 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2272 const auto &OpcMatcher = getOpcodeMatcher();
2273
2274 Stash.push_back(predicates_pop_front());
2275 if (Stash.back().get() == &OpcMatcher) {
Roman Tereshin6082a062019-10-30 20:58:46 -07002276 if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
Roman Tereshin19da6672018-05-22 04:31:50 +00002277 Stash.emplace_back(
2278 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2279 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002280
2281 for (auto &OM : Operands)
2282 for (auto &OP : OM->predicates())
2283 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2284 Stash.push_back(std::move(OP));
2285 OM->eraseNullPredicates();
2286 break;
2287 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002288 }
2289
2290 if (InsnVarID > 0) {
2291 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2292 for (auto &OP : Operands[0]->predicates())
2293 OP.reset();
2294 Operands[0]->eraseNullPredicates();
2295 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002296 for (auto &OM : Operands) {
2297 for (auto &OP : OM->predicates())
2298 if (isa<LLTOperandMatcher>(OP))
2299 Stash.push_back(std::move(OP));
2300 OM->eraseNullPredicates();
2301 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002302 while (!Stash.empty())
2303 prependPredicate(Stash.pop_back_val());
2304}
2305
Daniel Sanders43c882c2017-02-01 10:53:10 +00002306//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002307class OperandRenderer {
2308public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002309 enum RendererKind {
2310 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002311 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002312 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002313 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002314 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002315 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002316 OR_Imm,
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002317 OR_SubRegIndex,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002318 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002319 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002320 OR_ComplexPattern,
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002321 OR_Custom,
2322 OR_CustomOperand
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002323 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002324
2325protected:
2326 RendererKind Kind;
2327
2328public:
2329 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2330 virtual ~OperandRenderer() {}
2331
2332 RendererKind getKind() const { return Kind; }
2333
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002334 virtual void emitRenderOpcodes(MatchTable &Table,
2335 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002336};
2337
2338/// A CopyRenderer emits code to copy a single operand from an existing
2339/// instruction to the one being built.
2340class CopyRenderer : public OperandRenderer {
2341protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002342 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002343 /// The name of the operand.
2344 const StringRef SymbolicName;
2345
2346public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002347 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2348 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002349 SymbolicName(SymbolicName) {
2350 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2351 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002352
2353 static bool classof(const OperandRenderer *R) {
2354 return R->getKind() == OR_Copy;
2355 }
2356
2357 const StringRef getSymbolicName() const { return SymbolicName; }
2358
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002359 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002360 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002361 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002362 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2363 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2364 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002365 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002366 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002367 }
2368};
2369
Matt Arsenault3e45c702019-09-06 20:32:37 +00002370/// A CopyRenderer emits code to copy a virtual register to a specific physical
2371/// register.
2372class CopyPhysRegRenderer : public OperandRenderer {
2373protected:
2374 unsigned NewInsnID;
2375 Record *PhysReg;
2376
2377public:
2378 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2379 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2380 PhysReg(Reg) {
2381 assert(PhysReg);
2382 }
2383
2384 static bool classof(const OperandRenderer *R) {
2385 return R->getKind() == OR_CopyPhysReg;
2386 }
2387
2388 Record *getPhysReg() const { return PhysReg; }
2389
2390 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2391 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2392 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2393 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2394 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2395 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2396 << MatchTable::IntValue(Operand.getOpIdx())
2397 << MatchTable::Comment(PhysReg->getName())
2398 << MatchTable::LineBreak;
2399 }
2400};
2401
Daniel Sandersd66e0902017-10-23 18:19:24 +00002402/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2403/// existing instruction to the one being built. If the operand turns out to be
2404/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2405class CopyOrAddZeroRegRenderer : public OperandRenderer {
2406protected:
2407 unsigned NewInsnID;
2408 /// The name of the operand.
2409 const StringRef SymbolicName;
2410 const Record *ZeroRegisterDef;
2411
2412public:
2413 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002414 StringRef SymbolicName, Record *ZeroRegisterDef)
2415 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2416 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2417 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2418 }
2419
2420 static bool classof(const OperandRenderer *R) {
2421 return R->getKind() == OR_CopyOrAddZeroReg;
2422 }
2423
2424 const StringRef getSymbolicName() const { return SymbolicName; }
2425
2426 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2427 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2428 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2429 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2430 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2431 << MatchTable::Comment("OldInsnID")
2432 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002433 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002434 << MatchTable::NamedValue(
2435 (ZeroRegisterDef->getValue("Namespace")
2436 ? ZeroRegisterDef->getValueAsString("Namespace")
2437 : ""),
2438 ZeroRegisterDef->getName())
2439 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2440 }
2441};
2442
Daniel Sanders05540042017-08-08 10:44:31 +00002443/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2444/// an extended immediate operand.
2445class CopyConstantAsImmRenderer : public OperandRenderer {
2446protected:
2447 unsigned NewInsnID;
2448 /// The name of the operand.
2449 const std::string SymbolicName;
2450 bool Signed;
2451
2452public:
2453 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2454 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2455 SymbolicName(SymbolicName), Signed(true) {}
2456
2457 static bool classof(const OperandRenderer *R) {
2458 return R->getKind() == OR_CopyConstantAsImm;
2459 }
2460
2461 const StringRef getSymbolicName() const { return SymbolicName; }
2462
2463 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002464 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002465 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2466 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2467 : "GIR_CopyConstantAsUImm")
2468 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2469 << MatchTable::Comment("OldInsnID")
2470 << MatchTable::IntValue(OldInsnVarID)
2471 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2472 }
2473};
2474
Daniel Sanders11300ce2017-10-13 21:28:03 +00002475/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2476/// instruction to an extended immediate operand.
2477class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2478protected:
2479 unsigned NewInsnID;
2480 /// The name of the operand.
2481 const std::string SymbolicName;
2482
2483public:
2484 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2485 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2486 SymbolicName(SymbolicName) {}
2487
2488 static bool classof(const OperandRenderer *R) {
2489 return R->getKind() == OR_CopyFConstantAsFPImm;
2490 }
2491
2492 const StringRef getSymbolicName() const { return SymbolicName; }
2493
2494 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002495 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002496 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2497 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2498 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2499 << MatchTable::Comment("OldInsnID")
2500 << MatchTable::IntValue(OldInsnVarID)
2501 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2502 }
2503};
2504
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002505/// A CopySubRegRenderer emits code to copy a single register operand from an
2506/// existing instruction to the one being built and indicate that only a
2507/// subregister should be copied.
2508class CopySubRegRenderer : public OperandRenderer {
2509protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002510 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002511 /// The name of the operand.
2512 const StringRef SymbolicName;
2513 /// The subregister to extract.
2514 const CodeGenSubRegIndex *SubReg;
2515
2516public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002517 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2518 const CodeGenSubRegIndex *SubReg)
2519 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002520 SymbolicName(SymbolicName), SubReg(SubReg) {}
2521
2522 static bool classof(const OperandRenderer *R) {
2523 return R->getKind() == OR_CopySubReg;
2524 }
2525
2526 const StringRef getSymbolicName() const { return SymbolicName; }
2527
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002528 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002529 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002530 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002531 Table << MatchTable::Opcode("GIR_CopySubReg")
2532 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2533 << MatchTable::Comment("OldInsnID")
2534 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002535 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002536 << MatchTable::Comment("SubRegIdx")
2537 << MatchTable::IntValue(SubReg->EnumValue)
2538 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002539 }
2540};
2541
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002542/// Adds a specific physical register to the instruction being built.
2543/// This is typically useful for WZR/XZR on AArch64.
2544class AddRegisterRenderer : public OperandRenderer {
2545protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002546 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002547 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002548 bool IsDef;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002549
2550public:
Matt Arsenault3e45c702019-09-06 20:32:37 +00002551 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2552 bool IsDef = false)
2553 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2554 IsDef(IsDef) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002555
2556 static bool classof(const OperandRenderer *R) {
2557 return R->getKind() == OR_Register;
2558 }
2559
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002560 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2561 Table << MatchTable::Opcode("GIR_AddRegister")
2562 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2563 << MatchTable::NamedValue(
2564 (RegisterDef->getValue("Namespace")
2565 ? RegisterDef->getValueAsString("Namespace")
2566 : ""),
2567 RegisterDef->getName())
Matt Arsenault3e45c702019-09-06 20:32:37 +00002568 << MatchTable::Comment("AddRegisterRegFlags");
2569
2570 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2571 // really needed for a physical register reference. We can pack the
2572 // register and flags in a single field.
2573 if (IsDef)
2574 Table << MatchTable::NamedValue("RegState::Define");
2575 else
2576 Table << MatchTable::IntValue(0);
2577 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002578 }
2579};
2580
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002581/// Adds a specific temporary virtual register to the instruction being built.
2582/// This is used to chain instructions together when emitting multiple
2583/// instructions.
2584class TempRegRenderer : public OperandRenderer {
2585protected:
2586 unsigned InsnID;
2587 unsigned TempRegID;
2588 bool IsDef;
2589
2590public:
2591 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2592 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2593 IsDef(IsDef) {}
2594
2595 static bool classof(const OperandRenderer *R) {
2596 return R->getKind() == OR_TempRegister;
2597 }
2598
2599 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2600 Table << MatchTable::Opcode("GIR_AddTempRegister")
2601 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2602 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2603 << MatchTable::Comment("TempRegFlags");
2604 if (IsDef)
2605 Table << MatchTable::NamedValue("RegState::Define");
2606 else
2607 Table << MatchTable::IntValue(0);
2608 Table << MatchTable::LineBreak;
2609 }
2610};
2611
Daniel Sanders0ed28822017-04-12 08:23:08 +00002612/// Adds a specific immediate to the instruction being built.
2613class ImmRenderer : public OperandRenderer {
2614protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002615 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002616 int64_t Imm;
2617
2618public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002619 ImmRenderer(unsigned InsnID, int64_t Imm)
2620 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002621
2622 static bool classof(const OperandRenderer *R) {
2623 return R->getKind() == OR_Imm;
2624 }
2625
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002626 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2627 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2628 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2629 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002630 }
2631};
2632
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002633/// Adds an enum value for a subreg index to the instruction being built.
2634class SubRegIndexRenderer : public OperandRenderer {
2635protected:
2636 unsigned InsnID;
2637 const CodeGenSubRegIndex *SubRegIdx;
2638
2639public:
2640 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2641 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2642
2643 static bool classof(const OperandRenderer *R) {
2644 return R->getKind() == OR_SubRegIndex;
2645 }
2646
2647 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2648 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2649 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2650 << MatchTable::IntValue(SubRegIdx->EnumValue)
2651 << MatchTable::LineBreak;
2652 }
2653};
2654
Daniel Sanders2deea182017-04-22 15:11:04 +00002655/// Adds operands by calling a renderer function supplied by the ComplexPattern
2656/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002657class RenderComplexPatternOperand : public OperandRenderer {
2658private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002659 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002660 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002661 /// The name of the operand.
2662 const StringRef SymbolicName;
2663 /// The renderer number. This must be unique within a rule since it's used to
2664 /// identify a temporary variable to hold the renderer function.
2665 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002666 /// When provided, this is the suboperand of the ComplexPattern operand to
2667 /// render. Otherwise all the suboperands will be rendered.
2668 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002669
2670 unsigned getNumOperands() const {
2671 return TheDef.getValueAsDag("Operands")->getNumArgs();
2672 }
2673
2674public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002675 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002676 StringRef SymbolicName, unsigned RendererID,
2677 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002678 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002679 SymbolicName(SymbolicName), RendererID(RendererID),
2680 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002681
2682 static bool classof(const OperandRenderer *R) {
2683 return R->getKind() == OR_ComplexPattern;
2684 }
2685
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002686 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002687 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2688 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002689 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2690 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002691 << MatchTable::IntValue(RendererID);
2692 if (SubOperand.hasValue())
2693 Table << MatchTable::Comment("SubOperand")
2694 << MatchTable::IntValue(SubOperand.getValue());
2695 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002696 }
2697};
2698
Volkan Kelesf7f25682018-01-16 18:44:05 +00002699class CustomRenderer : public OperandRenderer {
2700protected:
2701 unsigned InsnID;
2702 const Record &Renderer;
2703 /// The name of the operand.
2704 const std::string SymbolicName;
2705
2706public:
2707 CustomRenderer(unsigned InsnID, const Record &Renderer,
2708 StringRef SymbolicName)
2709 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2710 SymbolicName(SymbolicName) {}
2711
2712 static bool classof(const OperandRenderer *R) {
2713 return R->getKind() == OR_Custom;
2714 }
2715
2716 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002717 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002718 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2719 Table << MatchTable::Opcode("GIR_CustomRenderer")
2720 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2721 << MatchTable::Comment("OldInsnID")
2722 << MatchTable::IntValue(OldInsnVarID)
2723 << MatchTable::Comment("Renderer")
2724 << MatchTable::NamedValue(
2725 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2726 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2727 }
2728};
2729
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002730class CustomOperandRenderer : public OperandRenderer {
2731protected:
2732 unsigned InsnID;
2733 const Record &Renderer;
2734 /// The name of the operand.
2735 const std::string SymbolicName;
2736
2737public:
2738 CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2739 StringRef SymbolicName)
2740 : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2741 SymbolicName(SymbolicName) {}
2742
2743 static bool classof(const OperandRenderer *R) {
2744 return R->getKind() == OR_CustomOperand;
2745 }
2746
2747 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2748 const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2749 Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2750 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2751 << MatchTable::Comment("OldInsnID")
2752 << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2753 << MatchTable::Comment("OpIdx")
2754 << MatchTable::IntValue(OpdMatcher.getOpIdx())
2755 << MatchTable::Comment("OperandRenderer")
2756 << MatchTable::NamedValue(
2757 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2758 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2759 }
2760};
2761
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002762/// An action taken when all Matcher predicates succeeded for a parent rule.
2763///
2764/// Typical actions include:
2765/// * Changing the opcode of an instruction.
2766/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002767class MatchAction {
2768public:
2769 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002770
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002771 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002772 virtual void emitActionOpcodes(MatchTable &Table,
2773 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002774};
2775
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002776/// Generates a comment describing the matched rule being acted upon.
2777class DebugCommentAction : public MatchAction {
2778private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002779 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002780
2781public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002782 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002783
Daniel Sandersa7b75262017-10-31 18:50:24 +00002784 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002785 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002786 }
2787};
2788
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002789/// Generates code to build an instruction or mutate an existing instruction
2790/// into the desired instruction when this is possible.
2791class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002792private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002793 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002794 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002795 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002796 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2797
2798 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002799 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2800 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002801 return false;
2802
Daniel Sandersa7b75262017-10-31 18:50:24 +00002803 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002804 return false;
2805
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002806 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002807 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002808 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002809 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002810 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002811 return false;
2812 } else
2813 return false;
2814 }
2815
2816 return true;
2817 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002818
Daniel Sanders43c882c2017-02-01 10:53:10 +00002819public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002820 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2821 : InsnID(InsnID), I(I), Matched(nullptr) {}
2822
Daniel Sanders08464522018-01-29 21:09:12 +00002823 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002824 const CodeGenInstruction *getCGI() const { return I; }
2825
Daniel Sandersa7b75262017-10-31 18:50:24 +00002826 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002827 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002828 if (canMutate(Rule, MutateCandidate)) {
2829 // Take the first one we're offered that we're able to mutate.
2830 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2831 Matched = MutateCandidate;
2832 return;
2833 }
2834 }
2835 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002836
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002837 template <class Kind, class... Args>
2838 Kind &addRenderer(Args&&... args) {
2839 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002840 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002841 return *static_cast<Kind *>(OperandRenderers.back().get());
2842 }
2843
Daniel Sandersa7b75262017-10-31 18:50:24 +00002844 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2845 if (Matched) {
2846 assert(canMutate(Rule, Matched) &&
2847 "Arranged to mutate an insn that isn't mutatable");
2848
2849 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002850 Table << MatchTable::Opcode("GIR_MutateOpcode")
2851 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2852 << MatchTable::Comment("RecycleInsnID")
2853 << MatchTable::IntValue(RecycleInsnID)
2854 << MatchTable::Comment("Opcode")
2855 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2856 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002857
2858 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002859 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002860 auto Namespace = Def->getValue("Namespace")
2861 ? Def->getValueAsString("Namespace")
2862 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002863 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2864 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2865 << MatchTable::NamedValue(Namespace, Def->getName())
2866 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002867 }
2868 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002869 auto Namespace = Use->getValue("Namespace")
2870 ? Use->getValueAsString("Namespace")
2871 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002872 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2873 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2874 << MatchTable::NamedValue(Namespace, Use->getName())
2875 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002876 }
2877 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002878 return;
2879 }
2880
2881 // TODO: Simple permutation looks like it could be almost as common as
2882 // mutation due to commutative operations.
2883
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002884 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2885 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2886 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2887 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002888 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002889 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002890
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002891 if (I->mayLoad || I->mayStore) {
2892 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2893 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2894 << MatchTable::Comment("MergeInsnID's");
2895 // Emit the ID's for all the instructions that are matched by this rule.
2896 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2897 // some other means of having a memoperand. Also limit this to
2898 // emitted instructions that expect to have a memoperand too. For
2899 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2900 // sign-extend instructions shouldn't put the memoperand on the
2901 // sign-extend since it has no effect there.
2902 std::vector<unsigned> MergeInsnIDs;
2903 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2904 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002905 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002906 for (const auto &MergeInsnID : MergeInsnIDs)
2907 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002908 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2909 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002910 }
2911
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002912 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2913 // better for combines. Particularly when there are multiple match
2914 // roots.
2915 if (InsnID == 0)
2916 Table << MatchTable::Opcode("GIR_EraseFromParent")
2917 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2918 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002919 }
2920};
2921
2922/// Generates code to constrain the operands of an output instruction to the
2923/// register classes specified by the definition of that instruction.
2924class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002925 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002926
2927public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002928 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002929
Daniel Sandersa7b75262017-10-31 18:50:24 +00002930 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002931 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2932 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2933 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002934 }
2935};
2936
2937/// Generates code to constrain the specified operand of an output instruction
2938/// to the specified register class.
2939class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002940 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002941 unsigned OpIdx;
2942 const CodeGenRegisterClass &RC;
2943
2944public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002945 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002946 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002947 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002948
Daniel Sandersa7b75262017-10-31 18:50:24 +00002949 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002950 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2951 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2952 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2953 << MatchTable::Comment("RC " + RC.getName())
2954 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002955 }
2956};
2957
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002958/// Generates code to create a temporary register which can be used to chain
2959/// instructions together.
2960class MakeTempRegisterAction : public MatchAction {
2961private:
2962 LLTCodeGen Ty;
2963 unsigned TempRegID;
2964
2965public:
2966 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002967 : Ty(Ty), TempRegID(TempRegID) {
2968 KnownTypes.insert(Ty);
2969 }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002970
2971 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2972 Table << MatchTable::Opcode("GIR_MakeTempReg")
2973 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2974 << MatchTable::Comment("TypeID")
2975 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2976 << MatchTable::LineBreak;
2977 }
2978};
2979
Daniel Sanders05540042017-08-08 10:44:31 +00002980InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002981 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002982 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002983 return *Matchers.back();
2984}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002985
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002986void RuleMatcher::addRequiredFeature(Record *Feature) {
2987 RequiredFeatures.push_back(Feature);
2988}
2989
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002990const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2991 return RequiredFeatures;
2992}
2993
Daniel Sanders7438b262017-10-31 23:03:18 +00002994// Emplaces an action of the specified Kind at the end of the action list.
2995//
2996// Returns a reference to the newly created action.
2997//
2998// Like std::vector::emplace_back(), may invalidate all iterators if the new
2999// size exceeds the capacity. Otherwise, only invalidates the past-the-end
3000// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003001template <class Kind, class... Args>
3002Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003003 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003004 return *static_cast<Kind *>(Actions.back().get());
3005}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003006
Daniel Sanders7438b262017-10-31 23:03:18 +00003007// Emplaces an action of the specified Kind before the given insertion point.
3008//
3009// Returns an iterator pointing at the newly created instruction.
3010//
3011// Like std::vector::insert(), may invalidate all iterators if the new size
3012// exceeds the capacity. Otherwise, only invalidates the iterators from the
3013// insertion point onwards.
3014template <class Kind, class... Args>
3015action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3016 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003017 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003018 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00003019}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003020
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003021unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003022 unsigned NewInsnVarID = NextInsnVarID++;
3023 InsnVariableIDs[&Matcher] = NewInsnVarID;
3024 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003025}
3026
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003027unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003028 const auto &I = InsnVariableIDs.find(&InsnMatcher);
3029 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003030 return I->second;
3031 llvm_unreachable("Matched Insn was not captured in a local variable");
3032}
3033
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003034void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3035 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3036 DefinedOperands[SymbolicName] = &OM;
3037 return;
3038 }
3039
3040 // If the operand is already defined, then we must ensure both references in
3041 // the matcher have the exact same node.
3042 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3043}
3044
Matt Arsenault3e45c702019-09-06 20:32:37 +00003045void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3046 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3047 PhysRegOperands[Reg] = &OM;
3048 return;
3049 }
3050}
3051
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003052InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00003053RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3054 for (const auto &I : InsnVariableIDs)
3055 if (I.first->getSymbolicName() == SymbolicName)
3056 return *I.first;
3057 llvm_unreachable(
3058 ("Failed to lookup instruction " + SymbolicName).str().c_str());
3059}
3060
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003061const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00003062RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3063 const auto &I = PhysRegOperands.find(Reg);
3064
3065 if (I == PhysRegOperands.end()) {
3066 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3067 " was not declared in matcher");
3068 }
3069
3070 return *I->second;
3071}
3072
3073const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003074RuleMatcher::getOperandMatcher(StringRef Name) const {
3075 const auto &I = DefinedOperands.find(Name);
3076
3077 if (I == DefinedOperands.end())
3078 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3079
3080 return *I->second;
3081}
3082
Daniel Sanders8e82af22017-07-27 11:03:45 +00003083void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003084 if (Matchers.empty())
3085 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003086
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003087 // The representation supports rules that require multiple roots such as:
3088 // %ptr(p0) = ...
3089 // %elt0(s32) = G_LOAD %ptr
3090 // %1(p0) = G_ADD %ptr, 4
3091 // %elt1(s32) = G_LOAD p0 %1
3092 // which could be usefully folded into:
3093 // %ptr(p0) = ...
3094 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3095 // on some targets but we don't need to make use of that yet.
3096 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003097
Daniel Sanders8e82af22017-07-27 11:03:45 +00003098 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003099 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003100 << MatchTable::Comment("On fail goto")
3101 << MatchTable::JumpTarget(LabelID)
3102 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003103 << MatchTable::LineBreak;
3104
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003105 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003106 Table << MatchTable::Opcode("GIM_CheckFeatures")
3107 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3108 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003109 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003110
Quentin Colombetaad20be2017-12-15 23:07:42 +00003111 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003112
Daniel Sandersbee57392017-04-04 13:25:23 +00003113 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003114 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003115 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003116 SmallVector<unsigned, 2> InsnIDs;
3117 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003118 // Skip the root node since it isn't moving anywhere. Everything else is
3119 // sinking to meet it.
3120 if (Pair.first == Matchers.front().get())
3121 continue;
3122
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003123 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003124 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003125 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003126
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003127 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003128 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003129 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3130 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3131 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003132
3133 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3134 // account for unsafe cases.
3135 //
3136 // Example:
3137 // MI1--> %0 = ...
3138 // %1 = ... %0
3139 // MI0--> %2 = ... %0
3140 // It's not safe to erase MI1. We currently handle this by not
3141 // erasing %0 (even when it's dead).
3142 //
3143 // Example:
3144 // MI1--> %0 = load volatile @a
3145 // %1 = load volatile @a
3146 // MI0--> %2 = ... %0
3147 // It's not safe to sink %0's def past %1. We currently handle
3148 // this by rejecting all loads.
3149 //
3150 // Example:
3151 // MI1--> %0 = load @a
3152 // %1 = store @a
3153 // MI0--> %2 = ... %0
3154 // It's not safe to sink %0's def past %1. We currently handle
3155 // this by rejecting all loads.
3156 //
3157 // Example:
3158 // G_CONDBR %cond, @BB1
3159 // BB0:
3160 // MI1--> %0 = load @a
3161 // G_BR @BB1
3162 // BB1:
3163 // MI0--> %2 = ... %0
3164 // It's not always safe to sink %0 across control flow. In this
3165 // case it may introduce a memory fault. We currentl handle this
3166 // by rejecting all loads.
3167 }
3168 }
3169
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003170 for (const auto &PM : EpilogueMatchers)
3171 PM->emitPredicateOpcodes(Table, *this);
3172
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003173 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003174 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003175
Roman Tereshinbeb39312018-05-02 20:15:11 +00003176 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003177 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3178 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003179 else
3180 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3181 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003182
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003183 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003184 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003185 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003186}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003187
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003188bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3189 // Rules involving more match roots have higher priority.
3190 if (Matchers.size() > B.Matchers.size())
3191 return true;
3192 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003193 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003194
Mark de Wevere8d448e2019-12-22 18:58:32 +01003195 for (auto Matcher : zip(Matchers, B.Matchers)) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003196 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3197 return true;
3198 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3199 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003200 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003201
3202 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003203}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003204
Daniel Sanders2deea182017-04-22 15:11:04 +00003205unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003206 return std::accumulate(
3207 Matchers.begin(), Matchers.end(), 0,
3208 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003209 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003210 });
3211}
3212
Daniel Sanders05540042017-08-08 10:44:31 +00003213bool OperandPredicateMatcher::isHigherPriorityThan(
3214 const OperandPredicateMatcher &B) const {
3215 // Generally speaking, an instruction is more important than an Int or a
3216 // LiteralInt because it can cover more nodes but theres an exception to
3217 // this. G_CONSTANT's are less important than either of those two because they
3218 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003219
3220 const InstructionOperandMatcher *AOM =
3221 dyn_cast<InstructionOperandMatcher>(this);
3222 const InstructionOperandMatcher *BOM =
3223 dyn_cast<InstructionOperandMatcher>(&B);
3224 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3225 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3226
3227 if (AOM && BOM) {
3228 // The relative priorities between a G_CONSTANT and any other instruction
3229 // don't actually matter but this code is needed to ensure a strict weak
3230 // ordering. This is particularly important on Windows where the rules will
3231 // be incorrectly sorted without it.
3232 if (AIsConstantInsn != BIsConstantInsn)
3233 return AIsConstantInsn < BIsConstantInsn;
3234 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003235 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003236
3237 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3238 return false;
3239 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3240 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003241
3242 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003243}
Daniel Sanders05540042017-08-08 10:44:31 +00003244
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003245void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003246 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003247 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003248 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003249 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003250
3251 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3252 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3253 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3254 << MatchTable::Comment("OtherMI")
3255 << MatchTable::IntValue(OtherInsnVarID)
3256 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003257 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003258 << MatchTable::LineBreak;
3259}
3260
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003261//===- GlobalISelEmitter class --------------------------------------------===//
3262
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003263class GlobalISelEmitter {
3264public:
3265 explicit GlobalISelEmitter(RecordKeeper &RK);
3266 void run(raw_ostream &OS);
3267
3268private:
3269 const RecordKeeper &RK;
3270 const CodeGenDAGPatterns CGP;
3271 const CodeGenTarget &Target;
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003272 CodeGenRegBank &CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003273
Daniel Sanders39690bd2017-10-15 02:41:12 +00003274 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003275 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3276 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003277 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003278 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003279
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003280 /// Keep track of the equivalence between ComplexPattern's and
3281 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3282 /// GIComplexPatternEquiv.
3283 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3284
Volkan Kelesf7f25682018-01-16 18:44:05 +00003285 /// Keep track of the equivalence between SDNodeXForm's and
3286 /// GICustomOperandRenderer. Map entries are specified by subclassing
3287 /// GISDNodeXFormEquiv.
3288 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3289
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003290 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3291 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3292 DenseMap<uint64_t, int> RuleMatcherScores;
3293
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003294 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003295 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003296
Daniel Sandersf76f3152017-11-16 00:46:35 +00003297 // Rule coverage information.
3298 Optional<CodeGenCoverage> RuleCoverage;
3299
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003300 void gatherOpcodeValues();
3301 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003302 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003303
Daniel Sanders39690bd2017-10-15 02:41:12 +00003304 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003305 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003306 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003307
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003308 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003309 Expected<InstructionMatcher &>
3310 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3311 InstructionMatcher &InsnMatcher,
3312 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003313 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3314 unsigned &TempOpIdx) const;
3315 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003316 const TreePatternNode *SrcChild,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003317 bool OperandIsAPointer, bool OperandIsImmArg,
3318 unsigned OpIdx, unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003319
Matt Arsenault3e45c702019-09-06 20:32:37 +00003320 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3321 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3322 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003323 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003324 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003325 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003326 Expected<action_iterator>
3327 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003328 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003329 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003330
Daniel Sanders7438b262017-10-31 23:03:18 +00003331 Expected<action_iterator>
3332 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3333 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003334 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003335 Expected<action_iterator>
3336 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3337 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003338 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003339 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3340 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003341 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003342 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003343 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3344 const std::vector<Record *> &ImplicitDefs) const;
3345
Daniel Sanders8ead1292018-06-15 23:13:43 +00003346 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3347 StringRef TypeIdentifier, StringRef ArgType,
3348 StringRef ArgName, StringRef AdditionalDeclarations,
3349 std::function<bool(const Record *R)> Filter);
3350 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3351 StringRef ArgType,
3352 std::function<bool(const Record *R)> Filter);
3353 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003354
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003355 /// Analyze pattern \p P, returning a matcher for it if possible.
3356 /// Otherwise, return an Error explaining why we don't support it.
3357 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003358
3359 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003360
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003361 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3362 bool WithCoverage);
3363
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003364 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3365 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3366 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3367 /// If no register class is found, return None.
3368 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003369 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3370 TreePatternNode *SuperRegNode,
3371 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003372 Optional<CodeGenSubRegIndex *>
3373 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003374
3375 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3376 /// Return None if no such class exists.
3377 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003378 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003379 TreePatternNode *SubRegIdxNode);
3380
3381 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3382 Optional<const CodeGenRegisterClass *>
3383 getRegClassFromLeaf(TreePatternNode *Leaf);
3384
3385 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3386 /// otherwise.
3387 Optional<const CodeGenRegisterClass *>
3388 inferRegClassFromPattern(TreePatternNode *N);
3389
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003390public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003391 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003392 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003393 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003394 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003395 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003396 /// Output without optimization:
3397 /// \verbatim
3398 /// # R1
3399 /// # predicate A
3400 /// # predicate B
3401 /// ...
3402 /// # R2
3403 /// # predicate A // <-- effectively this is going to be checked twice.
3404 /// // Once in R1 and once in R2.
3405 /// # predicate C
3406 /// \endverbatim
3407 /// Output with optimization:
3408 /// \verbatim
3409 /// # Group1_2
3410 /// # predicate A // <-- Check is now shared.
3411 /// # R1
3412 /// # predicate B
3413 /// # R2
3414 /// # predicate C
3415 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003416 template <class GroupT>
3417 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003418 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003419 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003420};
3421
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003422void GlobalISelEmitter::gatherOpcodeValues() {
3423 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3424}
3425
3426void GlobalISelEmitter::gatherTypeIDValues() {
3427 LLTOperandMatcher::initTypeIDValuesMap();
3428}
3429
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003430void GlobalISelEmitter::gatherNodeEquivs() {
3431 assert(NodeEquivs.empty());
3432 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003433 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003434
3435 assert(ComplexPatternEquivs.empty());
3436 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3437 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3438 if (!SelDAGEquiv)
3439 continue;
3440 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3441 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003442
3443 assert(SDNodeXFormEquivs.empty());
3444 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3445 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3446 if (!SelDAGEquiv)
3447 continue;
3448 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3449 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003450}
3451
Daniel Sanders39690bd2017-10-15 02:41:12 +00003452Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003453 return NodeEquivs.lookup(N);
3454}
3455
Daniel Sandersf84bc372018-05-05 20:53:24 +00003456const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003457GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003458 if (N->getNumChildren() >= 1) {
3459 // setcc operation maps to two different G_* instructions based on the type.
3460 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3461 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3462 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3463 }
3464
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003465 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3466 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003467 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3468 Predicate.isSignExtLoad())
3469 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3470 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3471 Predicate.isZeroExtLoad())
3472 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3473 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003474
Daniel Sandersf84bc372018-05-05 20:53:24 +00003475 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3476}
3477
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003478GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003479 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003480 CGRegs(Target.getRegBank()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003481
3482//===- Emitter ------------------------------------------------------------===//
3483
Daniel Sandersc270c502017-03-30 09:36:33 +00003484Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003485GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003486 ArrayRef<Predicate> Predicates) {
3487 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003488 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003489 continue;
3490 declareSubtargetFeature(P.Def);
3491 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003492 }
3493
Daniel Sandersc270c502017-03-30 09:36:33 +00003494 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003495}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003496
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003497Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3498 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003499 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003500 Record *SrcGIEquivOrNull = nullptr;
3501 const CodeGenInstruction *SrcGIOrNull = nullptr;
3502
3503 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003504 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003505 return failedImport("Src pattern has multiple results");
3506
Florian Hahn6b1db822018-06-14 20:32:58 +00003507 if (Src->isLeaf()) {
3508 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003509 if (isa<IntInit>(SrcInit)) {
3510 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3511 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3512 } else
3513 return failedImport(
3514 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3515 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003516 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003517 if (!SrcGIEquivOrNull)
3518 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003519 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003520 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003521
3522 // The operators look good: match the opcode
3523 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3524 }
3525
3526 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003527 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003528 // Results don't have a name unless they are the root node. The caller will
3529 // set the name if appropriate.
3530 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3531 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3532 return failedImport(toString(std::move(Error)) +
3533 " for result of Src pattern operator");
3534 }
3535
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003536 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3537 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003538 if (Predicate.isAlwaysTrue())
3539 continue;
3540
3541 if (Predicate.isImmediatePattern()) {
3542 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3543 continue;
3544 }
3545
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003546 // An address space check is needed in all contexts if there is one.
3547 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3548 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3549 SmallVector<unsigned, 4> ParsedAddrSpaces;
3550
3551 for (Init *Val : AddrSpaces->getValues()) {
3552 IntInit *IntVal = dyn_cast<IntInit>(Val);
3553 if (!IntVal)
3554 return failedImport("Address space is not an integer");
3555 ParsedAddrSpaces.push_back(IntVal->getValue());
3556 }
3557
3558 if (!ParsedAddrSpaces.empty()) {
3559 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3560 0, ParsedAddrSpaces);
3561 }
3562 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003563
3564 int64_t MinAlign = Predicate.getMinAlignment();
3565 if (MinAlign > 0)
3566 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003567 }
3568
3569 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003570 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3571 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3572 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3573 continue;
3574 }
3575 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3576 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3577 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3578 continue;
3579 }
3580
Amara Emerson52e6d522019-08-02 23:33:13 +00003581 if (Predicate.isStore()) {
3582 if (Predicate.isTruncStore()) {
3583 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3584 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3585 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3586 continue;
3587 }
3588 if (Predicate.isNonTruncStore()) {
3589 // We need to check the sizes match here otherwise we could incorrectly
3590 // match truncating stores with non-truncating ones.
3591 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3592 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3593 }
Matt Arsenault02772492019-07-15 21:15:20 +00003594 }
3595
Daniel Sandersf84bc372018-05-05 20:53:24 +00003596 // No check required. We already did it by swapping the opcode.
3597 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3598 Predicate.isSignExtLoad())
3599 continue;
3600
3601 // No check required. We already did it by swapping the opcode.
3602 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3603 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003604 continue;
3605
Daniel Sandersd66e0902017-10-23 18:19:24 +00003606 // No check required. G_STORE by itself is a non-extending store.
3607 if (Predicate.isNonTruncStore())
3608 continue;
3609
Daniel Sanders76664652017-11-28 22:07:05 +00003610 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3611 if (Predicate.getMemoryVT() != nullptr) {
3612 Optional<LLTCodeGen> MemTyOrNone =
3613 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003614
Daniel Sanders76664652017-11-28 22:07:05 +00003615 if (!MemTyOrNone)
3616 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003617
Daniel Sandersf84bc372018-05-05 20:53:24 +00003618 // MMO's work in bytes so we must take care of unusual types like i1
3619 // don't round down.
3620 unsigned MemSizeInBits =
3621 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3622
3623 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3624 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003625 continue;
3626 }
3627 }
3628
3629 if (Predicate.isLoad() || Predicate.isStore()) {
3630 // No check required. A G_LOAD/G_STORE is an unindexed load.
3631 if (Predicate.isUnindexed())
3632 continue;
3633 }
3634
3635 if (Predicate.isAtomic()) {
3636 if (Predicate.isAtomicOrderingMonotonic()) {
3637 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3638 "Monotonic");
3639 continue;
3640 }
3641 if (Predicate.isAtomicOrderingAcquire()) {
3642 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3643 continue;
3644 }
3645 if (Predicate.isAtomicOrderingRelease()) {
3646 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3647 continue;
3648 }
3649 if (Predicate.isAtomicOrderingAcquireRelease()) {
3650 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3651 "AcquireRelease");
3652 continue;
3653 }
3654 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3655 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3656 "SequentiallyConsistent");
3657 continue;
3658 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003659
3660 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3661 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3662 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3663 continue;
3664 }
3665 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3666 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3667 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3668 continue;
3669 }
3670
3671 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3672 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3673 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3674 continue;
3675 }
3676 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3677 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3678 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3679 continue;
3680 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003681 }
3682
Daniel Sanders8ead1292018-06-15 23:13:43 +00003683 if (Predicate.hasGISelPredicateCode()) {
3684 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3685 continue;
3686 }
3687
Daniel Sanders2c269f62017-08-24 09:11:20 +00003688 return failedImport("Src pattern child has predicate (" +
3689 explainPredicates(Src) + ")");
3690 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003691 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3692 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003693 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3694 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3695 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3696 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003697
Florian Hahn6b1db822018-06-14 20:32:58 +00003698 if (Src->isLeaf()) {
3699 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003700 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003701 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003702 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003703 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3704 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003705 return failedImport(
3706 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003707 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003708 assert(SrcGIOrNull &&
3709 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003710 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3711 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3712 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003713 // here since we don't support ImmLeaf predicates yet. However, we still
3714 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3715 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3716 return InsnMatcher;
3717 }
3718
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003719 // Special case because the operand order is changed from setcc. The
3720 // predicate operand needs to be swapped from the last operand to the first
3721 // source.
3722
3723 unsigned NumChildren = Src->getNumChildren();
3724 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3725
3726 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3727 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3728 if (SrcChild->isLeaf()) {
3729 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3730 Record *CCDef = DI ? DI->getDef() : nullptr;
3731 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3732 return failedImport("Unable to handle CondCode");
3733
3734 OperandMatcher &OM =
3735 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3736 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3737 CCDef->getValueAsString("ICmpPredicate");
3738
3739 if (!PredType.empty()) {
3740 OM.addPredicate<CmpPredicateOperandMatcher>(PredType);
3741 // Process the other 2 operands normally.
3742 --NumChildren;
3743 }
3744 }
3745 }
3746
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003747 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003748 bool IsIntrinsic =
3749 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3750 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3751 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3752 if (IsIntrinsic && !II)
3753 return failedImport("Expected IntInit containing intrinsic ID)");
3754
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003755 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003756 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003757
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003758 // We need to determine the meaning of a literal integer based on the
3759 // context. If this is a field required to be an immediate (such as an
3760 // immarg intrinsic argument), the required predicates are different than
3761 // a constant which may be materialized in a register. If we have an
3762 // argument that is required to be an immediate, we should not emit an LLT
3763 // type check, and should not be looking for a G_CONSTANT defined
3764 // register.
3765 bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
3766
Daniel Sandersa71f4542017-10-16 00:56:30 +00003767 // SelectionDAG allows pointers to be represented with iN since it doesn't
3768 // distinguish between pointers and integers but they are different types in GlobalISel.
3769 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003770 //
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003771 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003772
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003773 if (IsIntrinsic) {
3774 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3775 // following the defs is an intrinsic ID.
3776 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003777 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003778 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003779 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003780 continue;
3781 }
3782
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003783 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003784 //
3785 // Note that we have to look at the i-1th parameter, because we don't
3786 // have the intrinsic ID in the intrinsic's parameter list.
3787 OperandIsAPointer |= II->isParamAPointer(i - 1);
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003788 OperandIsImmArg |= II->isParamImmArg(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003789 }
3790
Daniel Sandersa71f4542017-10-16 00:56:30 +00003791 if (auto Error =
3792 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003793 OperandIsImmArg, OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003794 return std::move(Error);
3795 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003796 }
3797
3798 return InsnMatcher;
3799}
3800
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003801Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3802 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3803 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3804 if (ComplexPattern == ComplexPatternEquivs.end())
3805 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3806 ") not mapped to GlobalISel");
3807
3808 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3809 TempOpIdx++;
3810 return Error::success();
3811}
3812
Matt Arsenault3e45c702019-09-06 20:32:37 +00003813// Get the name to use for a pattern operand. For an anonymous physical register
3814// input, this should use the register name.
3815static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3816 Record *&PhysReg) {
3817 StringRef SrcChildName = SrcChild->getName();
3818 if (SrcChildName.empty() && SrcChild->isLeaf()) {
3819 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3820 auto *ChildRec = ChildDefInit->getDef();
3821 if (ChildRec->isSubClassOf("Register")) {
3822 SrcChildName = ChildRec->getName();
3823 PhysReg = ChildRec;
3824 }
3825 }
3826 }
3827
3828 return SrcChildName;
3829}
3830
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003831Error GlobalISelEmitter::importChildMatcher(
3832 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3833 const TreePatternNode *SrcChild, bool OperandIsAPointer,
3834 bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00003835
3836 Record *PhysReg = nullptr;
3837 StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3838
3839 OperandMatcher &OM = PhysReg ?
3840 InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx) :
3841 InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003842 if (OM.isSameAsAnotherOperand())
3843 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003844
Florian Hahn6b1db822018-06-14 20:32:58 +00003845 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003846 if (ChildTypes.size() != 1)
3847 return failedImport("Src pattern child has multiple results");
3848
3849 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003850 if (!SrcChild->isLeaf()) {
3851 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3852 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003853 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3854 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003855 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003856 }
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00003857 if (SrcChild->getOperator()->getName() == "timm") {
3858 OM.addPredicate<ImmOperandMatcher>();
3859 return Error::success();
3860 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003861 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003862 }
3863
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003864 // Immediate arguments have no meaningful type to check as they don't have
3865 // registers.
3866 if (!OperandIsImmArg) {
3867 if (auto Error =
3868 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3869 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3870 to_string(*SrcChild) + ")");
3871 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003872
Daniel Sandersbee57392017-04-04 13:25:23 +00003873 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003874 if (!SrcChild->isLeaf()) {
3875 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003876 // When a ComplexPattern is used as an operator, it should do the same
3877 // thing as when used as a leaf. However, the children of the operator
3878 // name the sub-operands that make up the complex operand and we must
3879 // prepare to reference them in the renderer too.
3880 unsigned RendererID = TempOpIdx;
3881 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003882 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003883 return Error;
3884
Florian Hahn6b1db822018-06-14 20:32:58 +00003885 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3886 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003887 if (!SubOperand->getName().empty()) {
3888 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3889 SrcChild->getOperator(),
3890 RendererID, i))
3891 return Error;
3892 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003893 }
3894
3895 return Error::success();
3896 }
3897
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003898 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003899 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003900 if (!MaybeInsnOperand.hasValue()) {
3901 // This isn't strictly true. If the user were to provide exactly the same
3902 // matchers as the original operand then we could allow it. However, it's
3903 // simpler to not permit the redundant specification.
3904 return failedImport("Nested instruction cannot be the same as another operand");
3905 }
3906
Daniel Sandersbee57392017-04-04 13:25:23 +00003907 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003908 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003909 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003910 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003911 if (auto Error = InsnMatcherOrError.takeError())
3912 return Error;
3913
3914 return Error::success();
3915 }
3916
Florian Hahn6b1db822018-06-14 20:32:58 +00003917 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003918 return failedImport("Src pattern child has unsupported predicate");
3919
Daniel Sandersffc7d582017-03-29 15:37:18 +00003920 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003921 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003922 if (OperandIsImmArg) {
3923 // Checks for argument directly in operand list
3924 OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
3925 } else {
3926 // Checks for materialized constant
3927 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
3928 }
Daniel Sandersc270c502017-03-30 09:36:33 +00003929 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003930 }
3931
3932 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003933 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003934 auto *ChildRec = ChildDefInit->getDef();
3935
3936 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003937 if (ChildRec->isSubClassOf("RegisterClass") ||
3938 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003939 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003940 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003941 return Error::success();
3942 }
3943
Matt Arsenault3e45c702019-09-06 20:32:37 +00003944 if (ChildRec->isSubClassOf("Register")) {
3945 // This just be emitted as a copy to the specific register.
3946 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
3947 const CodeGenRegisterClass *RC
3948 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
3949 if (!RC) {
3950 return failedImport(
3951 "Could not determine physical register class of pattern source");
3952 }
3953
3954 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
3955 return Error::success();
3956 }
3957
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003958 // Check for ValueType.
3959 if (ChildRec->isSubClassOf("ValueType")) {
3960 // We already added a type check as standard practice so this doesn't need
3961 // to do anything.
3962 return Error::success();
3963 }
3964
Daniel Sandersffc7d582017-03-29 15:37:18 +00003965 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003966 if (ChildRec->isSubClassOf("ComplexPattern"))
3967 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003968
Daniel Sandersd0656a32017-04-13 09:45:37 +00003969 if (ChildRec->isSubClassOf("ImmLeaf")) {
3970 return failedImport(
3971 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3972 }
3973
Matt Arsenault03a592f2020-01-16 10:47:13 -05003974 // Place holder for SRCVALUE nodes. Nothing to do here.
3975 if (ChildRec->getName() == "srcvalue")
3976 return Error::success();
3977
Daniel Sandersffc7d582017-03-29 15:37:18 +00003978 return failedImport(
3979 "Src pattern child def is an unsupported tablegen class");
3980 }
3981
3982 return failedImport("Src pattern child is an unsupported kind");
3983}
3984
Daniel Sanders7438b262017-10-31 23:03:18 +00003985Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3986 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003987 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003988
Florian Hahn6b1db822018-06-14 20:32:58 +00003989 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003990 if (SubOperand.hasValue()) {
3991 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003992 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003993 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003994 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003995 }
3996
Florian Hahn6b1db822018-06-14 20:32:58 +00003997 if (!DstChild->isLeaf()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003998 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3999 auto Child = DstChild->getChild(0);
4000 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00004001 if (I != SDNodeXFormEquivs.end()) {
Matt Arsenaultb4a64742020-01-08 12:53:15 -05004002 Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4003 if (XFormOpc->getName() == "timm") {
4004 // If this is a TargetConstant, there won't be a corresponding
4005 // instruction to transform. Instead, this will refer directly to an
4006 // operand in an instruction's operand list.
4007 DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4008 Child->getName());
4009 } else {
4010 DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4011 Child->getName());
4012 }
4013
Volkan Kelesf7f25682018-01-16 18:44:05 +00004014 return InsertPt;
4015 }
Florian Hahn6b1db822018-06-14 20:32:58 +00004016 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00004017 " has no custom renderer");
4018 }
4019
Daniel Sanders05540042017-08-08 10:44:31 +00004020 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4021 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004022 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4023 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004024 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004025 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004026 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004027 }
4028 }
Daniel Sanders05540042017-08-08 10:44:31 +00004029
4030 // Similarly, imm is an operator in TreePatternNode's view but must be
4031 // rendered as operands.
4032 // FIXME: The target should be able to choose sign-extended when appropriate
4033 // (e.g. on Mips).
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00004034 if (DstChild->getOperator()->getName() == "timm") {
4035 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4036 return InsertPt;
4037 } else if (DstChild->getOperator()->getName() == "imm") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004038 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004039 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00004040 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004041 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004042 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004043 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00004044 }
4045
Florian Hahn6b1db822018-06-14 20:32:58 +00004046 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
4047 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004048 if (ChildTypes.size() != 1)
4049 return failedImport("Dst pattern child has multiple results");
4050
4051 Optional<LLTCodeGen> OpTyOrNone = None;
4052 if (ChildTypes.front().isMachineValueType())
4053 OpTyOrNone =
4054 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
4055 if (!OpTyOrNone)
4056 return failedImport("Dst operand has an unsupported type");
4057
4058 unsigned TempRegID = Rule.allocateTempRegID();
4059 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
4060 InsertPt, OpTyOrNone.getValue(), TempRegID);
4061 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4062
4063 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4064 ++InsertPt, Rule, DstChild, TempRegID);
4065 if (auto Error = InsertPtOrError.takeError())
4066 return std::move(Error);
4067 return InsertPtOrError.get();
4068 }
4069
Florian Hahn6b1db822018-06-14 20:32:58 +00004070 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00004071 }
4072
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004073 // It could be a specific immediate in which case we should just check for
4074 // that immediate.
4075 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004076 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004077 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4078 return InsertPt;
4079 }
4080
Daniel Sandersffc7d582017-03-29 15:37:18 +00004081 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004082 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004083 auto *ChildRec = ChildDefInit->getDef();
4084
Florian Hahn6b1db822018-06-14 20:32:58 +00004085 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004086 if (ChildTypes.size() != 1)
4087 return failedImport("Dst pattern child has multiple results");
4088
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004089 Optional<LLTCodeGen> OpTyOrNone = None;
4090 if (ChildTypes.front().isMachineValueType())
4091 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004092 if (!OpTyOrNone)
4093 return failedImport("Dst operand has an unsupported type");
4094
4095 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004096 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00004097 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004098 }
4099
Daniel Sanders658541f2017-04-22 15:53:21 +00004100 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004101 ChildRec->isSubClassOf("RegisterOperand") ||
4102 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00004103 if (ChildRec->isSubClassOf("RegisterOperand") &&
4104 !ChildRec->isValueUnset("GIZeroRegister")) {
4105 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004106 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00004107 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00004108 }
4109
Florian Hahn6b1db822018-06-14 20:32:58 +00004110 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004111 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004112 }
4113
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004114 if (ChildRec->isSubClassOf("SubRegIndex")) {
4115 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4116 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4117 return InsertPt;
4118 }
4119
Daniel Sandersffc7d582017-03-29 15:37:18 +00004120 if (ChildRec->isSubClassOf("ComplexPattern")) {
4121 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4122 if (ComplexPattern == ComplexPatternEquivs.end())
4123 return failedImport(
4124 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4125
Florian Hahn6b1db822018-06-14 20:32:58 +00004126 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004127 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004128 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004129 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004130 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004131 }
4132
4133 return failedImport(
4134 "Dst pattern child def is an unsupported tablegen class");
4135 }
4136
4137 return failedImport("Dst pattern child is an unsupported kind");
4138}
4139
Daniel Sandersc270c502017-03-30 09:36:33 +00004140Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004141 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4142 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004143 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4144 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004145 return std::move(Error);
4146
Daniel Sanders7438b262017-10-31 23:03:18 +00004147 action_iterator InsertPt = InsertPtOrError.get();
4148 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004149
Matt Arsenault3e45c702019-09-06 20:32:37 +00004150 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4151 InsertPt = M.insertAction<BuildMIAction>(
4152 InsertPt, M.allocateOutputInsnID(),
4153 &Target.getInstruction(RK.getDef("COPY")));
4154 BuildMIAction &CopyToPhysRegMIBuilder =
4155 *static_cast<BuildMIAction *>(InsertPt->get());
4156 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4157 true);
4158 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4159 }
4160
Daniel Sandersdf258e32017-10-31 19:09:29 +00004161 importExplicitDefRenderers(DstMIBuilder);
4162
Daniel Sanders7438b262017-10-31 23:03:18 +00004163 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4164 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004165 return std::move(Error);
4166
4167 return DstMIBuilder;
4168}
4169
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004170Expected<action_iterator>
4171GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004172 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004173 unsigned TempRegID) {
4174 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4175
4176 // TODO: Assert there's exactly one result.
4177
4178 if (auto Error = InsertPtOrError.takeError())
4179 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004180
4181 BuildMIAction &DstMIBuilder =
4182 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4183
4184 // Assign the result to TempReg.
4185 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4186
Daniel Sanders08464522018-01-29 21:09:12 +00004187 InsertPtOrError =
4188 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004189 if (auto Error = InsertPtOrError.takeError())
4190 return std::move(Error);
4191
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004192 // We need to make sure that when we import an INSERT_SUBREG as a
4193 // subinstruction that it ends up being constrained to the correct super
4194 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004195 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4196 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004197 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4198 if (!SubClass)
4199 return failedImport(
4200 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004201 Optional<const CodeGenRegisterClass *> SuperClass =
4202 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4203 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004204 if (!SuperClass)
4205 return failedImport(
4206 "Cannot infer register class for INSERT_SUBREG operand #0");
4207 // The destination and the super register source of an INSERT_SUBREG must
4208 // be the same register class.
4209 M.insertAction<ConstrainOperandToRegClassAction>(
4210 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4211 M.insertAction<ConstrainOperandToRegClassAction>(
4212 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4213 M.insertAction<ConstrainOperandToRegClassAction>(
4214 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4215 return InsertPtOrError.get();
4216 }
4217
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004218 if (OpName == "EXTRACT_SUBREG") {
4219 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4220 // instructions, the result register class is controlled by the
4221 // subregisters of the operand. As a result, we must constrain the result
4222 // class rather than check that it's already the right one.
4223 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4224 if (!SuperClass)
4225 return failedImport(
4226 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4227
4228 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4229 if (!SubIdx)
4230 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4231
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004232 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004233 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4234 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4235 M.insertAction<ConstrainOperandToRegClassAction>(
4236 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4237 M.insertAction<ConstrainOperandToRegClassAction>(
4238 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4239
4240 // We're done with this pattern! It's eligible for GISel emission; return
4241 // it.
4242 return InsertPtOrError.get();
4243 }
4244
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004245 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4246 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004247 if (OpName == "SUBREG_TO_REG") {
4248 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4249 if (!SubClass)
4250 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004251 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004252 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4253 Dst->getChild(2));
4254 if (!SuperClass)
4255 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004256 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004257 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004258 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004259 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004260 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004261 return InsertPtOrError.get();
4262 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004263
Daniel Sanders08464522018-01-29 21:09:12 +00004264 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4265 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004266 return InsertPtOrError.get();
4267}
4268
Daniel Sanders7438b262017-10-31 23:03:18 +00004269Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004270 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4271 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004272 if (!DstOp->isSubClassOf("Instruction")) {
4273 if (DstOp->isSubClassOf("ValueType"))
4274 return failedImport(
4275 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004276 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004277 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004278 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004279
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004280 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004281 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004282 StringRef Name = DstI->TheDef->getName();
4283 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004284 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004285
Daniel Sanders198447a2017-11-01 00:29:47 +00004286 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4287 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004288}
4289
4290void GlobalISelEmitter::importExplicitDefRenderers(
4291 BuildMIAction &DstMIBuilder) {
4292 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004293 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
4294 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00004295 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004296 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00004297}
4298
Daniel Sanders7438b262017-10-31 23:03:18 +00004299Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4300 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004301 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004302 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004303 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004304
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004305 StringRef Name = OrigDstI->TheDef->getName();
4306 unsigned ExpectedDstINumUses = Dst->getNumChildren();
4307
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004308 // EXTRACT_SUBREG needs to use a subregister COPY.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004309 if (Name == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004310 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004311 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4312
Daniel Sanders32291982017-06-28 13:50:04 +00004313 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004314 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
4315 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004316 if (!RCDef)
4317 return failedImport("EXTRACT_SUBREG child #0 could not "
4318 "be coerced to a register class");
4319
4320 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004321 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4322
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004323 const auto SrcRCDstRCPair =
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004324 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4325 if (SrcRCDstRCPair.hasValue()) {
4326 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4327 if (SrcRCDstRCPair->first != RC)
4328 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4329 }
4330
Florian Hahn6b1db822018-06-14 20:32:58 +00004331 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00004332 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004333 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004334 }
4335
4336 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4337 }
4338
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004339 if (Name == "REG_SEQUENCE") {
4340 if (!Dst->getChild(0)->isLeaf())
4341 return failedImport("REG_SEQUENCE child #0 is not a leaf");
4342
4343 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4344 if (!RCDef)
4345 return failedImport("REG_SEQUENCE child #0 could not "
4346 "be coerced to a register class");
4347
4348 if ((ExpectedDstINumUses - 1) % 2 != 0)
4349 return failedImport("Malformed REG_SEQUENCE");
4350
4351 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4352 TreePatternNode *ValChild = Dst->getChild(I);
4353 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4354
4355 if (DefInit *SubRegInit =
4356 dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4357 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4358
4359 auto InsertPtOrError =
4360 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4361 if (auto Error = InsertPtOrError.takeError())
4362 return std::move(Error);
4363 InsertPt = InsertPtOrError.get();
4364 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4365 }
4366 }
4367
4368 return InsertPt;
4369 }
4370
Daniel Sandersffc7d582017-03-29 15:37:18 +00004371 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004372 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004373 if (Name == "COPY_TO_REGCLASS") {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004374 DstINumUses--; // Ignore the class constraint.
4375 ExpectedDstINumUses--;
4376 }
4377
Matt Arsenault26f714f2019-10-21 21:39:42 -07004378 // NumResults - This is the number of results produced by the instruction in
4379 // the "outs" list.
4380 unsigned NumResults = OrigDstI->Operands.NumDefs;
4381
4382 // Number of operands we know the output instruction must have. If it is
4383 // variadic, we could have more operands.
4384 unsigned NumFixedOperands = DstI->Operands.size();
4385
4386 // Loop over all of the fixed operands of the instruction pattern, emitting
4387 // code to fill them all in. The node 'N' usually has number children equal to
4388 // the number of input operands of the instruction. However, in cases where
4389 // there are predicate operands for an instruction, we need to fill in the
4390 // 'execute always' values. Match up the node operands to the instruction
4391 // operands to do this.
Daniel Sanders0ed28822017-04-12 08:23:08 +00004392 unsigned Child = 0;
Matt Arsenault26f714f2019-10-21 21:39:42 -07004393
4394 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4395 // number of operands at the end of the list which have default values.
4396 // Those can come from the pattern if it provides enough arguments, or be
4397 // filled in with the default if the pattern hasn't provided them. But any
4398 // operand with a default value _before_ the last mandatory one will be
4399 // filled in with their defaults unconditionally.
4400 unsigned NonOverridableOperands = NumFixedOperands;
4401 while (NonOverridableOperands > NumResults &&
4402 CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4403 --NonOverridableOperands;
4404
Diana Picus382602f2017-05-17 08:57:28 +00004405 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004406 for (unsigned I = 0; I != DstINumUses; ++I) {
Matt Arsenault26f714f2019-10-21 21:39:42 -07004407 unsigned InstOpNo = DstI->Operands.NumDefs + I;
4408
4409 // Determine what to emit for this operand.
4410 Record *OperandNode = DstI->Operands[InstOpNo].Rec;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004411
Diana Picus382602f2017-05-17 08:57:28 +00004412 // If the operand has default values, introduce them now.
Matt Arsenault26f714f2019-10-21 21:39:42 -07004413 if (CGP.operandHasDefault(OperandNode) &&
4414 (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4415 // This is a predicate or optional def operand which the pattern has not
4416 // overridden, or which we aren't letting it override; emit the 'default
4417 // ops' operands.
4418
4419 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004420 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004421 if (auto Error = importDefaultOperandRenderers(
4422 InsertPt, M, DstMIBuilder, DefaultOps))
Diana Picus382602f2017-05-17 08:57:28 +00004423 return std::move(Error);
4424 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004425 continue;
4426 }
4427
Daniel Sanders7438b262017-10-31 23:03:18 +00004428 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004429 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004430 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00004431 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004432 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004433 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004434 }
4435
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004436 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004437 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004438 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004439 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004440 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004441 " default ones");
4442
Daniel Sanders7438b262017-10-31 23:03:18 +00004443 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004444}
4445
Diana Picus382602f2017-05-17 08:57:28 +00004446Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004447 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4448 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004449 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004450 Optional<LLTCodeGen> OpTyOrNone = None;
4451
Diana Picus382602f2017-05-17 08:57:28 +00004452 // Look through ValueType operators.
4453 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4454 if (const DefInit *DefaultDagOperator =
4455 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004456 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004457 OpTyOrNone = MVTToLLT(getValueType(
4458 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004459 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004460 }
Diana Picus382602f2017-05-17 08:57:28 +00004461 }
4462 }
4463
4464 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004465 auto Def = DefaultDefOp->getDef();
4466 if (Def->getName() == "undef_tied_input") {
4467 unsigned TempRegID = M.allocateTempRegID();
4468 M.insertAction<MakeTempRegisterAction>(
4469 InsertPt, OpTyOrNone.getValue(), TempRegID);
4470 InsertPt = M.insertAction<BuildMIAction>(
4471 InsertPt, M.allocateOutputInsnID(),
4472 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4473 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4474 InsertPt->get());
4475 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4476 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4477 } else {
4478 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4479 }
Diana Picus382602f2017-05-17 08:57:28 +00004480 continue;
4481 }
4482
4483 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004484 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004485 continue;
4486 }
4487
4488 return failedImport("Could not add default op");
4489 }
4490
4491 return Error::success();
4492}
4493
Daniel Sandersc270c502017-03-30 09:36:33 +00004494Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004495 BuildMIAction &DstMIBuilder,
4496 const std::vector<Record *> &ImplicitDefs) const {
4497 if (!ImplicitDefs.empty())
4498 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004499 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004500}
4501
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004502Optional<const CodeGenRegisterClass *>
4503GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4504 assert(Leaf && "Expected node?");
4505 assert(Leaf->isLeaf() && "Expected leaf?");
4506 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4507 if (!RCRec)
4508 return None;
4509 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4510 if (!RC)
4511 return None;
4512 return RC;
4513}
4514
4515Optional<const CodeGenRegisterClass *>
4516GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4517 if (!N)
4518 return None;
4519
4520 if (N->isLeaf())
4521 return getRegClassFromLeaf(N);
4522
4523 // We don't have a leaf node, so we have to try and infer something. Check
4524 // that we have an instruction that we an infer something from.
4525
4526 // Only handle things that produce a single type.
4527 if (N->getNumTypes() != 1)
4528 return None;
4529 Record *OpRec = N->getOperator();
4530
4531 // We only want instructions.
4532 if (!OpRec->isSubClassOf("Instruction"))
4533 return None;
4534
4535 // Don't want to try and infer things when there could potentially be more
4536 // than one candidate register class.
4537 auto &Inst = Target.getInstruction(OpRec);
4538 if (Inst.Operands.NumDefs > 1)
4539 return None;
4540
4541 // Handle any special-case instructions which we can safely infer register
4542 // classes from.
4543 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004544 bool IsRegSequence = InstName == "REG_SEQUENCE";
4545 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004546 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4547 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004548 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004549 if (!RCChild->isLeaf())
4550 return None;
4551 return getRegClassFromLeaf(RCChild);
4552 }
4553
4554 // Handle destination record types that we can safely infer a register class
4555 // from.
4556 const auto &DstIOperand = Inst.Operands[0];
4557 Record *DstIOpRec = DstIOperand.Rec;
4558 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4559 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4560 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4561 return &RC;
4562 }
4563
4564 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4565 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4566 return &RC;
4567 }
4568
4569 return None;
4570}
4571
4572Optional<const CodeGenRegisterClass *>
4573GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004574 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004575 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004576 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4577 if (!Ty.isValueTypeByHwMode(false))
4578 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004579 if (!SubRegIdxNode->isLeaf())
4580 return None;
4581 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4582 if (!SubRegInit)
4583 return None;
4584 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4585
4586 // Use the information we found above to find a minimal register class which
4587 // supports the subregister and type we want.
4588 auto RC =
4589 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4590 if (!RC)
4591 return None;
4592 return *RC;
4593}
4594
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004595Optional<const CodeGenRegisterClass *>
4596GlobalISelEmitter::inferSuperRegisterClassForNode(
4597 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4598 TreePatternNode *SubRegIdxNode) {
4599 assert(SuperRegNode && "Expected super register node!");
4600 // Check if we already have a defined register class for the super register
4601 // node. If we do, then we should preserve that rather than inferring anything
4602 // from the subregister index node. We can assume that whoever wrote the
4603 // pattern in the first place made sure that the super register and
4604 // subregister are compatible.
4605 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4606 inferRegClassFromPattern(SuperRegNode))
4607 return *SuperRegisterClass;
4608 return inferSuperRegisterClass(Ty, SubRegIdxNode);
4609}
4610
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004611Optional<CodeGenSubRegIndex *>
4612GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4613 if (!SubRegIdxNode->isLeaf())
4614 return None;
4615
4616 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4617 if (!SubRegInit)
4618 return None;
4619 return CGRegs.getSubRegIdx(SubRegInit->getDef());
4620}
4621
Daniel Sandersffc7d582017-03-29 15:37:18 +00004622Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004623 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004624 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004625 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004626 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004627 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4628 " => " +
4629 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004630
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004631 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004632 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004633
4634 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004635 TreePatternNode *Src = P.getSrcPattern();
4636 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004637
4638 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004639 if (auto Err = isTrivialOperatorNode(Dst))
4640 return failedImport("Dst pattern root isn't a trivial operator (" +
4641 toString(std::move(Err)) + ")");
4642 if (auto Err = isTrivialOperatorNode(Src))
4643 return failedImport("Src pattern root isn't a trivial operator (" +
4644 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004645
Quentin Colombetaad20be2017-12-15 23:07:42 +00004646 // The different predicates and matchers created during
4647 // addInstructionMatcher use the RuleMatcher M to set up their
4648 // instruction ID (InsnVarID) that are going to be used when
4649 // M is going to be emitted.
4650 // However, the code doing the emission still relies on the IDs
4651 // returned during that process by the RuleMatcher when issuing
4652 // the recordInsn opcodes.
4653 // Because of that:
4654 // 1. The order in which we created the predicates
4655 // and such must be the same as the order in which we emit them,
4656 // and
4657 // 2. We need to reset the generation of the IDs in M somewhere between
4658 // addInstructionMatcher and emit
4659 //
4660 // FIXME: Long term, we don't want to have to rely on this implicit
4661 // naming being the same. One possible solution would be to have
4662 // explicit operator for operation capture and reference those.
4663 // The plus side is that it would expose opportunities to share
4664 // the capture accross rules. The downside is that it would
4665 // introduce a dependency between predicates (captures must happen
4666 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004667 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004668 unsigned TempOpIdx = 0;
4669 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004670 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004671 if (auto Error = InsnMatcherOrError.takeError())
4672 return std::move(Error);
4673 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4674
Florian Hahn6b1db822018-06-14 20:32:58 +00004675 if (Dst->isLeaf()) {
4676 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004677
4678 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4679 if (RCDef) {
4680 // We need to replace the def and all its uses with the specified
4681 // operand. However, we must also insert COPY's wherever needed.
4682 // For now, emit a copy and let the register allocator clean up.
4683 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4684 const auto &DstIOperand = DstI.Operands[0];
4685
4686 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4687 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004688 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004689 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4690
Daniel Sanders198447a2017-11-01 00:29:47 +00004691 auto &DstMIBuilder =
4692 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4693 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004694 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004695 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4696
4697 // We're done with this pattern! It's eligible for GISel emission; return
4698 // it.
4699 ++NumPatternImported;
4700 return std::move(M);
4701 }
4702
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004703 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004704 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004705
Daniel Sandersbee57392017-04-04 13:25:23 +00004706 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004707 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004708 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004709 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004710
4711 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004712 StringRef DstIName = DstI.TheDef->getName();
4713
Florian Hahn6b1db822018-06-14 20:32:58 +00004714 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00004715 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004716 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004717 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004718
Daniel Sandersffc7d582017-03-29 15:37:18 +00004719 // The root of the match also has constraints on the register bank so that it
4720 // matches the result instruction.
4721 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004722 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004723 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004724
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004725 const auto &DstIOperand = DstI.Operands[OpIdx];
4726 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004727 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004728 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004729
4730 if (DstIOpRec == nullptr)
4731 return failedImport(
4732 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004733 } else if (DstIName == "REG_SEQUENCE") {
4734 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4735 if (DstIOpRec == nullptr)
4736 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4737 } else if (DstIName == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004738 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004739 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
4740
Daniel Sanders32291982017-06-28 13:50:04 +00004741 // We can assume that a subregister is in the same bank as it's super
4742 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00004743 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004744
4745 if (DstIOpRec == nullptr)
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004746 return failedImport("EXTRACT_SUBREG operand #0 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004747 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004748 auto MaybeSuperClass = inferSuperRegisterClassForNode(
4749 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004750 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004751 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004752 "Cannot infer register class for INSERT_SUBREG operand #0");
4753 // Move to the next pattern here, because the register class we found
4754 // doesn't necessarily have a record associated with it. So, we can't
4755 // set DstIOpRec using this.
4756 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4757 OM.setSymbolicName(DstIOperand.Name);
4758 M.defineOperand(OM.getSymbolicName(), OM);
4759 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4760 ++OpIdx;
4761 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004762 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004763 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
4764 if (!MaybeRegClass)
4765 return failedImport(
4766 "Cannot infer register class for SUBREG_TO_REG operand #0");
4767 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4768 OM.setSymbolicName(DstIOperand.Name);
4769 M.defineOperand(OM.getSymbolicName(), OM);
4770 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
4771 ++OpIdx;
4772 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004773 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004774 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004775 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004776 return failedImport("Dst MI def isn't a register class" +
4777 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004778
Daniel Sandersffc7d582017-03-29 15:37:18 +00004779 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4780 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004781 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004782 OM.addPredicate<RegisterBankOperandMatcher>(
4783 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004784 ++OpIdx;
4785 }
4786
Matt Arsenault3e45c702019-09-06 20:32:37 +00004787 auto DstMIBuilderOrError =
4788 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004789 if (auto Error = DstMIBuilderOrError.takeError())
4790 return std::move(Error);
4791 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004792
Daniel Sandersffc7d582017-03-29 15:37:18 +00004793 // Render the implicit defs.
4794 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004795 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004796 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004797
Daniel Sandersa7b75262017-10-31 18:50:24 +00004798 DstMIBuilder.chooseInsnToMutate(M);
4799
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004800 // Constrain the registers to classes. This is normally derived from the
4801 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004802 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004803 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4804 // result is constrained to the class given by the second child.
4805 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004806 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004807
4808 if (DstIOpRec == nullptr)
4809 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4810
4811 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004812 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004813
4814 // We're done with this pattern! It's eligible for GISel emission; return
4815 // it.
4816 ++NumPatternImported;
4817 return std::move(M);
4818 }
4819
Matt Arsenault38fb3442019-09-04 16:19:34 +00004820 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004821 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4822 if (!SuperClass)
4823 return failedImport(
4824 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004825
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004826 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4827 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00004828 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004829
Daniel Sanders320390b2017-06-28 15:16:03 +00004830 // It would be nice to leave this constraint implicit but we're required
4831 // to pick a register class so constrain the result to a register class
4832 // that can hold the correct MVT.
4833 //
4834 // FIXME: This may introduce an extra copy if the chosen class doesn't
4835 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004836 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004837 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004838
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004839 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004840 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Daniel Sanders320390b2017-06-28 15:16:03 +00004841 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004842 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4843 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4844
4845 // We're done with this pattern! It's eligible for GISel emission; return
4846 // it.
4847 ++NumPatternImported;
4848 return std::move(M);
4849 }
4850
Matt Arsenault38fb3442019-09-04 16:19:34 +00004851 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004852 assert(Src->getExtTypes().size() == 1 &&
4853 "Expected Src of INSERT_SUBREG to have one result type");
4854 // We need to constrain the destination, a super regsister source, and a
4855 // subregister source.
4856 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4857 if (!SubClass)
4858 return failedImport(
4859 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004860 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004861 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4862 if (!SuperClass)
4863 return failedImport(
4864 "Cannot infer register class for INSERT_SUBREG operand #0");
4865 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4866 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4867 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4868 ++NumPatternImported;
4869 return std::move(M);
4870 }
4871
Matt Arsenault38fb3442019-09-04 16:19:34 +00004872 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004873 // We need to constrain the destination and subregister source.
4874 assert(Src->getExtTypes().size() == 1 &&
4875 "Expected Src of SUBREG_TO_REG to have one result type");
4876
4877 // Attempt to infer the subregister source from the first child. If it has
4878 // an explicitly given register class, we'll use that. Otherwise, we will
4879 // fail.
4880 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4881 if (!SubClass)
4882 return failedImport(
4883 "Cannot infer register class from SUBREG_TO_REG child #1");
4884 // We don't have a child to look at that might have a super register node.
4885 auto SuperClass =
4886 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
4887 if (!SuperClass)
4888 return failedImport(
4889 "Cannot infer register class for SUBREG_TO_REG operand #0");
4890 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4891 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4892 ++NumPatternImported;
4893 return std::move(M);
4894 }
4895
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004896 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004897
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004898 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004899 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004900 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004901}
4902
Daniel Sanders649c5852017-10-13 20:42:18 +00004903// Emit imm predicate table and an enum to reference them with.
4904// The 'Predicate_' part of the name is redundant but eliminating it is more
4905// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004906void GlobalISelEmitter::emitCxxPredicateFns(
4907 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4908 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004909 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004910 std::vector<const Record *> MatchedRecords;
4911 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4912 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4913 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004914 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004915 Filter(Record);
4916 });
4917
Daniel Sanders11300ce2017-10-13 21:28:03 +00004918 if (!MatchedRecords.empty()) {
4919 OS << "// PatFrag predicates.\n"
4920 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004921 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004922 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4923 for (const auto *Record : MatchedRecords) {
4924 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4925 << EnumeratorSeparator;
4926 EnumeratorSeparator = ",\n";
4927 }
4928 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004929 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004930
Daniel Sanders8ead1292018-06-15 23:13:43 +00004931 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4932 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4933 << ArgName << ") const {\n"
4934 << AdditionalDeclarations;
4935 if (!AdditionalDeclarations.empty())
4936 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004937 if (!MatchedRecords.empty())
4938 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004939 for (const auto *Record : MatchedRecords) {
4940 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4941 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004942 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4943 << " llvm_unreachable(\"" << CodeFieldName
4944 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004945 << " return false;\n"
4946 << " }\n";
4947 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004948 if (!MatchedRecords.empty())
4949 OS << " }\n";
4950 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004951 << " return false;\n"
4952 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004953}
4954
Daniel Sanders8ead1292018-06-15 23:13:43 +00004955void GlobalISelEmitter::emitImmPredicateFns(
4956 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4957 std::function<bool(const Record *R)> Filter) {
4958 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4959 "Imm", "", Filter);
4960}
4961
4962void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4963 return emitCxxPredicateFns(
4964 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4965 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00004966 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4967 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00004968 [](const Record *R) { return true; });
4969}
4970
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004971template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004972std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004973 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004974 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4975
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004976 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004977 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004978 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4979 unsigned NumGroups = 0;
4980
4981 auto ProcessCurrentGroup = [&]() {
4982 if (CurrentGroup->empty())
4983 // An empty group is good to be reused:
4984 return;
4985
4986 // If the group isn't large enough to provide any benefit, move all the
4987 // added rules out of it and make sure to re-create the group to properly
4988 // re-initialize it:
4989 if (CurrentGroup->size() < 2)
4990 for (Matcher *M : CurrentGroup->matchers())
4991 OptRules.push_back(M);
4992 else {
4993 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004994 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004995 MatcherStorage.emplace_back(std::move(CurrentGroup));
4996 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004997 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004998 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004999 };
5000 for (Matcher *Rule : Rules) {
5001 // Greedily add as many matchers as possible to the current group:
5002 if (CurrentGroup->addMatcher(*Rule))
5003 continue;
5004
5005 ProcessCurrentGroup();
5006 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5007
5008 // Try to add the pending matcher to a newly created empty group:
5009 if (!CurrentGroup->addMatcher(*Rule))
5010 // If we couldn't add the matcher to an empty group, that group type
5011 // doesn't support that kind of matchers at all, so just skip it:
5012 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005013 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005014 ProcessCurrentGroup();
5015
Nicola Zaghen03d0b912018-05-23 15:09:29 +00005016 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005017 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005018 return OptRules;
5019}
5020
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005021MatchTable
5022GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00005023 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005024 std::vector<Matcher *> InputRules;
5025 for (Matcher &Rule : Rules)
5026 InputRules.push_back(&Rule);
5027
5028 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00005029 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005030
Roman Tereshin77013602018-05-22 16:54:27 +00005031 unsigned CurrentOrdering = 0;
5032 StringMap<unsigned> OpcodeOrder;
5033 for (RuleMatcher &Rule : Rules) {
5034 const StringRef Opcode = Rule.getOpcode();
5035 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5036 if (OpcodeOrder.count(Opcode) == 0)
5037 OpcodeOrder[Opcode] = CurrentOrdering++;
5038 }
5039
5040 std::stable_sort(InputRules.begin(), InputRules.end(),
5041 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5042 auto *L = static_cast<const RuleMatcher *>(A);
5043 auto *R = static_cast<const RuleMatcher *>(B);
5044 return std::make_tuple(OpcodeOrder[L->getOpcode()],
5045 L->getNumOperands()) <
5046 std::make_tuple(OpcodeOrder[R->getOpcode()],
5047 R->getNumOperands());
5048 });
5049
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005050 for (Matcher *Rule : InputRules)
5051 Rule->optimize();
5052
5053 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005054 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005055 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5056
5057 for (Matcher *Rule : OptRules)
5058 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005059
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005060 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5061
Roman Tereshinbeb39312018-05-02 20:15:11 +00005062 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005063}
5064
Roman Tereshinfedae332018-05-23 02:04:19 +00005065void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00005066 // Make sure we only sort by a specific predicate within a range of rules that
5067 // all have that predicate checked against a specific value (not a wildcard):
5068 auto F = Matchers.begin();
5069 auto T = F;
5070 auto E = Matchers.end();
5071 while (T != E) {
5072 while (T != E) {
5073 auto *R = static_cast<RuleMatcher *>(*T);
5074 if (!R->getFirstConditionAsRootType().get().isValid())
5075 break;
5076 ++T;
5077 }
5078 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5079 auto *L = static_cast<RuleMatcher *>(A);
5080 auto *R = static_cast<RuleMatcher *>(B);
5081 return L->getFirstConditionAsRootType() <
5082 R->getFirstConditionAsRootType();
5083 });
5084 if (T != E)
5085 F = ++T;
5086 }
Roman Tereshinfedae332018-05-23 02:04:19 +00005087 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5088 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00005089 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5090 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00005091}
5092
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005093void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00005094 if (!UseCoverageFile.empty()) {
5095 RuleCoverage = CodeGenCoverage();
5096 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5097 if (!RuleCoverageBufOrErr) {
5098 PrintWarning(SMLoc(), "Missing rule coverage data");
5099 RuleCoverage = None;
5100 } else {
5101 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5102 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5103 RuleCoverage = None;
5104 }
5105 }
5106 }
5107
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005108 // Track the run-time opcode values
5109 gatherOpcodeValues();
5110 // Track the run-time LLT ID values
5111 gatherTypeIDValues();
5112
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005113 // Track the GINodeEquiv definitions.
5114 gatherNodeEquivs();
5115
5116 emitSourceFileHeader(("Global Instruction Selector for the " +
5117 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005118 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005119 // Look through the SelectionDAG patterns we found, possibly emitting some.
5120 for (const PatternToMatch &Pat : CGP.ptms()) {
5121 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00005122
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005123 auto MatcherOrErr = runOnPattern(Pat);
5124
5125 // The pattern analysis can fail, indicating an unsupported pattern.
5126 // Report that if we've been asked to do so.
5127 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005128 if (WarnOnSkippedPatterns) {
5129 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005130 "Skipped pattern: " + toString(std::move(Err)));
5131 } else {
5132 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005133 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005134 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005135 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005136 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005137
Daniel Sandersf76f3152017-11-16 00:46:35 +00005138 if (RuleCoverage) {
5139 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5140 ++NumPatternsTested;
5141 else
5142 PrintWarning(Pat.getSrcRecord()->getLoc(),
5143 "Pattern is not covered by a test");
5144 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005145 Rules.push_back(std::move(MatcherOrErr.get()));
5146 }
5147
Volkan Kelesf7f25682018-01-16 18:44:05 +00005148 // Comparison function to order records by name.
5149 auto orderByName = [](const Record *A, const Record *B) {
5150 return A->getName() < B->getName();
5151 };
5152
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005153 std::vector<Record *> ComplexPredicates =
5154 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00005155 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005156
5157 std::vector<Record *> CustomRendererFns =
5158 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00005159 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005160
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005161 unsigned MaxTemporaries = 0;
5162 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00005163 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005164
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005165 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5166 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5167 << ";\n"
5168 << "using PredicateBitset = "
5169 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5170 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5171
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005172 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5173 << " mutable MatcherState State;\n"
5174 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00005175 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005176 << Target.getName()
5177 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005178
5179 << " typedef void(" << Target.getName()
5180 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
Matt Arsenaultb4a64742020-01-08 12:53:15 -05005181 "MachineInstr&, int) "
Volkan Kelesf7f25682018-01-16 18:44:05 +00005182 "const;\n"
5183 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5184 "CustomRendererFn> "
5185 "ISelInfo;\n";
5186 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005187 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005188 << " static " << Target.getName()
5189 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005190 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005191 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005192 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005193 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005194 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005195 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005196 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005197 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5198 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005199 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005200
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005201 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5202 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005203 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5204 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005205 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005206
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005207 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5208 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5209 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005210
5211 // Separate subtarget features by how often they must be recomputed.
5212 SubtargetFeatureInfoMap ModuleFeatures;
5213 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5214 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5215 [](const SubtargetFeatureInfoMap::value_type &X) {
5216 return !X.second.mustRecomputePerFunction();
5217 });
5218 SubtargetFeatureInfoMap FunctionFeatures;
5219 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5220 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5221 [](const SubtargetFeatureInfoMap::value_type &X) {
5222 return X.second.mustRecomputePerFunction();
5223 });
5224
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005225 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Matt Arsenaultf937b432020-01-08 19:49:30 -05005226 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005227 ModuleFeatures, OS);
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005228
Matt Arsenaultf937b432020-01-08 19:49:30 -05005229
5230 OS << "void " << Target.getName() << "InstructionSelector"
5231 "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5232 " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5233 "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5234 "}\n";
5235
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005236 if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5237 // TODO: Implement PGSO.
5238 OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5239 OS << " return MF->getFunction().hasOptSize();\n";
5240 OS << "}\n\n";
5241 }
5242
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005243 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5244 Target.getName(), "InstructionSelector",
5245 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5246 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005247
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005248 // Emit a table containing the LLT objects needed by the matcher and an enum
5249 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005250 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005251 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005252 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005253 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005254 OS << "// LLT Objects.\n"
5255 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005256 for (const auto &TypeObject : TypeObjects) {
5257 OS << " ";
5258 TypeObject.emitCxxEnumValue(OS);
5259 OS << ",\n";
5260 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005261 OS << "};\n";
5262 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005263 << "const static LLT TypeObjects[] = {\n";
5264 for (const auto &TypeObject : TypeObjects) {
5265 OS << " ";
5266 TypeObject.emitCxxConstructorCall(OS);
5267 OS << ",\n";
5268 }
5269 OS << "};\n\n";
5270
5271 // Emit a table containing the PredicateBitsets objects needed by the matcher
5272 // and an enum for the matcher to reference them with.
5273 std::vector<std::vector<Record *>> FeatureBitsets;
5274 for (auto &Rule : Rules)
5275 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005276 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5277 const std::vector<Record *> &B) {
5278 if (A.size() < B.size())
5279 return true;
5280 if (A.size() > B.size())
5281 return false;
Mark de Wevere8d448e2019-12-22 18:58:32 +01005282 for (auto Pair : zip(A, B)) {
Fangrui Song3507c6e2018-09-30 22:31:29 +00005283 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5284 return true;
5285 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005286 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005287 }
5288 return false;
5289 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005290 FeatureBitsets.erase(
5291 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5292 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005293 OS << "// Feature bitsets.\n"
5294 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005295 << " GIFBS_Invalid,\n";
5296 for (const auto &FeatureBitset : FeatureBitsets) {
5297 if (FeatureBitset.empty())
5298 continue;
5299 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5300 }
5301 OS << "};\n"
5302 << "const static PredicateBitset FeatureBitsets[] {\n"
5303 << " {}, // GIFBS_Invalid\n";
5304 for (const auto &FeatureBitset : FeatureBitsets) {
5305 if (FeatureBitset.empty())
5306 continue;
5307 OS << " {";
5308 for (const auto &Feature : FeatureBitset) {
5309 const auto &I = SubtargetFeatures.find(Feature);
5310 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5311 OS << I->second.getEnumBitName() << ", ";
5312 }
5313 OS << "},\n";
5314 }
5315 OS << "};\n\n";
5316
5317 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005318 OS << "// ComplexPattern predicates.\n"
5319 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005320 << " GICP_Invalid,\n";
5321 for (const auto &Record : ComplexPredicates)
5322 OS << " GICP_" << Record->getName() << ",\n";
5323 OS << "};\n"
5324 << "// See constructor for table contents\n\n";
5325
Daniel Sanders8ead1292018-06-15 23:13:43 +00005326 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005327 bool Unset;
5328 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5329 !R->getValueAsBit("IsAPInt");
5330 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005331 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005332 bool Unset;
5333 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5334 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005335 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005336 return R->getValueAsBit("IsAPInt");
5337 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005338 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005339 OS << "\n";
5340
5341 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5342 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5343 << " nullptr, // GICP_Invalid\n";
5344 for (const auto &Record : ComplexPredicates)
5345 OS << " &" << Target.getName()
5346 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5347 << ", // " << Record->getName() << "\n";
5348 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005349
Volkan Kelesf7f25682018-01-16 18:44:05 +00005350 OS << "// Custom renderers.\n"
5351 << "enum {\n"
5352 << " GICR_Invalid,\n";
5353 for (const auto &Record : CustomRendererFns)
5354 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5355 OS << "};\n";
5356
5357 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5358 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
Matt Arsenault0274ed92020-01-08 18:57:44 -05005359 << " nullptr, // GICR_Invalid\n";
Volkan Kelesf7f25682018-01-16 18:44:05 +00005360 for (const auto &Record : CustomRendererFns)
5361 OS << " &" << Target.getName()
5362 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5363 << ", // " << Record->getName() << "\n";
5364 OS << "};\n\n";
5365
Fangrui Songefd94c52019-04-23 14:51:27 +00005366 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005367 int ScoreA = RuleMatcherScores[A.getRuleID()];
5368 int ScoreB = RuleMatcherScores[B.getRuleID()];
5369 if (ScoreA > ScoreB)
5370 return true;
5371 if (ScoreB > ScoreA)
5372 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005373 if (A.isHigherPriorityThan(B)) {
5374 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5375 "and less important at "
5376 "the same time");
5377 return true;
5378 }
5379 return false;
5380 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005381
Roman Tereshin2df4c222018-05-02 20:07:15 +00005382 OS << "bool " << Target.getName()
5383 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5384 "&CoverageInfo) const {\n"
5385 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5386 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005387 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5388 << " NewMIVector OutMIs;\n"
5389 << " State.MIs.clear();\n"
5390 << " State.MIs.push_back(&I);\n\n"
5391 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5392 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5393 << ", CoverageInfo)) {\n"
5394 << " return true;\n"
5395 << " }\n\n"
5396 << " return false;\n"
5397 << "}\n\n";
5398
Roman Tereshinbeb39312018-05-02 20:15:11 +00005399 const MatchTable Table =
5400 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005401 OS << "const int64_t *" << Target.getName()
5402 << "InstructionSelector::getMatchTable() const {\n";
5403 Table.emitDeclaration(OS);
5404 OS << " return ";
5405 Table.emitUse(OS);
5406 OS << ";\n}\n";
5407 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005408
5409 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5410 << "PredicateBitset AvailableModuleFeatures;\n"
5411 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5412 << "PredicateBitset getAvailableFeatures() const {\n"
5413 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5414 << "}\n"
5415 << "PredicateBitset\n"
5416 << "computeAvailableModuleFeatures(const " << Target.getName()
5417 << "Subtarget *Subtarget) const;\n"
5418 << "PredicateBitset\n"
5419 << "computeAvailableFunctionFeatures(const " << Target.getName()
5420 << "Subtarget *Subtarget,\n"
5421 << " const MachineFunction *MF) const;\n"
Matt Arsenaultf937b432020-01-08 19:49:30 -05005422 << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005423 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5424
5425 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5426 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5427 << "AvailableFunctionFeatures()\n"
5428 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005429}
5430
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005431void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5432 if (SubtargetFeatures.count(Predicate) == 0)
5433 SubtargetFeatures.emplace(
5434 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5435}
5436
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005437void RuleMatcher::optimize() {
5438 for (auto &Item : InsnVariableIDs) {
5439 InstructionMatcher &InsnMatcher = *Item.first;
5440 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005441 // Complex Patterns are usually expensive and they relatively rarely fail
5442 // on their own: more often we end up throwing away all the work done by a
5443 // matching part of a complex pattern because some other part of the
5444 // enclosing pattern didn't match. All of this makes it beneficial to
5445 // delay complex patterns until the very end of the rule matching,
5446 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005447 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005448 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005449 EpilogueMatchers.emplace_back(std::move(OP));
5450 OM->eraseNullPredicates();
5451 }
5452 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005453 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005454 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5455 const std::unique_ptr<PredicateMatcher> &R) {
5456 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5457 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5458 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005459}
5460
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005461bool RuleMatcher::hasFirstCondition() const {
5462 if (insnmatchers_empty())
5463 return false;
5464 InstructionMatcher &Matcher = insnmatchers_front();
5465 if (!Matcher.predicates_empty())
5466 return true;
5467 for (auto &OM : Matcher.operands())
5468 for (auto &OP : OM->predicates())
5469 if (!isa<InstructionOperandMatcher>(OP))
5470 return true;
5471 return false;
5472}
5473
5474const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5475 assert(!insnmatchers_empty() &&
5476 "Trying to get a condition from an empty RuleMatcher");
5477
5478 InstructionMatcher &Matcher = insnmatchers_front();
5479 if (!Matcher.predicates_empty())
5480 return **Matcher.predicates_begin();
5481 // If there is no more predicate on the instruction itself, look at its
5482 // operands.
5483 for (auto &OM : Matcher.operands())
5484 for (auto &OP : OM->predicates())
5485 if (!isa<InstructionOperandMatcher>(OP))
5486 return *OP;
5487
5488 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5489 "no conditions");
5490}
5491
5492std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5493 assert(!insnmatchers_empty() &&
5494 "Trying to pop a condition from an empty RuleMatcher");
5495
5496 InstructionMatcher &Matcher = insnmatchers_front();
5497 if (!Matcher.predicates_empty())
5498 return Matcher.predicates_pop_front();
5499 // If there is no more predicate on the instruction itself, look at its
5500 // operands.
5501 for (auto &OM : Matcher.operands())
5502 for (auto &OP : OM->predicates())
5503 if (!isa<InstructionOperandMatcher>(OP)) {
5504 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5505 OM->eraseNullPredicates();
5506 return Result;
5507 }
5508
5509 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5510 "no conditions");
5511}
5512
5513bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005514 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005515
5516 if (empty()) {
5517 // Sharing predicates for nested instructions is not supported yet as we
5518 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5519 // only work on the original root instruction (InsnVarID == 0):
5520 if (Predicate.getInsnVarID() != 0)
5521 return false;
5522 // ... otherwise an empty group can handle any predicate with no specific
5523 // requirements:
5524 return true;
5525 }
5526
5527 const Matcher &Representative = **Matchers.begin();
5528 const auto &RepresentativeCondition = Representative.getFirstCondition();
5529 // ... if not empty, the group can only accomodate matchers with the exact
5530 // same first condition:
5531 return Predicate.isIdentical(RepresentativeCondition);
5532}
5533
5534bool GroupMatcher::addMatcher(Matcher &Candidate) {
5535 if (!Candidate.hasFirstCondition())
5536 return false;
5537
5538 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5539 if (!candidateConditionMatches(Predicate))
5540 return false;
5541
5542 Matchers.push_back(&Candidate);
5543 return true;
5544}
5545
5546void GroupMatcher::finalize() {
5547 assert(Conditions.empty() && "Already finalized?");
5548 if (empty())
5549 return;
5550
5551 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005552 for (;;) {
5553 // All the checks are expected to succeed during the first iteration:
5554 for (const auto &Rule : Matchers)
5555 if (!Rule->hasFirstCondition())
5556 return;
5557 const auto &FirstCondition = FirstRule.getFirstCondition();
5558 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5559 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5560 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005561
Roman Tereshin152fc162018-05-23 22:50:53 +00005562 Conditions.push_back(FirstRule.popFirstCondition());
5563 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5564 Matchers[I]->popFirstCondition();
5565 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005566}
5567
5568void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005569 unsigned LabelID = ~0U;
5570 if (!Conditions.empty()) {
5571 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005572 Table << MatchTable::Opcode("GIM_Try", +1)
5573 << MatchTable::Comment("On fail goto")
5574 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005575 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005576 for (auto &Condition : Conditions)
5577 Condition->emitPredicateOpcodes(
5578 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5579
5580 for (const auto &M : Matchers)
5581 M->emit(Table);
5582
5583 // Exit the group
5584 if (!Conditions.empty())
5585 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005586 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005587}
5588
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005589bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005590 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005591}
5592
5593bool SwitchMatcher::candidateConditionMatches(
5594 const PredicateMatcher &Predicate) const {
5595
5596 if (empty()) {
5597 // Sharing predicates for nested instructions is not supported yet as we
5598 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5599 // only work on the original root instruction (InsnVarID == 0):
5600 if (Predicate.getInsnVarID() != 0)
5601 return false;
5602 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5603 // could fail as not all the types of conditions are supported:
5604 if (!isSupportedPredicateType(Predicate))
5605 return false;
5606 // ... or the condition might not have a proper implementation of
5607 // getValue() / isIdenticalDownToValue() yet:
5608 if (!Predicate.hasValue())
5609 return false;
5610 // ... otherwise an empty Switch can accomodate the condition with no
5611 // further requirements:
5612 return true;
5613 }
5614
5615 const Matcher &CaseRepresentative = **Matchers.begin();
5616 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5617 // Switch-cases must share the same kind of condition and path to the value it
5618 // checks:
5619 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5620 return false;
5621
5622 const auto Value = Predicate.getValue();
5623 // ... but be unique with respect to the actual value they check:
5624 return Values.count(Value) == 0;
5625}
5626
5627bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5628 if (!Candidate.hasFirstCondition())
5629 return false;
5630
5631 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5632 if (!candidateConditionMatches(Predicate))
5633 return false;
5634 const auto Value = Predicate.getValue();
5635 Values.insert(Value);
5636
5637 Matchers.push_back(&Candidate);
5638 return true;
5639}
5640
5641void SwitchMatcher::finalize() {
5642 assert(Condition == nullptr && "Already finalized");
5643 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5644 if (empty())
5645 return;
5646
5647 std::stable_sort(Matchers.begin(), Matchers.end(),
5648 [](const Matcher *L, const Matcher *R) {
5649 return L->getFirstCondition().getValue() <
5650 R->getFirstCondition().getValue();
5651 });
5652 Condition = Matchers[0]->popFirstCondition();
5653 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5654 Matchers[I]->popFirstCondition();
5655}
5656
5657void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5658 MatchTable &Table) {
5659 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5660
5661 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5662 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5663 << MatchTable::IntValue(Condition->getInsnVarID());
5664 return;
5665 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005666 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5667 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5668 << MatchTable::IntValue(Condition->getInsnVarID())
5669 << MatchTable::Comment("Op")
5670 << MatchTable::IntValue(Condition->getOpIdx());
5671 return;
5672 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005673
5674 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5675 "predicate type that is claimed to be supported");
5676}
5677
5678void SwitchMatcher::emit(MatchTable &Table) {
5679 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5680 if (empty())
5681 return;
5682 assert(Condition != nullptr &&
5683 "Broken SwitchMatcher, hasn't been finalized?");
5684
5685 std::vector<unsigned> LabelIDs(Values.size());
5686 std::generate(LabelIDs.begin(), LabelIDs.end(),
5687 [&Table]() { return Table.allocateLabelID(); });
5688 const unsigned Default = Table.allocateLabelID();
5689
5690 const int64_t LowerBound = Values.begin()->getRawValue();
5691 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5692
5693 emitPredicateSpecificOpcodes(*Condition, Table);
5694
5695 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5696 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5697 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5698
5699 int64_t J = LowerBound;
5700 auto VI = Values.begin();
5701 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5702 auto V = *VI++;
5703 while (J++ < V.getRawValue())
5704 Table << MatchTable::IntValue(0);
5705 V.turnIntoComment();
5706 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5707 }
5708 Table << MatchTable::LineBreak;
5709
5710 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5711 Table << MatchTable::Label(LabelIDs[I]);
5712 Matchers[I]->emit(Table);
5713 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5714 }
5715 Table << MatchTable::Label(Default);
5716}
5717
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005718unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005719
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005720} // end anonymous namespace
5721
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005722//===----------------------------------------------------------------------===//
5723
5724namespace llvm {
5725void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5726 GlobalISelEmitter(RK).run(OS);
5727}
5728} // End llvm namespace