blob: ec7d20692096bc605ae49244888fae912aeeb577 [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
Petar Avramovic09b88712020-09-14 10:39:25 +0200392static std::string getScopedName(unsigned Scope, const std::string &Name) {
393 return ("pred:" + Twine(Scope) + ":" + Name).str();
394}
395
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000396//===- MatchTable Helpers -------------------------------------------------===//
397
398class MatchTable;
399
400/// A record to be stored in a MatchTable.
401///
402/// This class represents any and all output that may be required to emit the
403/// MatchTable. Instances are most often configured to represent an opcode or
404/// value that will be emitted to the table with some formatting but it can also
405/// represent commas, comments, and other formatting instructions.
406struct MatchTableRecord {
407 enum RecordFlagsBits {
408 MTRF_None = 0x0,
409 /// Causes EmitStr to be formatted as comment when emitted.
410 MTRF_Comment = 0x1,
411 /// Causes the record value to be followed by a comma when emitted.
412 MTRF_CommaFollows = 0x2,
413 /// Causes the record value to be followed by a line break when emitted.
414 MTRF_LineBreakFollows = 0x4,
415 /// Indicates that the record defines a label and causes an additional
416 /// comment to be emitted containing the index of the label.
417 MTRF_Label = 0x8,
418 /// Causes the record to be emitted as the index of the label specified by
419 /// LabelID along with a comment indicating where that label is.
420 MTRF_JumpTarget = 0x10,
421 /// Causes the formatter to add a level of indentation before emitting the
422 /// record.
423 MTRF_Indent = 0x20,
424 /// Causes the formatter to remove a level of indentation after emitting the
425 /// record.
426 MTRF_Outdent = 0x40,
427 };
428
429 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
430 /// reference or define.
431 unsigned LabelID;
432 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
433 /// value, a label name.
434 std::string EmitStr;
435
436private:
437 /// The number of MatchTable elements described by this record. Comments are 0
438 /// while values are typically 1. Values >1 may occur when we need to emit
439 /// values that exceed the size of a MatchTable element.
440 unsigned NumElements;
441
442public:
443 /// A bitfield of RecordFlagsBits flags.
444 unsigned Flags;
445
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 /// The actual run-time value, if known
447 int64_t RawValue;
448
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000449 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000450 unsigned NumElements, unsigned Flags,
451 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000452 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000453 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
454 RawValue(RawValue) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000455 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
456 "This value is reserved for non-labels");
457 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000458 MatchTableRecord(const MatchTableRecord &Other) = default;
459 MatchTableRecord(MatchTableRecord &&Other) = default;
460
461 /// Useful if a Match Table Record gets optimized out
462 void turnIntoComment() {
463 Flags |= MTRF_Comment;
464 Flags &= ~MTRF_CommaFollows;
465 NumElements = 0;
466 }
467
468 /// For Jump Table generation purposes
469 bool operator<(const MatchTableRecord &Other) const {
470 return RawValue < Other.RawValue;
471 }
472 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000473
474 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
475 const MatchTable &Table) const;
476 unsigned size() const { return NumElements; }
477};
478
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000479class Matcher;
480
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000481/// Holds the contents of a generated MatchTable to enable formatting and the
482/// necessary index tracking needed to support GIM_Try.
483class MatchTable {
484 /// An unique identifier for the table. The generated table will be named
485 /// MatchTable${ID}.
486 unsigned ID;
487 /// The records that make up the table. Also includes comments describing the
488 /// values being emitted and line breaks to format it.
489 std::vector<MatchTableRecord> Contents;
490 /// The currently defined labels.
491 DenseMap<unsigned, unsigned> LabelMap;
492 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000493 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000494 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000495 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000496 /// Determines if the table should be instrumented for rule coverage tracking.
497 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000498
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000499public:
500 static MatchTableRecord LineBreak;
501 static MatchTableRecord Comment(StringRef Comment) {
502 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
503 }
504 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
505 unsigned ExtraFlags = 0;
506 if (IndentAdjust > 0)
507 ExtraFlags |= MatchTableRecord::MTRF_Indent;
508 if (IndentAdjust < 0)
509 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
510
511 return MatchTableRecord(None, Opcode, 1,
512 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
513 }
514 static MatchTableRecord NamedValue(StringRef NamedValue) {
515 return MatchTableRecord(None, NamedValue, 1,
516 MatchTableRecord::MTRF_CommaFollows);
517 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000518 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
519 return MatchTableRecord(None, NamedValue, 1,
520 MatchTableRecord::MTRF_CommaFollows, RawValue);
521 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000522 static MatchTableRecord NamedValue(StringRef Namespace,
523 StringRef NamedValue) {
524 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
525 MatchTableRecord::MTRF_CommaFollows);
526 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000527 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
528 int64_t RawValue) {
529 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
530 MatchTableRecord::MTRF_CommaFollows, RawValue);
531 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000532 static MatchTableRecord IntValue(int64_t IntValue) {
533 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
534 MatchTableRecord::MTRF_CommaFollows);
535 }
536 static MatchTableRecord Label(unsigned LabelID) {
537 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
538 MatchTableRecord::MTRF_Label |
539 MatchTableRecord::MTRF_Comment |
540 MatchTableRecord::MTRF_LineBreakFollows);
541 }
542 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000543 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000544 MatchTableRecord::MTRF_JumpTarget |
545 MatchTableRecord::MTRF_Comment |
546 MatchTableRecord::MTRF_CommaFollows);
547 }
548
Roman Tereshinbeb39312018-05-02 20:15:11 +0000549 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000550
Roman Tereshinbeb39312018-05-02 20:15:11 +0000551 MatchTable(bool WithCoverage, unsigned ID = 0)
552 : ID(ID), IsWithCoverage(WithCoverage) {}
553
554 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000555
556 void push_back(const MatchTableRecord &Value) {
557 if (Value.Flags & MatchTableRecord::MTRF_Label)
558 defineLabel(Value.LabelID);
559 Contents.push_back(Value);
560 CurrentSize += Value.size();
561 }
562
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000563 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000564
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000565 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000566 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000567 }
568
569 unsigned getLabelIndex(unsigned LabelID) const {
570 const auto I = LabelMap.find(LabelID);
571 assert(I != LabelMap.end() && "Use of undeclared label");
572 return I->second;
573 }
574
Daniel Sanders8e82af22017-07-27 11:03:45 +0000575 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
576
577 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000578 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000579 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000580 LineBreak.emit(OS, true, *this);
581 OS << std::string(Indentation, ' ');
582
583 for (auto I = Contents.begin(), E = Contents.end(); I != E;
584 ++I) {
585 bool LineBreakIsNext = false;
586 const auto &NextI = std::next(I);
587
588 if (NextI != E) {
589 if (NextI->EmitStr == "" &&
590 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
591 LineBreakIsNext = true;
592 }
593
594 if (I->Flags & MatchTableRecord::MTRF_Indent)
595 Indentation += 2;
596
597 I->emit(OS, LineBreakIsNext, *this);
598 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
599 OS << std::string(Indentation, ' ');
600
601 if (I->Flags & MatchTableRecord::MTRF_Outdent)
602 Indentation -= 2;
603 }
604 OS << "};\n";
605 }
606};
607
608MatchTableRecord MatchTable::LineBreak = {
609 None, "" /* Emit String */, 0 /* Elements */,
610 MatchTableRecord::MTRF_LineBreakFollows};
611
612void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
613 const MatchTable &Table) const {
614 bool UseLineComment =
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000615 LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000616 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
617 UseLineComment = false;
618
619 if (Flags & MTRF_Comment)
620 OS << (UseLineComment ? "// " : "/*");
621
622 OS << EmitStr;
623 if (Flags & MTRF_Label)
624 OS << ": @" << Table.getLabelIndex(LabelID);
625
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000626 if ((Flags & MTRF_Comment) && !UseLineComment)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000627 OS << "*/";
628
629 if (Flags & MTRF_JumpTarget) {
630 if (Flags & MTRF_Comment)
631 OS << " ";
632 OS << Table.getLabelIndex(LabelID);
633 }
634
635 if (Flags & MTRF_CommaFollows) {
636 OS << ",";
637 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
638 OS << " ";
639 }
640
641 if (Flags & MTRF_LineBreakFollows)
642 OS << "\n";
643}
644
645MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
646 Table.push_back(Value);
647 return Table;
648}
649
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000650//===- Matchers -----------------------------------------------------------===//
651
Daniel Sandersbee57392017-04-04 13:25:23 +0000652class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000653class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000654class PredicateMatcher;
655class RuleMatcher;
656
657class Matcher {
658public:
659 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000660 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000661 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000662
663 virtual bool hasFirstCondition() const = 0;
664 virtual const PredicateMatcher &getFirstCondition() const = 0;
665 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000666};
667
Roman Tereshinbeb39312018-05-02 20:15:11 +0000668MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
669 bool WithCoverage) {
670 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000671 for (Matcher *Rule : Rules)
672 Rule->emit(Table);
673
674 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
675}
676
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000677class GroupMatcher final : public Matcher {
678 /// Conditions that form a common prefix of all the matchers contained.
679 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
680
681 /// All the nested matchers, sharing a common prefix.
682 std::vector<Matcher *> Matchers;
683
684 /// An owning collection for any auxiliary matchers created while optimizing
685 /// nested matchers contained.
686 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000687
688public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000689 /// Add a matcher to the collection of nested matchers if it meets the
690 /// requirements, and return true. If it doesn't, do nothing and return false.
691 ///
692 /// Expected to preserve its argument, so it could be moved out later on.
693 bool addMatcher(Matcher &Candidate);
694
695 /// Mark the matcher as fully-built and ensure any invariants expected by both
696 /// optimize() and emit(...) methods. Generally, both sequences of calls
697 /// are expected to lead to a sensible result:
698 ///
699 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
700 /// addMatcher(...)*; finalize(); emit(...);
701 ///
702 /// or generally
703 ///
704 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
705 ///
706 /// Multiple calls to optimize() are expected to be handled gracefully, though
707 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
708 /// aren't generally supported. emit(...) is expected to be non-mutating and
709 /// producing the exact same results upon repeated calls.
710 ///
711 /// addMatcher() calls after the finalize() call are not supported.
712 ///
713 /// finalize() and optimize() are both allowed to mutate the contained
714 /// matchers, so moving them out after finalize() is not supported.
715 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000716 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000717 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000718
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000719 /// Could be used to move out the matchers added previously, unless finalize()
720 /// has been already called. If any of the matchers are moved out, the group
721 /// becomes safe to destroy, but not safe to re-use for anything else.
722 iterator_range<std::vector<Matcher *>::iterator> matchers() {
723 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000724 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000725 size_t size() const { return Matchers.size(); }
726 bool empty() const { return Matchers.empty(); }
727
728 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
729 assert(!Conditions.empty() &&
730 "Trying to pop a condition from a condition-less group");
731 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
732 Conditions.erase(Conditions.begin());
733 return P;
734 }
735 const PredicateMatcher &getFirstCondition() const override {
736 assert(!Conditions.empty() &&
737 "Trying to get a condition from a condition-less group");
738 return *Conditions.front();
739 }
740 bool hasFirstCondition() const override { return !Conditions.empty(); }
741
742private:
743 /// See if a candidate matcher could be added to this group solely by
744 /// analyzing its first condition.
745 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000746};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000747
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000748class SwitchMatcher : public Matcher {
749 /// All the nested matchers, representing distinct switch-cases. The first
750 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
751 /// matchers must share the same type and path to a value they check, in other
752 /// words, be isIdenticalDownToValue, but have different values they check
753 /// against.
754 std::vector<Matcher *> Matchers;
755
756 /// The representative condition, with a type and a path (InsnVarID and OpIdx
757 /// in most cases) shared by all the matchers contained.
758 std::unique_ptr<PredicateMatcher> Condition = nullptr;
759
760 /// Temporary set used to check that the case values don't repeat within the
761 /// same switch.
762 std::set<MatchTableRecord> Values;
763
764 /// An owning collection for any auxiliary matchers created while optimizing
765 /// nested matchers contained.
766 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
767
768public:
769 bool addMatcher(Matcher &Candidate);
770
771 void finalize();
772 void emit(MatchTable &Table) override;
773
774 iterator_range<std::vector<Matcher *>::iterator> matchers() {
775 return make_range(Matchers.begin(), Matchers.end());
776 }
777 size_t size() const { return Matchers.size(); }
778 bool empty() const { return Matchers.empty(); }
779
780 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
781 // SwitchMatcher doesn't have a common first condition for its cases, as all
782 // the cases only share a kind of a value (a type and a path to it) they
783 // match, but deliberately differ in the actual value they match.
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
785 }
786 const PredicateMatcher &getFirstCondition() const override {
787 llvm_unreachable("Trying to pop a condition from a condition-less group");
788 }
789 bool hasFirstCondition() const override { return false; }
790
791private:
792 /// See if the predicate type has a Switch-implementation for it.
793 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
794
795 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
796
797 /// emit()-helper
798 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
799 MatchTable &Table);
800};
801
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000802/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000803class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000804public:
Daniel Sanders08464522018-01-29 21:09:12 +0000805 using ActionList = std::list<std::unique_ptr<MatchAction>>;
806 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000807
808protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000809 /// A list of matchers that all need to succeed for the current rule to match.
810 /// FIXME: This currently supports a single match position but could be
811 /// extended to support multiple positions to support div/rem fusion or
812 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000813 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
814 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000815
816 /// A list of actions that need to be taken when all predicates in this rule
817 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000818 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000819
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000820 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000821
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000822 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000823 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000824
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000825 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000826
827 // The set of instruction matchers that have not yet been claimed for mutation
828 // by a BuildMI.
829 MutatableInsnSet MutatableInsns;
830
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000831 /// A map of named operands defined by the matchers that may be referenced by
832 /// the renderers.
833 StringMap<OperandMatcher *> DefinedOperands;
834
Matt Arsenault3e45c702019-09-06 20:32:37 +0000835 /// A map of anonymous physical register operands defined by the matchers that
836 /// may be referenced by the renderers.
837 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
838
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000839 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000840 unsigned NextInsnVarID;
841
Daniel Sanders198447a2017-11-01 00:29:47 +0000842 /// ID for the next output instruction allocated with allocateOutputInsnID()
843 unsigned NextOutputInsnID;
844
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000845 /// ID for the next temporary register ID allocated with allocateTempRegID()
846 unsigned NextTempRegID;
847
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000848 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000849 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000850
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000851 ArrayRef<SMLoc> SrcLoc;
852
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000853 typedef std::tuple<Record *, unsigned, unsigned>
854 DefinedComplexPatternSubOperand;
855 typedef StringMap<DefinedComplexPatternSubOperand>
856 DefinedComplexPatternSubOperandMap;
857 /// A map of Symbolic Names to ComplexPattern sub-operands.
858 DefinedComplexPatternSubOperandMap ComplexSubOperands;
Petar Avramovic416346d2020-09-14 11:37:14 +0200859 /// A map used to for multiple referenced error check of ComplexSubOperand.
860 /// ComplexSubOperand can't be referenced multiple from different operands,
861 /// however multiple references from same operand are allowed since that is
862 /// how 'same operand checks' are generated.
863 StringMap<std::string> ComplexSubOperandsParentName;
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000864
Daniel Sandersf76f3152017-11-16 00:46:35 +0000865 uint64_t RuleID;
866 static uint64_t NextRuleID;
867
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000868public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000869 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000870 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000871 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000872 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
873 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000874 RuleMatcher(RuleMatcher &&Other) = default;
875 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000876
Daniel Sandersf76f3152017-11-16 00:46:35 +0000877 uint64_t getRuleID() const { return RuleID; }
878
Daniel Sanders05540042017-08-08 10:44:31 +0000879 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000880 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000881 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000882
883 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000884 template <class Kind, class... Args>
885 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000886
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000887 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000888 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
889
890 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000891 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
892 return InsnVariableIDs.begin();
893 }
894 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
895 return InsnVariableIDs.end();
896 }
897 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
898 defined_insn_vars() const {
899 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
900 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000901
Daniel Sandersa7b75262017-10-31 18:50:24 +0000902 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
903 return MutatableInsns.begin();
904 }
905 MutatableInsnSet::const_iterator mutatable_insns_end() const {
906 return MutatableInsns.end();
907 }
908 iterator_range<typename MutatableInsnSet::const_iterator>
909 mutatable_insns() const {
910 return make_range(mutatable_insns_begin(), mutatable_insns_end());
911 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000912 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000913 bool R = MutatableInsns.erase(InsnMatcher);
914 assert(R && "Reserving a mutatable insn that isn't available");
915 (void)R;
916 }
917
Daniel Sanders7438b262017-10-31 23:03:18 +0000918 action_iterator actions_begin() { return Actions.begin(); }
919 action_iterator actions_end() { return Actions.end(); }
920 iterator_range<action_iterator> actions() {
921 return make_range(actions_begin(), actions_end());
922 }
923
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000924 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
925
Matt Arsenault3e45c702019-09-06 20:32:37 +0000926 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
927
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000928 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
Petar Avramovic416346d2020-09-14 11:37:14 +0200929 unsigned RendererID, unsigned SubOperandID,
930 StringRef ParentSymbolicName) {
931 std::string ParentName(ParentSymbolicName);
932 if (ComplexSubOperands.count(SymbolicName)) {
933 auto RecordedParentName = ComplexSubOperandsParentName[SymbolicName];
934 if (RecordedParentName.compare(ParentName) != 0)
935 return failedImport("Error: Complex suboperand " + SymbolicName +
936 " referenced by different operands: " +
937 RecordedParentName + " and " + ParentName + ".");
938 // Complex suboperand referenced more than once from same the operand is
939 // used to generate 'same operand check'. Emitting of
940 // GIR_ComplexSubOperandRenderer for them is already handled.
941 return Error::success();
942 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000943
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000944 ComplexSubOperands[SymbolicName] =
945 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Petar Avramovic416346d2020-09-14 11:37:14 +0200946 ComplexSubOperandsParentName[SymbolicName] = ParentName;
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000947
948 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000949 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000950
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000951 Optional<DefinedComplexPatternSubOperand>
952 getComplexSubOperand(StringRef SymbolicName) const {
953 const auto &I = ComplexSubOperands.find(SymbolicName);
954 if (I == ComplexSubOperands.end())
955 return None;
956 return I->second;
957 }
958
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000959 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000960 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000961 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000962
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000963 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000964 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000965
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000966 /// Compare the priority of this object and B.
967 ///
968 /// Returns true if this object is more important than B.
969 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000970
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000971 /// Report the maximum number of temporary operands needed by the rule
972 /// matcher.
973 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000974
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000975 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
976 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000977 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000978 bool hasFirstCondition() const override;
979 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000980 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000981
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000982 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000983 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000984
985 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000986 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000987
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000988 iterator_range<MatchersTy::iterator> insnmatchers() {
989 return make_range(Matchers.begin(), Matchers.end());
990 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000991 bool insnmatchers_empty() const { return Matchers.empty(); }
992 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000993};
994
Daniel Sandersf76f3152017-11-16 00:46:35 +0000995uint64_t RuleMatcher::NextRuleID = 0;
996
Daniel Sanders7438b262017-10-31 23:03:18 +0000997using action_iterator = RuleMatcher::action_iterator;
998
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000999template <class PredicateTy> class PredicateListMatcher {
1000private:
Daniel Sanders2c269f62017-08-24 09:11:20 +00001001 /// Template instantiations should specialize this to return a string to use
1002 /// for the comment emitted when there are no predicates.
1003 std::string getNoPredicateComment() const;
1004
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001005protected:
1006 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
1007 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +00001008
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001009 /// Track if the list of predicates was manipulated by one of the optimization
1010 /// methods.
1011 bool Optimized = false;
1012
1013public:
1014 /// Construct a new predicate and add it to the matcher.
1015 template <class Kind, class... Args>
1016 Optional<Kind *> addPredicate(Args &&... args);
1017
1018 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001019 return Predicates.begin();
1020 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001021 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001022 return Predicates.end();
1023 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001024 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001025 return make_range(predicates_begin(), predicates_end());
1026 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001027 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001028 return Predicates.size();
1029 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001030 bool predicates_empty() const { return Predicates.empty(); }
1031
1032 std::unique_ptr<PredicateTy> predicates_pop_front() {
1033 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001034 Predicates.pop_front();
1035 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001036 return Front;
1037 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001038
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001039 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1040 Predicates.push_front(std::move(Predicate));
1041 }
1042
1043 void eraseNullPredicates() {
1044 const auto NewEnd =
1045 std::stable_partition(Predicates.begin(), Predicates.end(),
1046 std::logical_not<std::unique_ptr<PredicateTy>>());
1047 if (NewEnd != Predicates.begin()) {
1048 Predicates.erase(Predicates.begin(), NewEnd);
1049 Optimized = true;
1050 }
1051 }
1052
Daniel Sanders9d662d22017-07-06 10:06:12 +00001053 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001054 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001055 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1056 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001057 Table << MatchTable::Comment(getNoPredicateComment())
1058 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001059 return;
1060 }
1061
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001062 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001063 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001064 }
Matt Arsenault1254f6d2020-06-20 21:38:43 -04001065
1066 /// Provide a function to avoid emitting certain predicates. This is used to
1067 /// defer some predicate checks until after others
1068 using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
1069
1070 /// Emit MatchTable opcodes for predicates which satisfy \p
1071 /// ShouldEmitPredicate. This should be called multiple times to ensure all
1072 /// predicates are eventually added to the match table.
1073 template <class... Args>
1074 void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
1075 MatchTable &Table, Args &&... args) {
1076 if (Predicates.empty() && !Optimized) {
1077 Table << MatchTable::Comment(getNoPredicateComment())
1078 << MatchTable::LineBreak;
1079 return;
1080 }
1081
1082 for (const auto &Predicate : predicates()) {
1083 if (ShouldEmitPredicate(*Predicate))
1084 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1085 }
1086 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001087};
1088
Quentin Colombet063d7982017-12-14 23:44:07 +00001089class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001090public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001091 /// This enum is used for RTTI and also defines the priority that is given to
1092 /// the predicate when generating the matcher code. Kinds with higher priority
1093 /// must be tested first.
1094 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001095 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1096 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1097 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001098 ///
1099 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1100 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001101 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001102 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001103 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001104 IPM_ImmPredicate,
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001105 IPM_Imm,
Quentin Colombet063d7982017-12-14 23:44:07 +00001106 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001107 IPM_MemoryLLTSize,
1108 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001109 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001110 IPM_MemoryAlignment,
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04001111 IPM_VectorSplatImm,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001112 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001113 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001114 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001115 OPM_IntrinsicID,
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001116 OPM_CmpPredicate,
Daniel Sanders05540042017-08-08 10:44:31 +00001117 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001118 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001119 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001120 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001121 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001122 OPM_RegBank,
1123 OPM_MBB,
Petar Avramovic09b88712020-09-14 10:39:25 +02001124 OPM_RecordNamedOperand,
Daniel Sanders759ff412017-02-24 13:58:11 +00001125 };
1126
1127protected:
1128 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001129 unsigned InsnVarID;
1130 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001131
1132public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001133 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1134 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001135
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001136 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001137 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001138
Quentin Colombet063d7982017-12-14 23:44:07 +00001139 virtual ~PredicateMatcher() = default;
1140 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001141 virtual void emitPredicateOpcodes(MatchTable &Table,
1142 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001143
Daniel Sanders759ff412017-02-24 13:58:11 +00001144 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001145
Matt Arsenault1254f6d2020-06-20 21:38:43 -04001146 bool dependsOnOperands() const {
1147 // Custom predicates really depend on the context pattern of the
1148 // instruction, not just the individual instruction. This therefore
1149 // implicitly depends on all other pattern constraints.
1150 return Kind == IPM_GenericPredicate;
1151 }
1152
Quentin Colombet893e0f12017-12-15 23:24:39 +00001153 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001154 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1155 OpIdx == B.OpIdx;
1156 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001157
1158 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1159 return hasValue() && PredicateMatcher::isIdentical(B);
1160 }
1161
1162 virtual MatchTableRecord getValue() const {
1163 assert(hasValue() && "Can not get a value of a value-less predicate!");
1164 llvm_unreachable("Not implemented yet");
1165 }
1166 virtual bool hasValue() const { return false; }
1167
1168 /// Report the maximum number of temporary operands needed by the predicate
1169 /// matcher.
1170 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001171};
1172
1173/// Generates code to check a predicate of an operand.
1174///
1175/// Typical predicates include:
1176/// * Operand is a particular register.
1177/// * Operand is assigned a particular register bank.
1178/// * Operand is an MBB.
1179class OperandPredicateMatcher : public PredicateMatcher {
1180public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001181 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1182 unsigned OpIdx)
1183 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001184 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001185
Daniel Sanders759ff412017-02-24 13:58:11 +00001186 /// Compare the priority of this object and B.
1187 ///
1188 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001189 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001190};
1191
Daniel Sanders2c269f62017-08-24 09:11:20 +00001192template <>
1193std::string
1194PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1195 return "No operand predicates";
1196}
1197
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001198/// Generates code to check that a register operand is defined by the same exact
1199/// one as another.
1200class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001201 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001202
1203public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001204 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001205 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1206 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001207
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001208 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001209 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001210 }
1211
Quentin Colombetaad20be2017-12-15 23:07:42 +00001212 void emitPredicateOpcodes(MatchTable &Table,
1213 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001214
1215 bool isIdentical(const PredicateMatcher &B) const override {
1216 return OperandPredicateMatcher::isIdentical(B) &&
1217 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1218 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001219};
1220
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001221/// Generates code to check that an operand is a particular LLT.
1222class LLTOperandMatcher : public OperandPredicateMatcher {
1223protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001224 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001225
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001226public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001227 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1228
1229 static void initTypeIDValuesMap() {
1230 TypeIDValues.clear();
1231
1232 unsigned ID = 0;
Mark de Wevere8d448e2019-12-22 18:58:32 +01001233 for (const LLTCodeGen &LLTy : KnownTypes)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001234 TypeIDValues[LLTy] = ID++;
1235 }
1236
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001237 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001238 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001239 KnownTypes.insert(Ty);
1240 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001241
Quentin Colombet063d7982017-12-14 23:44:07 +00001242 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001243 return P->getKind() == OPM_LLT;
1244 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001245 bool isIdentical(const PredicateMatcher &B) const override {
1246 return OperandPredicateMatcher::isIdentical(B) &&
1247 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1248 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001249 MatchTableRecord getValue() const override {
1250 const auto VI = TypeIDValues.find(Ty);
1251 if (VI == TypeIDValues.end())
1252 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1253 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1254 }
1255 bool hasValue() const override {
1256 if (TypeIDValues.size() != KnownTypes.size())
1257 initTypeIDValuesMap();
1258 return TypeIDValues.count(Ty);
1259 }
1260
1261 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001262
Quentin Colombetaad20be2017-12-15 23:07:42 +00001263 void emitPredicateOpcodes(MatchTable &Table,
1264 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001265 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1266 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1267 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001268 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001269 }
1270};
1271
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001272std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1273
Daniel Sandersa71f4542017-10-16 00:56:30 +00001274/// Generates code to check that an operand is a pointer to any address space.
1275///
1276/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1277/// result, iN is used to describe a pointer of N bits to any address space and
1278/// PatFrag predicates are typically used to constrain the address space. There's
1279/// no reliable means to derive the missing type information from the pattern so
1280/// imported rules must test the components of a pointer separately.
1281///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001282/// If SizeInBits is zero, then the pointer size will be obtained from the
1283/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001284class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1285protected:
1286 unsigned SizeInBits;
1287
1288public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001289 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1290 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001291 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1292 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001293
Gabriel Hjort Ã…kerlundb2b9af52020-08-26 10:48:15 +02001294 static bool classof(const PredicateMatcher *P) {
Daniel Sandersa71f4542017-10-16 00:56:30 +00001295 return P->getKind() == OPM_PointerToAny;
1296 }
1297
Gabriel Hjort Ã…kerlundb2b9af52020-08-26 10:48:15 +02001298 bool isIdentical(const PredicateMatcher &B) const override {
1299 return OperandPredicateMatcher::isIdentical(B) &&
1300 SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits;
1301 }
1302
Quentin Colombetaad20be2017-12-15 23:07:42 +00001303 void emitPredicateOpcodes(MatchTable &Table,
1304 RuleMatcher &Rule) const override {
1305 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1306 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1307 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1308 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001309 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1310 }
1311};
1312
Petar Avramovic09b88712020-09-14 10:39:25 +02001313/// Generates code to record named operand in RecordedOperands list at StoreIdx.
1314/// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as
1315/// an argument to predicate's c++ code once all operands have been matched.
1316class RecordNamedOperandMatcher : public OperandPredicateMatcher {
1317protected:
1318 unsigned StoreIdx;
1319 std::string Name;
1320
1321public:
1322 RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1323 unsigned StoreIdx, StringRef Name)
1324 : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx),
1325 StoreIdx(StoreIdx), Name(Name) {}
1326
1327 static bool classof(const PredicateMatcher *P) {
1328 return P->getKind() == OPM_RecordNamedOperand;
1329 }
1330
1331 bool isIdentical(const PredicateMatcher &B) const override {
1332 return OperandPredicateMatcher::isIdentical(B) &&
1333 StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx &&
1334 Name.compare(cast<RecordNamedOperandMatcher>(&B)->Name) == 0;
1335 }
1336
1337 void emitPredicateOpcodes(MatchTable &Table,
1338 RuleMatcher &Rule) const override {
1339 Table << MatchTable::Opcode("GIM_RecordNamedOperand")
1340 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1341 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1342 << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx)
1343 << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak;
1344 }
1345};
1346
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001347/// Generates code to check that an operand is a particular target constant.
1348class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1349protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001350 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001351 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001352
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001353 unsigned getAllocatedTemporariesBaseID() const;
1354
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001355public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001356 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1357
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001358 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1359 const OperandMatcher &Operand,
1360 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001361 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1362 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001363
Quentin Colombet063d7982017-12-14 23:44:07 +00001364 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001365 return P->getKind() == OPM_ComplexPattern;
1366 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001367
Quentin Colombetaad20be2017-12-15 23:07:42 +00001368 void emitPredicateOpcodes(MatchTable &Table,
1369 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001370 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001371 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1372 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1373 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1374 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1375 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1376 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001377 }
1378
Daniel Sanders2deea182017-04-22 15:11:04 +00001379 unsigned countRendererFns() const override {
1380 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001381 }
1382};
1383
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001384/// Generates code to check that an operand is in a particular register bank.
1385class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1386protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001387 const CodeGenRegisterClass &RC;
1388
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001389public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001390 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1391 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001392 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001393
Quentin Colombet893e0f12017-12-15 23:24:39 +00001394 bool isIdentical(const PredicateMatcher &B) const override {
1395 return OperandPredicateMatcher::isIdentical(B) &&
1396 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1397 }
1398
Quentin Colombet063d7982017-12-14 23:44:07 +00001399 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001400 return P->getKind() == OPM_RegBank;
1401 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001402
Quentin Colombetaad20be2017-12-15 23:07:42 +00001403 void emitPredicateOpcodes(MatchTable &Table,
1404 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001405 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1406 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1407 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1408 << MatchTable::Comment("RC")
1409 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1410 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001411 }
1412};
1413
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001414/// Generates code to check that an operand is a basic block.
1415class MBBOperandMatcher : public OperandPredicateMatcher {
1416public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001417 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1418 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001419
Quentin Colombet063d7982017-12-14 23:44:07 +00001420 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001421 return P->getKind() == OPM_MBB;
1422 }
1423
Quentin Colombetaad20be2017-12-15 23:07:42 +00001424 void emitPredicateOpcodes(MatchTable &Table,
1425 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001426 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1427 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1428 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001429 }
1430};
1431
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001432class ImmOperandMatcher : public OperandPredicateMatcher {
1433public:
1434 ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1435 : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1436
1437 static bool classof(const PredicateMatcher *P) {
1438 return P->getKind() == IPM_Imm;
1439 }
1440
1441 void emitPredicateOpcodes(MatchTable &Table,
1442 RuleMatcher &Rule) const override {
1443 Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1444 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1445 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1446 }
1447};
1448
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001449/// Generates code to check that an operand is a G_CONSTANT with a particular
1450/// int.
1451class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001452protected:
1453 int64_t Value;
1454
1455public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001456 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001457 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001458
Quentin Colombet893e0f12017-12-15 23:24:39 +00001459 bool isIdentical(const PredicateMatcher &B) const override {
1460 return OperandPredicateMatcher::isIdentical(B) &&
1461 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1462 }
1463
Quentin Colombet063d7982017-12-14 23:44:07 +00001464 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001465 return P->getKind() == OPM_Int;
1466 }
1467
Quentin Colombetaad20be2017-12-15 23:07:42 +00001468 void emitPredicateOpcodes(MatchTable &Table,
1469 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001470 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1471 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1472 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1473 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001474 }
1475};
1476
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001477/// Generates code to check that an operand is a raw int (where MO.isImm() or
1478/// MO.isCImm() is true).
1479class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1480protected:
1481 int64_t Value;
1482
1483public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001484 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001485 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1486 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001487
Quentin Colombet893e0f12017-12-15 23:24:39 +00001488 bool isIdentical(const PredicateMatcher &B) const override {
1489 return OperandPredicateMatcher::isIdentical(B) &&
1490 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1491 }
1492
Quentin Colombet063d7982017-12-14 23:44:07 +00001493 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001494 return P->getKind() == OPM_LiteralInt;
1495 }
1496
Quentin Colombetaad20be2017-12-15 23:07:42 +00001497 void emitPredicateOpcodes(MatchTable &Table,
1498 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001499 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1500 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1501 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1502 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001503 }
1504};
1505
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001506/// Generates code to check that an operand is an CmpInst predicate
1507class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1508protected:
1509 std::string PredName;
1510
1511public:
1512 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1513 std::string P)
1514 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1515
1516 bool isIdentical(const PredicateMatcher &B) const override {
1517 return OperandPredicateMatcher::isIdentical(B) &&
1518 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1519 }
1520
1521 static bool classof(const PredicateMatcher *P) {
1522 return P->getKind() == OPM_CmpPredicate;
1523 }
1524
1525 void emitPredicateOpcodes(MatchTable &Table,
1526 RuleMatcher &Rule) const override {
1527 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1528 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1529 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1530 << MatchTable::Comment("Predicate")
1531 << MatchTable::NamedValue("CmpInst", PredName)
1532 << MatchTable::LineBreak;
1533 }
1534};
1535
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001536/// Generates code to check that an operand is an intrinsic ID.
1537class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1538protected:
1539 const CodeGenIntrinsic *II;
1540
1541public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001542 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1543 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001544 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001545
Quentin Colombet893e0f12017-12-15 23:24:39 +00001546 bool isIdentical(const PredicateMatcher &B) const override {
1547 return OperandPredicateMatcher::isIdentical(B) &&
1548 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1549 }
1550
Quentin Colombet063d7982017-12-14 23:44:07 +00001551 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001552 return P->getKind() == OPM_IntrinsicID;
1553 }
1554
Quentin Colombetaad20be2017-12-15 23:07:42 +00001555 void emitPredicateOpcodes(MatchTable &Table,
1556 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001557 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1558 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1559 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1560 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1561 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001562 }
1563};
1564
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001565/// Generates code to check that a set of predicates match for a particular
1566/// operand.
1567class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1568protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001569 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001570 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001571 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001572
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001573 /// The index of the first temporary variable allocated to this operand. The
1574 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001575 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001576 unsigned AllocatedTemporariesBaseID;
1577
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001578public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001579 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001580 const std::string &SymbolicName,
1581 unsigned AllocatedTemporariesBaseID)
1582 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1583 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001584
1585 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1586 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001587 void setSymbolicName(StringRef Name) {
1588 assert(SymbolicName.empty() && "Operand already has a symbolic name");
Benjamin Krameradcd0262020-01-28 20:23:46 +01001589 SymbolicName = std::string(Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001590 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001591
1592 /// Construct a new operand predicate and add it to the matcher.
1593 template <class Kind, class... Args>
1594 Optional<Kind *> addPredicate(Args &&... args) {
1595 if (isSameAsAnotherOperand())
1596 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001597 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001598 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1599 return static_cast<Kind *>(Predicates.back().get());
1600 }
1601
1602 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001603 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001604
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001605 std::string getOperandExpr(unsigned InsnVarID) const {
1606 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1607 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001608 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001609
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001610 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1611
Daniel Sandersa71f4542017-10-16 00:56:30 +00001612 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001613 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001614
Daniel Sanders9d662d22017-07-06 10:06:12 +00001615 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001616 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001617 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1618 if (!Optimized) {
1619 std::string Comment;
1620 raw_string_ostream CommentOS(Comment);
1621 CommentOS << "MIs[" << getInsnVarID() << "] ";
1622 if (SymbolicName.empty())
1623 CommentOS << "Operand " << OpIdx;
1624 else
1625 CommentOS << SymbolicName;
1626 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1627 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001628
Quentin Colombetaad20be2017-12-15 23:07:42 +00001629 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001630 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001631
1632 /// Compare the priority of this object and B.
1633 ///
1634 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001635 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001636 // Operand matchers involving more predicates have higher priority.
1637 if (predicates_size() > B.predicates_size())
1638 return true;
1639 if (predicates_size() < B.predicates_size())
1640 return false;
1641
1642 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001643 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001644 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1645 return true;
1646 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1647 return false;
1648 }
1649
1650 return false;
1651 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001652
1653 /// Report the maximum number of temporary operands needed by the operand
1654 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001655 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001656 return std::accumulate(
1657 predicates().begin(), predicates().end(), 0,
1658 [](unsigned A,
1659 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001660 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001661 });
1662 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001663
1664 unsigned getAllocatedTemporariesBaseID() const {
1665 return AllocatedTemporariesBaseID;
1666 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001667
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001668 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001669 for (const auto &Predicate : predicates())
1670 if (isa<SameOperandMatcher>(Predicate))
1671 return true;
1672 return false;
1673 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001674};
1675
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001676Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001677 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001678 if (!VTy.isMachineValueType())
1679 return failedImport("unsupported typeset");
1680
1681 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1682 addPredicate<PointerToAnyOperandMatcher>(0);
1683 return Error::success();
1684 }
1685
1686 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1687 if (!OpTyOrNone)
1688 return failedImport("unsupported type");
1689
1690 if (OperandIsAPointer)
1691 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001692 else if (VTy.isPointer())
1693 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1694 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001695 else
1696 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1697 return Error::success();
1698}
1699
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001700unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1701 return Operand.getAllocatedTemporariesBaseID();
1702}
1703
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001704/// Generates code to check a predicate on an instruction.
1705///
1706/// Typical predicates include:
1707/// * The opcode of the instruction is a particular value.
1708/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001709class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001710public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001711 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1712 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001713 virtual ~InstructionPredicateMatcher() {}
1714
Daniel Sanders759ff412017-02-24 13:58:11 +00001715 /// Compare the priority of this object and B.
1716 ///
1717 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001718 virtual bool
1719 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001720 return Kind < B.Kind;
1721 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001722};
1723
Daniel Sanders2c269f62017-08-24 09:11:20 +00001724template <>
1725std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001726PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001727 return "No instruction predicates";
1728}
1729
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001730/// Generates code to check the opcode of an instruction.
1731class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1732protected:
Matt Arsenault116affb2020-08-02 14:52:20 -04001733 // Allow matching one to several, similar opcodes that share properties. This
1734 // is to handle patterns where one SelectionDAG operation maps to multiple
1735 // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
1736 // is treated as the canonical opcode.
1737 SmallVector<const CodeGenInstruction *, 2> Insts;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001738
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001739 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1740
Matt Arsenault116affb2020-08-02 14:52:20 -04001741
1742 MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
1743 const auto VI = OpcodeValues.find(I);
1744 if (VI != OpcodeValues.end())
1745 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1746 VI->second);
1747 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1748 }
1749
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001750public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001751 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1752 OpcodeValues.clear();
1753
1754 unsigned OpcodeValue = 0;
1755 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1756 OpcodeValues[I] = OpcodeValue++;
1757 }
1758
Matt Arsenault116affb2020-08-02 14:52:20 -04001759 InstructionOpcodeMatcher(unsigned InsnVarID,
1760 ArrayRef<const CodeGenInstruction *> I)
1761 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
1762 Insts(I.begin(), I.end()) {
1763 assert((Insts.size() == 1 || Insts.size() == 2) &&
1764 "unexpected number of opcode alternatives");
1765 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001766
Quentin Colombet063d7982017-12-14 23:44:07 +00001767 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001768 return P->getKind() == IPM_Opcode;
1769 }
1770
Quentin Colombet893e0f12017-12-15 23:24:39 +00001771 bool isIdentical(const PredicateMatcher &B) const override {
1772 return InstructionPredicateMatcher::isIdentical(B) &&
Matt Arsenault116affb2020-08-02 14:52:20 -04001773 Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
Quentin Colombet893e0f12017-12-15 23:24:39 +00001774 }
Matt Arsenault116affb2020-08-02 14:52:20 -04001775
1776 bool hasValue() const override {
1777 return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
1778 }
1779
1780 // TODO: This is used for the SwitchMatcher optimization. We should be able to
1781 // return a list of the opcodes to match.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001782 MatchTableRecord getValue() const override {
Matt Arsenault116affb2020-08-02 14:52:20 -04001783 assert(Insts.size() == 1);
1784
1785 const CodeGenInstruction *I = Insts[0];
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001786 const auto VI = OpcodeValues.find(I);
1787 if (VI != OpcodeValues.end())
1788 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1789 VI->second);
1790 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1791 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001792
Quentin Colombetaad20be2017-12-15 23:07:42 +00001793 void emitPredicateOpcodes(MatchTable &Table,
1794 RuleMatcher &Rule) const override {
Matt Arsenault116affb2020-08-02 14:52:20 -04001795 StringRef CheckType = Insts.size() == 1 ?
1796 "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
1797 Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
1798 << MatchTable::IntValue(InsnVarID);
1799
1800 for (const CodeGenInstruction *I : Insts)
1801 Table << getInstValue(I);
1802 Table << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001803 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001804
1805 /// Compare the priority of this object and B.
1806 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001807 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001808 bool
1809 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001810 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1811 return true;
1812 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1813 return false;
1814
1815 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1816 // this is cosmetic at the moment, we may want to drive a similar ordering
1817 // using instruction frequency information to improve compile time.
1818 if (const InstructionOpcodeMatcher *BO =
1819 dyn_cast<InstructionOpcodeMatcher>(&B))
Matt Arsenault116affb2020-08-02 14:52:20 -04001820 return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
Daniel Sanders759ff412017-02-24 13:58:11 +00001821
1822 return false;
1823 };
Daniel Sanders05540042017-08-08 10:44:31 +00001824
1825 bool isConstantInstruction() const {
Matt Arsenault116affb2020-08-02 14:52:20 -04001826 return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
Daniel Sanders05540042017-08-08 10:44:31 +00001827 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001828
Matt Arsenault116affb2020-08-02 14:52:20 -04001829 // The first opcode is the canonical opcode, and later are alternatives.
1830 StringRef getOpcode() const {
1831 return Insts[0]->TheDef->getName();
1832 }
1833
1834 ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
1835 return Insts;
1836 }
1837
1838 bool isVariadicNumOperands() const {
1839 // If one is variadic, they all should be.
1840 return Insts[0]->Operands.isVariadic;
1841 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001842
1843 StringRef getOperandType(unsigned OpIdx) const {
Matt Arsenault116affb2020-08-02 14:52:20 -04001844 // Types expected to be uniform for all alternatives.
1845 return Insts[0]->Operands[OpIdx].OperandType;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001846 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001847};
1848
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001849DenseMap<const CodeGenInstruction *, unsigned>
1850 InstructionOpcodeMatcher::OpcodeValues;
1851
Roman Tereshin19da6672018-05-22 04:31:50 +00001852class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1853 unsigned NumOperands = 0;
1854
1855public:
1856 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1857 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1858 NumOperands(NumOperands) {}
1859
1860 static bool classof(const PredicateMatcher *P) {
1861 return P->getKind() == IPM_NumOperands;
1862 }
1863
1864 bool isIdentical(const PredicateMatcher &B) const override {
1865 return InstructionPredicateMatcher::isIdentical(B) &&
1866 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1867 }
1868
1869 void emitPredicateOpcodes(MatchTable &Table,
1870 RuleMatcher &Rule) const override {
1871 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1872 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1873 << MatchTable::Comment("Expected")
1874 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1875 }
1876};
1877
Daniel Sanders2c269f62017-08-24 09:11:20 +00001878/// Generates code to check that this instruction is a constant whose value
1879/// meets an immediate predicate.
1880///
1881/// Immediates are slightly odd since they are typically used like an operand
1882/// but are represented as an operator internally. We typically write simm8:$src
1883/// in a tablegen pattern, but this is just syntactic sugar for
1884/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1885/// that will be matched and the predicate (which is attached to the imm
1886/// operator) that will be tested. In SelectionDAG this describes a
1887/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1888///
1889/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1890/// this representation, the immediate could be tested with an
1891/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1892/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1893/// there are two implementation issues with producing that matcher
1894/// configuration from the SelectionDAG pattern:
1895/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1896/// were we to sink the immediate predicate to the operand we would have to
1897/// have two partial implementations of PatFrag support, one for immediates
1898/// and one for non-immediates.
1899/// * At the point we handle the predicate, the OperandMatcher hasn't been
1900/// created yet. If we were to sink the predicate to the OperandMatcher we
1901/// would also have to complicate (or duplicate) the code that descends and
1902/// creates matchers for the subtree.
1903/// Overall, it's simpler to handle it in the place it was found.
1904class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1905protected:
1906 TreePredicateFn Predicate;
1907
1908public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001909 InstructionImmPredicateMatcher(unsigned InsnVarID,
1910 const TreePredicateFn &Predicate)
1911 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1912 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001913
Quentin Colombet893e0f12017-12-15 23:24:39 +00001914 bool isIdentical(const PredicateMatcher &B) const override {
1915 return InstructionPredicateMatcher::isIdentical(B) &&
1916 Predicate.getOrigPatFragRecord() ==
1917 cast<InstructionImmPredicateMatcher>(&B)
1918 ->Predicate.getOrigPatFragRecord();
1919 }
1920
Quentin Colombet063d7982017-12-14 23:44:07 +00001921 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001922 return P->getKind() == IPM_ImmPredicate;
1923 }
1924
Quentin Colombetaad20be2017-12-15 23:07:42 +00001925 void emitPredicateOpcodes(MatchTable &Table,
1926 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001927 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001928 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1929 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001930 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001931 << MatchTable::LineBreak;
1932 }
1933};
1934
Daniel Sanders76664652017-11-28 22:07:05 +00001935/// Generates code to check that a memory instruction has a atomic ordering
1936/// MachineMemoryOperand.
1937class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001938public:
1939 enum AOComparator {
1940 AO_Exactly,
1941 AO_OrStronger,
1942 AO_WeakerThan,
1943 };
1944
1945protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001946 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001947 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001948
Daniel Sanders39690bd2017-10-15 02:41:12 +00001949public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001950 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001951 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001952 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1953 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001954
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001955 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001956 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001957 }
1958
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001959 bool isIdentical(const PredicateMatcher &B) const override {
1960 if (!InstructionPredicateMatcher::isIdentical(B))
1961 return false;
1962 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1963 return Order == R.Order && Comparator == R.Comparator;
1964 }
1965
Quentin Colombetaad20be2017-12-15 23:07:42 +00001966 void emitPredicateOpcodes(MatchTable &Table,
1967 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001968 StringRef Opcode = "GIM_CheckAtomicOrdering";
1969
1970 if (Comparator == AO_OrStronger)
1971 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1972 if (Comparator == AO_WeakerThan)
1973 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1974
1975 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1976 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001977 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001978 << MatchTable::LineBreak;
1979 }
1980};
1981
Daniel Sandersf84bc372018-05-05 20:53:24 +00001982/// Generates code to check that the size of an MMO is exactly N bytes.
1983class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1984protected:
1985 unsigned MMOIdx;
1986 uint64_t Size;
1987
1988public:
1989 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1990 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1991 MMOIdx(MMOIdx), Size(Size) {}
1992
1993 static bool classof(const PredicateMatcher *P) {
1994 return P->getKind() == IPM_MemoryLLTSize;
1995 }
1996 bool isIdentical(const PredicateMatcher &B) const override {
1997 return InstructionPredicateMatcher::isIdentical(B) &&
1998 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1999 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
2000 }
2001
2002 void emitPredicateOpcodes(MatchTable &Table,
2003 RuleMatcher &Rule) const override {
2004 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
2005 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2006 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2007 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
2008 << MatchTable::LineBreak;
2009 }
2010};
2011
Matt Arsenaultd00d8572019-07-15 20:59:42 +00002012class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
2013protected:
2014 unsigned MMOIdx;
2015 SmallVector<unsigned, 4> AddrSpaces;
2016
2017public:
2018 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2019 ArrayRef<unsigned> AddrSpaces)
2020 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
2021 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
2022
2023 static bool classof(const PredicateMatcher *P) {
2024 return P->getKind() == IPM_MemoryAddressSpace;
2025 }
2026 bool isIdentical(const PredicateMatcher &B) const override {
2027 if (!InstructionPredicateMatcher::isIdentical(B))
2028 return false;
2029 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
2030 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
2031 }
2032
2033 void emitPredicateOpcodes(MatchTable &Table,
2034 RuleMatcher &Rule) const override {
2035 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
2036 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2037 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2038 // Encode number of address spaces to expect.
2039 << MatchTable::Comment("NumAddrSpace")
2040 << MatchTable::IntValue(AddrSpaces.size());
2041 for (unsigned AS : AddrSpaces)
2042 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
2043
2044 Table << MatchTable::LineBreak;
2045 }
2046};
2047
Matt Arsenault52c26242019-07-31 00:14:43 +00002048class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
2049protected:
2050 unsigned MMOIdx;
2051 int MinAlign;
2052
2053public:
2054 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2055 int MinAlign)
2056 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
2057 MMOIdx(MMOIdx), MinAlign(MinAlign) {
2058 assert(MinAlign > 0);
2059 }
2060
2061 static bool classof(const PredicateMatcher *P) {
2062 return P->getKind() == IPM_MemoryAlignment;
2063 }
2064
2065 bool isIdentical(const PredicateMatcher &B) const override {
2066 if (!InstructionPredicateMatcher::isIdentical(B))
2067 return false;
2068 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
2069 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
2070 }
2071
2072 void emitPredicateOpcodes(MatchTable &Table,
2073 RuleMatcher &Rule) const override {
2074 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
2075 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2076 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2077 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
2078 << MatchTable::LineBreak;
2079 }
2080};
2081
Daniel Sandersf84bc372018-05-05 20:53:24 +00002082/// Generates code to check that the size of an MMO is less-than, equal-to, or
2083/// greater than a given LLT.
2084class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
2085public:
2086 enum RelationKind {
2087 GreaterThan,
2088 EqualTo,
2089 LessThan,
2090 };
2091
2092protected:
2093 unsigned MMOIdx;
2094 RelationKind Relation;
2095 unsigned OpIdx;
2096
2097public:
2098 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2099 enum RelationKind Relation,
2100 unsigned OpIdx)
2101 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
2102 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
2103
2104 static bool classof(const PredicateMatcher *P) {
2105 return P->getKind() == IPM_MemoryVsLLTSize;
2106 }
2107 bool isIdentical(const PredicateMatcher &B) const override {
2108 return InstructionPredicateMatcher::isIdentical(B) &&
2109 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2110 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2111 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2112 }
2113
2114 void emitPredicateOpcodes(MatchTable &Table,
2115 RuleMatcher &Rule) const override {
2116 Table << MatchTable::Opcode(Relation == EqualTo
2117 ? "GIM_CheckMemorySizeEqualToLLT"
2118 : Relation == GreaterThan
2119 ? "GIM_CheckMemorySizeGreaterThanLLT"
2120 : "GIM_CheckMemorySizeLessThanLLT")
2121 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2122 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2123 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2124 << MatchTable::LineBreak;
2125 }
2126};
2127
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04002128// Matcher for immAllOnesV/immAllZerosV
2129class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
2130public:
2131 enum SplatKind {
2132 AllZeros,
2133 AllOnes
2134 };
2135
2136private:
2137 SplatKind Kind;
2138
2139public:
2140 VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
2141 : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
2142
2143 static bool classof(const PredicateMatcher *P) {
2144 return P->getKind() == IPM_VectorSplatImm;
2145 }
2146
2147 bool isIdentical(const PredicateMatcher &B) const override {
2148 return InstructionPredicateMatcher::isIdentical(B) &&
2149 Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
2150 }
2151
2152 void emitPredicateOpcodes(MatchTable &Table,
2153 RuleMatcher &Rule) const override {
2154 if (Kind == AllOnes)
2155 Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
2156 else
2157 Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
2158
2159 Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
2160 Table << MatchTable::LineBreak;
2161 }
2162};
2163
Daniel Sanders8ead1292018-06-15 23:13:43 +00002164/// Generates code to check an arbitrary C++ instruction predicate.
2165class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2166protected:
2167 TreePredicateFn Predicate;
2168
2169public:
2170 GenericInstructionPredicateMatcher(unsigned InsnVarID,
2171 TreePredicateFn Predicate)
2172 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2173 Predicate(Predicate) {}
2174
2175 static bool classof(const InstructionPredicateMatcher *P) {
2176 return P->getKind() == IPM_GenericPredicate;
2177 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00002178 bool isIdentical(const PredicateMatcher &B) const override {
2179 return InstructionPredicateMatcher::isIdentical(B) &&
2180 Predicate ==
2181 static_cast<const GenericInstructionPredicateMatcher &>(B)
2182 .Predicate;
2183 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00002184 void emitPredicateOpcodes(MatchTable &Table,
2185 RuleMatcher &Rule) const override {
2186 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2187 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2188 << MatchTable::Comment("FnId")
2189 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2190 << MatchTable::LineBreak;
2191 }
2192};
2193
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002194/// Generates code to check that a set of predicates and operands match for a
2195/// particular instruction.
2196///
2197/// Typical predicates include:
2198/// * Has a specific opcode.
2199/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002200class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002201protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002202 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002203
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002204 RuleMatcher &Rule;
2205
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002206 /// The operands to match. All rendered operands must be present even if the
2207 /// condition is always true.
2208 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002209 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002210
Daniel Sanders05540042017-08-08 10:44:31 +00002211 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002212 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002213
Matt Arsenault3e45c702019-09-06 20:32:37 +00002214 /// PhysRegInputs - List list has an entry for each explicitly specified
2215 /// physreg input to the pattern. The first elt is the Register node, the
2216 /// second is the recorded slot number the input pattern match saved it in.
2217 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2218
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002219public:
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04002220 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
2221 bool NumOpsCheck = true)
2222 : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
Quentin Colombetaad20be2017-12-15 23:07:42 +00002223 // We create a new instruction matcher.
2224 // Get a new ID for that instruction.
2225 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2226 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002227
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002228 /// Construct a new instruction predicate and add it to the matcher.
2229 template <class Kind, class... Args>
2230 Optional<Kind *> addPredicate(Args &&... args) {
2231 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002232 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002233 return static_cast<Kind *>(Predicates.back().get());
2234 }
2235
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002236 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002237
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002238 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002239
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002240 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002241 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2242 unsigned AllocatedTemporariesBaseID) {
2243 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2244 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002245 if (!SymbolicName.empty())
2246 Rule.defineOperand(SymbolicName, *Operands.back());
2247
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002248 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002249 }
2250
Daniel Sandersffc7d582017-03-29 15:37:18 +00002251 OperandMatcher &getOperand(unsigned OpIdx) {
2252 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002253 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002254 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002255 });
2256 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002257 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002258 llvm_unreachable("Failed to lookup operand");
2259 }
2260
Matt Arsenault3e45c702019-09-06 20:32:37 +00002261 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2262 unsigned TempOpIdx) {
2263 assert(SymbolicName.empty());
2264 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2265 Operands.emplace_back(OM);
2266 Rule.definePhysRegOperand(Reg, *OM);
2267 PhysRegInputs.emplace_back(Reg, OpIdx);
2268 return *OM;
2269 }
2270
2271 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2272 return PhysRegInputs;
2273 }
2274
Daniel Sanders05540042017-08-08 10:44:31 +00002275 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002276 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002277 OperandVec::iterator operands_begin() { return Operands.begin(); }
2278 OperandVec::iterator operands_end() { return Operands.end(); }
2279 iterator_range<OperandVec::iterator> operands() {
2280 return make_range(operands_begin(), operands_end());
2281 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002282 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2283 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002284 iterator_range<OperandVec::const_iterator> operands() const {
2285 return make_range(operands_begin(), operands_end());
2286 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002287 bool operands_empty() const { return Operands.empty(); }
2288
2289 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002290
Roman Tereshin19da6672018-05-22 04:31:50 +00002291 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002292
2293 /// Emit MatchTable opcodes that test whether the instruction named in
2294 /// InsnVarName matches all the predicates and all the operands.
2295 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002296 if (NumOperandsCheck)
2297 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2298 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002299
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002300 // First emit all instruction level predicates need to be verified before we
2301 // can verify operands.
2302 emitFilteredPredicateListOpcodes(
2303 [](const PredicateMatcher &P) {
2304 return !P.dependsOnOperands();
2305 }, Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002306
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002307 // Emit all operand constraints.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002308 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002309 Operand->emitPredicateOpcodes(Table, Rule);
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002310
2311 // All of the tablegen defined predicates should now be matched. Now emit
2312 // any custom predicates that rely on all generated checks.
2313 emitFilteredPredicateListOpcodes(
2314 [](const PredicateMatcher &P) {
2315 return P.dependsOnOperands();
2316 }, Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002317 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002318
2319 /// Compare the priority of this object and B.
2320 ///
2321 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002322 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002323 // Instruction matchers involving more operands have higher priority.
2324 if (Operands.size() > B.Operands.size())
2325 return true;
2326 if (Operands.size() < B.Operands.size())
2327 return false;
2328
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002329 for (auto &&P : zip(predicates(), B.predicates())) {
2330 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2331 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2332 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002333 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002334 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002335 return false;
2336 }
2337
Mark de Wevere8d448e2019-12-22 18:58:32 +01002338 for (auto Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002339 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002340 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002341 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002342 return false;
2343 }
2344
2345 return false;
2346 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002347
2348 /// Report the maximum number of temporary operands needed by the instruction
2349 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002350 unsigned countRendererFns() {
2351 return std::accumulate(
2352 predicates().begin(), predicates().end(), 0,
2353 [](unsigned A,
2354 const std::unique_ptr<PredicateMatcher> &Predicate) {
2355 return A + Predicate->countRendererFns();
2356 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002357 std::accumulate(
2358 Operands.begin(), Operands.end(), 0,
2359 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002360 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002361 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002362 }
Daniel Sanders05540042017-08-08 10:44:31 +00002363
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002364 InstructionOpcodeMatcher &getOpcodeMatcher() {
2365 for (auto &P : predicates())
2366 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2367 return *OpMatcher;
2368 llvm_unreachable("Didn't find an opcode matcher");
2369 }
2370
2371 bool isConstantInstruction() {
2372 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002373 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002374
2375 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002376};
2377
Roman Tereshin19da6672018-05-22 04:31:50 +00002378StringRef RuleMatcher::getOpcode() const {
2379 return Matchers.front()->getOpcode();
2380}
2381
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002382unsigned RuleMatcher::getNumOperands() const {
2383 return Matchers.front()->getNumOperands();
2384}
2385
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002386LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2387 InstructionMatcher &InsnMatcher = *Matchers.front();
2388 if (!InsnMatcher.predicates_empty())
2389 if (const auto *TM =
2390 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2391 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2392 return TM->getTy();
2393 return {};
2394}
2395
Daniel Sandersbee57392017-04-04 13:25:23 +00002396/// Generates code to check that the operand is a register defined by an
2397/// instruction that matches the given instruction matcher.
2398///
2399/// For example, the pattern:
2400/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2401/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2402/// the:
2403/// (G_ADD $src1, $src2)
2404/// subpattern.
2405class InstructionOperandMatcher : public OperandPredicateMatcher {
2406protected:
2407 std::unique_ptr<InstructionMatcher> InsnMatcher;
2408
2409public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002410 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04002411 RuleMatcher &Rule, StringRef SymbolicName,
2412 bool NumOpsCheck = true)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002413 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04002414 InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002415
Quentin Colombet063d7982017-12-14 23:44:07 +00002416 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002417 return P->getKind() == OPM_Instruction;
2418 }
2419
2420 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2421
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002422 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2423 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2424 Table << MatchTable::Opcode("GIM_RecordInsn")
2425 << MatchTable::Comment("DefineMI")
2426 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2427 << MatchTable::IntValue(getInsnVarID())
2428 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2429 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2430 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002431 }
2432
Quentin Colombetaad20be2017-12-15 23:07:42 +00002433 void emitPredicateOpcodes(MatchTable &Table,
2434 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002435 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002436 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002437 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002438
2439 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2440 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2441 return true;
2442 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2443 return false;
2444
2445 if (const InstructionOperandMatcher *BP =
2446 dyn_cast<InstructionOperandMatcher>(&B))
2447 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2448 return true;
2449 return false;
2450 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002451};
2452
Roman Tereshin19da6672018-05-22 04:31:50 +00002453void InstructionMatcher::optimize() {
2454 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2455 const auto &OpcMatcher = getOpcodeMatcher();
2456
2457 Stash.push_back(predicates_pop_front());
2458 if (Stash.back().get() == &OpcMatcher) {
Roman Tereshin6082a062019-10-30 20:58:46 -07002459 if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
Roman Tereshin19da6672018-05-22 04:31:50 +00002460 Stash.emplace_back(
2461 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2462 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002463
2464 for (auto &OM : Operands)
2465 for (auto &OP : OM->predicates())
2466 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2467 Stash.push_back(std::move(OP));
2468 OM->eraseNullPredicates();
2469 break;
2470 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002471 }
2472
2473 if (InsnVarID > 0) {
2474 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2475 for (auto &OP : Operands[0]->predicates())
2476 OP.reset();
2477 Operands[0]->eraseNullPredicates();
2478 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002479 for (auto &OM : Operands) {
2480 for (auto &OP : OM->predicates())
2481 if (isa<LLTOperandMatcher>(OP))
2482 Stash.push_back(std::move(OP));
2483 OM->eraseNullPredicates();
2484 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002485 while (!Stash.empty())
2486 prependPredicate(Stash.pop_back_val());
2487}
2488
Daniel Sanders43c882c2017-02-01 10:53:10 +00002489//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002490class OperandRenderer {
2491public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002492 enum RendererKind {
2493 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002494 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002495 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002496 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002497 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002498 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002499 OR_Imm,
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002500 OR_SubRegIndex,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002501 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002502 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002503 OR_ComplexPattern,
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002504 OR_Custom,
2505 OR_CustomOperand
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002506 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002507
2508protected:
2509 RendererKind Kind;
2510
2511public:
2512 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2513 virtual ~OperandRenderer() {}
2514
2515 RendererKind getKind() const { return Kind; }
2516
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002517 virtual void emitRenderOpcodes(MatchTable &Table,
2518 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002519};
2520
2521/// A CopyRenderer emits code to copy a single operand from an existing
2522/// instruction to the one being built.
2523class CopyRenderer : public OperandRenderer {
2524protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002525 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002526 /// The name of the operand.
2527 const StringRef SymbolicName;
2528
2529public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002530 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2531 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002532 SymbolicName(SymbolicName) {
2533 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2534 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002535
2536 static bool classof(const OperandRenderer *R) {
2537 return R->getKind() == OR_Copy;
2538 }
2539
2540 const StringRef getSymbolicName() const { return SymbolicName; }
2541
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002542 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002543 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002544 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002545 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2546 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2547 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002548 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002549 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002550 }
2551};
2552
Matt Arsenault3e45c702019-09-06 20:32:37 +00002553/// A CopyRenderer emits code to copy a virtual register to a specific physical
2554/// register.
2555class CopyPhysRegRenderer : public OperandRenderer {
2556protected:
2557 unsigned NewInsnID;
2558 Record *PhysReg;
2559
2560public:
2561 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2562 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2563 PhysReg(Reg) {
2564 assert(PhysReg);
2565 }
2566
2567 static bool classof(const OperandRenderer *R) {
2568 return R->getKind() == OR_CopyPhysReg;
2569 }
2570
2571 Record *getPhysReg() const { return PhysReg; }
2572
2573 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2574 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2575 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2576 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2577 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2578 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2579 << MatchTable::IntValue(Operand.getOpIdx())
2580 << MatchTable::Comment(PhysReg->getName())
2581 << MatchTable::LineBreak;
2582 }
2583};
2584
Daniel Sandersd66e0902017-10-23 18:19:24 +00002585/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2586/// existing instruction to the one being built. If the operand turns out to be
2587/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2588class CopyOrAddZeroRegRenderer : public OperandRenderer {
2589protected:
2590 unsigned NewInsnID;
2591 /// The name of the operand.
2592 const StringRef SymbolicName;
2593 const Record *ZeroRegisterDef;
2594
2595public:
2596 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002597 StringRef SymbolicName, Record *ZeroRegisterDef)
2598 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2599 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2600 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2601 }
2602
2603 static bool classof(const OperandRenderer *R) {
2604 return R->getKind() == OR_CopyOrAddZeroReg;
2605 }
2606
2607 const StringRef getSymbolicName() const { return SymbolicName; }
2608
2609 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2610 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2611 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2612 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2613 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2614 << MatchTable::Comment("OldInsnID")
2615 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002616 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002617 << MatchTable::NamedValue(
2618 (ZeroRegisterDef->getValue("Namespace")
2619 ? ZeroRegisterDef->getValueAsString("Namespace")
2620 : ""),
2621 ZeroRegisterDef->getName())
2622 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2623 }
2624};
2625
Daniel Sanders05540042017-08-08 10:44:31 +00002626/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2627/// an extended immediate operand.
2628class CopyConstantAsImmRenderer : public OperandRenderer {
2629protected:
2630 unsigned NewInsnID;
2631 /// The name of the operand.
2632 const std::string SymbolicName;
2633 bool Signed;
2634
2635public:
2636 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2637 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2638 SymbolicName(SymbolicName), Signed(true) {}
2639
2640 static bool classof(const OperandRenderer *R) {
2641 return R->getKind() == OR_CopyConstantAsImm;
2642 }
2643
2644 const StringRef getSymbolicName() const { return SymbolicName; }
2645
2646 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002647 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002648 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2649 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2650 : "GIR_CopyConstantAsUImm")
2651 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2652 << MatchTable::Comment("OldInsnID")
2653 << MatchTable::IntValue(OldInsnVarID)
2654 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2655 }
2656};
2657
Daniel Sanders11300ce2017-10-13 21:28:03 +00002658/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2659/// instruction to an extended immediate operand.
2660class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2661protected:
2662 unsigned NewInsnID;
2663 /// The name of the operand.
2664 const std::string SymbolicName;
2665
2666public:
2667 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2668 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2669 SymbolicName(SymbolicName) {}
2670
2671 static bool classof(const OperandRenderer *R) {
2672 return R->getKind() == OR_CopyFConstantAsFPImm;
2673 }
2674
2675 const StringRef getSymbolicName() const { return SymbolicName; }
2676
2677 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002678 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002679 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2680 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2681 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2682 << MatchTable::Comment("OldInsnID")
2683 << MatchTable::IntValue(OldInsnVarID)
2684 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2685 }
2686};
2687
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002688/// A CopySubRegRenderer emits code to copy a single register operand from an
2689/// existing instruction to the one being built and indicate that only a
2690/// subregister should be copied.
2691class CopySubRegRenderer : public OperandRenderer {
2692protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002693 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002694 /// The name of the operand.
2695 const StringRef SymbolicName;
2696 /// The subregister to extract.
2697 const CodeGenSubRegIndex *SubReg;
2698
2699public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002700 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2701 const CodeGenSubRegIndex *SubReg)
2702 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002703 SymbolicName(SymbolicName), SubReg(SubReg) {}
2704
2705 static bool classof(const OperandRenderer *R) {
2706 return R->getKind() == OR_CopySubReg;
2707 }
2708
2709 const StringRef getSymbolicName() const { return SymbolicName; }
2710
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002711 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002712 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002713 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002714 Table << MatchTable::Opcode("GIR_CopySubReg")
2715 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2716 << MatchTable::Comment("OldInsnID")
2717 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002718 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002719 << MatchTable::Comment("SubRegIdx")
2720 << MatchTable::IntValue(SubReg->EnumValue)
2721 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002722 }
2723};
2724
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002725/// Adds a specific physical register to the instruction being built.
2726/// This is typically useful for WZR/XZR on AArch64.
2727class AddRegisterRenderer : public OperandRenderer {
2728protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002729 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002730 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002731 bool IsDef;
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02002732 const CodeGenTarget &Target;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002733
2734public:
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02002735 AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target,
2736 const Record *RegisterDef, bool IsDef = false)
Matt Arsenault3e45c702019-09-06 20:32:37 +00002737 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02002738 IsDef(IsDef), Target(Target) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002739
2740 static bool classof(const OperandRenderer *R) {
2741 return R->getKind() == OR_Register;
2742 }
2743
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002744 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2745 Table << MatchTable::Opcode("GIR_AddRegister")
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02002746 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID);
2747 if (RegisterDef->getName() != "zero_reg") {
2748 Table << MatchTable::NamedValue(
2749 (RegisterDef->getValue("Namespace")
2750 ? RegisterDef->getValueAsString("Namespace")
2751 : ""),
2752 RegisterDef->getName());
2753 } else {
2754 Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister");
2755 }
2756 Table << MatchTable::Comment("AddRegisterRegFlags");
Matt Arsenault3e45c702019-09-06 20:32:37 +00002757
2758 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2759 // really needed for a physical register reference. We can pack the
2760 // register and flags in a single field.
2761 if (IsDef)
2762 Table << MatchTable::NamedValue("RegState::Define");
2763 else
2764 Table << MatchTable::IntValue(0);
2765 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002766 }
2767};
2768
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002769/// Adds a specific temporary virtual register to the instruction being built.
2770/// This is used to chain instructions together when emitting multiple
2771/// instructions.
2772class TempRegRenderer : public OperandRenderer {
2773protected:
2774 unsigned InsnID;
2775 unsigned TempRegID;
Matt Arsenault9c346462020-01-14 16:02:02 -05002776 const CodeGenSubRegIndex *SubRegIdx;
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002777 bool IsDef;
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002778 bool IsDead;
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002779
2780public:
Matt Arsenault9c346462020-01-14 16:02:02 -05002781 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002782 const CodeGenSubRegIndex *SubReg = nullptr,
2783 bool IsDead = false)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002784 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002785 SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002786
2787 static bool classof(const OperandRenderer *R) {
2788 return R->getKind() == OR_TempRegister;
2789 }
2790
2791 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Matt Arsenault9c346462020-01-14 16:02:02 -05002792 if (SubRegIdx) {
2793 assert(!IsDef);
2794 Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2795 } else
2796 Table << MatchTable::Opcode("GIR_AddTempRegister");
2797
2798 Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002799 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2800 << MatchTable::Comment("TempRegFlags");
Matt Arsenault9c346462020-01-14 16:02:02 -05002801
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002802 if (IsDef) {
2803 SmallString<32> RegFlags;
2804 RegFlags += "RegState::Define";
2805 if (IsDead)
2806 RegFlags += "|RegState::Dead";
2807 Table << MatchTable::NamedValue(RegFlags);
2808 } else
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002809 Table << MatchTable::IntValue(0);
Matt Arsenault9c346462020-01-14 16:02:02 -05002810
2811 if (SubRegIdx)
2812 Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002813 Table << MatchTable::LineBreak;
2814 }
2815};
2816
Daniel Sanders0ed28822017-04-12 08:23:08 +00002817/// Adds a specific immediate to the instruction being built.
2818class ImmRenderer : public OperandRenderer {
2819protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002820 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002821 int64_t Imm;
2822
2823public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002824 ImmRenderer(unsigned InsnID, int64_t Imm)
2825 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002826
2827 static bool classof(const OperandRenderer *R) {
2828 return R->getKind() == OR_Imm;
2829 }
2830
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002831 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2832 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2833 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2834 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002835 }
2836};
2837
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002838/// Adds an enum value for a subreg index to the instruction being built.
2839class SubRegIndexRenderer : public OperandRenderer {
2840protected:
2841 unsigned InsnID;
2842 const CodeGenSubRegIndex *SubRegIdx;
2843
2844public:
2845 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2846 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2847
2848 static bool classof(const OperandRenderer *R) {
2849 return R->getKind() == OR_SubRegIndex;
2850 }
2851
2852 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2853 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2854 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2855 << MatchTable::IntValue(SubRegIdx->EnumValue)
2856 << MatchTable::LineBreak;
2857 }
2858};
2859
Daniel Sanders2deea182017-04-22 15:11:04 +00002860/// Adds operands by calling a renderer function supplied by the ComplexPattern
2861/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002862class RenderComplexPatternOperand : public OperandRenderer {
2863private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002864 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002865 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002866 /// The name of the operand.
2867 const StringRef SymbolicName;
2868 /// The renderer number. This must be unique within a rule since it's used to
2869 /// identify a temporary variable to hold the renderer function.
2870 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002871 /// When provided, this is the suboperand of the ComplexPattern operand to
2872 /// render. Otherwise all the suboperands will be rendered.
2873 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002874
2875 unsigned getNumOperands() const {
2876 return TheDef.getValueAsDag("Operands")->getNumArgs();
2877 }
2878
2879public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002880 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002881 StringRef SymbolicName, unsigned RendererID,
2882 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002883 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002884 SymbolicName(SymbolicName), RendererID(RendererID),
2885 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002886
2887 static bool classof(const OperandRenderer *R) {
2888 return R->getKind() == OR_ComplexPattern;
2889 }
2890
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002891 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002892 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2893 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002894 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2895 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002896 << MatchTable::IntValue(RendererID);
2897 if (SubOperand.hasValue())
2898 Table << MatchTable::Comment("SubOperand")
2899 << MatchTable::IntValue(SubOperand.getValue());
2900 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002901 }
2902};
2903
Volkan Kelesf7f25682018-01-16 18:44:05 +00002904class CustomRenderer : public OperandRenderer {
2905protected:
2906 unsigned InsnID;
2907 const Record &Renderer;
2908 /// The name of the operand.
2909 const std::string SymbolicName;
2910
2911public:
2912 CustomRenderer(unsigned InsnID, const Record &Renderer,
2913 StringRef SymbolicName)
2914 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2915 SymbolicName(SymbolicName) {}
2916
2917 static bool classof(const OperandRenderer *R) {
2918 return R->getKind() == OR_Custom;
2919 }
2920
2921 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002922 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002923 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2924 Table << MatchTable::Opcode("GIR_CustomRenderer")
2925 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2926 << MatchTable::Comment("OldInsnID")
2927 << MatchTable::IntValue(OldInsnVarID)
2928 << MatchTable::Comment("Renderer")
2929 << MatchTable::NamedValue(
2930 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2931 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2932 }
2933};
2934
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002935class CustomOperandRenderer : public OperandRenderer {
2936protected:
2937 unsigned InsnID;
2938 const Record &Renderer;
2939 /// The name of the operand.
2940 const std::string SymbolicName;
2941
2942public:
2943 CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2944 StringRef SymbolicName)
2945 : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2946 SymbolicName(SymbolicName) {}
2947
2948 static bool classof(const OperandRenderer *R) {
2949 return R->getKind() == OR_CustomOperand;
2950 }
2951
2952 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2953 const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2954 Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2955 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2956 << MatchTable::Comment("OldInsnID")
2957 << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2958 << MatchTable::Comment("OpIdx")
2959 << MatchTable::IntValue(OpdMatcher.getOpIdx())
2960 << MatchTable::Comment("OperandRenderer")
2961 << MatchTable::NamedValue(
2962 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2963 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2964 }
2965};
2966
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002967/// An action taken when all Matcher predicates succeeded for a parent rule.
2968///
2969/// Typical actions include:
2970/// * Changing the opcode of an instruction.
2971/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002972class MatchAction {
2973public:
2974 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002975
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002976 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002977 virtual void emitActionOpcodes(MatchTable &Table,
2978 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002979};
2980
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002981/// Generates a comment describing the matched rule being acted upon.
2982class DebugCommentAction : public MatchAction {
2983private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002984 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002985
2986public:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002987 DebugCommentAction(StringRef S) : S(std::string(S)) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002988
Daniel Sandersa7b75262017-10-31 18:50:24 +00002989 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002990 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002991 }
2992};
2993
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002994/// Generates code to build an instruction or mutate an existing instruction
2995/// into the desired instruction when this is possible.
2996class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002997private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002998 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002999 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003000 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003001 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
3002
3003 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00003004 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
3005 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00003006 return false;
3007
Daniel Sandersa7b75262017-10-31 18:50:24 +00003008 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003009 return false;
3010
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003011 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00003012 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003013 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00003014 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003015 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003016 return false;
3017 } else
3018 return false;
3019 }
3020
3021 return true;
3022 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003023
Daniel Sanders43c882c2017-02-01 10:53:10 +00003024public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00003025 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
3026 : InsnID(InsnID), I(I), Matched(nullptr) {}
3027
Daniel Sanders08464522018-01-29 21:09:12 +00003028 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003029 const CodeGenInstruction *getCGI() const { return I; }
3030
Daniel Sandersa7b75262017-10-31 18:50:24 +00003031 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003032 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00003033 if (canMutate(Rule, MutateCandidate)) {
3034 // Take the first one we're offered that we're able to mutate.
3035 Rule.reserveInsnMatcherForMutation(MutateCandidate);
3036 Matched = MutateCandidate;
3037 return;
3038 }
3039 }
3040 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00003041
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003042 template <class Kind, class... Args>
3043 Kind &addRenderer(Args&&... args) {
3044 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003045 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003046 return *static_cast<Kind *>(OperandRenderers.back().get());
3047 }
3048
Daniel Sandersa7b75262017-10-31 18:50:24 +00003049 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3050 if (Matched) {
3051 assert(canMutate(Rule, Matched) &&
3052 "Arranged to mutate an insn that isn't mutatable");
3053
3054 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003055 Table << MatchTable::Opcode("GIR_MutateOpcode")
3056 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3057 << MatchTable::Comment("RecycleInsnID")
3058 << MatchTable::IntValue(RecycleInsnID)
3059 << MatchTable::Comment("Opcode")
3060 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3061 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00003062
3063 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00003064 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00003065 auto Namespace = Def->getValue("Namespace")
3066 ? Def->getValueAsString("Namespace")
3067 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003068 Table << MatchTable::Opcode("GIR_AddImplicitDef")
3069 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3070 << MatchTable::NamedValue(Namespace, Def->getName())
3071 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00003072 }
3073 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00003074 auto Namespace = Use->getValue("Namespace")
3075 ? Use->getValueAsString("Namespace")
3076 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003077 Table << MatchTable::Opcode("GIR_AddImplicitUse")
3078 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3079 << MatchTable::NamedValue(Namespace, Use->getName())
3080 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00003081 }
3082 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003083 return;
3084 }
3085
3086 // TODO: Simple permutation looks like it could be almost as common as
3087 // mutation due to commutative operations.
3088
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003089 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
3090 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
3091 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3092 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003093 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003094 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003095
Florian Hahn3bc3ec62017-08-03 14:48:22 +00003096 if (I->mayLoad || I->mayStore) {
3097 Table << MatchTable::Opcode("GIR_MergeMemOperands")
3098 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3099 << MatchTable::Comment("MergeInsnID's");
3100 // Emit the ID's for all the instructions that are matched by this rule.
3101 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
3102 // some other means of having a memoperand. Also limit this to
3103 // emitted instructions that expect to have a memoperand too. For
3104 // example, (G_SEXT (G_LOAD x)) that results in separate load and
3105 // sign-extend instructions shouldn't put the memoperand on the
3106 // sign-extend since it has no effect there.
3107 std::vector<unsigned> MergeInsnIDs;
3108 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
3109 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00003110 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00003111 for (const auto &MergeInsnID : MergeInsnIDs)
3112 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00003113 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
3114 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00003115 }
3116
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003117 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
3118 // better for combines. Particularly when there are multiple match
3119 // roots.
3120 if (InsnID == 0)
3121 Table << MatchTable::Opcode("GIR_EraseFromParent")
3122 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3123 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003124 }
3125};
3126
3127/// Generates code to constrain the operands of an output instruction to the
3128/// register classes specified by the definition of that instruction.
3129class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003130 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003131
3132public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003133 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003134
Daniel Sandersa7b75262017-10-31 18:50:24 +00003135 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003136 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
3137 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3138 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003139 }
3140};
3141
3142/// Generates code to constrain the specified operand of an output instruction
3143/// to the specified register class.
3144class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003145 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003146 unsigned OpIdx;
3147 const CodeGenRegisterClass &RC;
3148
3149public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003150 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003151 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003152 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003153
Daniel Sandersa7b75262017-10-31 18:50:24 +00003154 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003155 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3156 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3157 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
Matt Arsenault2e2af602020-07-13 13:14:29 -04003158 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3159 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003160 }
3161};
3162
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003163/// Generates code to create a temporary register which can be used to chain
3164/// instructions together.
3165class MakeTempRegisterAction : public MatchAction {
3166private:
3167 LLTCodeGen Ty;
3168 unsigned TempRegID;
3169
3170public:
3171 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
Matt Arsenault4a23ae52019-09-10 17:57:33 +00003172 : Ty(Ty), TempRegID(TempRegID) {
3173 KnownTypes.insert(Ty);
3174 }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003175
3176 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3177 Table << MatchTable::Opcode("GIR_MakeTempReg")
3178 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3179 << MatchTable::Comment("TypeID")
3180 << MatchTable::NamedValue(Ty.getCxxEnumValue())
3181 << MatchTable::LineBreak;
3182 }
3183};
3184
Daniel Sanders05540042017-08-08 10:44:31 +00003185InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003186 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00003187 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003188 return *Matchers.back();
3189}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00003190
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003191void RuleMatcher::addRequiredFeature(Record *Feature) {
3192 RequiredFeatures.push_back(Feature);
3193}
3194
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003195const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3196 return RequiredFeatures;
3197}
3198
Daniel Sanders7438b262017-10-31 23:03:18 +00003199// Emplaces an action of the specified Kind at the end of the action list.
3200//
3201// Returns a reference to the newly created action.
3202//
3203// Like std::vector::emplace_back(), may invalidate all iterators if the new
3204// size exceeds the capacity. Otherwise, only invalidates the past-the-end
3205// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003206template <class Kind, class... Args>
3207Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003208 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003209 return *static_cast<Kind *>(Actions.back().get());
3210}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003211
Daniel Sanders7438b262017-10-31 23:03:18 +00003212// Emplaces an action of the specified Kind before the given insertion point.
3213//
3214// Returns an iterator pointing at the newly created instruction.
3215//
3216// Like std::vector::insert(), may invalidate all iterators if the new size
3217// exceeds the capacity. Otherwise, only invalidates the iterators from the
3218// insertion point onwards.
3219template <class Kind, class... Args>
3220action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3221 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003222 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003223 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00003224}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003225
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003226unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003227 unsigned NewInsnVarID = NextInsnVarID++;
3228 InsnVariableIDs[&Matcher] = NewInsnVarID;
3229 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003230}
3231
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003232unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003233 const auto &I = InsnVariableIDs.find(&InsnMatcher);
3234 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003235 return I->second;
3236 llvm_unreachable("Matched Insn was not captured in a local variable");
3237}
3238
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003239void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3240 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3241 DefinedOperands[SymbolicName] = &OM;
3242 return;
3243 }
3244
3245 // If the operand is already defined, then we must ensure both references in
3246 // the matcher have the exact same node.
3247 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3248}
3249
Matt Arsenault3e45c702019-09-06 20:32:37 +00003250void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3251 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3252 PhysRegOperands[Reg] = &OM;
3253 return;
3254 }
3255}
3256
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003257InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00003258RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3259 for (const auto &I : InsnVariableIDs)
3260 if (I.first->getSymbolicName() == SymbolicName)
3261 return *I.first;
3262 llvm_unreachable(
3263 ("Failed to lookup instruction " + SymbolicName).str().c_str());
3264}
3265
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003266const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00003267RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3268 const auto &I = PhysRegOperands.find(Reg);
3269
3270 if (I == PhysRegOperands.end()) {
3271 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3272 " was not declared in matcher");
3273 }
3274
3275 return *I->second;
3276}
3277
3278const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003279RuleMatcher::getOperandMatcher(StringRef Name) const {
3280 const auto &I = DefinedOperands.find(Name);
3281
3282 if (I == DefinedOperands.end())
3283 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3284
3285 return *I->second;
3286}
3287
Daniel Sanders8e82af22017-07-27 11:03:45 +00003288void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003289 if (Matchers.empty())
3290 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003291
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003292 // The representation supports rules that require multiple roots such as:
3293 // %ptr(p0) = ...
3294 // %elt0(s32) = G_LOAD %ptr
3295 // %1(p0) = G_ADD %ptr, 4
3296 // %elt1(s32) = G_LOAD p0 %1
3297 // which could be usefully folded into:
3298 // %ptr(p0) = ...
3299 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3300 // on some targets but we don't need to make use of that yet.
3301 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003302
Daniel Sanders8e82af22017-07-27 11:03:45 +00003303 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003304 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003305 << MatchTable::Comment("On fail goto")
3306 << MatchTable::JumpTarget(LabelID)
3307 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003308 << MatchTable::LineBreak;
3309
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003310 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003311 Table << MatchTable::Opcode("GIM_CheckFeatures")
3312 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3313 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003314 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003315
Quentin Colombetaad20be2017-12-15 23:07:42 +00003316 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003317
Daniel Sandersbee57392017-04-04 13:25:23 +00003318 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003319 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003320 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003321 SmallVector<unsigned, 2> InsnIDs;
3322 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003323 // Skip the root node since it isn't moving anywhere. Everything else is
3324 // sinking to meet it.
3325 if (Pair.first == Matchers.front().get())
3326 continue;
3327
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003328 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003329 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003330 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003331
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003332 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003333 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003334 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3335 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3336 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003337
3338 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3339 // account for unsafe cases.
3340 //
3341 // Example:
3342 // MI1--> %0 = ...
3343 // %1 = ... %0
3344 // MI0--> %2 = ... %0
3345 // It's not safe to erase MI1. We currently handle this by not
3346 // erasing %0 (even when it's dead).
3347 //
3348 // Example:
3349 // MI1--> %0 = load volatile @a
3350 // %1 = load volatile @a
3351 // MI0--> %2 = ... %0
3352 // It's not safe to sink %0's def past %1. We currently handle
3353 // this by rejecting all loads.
3354 //
3355 // Example:
3356 // MI1--> %0 = load @a
3357 // %1 = store @a
3358 // MI0--> %2 = ... %0
3359 // It's not safe to sink %0's def past %1. We currently handle
3360 // this by rejecting all loads.
3361 //
3362 // Example:
3363 // G_CONDBR %cond, @BB1
3364 // BB0:
3365 // MI1--> %0 = load @a
3366 // G_BR @BB1
3367 // BB1:
3368 // MI0--> %2 = ... %0
3369 // It's not always safe to sink %0 across control flow. In this
3370 // case it may introduce a memory fault. We currentl handle this
3371 // by rejecting all loads.
3372 }
3373 }
3374
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003375 for (const auto &PM : EpilogueMatchers)
3376 PM->emitPredicateOpcodes(Table, *this);
3377
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003378 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003379 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003380
Roman Tereshinbeb39312018-05-02 20:15:11 +00003381 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003382 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3383 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003384 else
3385 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3386 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003387
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003388 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003389 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003390 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003391}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003392
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003393bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3394 // Rules involving more match roots have higher priority.
3395 if (Matchers.size() > B.Matchers.size())
3396 return true;
3397 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003398 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003399
Mark de Wevere8d448e2019-12-22 18:58:32 +01003400 for (auto Matcher : zip(Matchers, B.Matchers)) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003401 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3402 return true;
3403 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3404 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003405 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003406
3407 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003408}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003409
Daniel Sanders2deea182017-04-22 15:11:04 +00003410unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003411 return std::accumulate(
3412 Matchers.begin(), Matchers.end(), 0,
3413 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003414 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003415 });
3416}
3417
Daniel Sanders05540042017-08-08 10:44:31 +00003418bool OperandPredicateMatcher::isHigherPriorityThan(
3419 const OperandPredicateMatcher &B) const {
3420 // Generally speaking, an instruction is more important than an Int or a
3421 // LiteralInt because it can cover more nodes but theres an exception to
3422 // this. G_CONSTANT's are less important than either of those two because they
3423 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003424
3425 const InstructionOperandMatcher *AOM =
3426 dyn_cast<InstructionOperandMatcher>(this);
3427 const InstructionOperandMatcher *BOM =
3428 dyn_cast<InstructionOperandMatcher>(&B);
3429 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3430 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3431
3432 if (AOM && BOM) {
3433 // The relative priorities between a G_CONSTANT and any other instruction
3434 // don't actually matter but this code is needed to ensure a strict weak
3435 // ordering. This is particularly important on Windows where the rules will
3436 // be incorrectly sorted without it.
3437 if (AIsConstantInsn != BIsConstantInsn)
3438 return AIsConstantInsn < BIsConstantInsn;
3439 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003440 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003441
3442 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3443 return false;
3444 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3445 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003446
3447 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003448}
Daniel Sanders05540042017-08-08 10:44:31 +00003449
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003450void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003451 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003452 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003453 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003454 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003455
3456 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3457 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3458 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3459 << MatchTable::Comment("OtherMI")
3460 << MatchTable::IntValue(OtherInsnVarID)
3461 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003462 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003463 << MatchTable::LineBreak;
3464}
3465
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003466//===- GlobalISelEmitter class --------------------------------------------===//
3467
Matt Arsenault9c346462020-01-14 16:02:02 -05003468static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3469 ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3470 if (ChildTypes.size() != 1)
3471 return failedImport("Dst pattern child has multiple results");
3472
3473 Optional<LLTCodeGen> MaybeOpTy;
3474 if (ChildTypes.front().isMachineValueType()) {
3475 MaybeOpTy =
3476 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3477 }
3478
3479 if (!MaybeOpTy)
3480 return failedImport("Dst operand has an unsupported type");
3481 return *MaybeOpTy;
3482}
3483
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003484class GlobalISelEmitter {
3485public:
3486 explicit GlobalISelEmitter(RecordKeeper &RK);
3487 void run(raw_ostream &OS);
3488
3489private:
3490 const RecordKeeper &RK;
3491 const CodeGenDAGPatterns CGP;
3492 const CodeGenTarget &Target;
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003493 CodeGenRegBank &CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003494
Daniel Sanders39690bd2017-10-15 02:41:12 +00003495 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003496 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3497 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003498 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003499 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003500
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003501 /// Keep track of the equivalence between ComplexPattern's and
3502 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3503 /// GIComplexPatternEquiv.
3504 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3505
Volkan Kelesf7f25682018-01-16 18:44:05 +00003506 /// Keep track of the equivalence between SDNodeXForm's and
3507 /// GICustomOperandRenderer. Map entries are specified by subclassing
3508 /// GISDNodeXFormEquiv.
3509 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3510
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003511 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3512 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3513 DenseMap<uint64_t, int> RuleMatcherScores;
3514
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003515 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003516 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003517
Daniel Sandersf76f3152017-11-16 00:46:35 +00003518 // Rule coverage information.
3519 Optional<CodeGenCoverage> RuleCoverage;
3520
Petar Avramovic09b88712020-09-14 10:39:25 +02003521 /// Variables used to help with collecting of named operands for predicates
3522 /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
3523 /// to the number of named operands that predicate expects. Store locations in
3524 /// StoreIdxForName correspond to the order in which operand names appear in
3525 /// predicate's argument list.
3526 /// When we visit named leaf operand and WaitingForNamedOperands is not zero,
3527 /// add matcher that will record operand and decrease counter.
3528 unsigned WaitingForNamedOperands = 0;
3529 StringMap<unsigned> StoreIdxForName;
3530
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003531 void gatherOpcodeValues();
3532 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003533 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003534
Daniel Sanders39690bd2017-10-15 02:41:12 +00003535 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003536 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003537 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003538
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003539 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003540 Expected<InstructionMatcher &>
3541 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3542 InstructionMatcher &InsnMatcher,
3543 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003544 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3545 unsigned &TempOpIdx) const;
3546 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003547 const TreePatternNode *SrcChild,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003548 bool OperandIsAPointer, bool OperandIsImmArg,
3549 unsigned OpIdx, unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003550
Matt Arsenault3e45c702019-09-06 20:32:37 +00003551 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3552 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3553 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003554 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003555 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003556 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003557 Expected<action_iterator>
3558 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003559 const TreePatternNode *Dst);
Matt Arsenaultee3feef2020-07-13 08:59:38 -04003560
3561 Expected<action_iterator>
3562 importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3563 BuildMIAction &DstMIBuilder,
3564 const TreePatternNode *Dst);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003565
Daniel Sanders7438b262017-10-31 23:03:18 +00003566 Expected<action_iterator>
3567 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3568 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003569 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003570 Expected<action_iterator>
3571 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3572 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003573 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003574 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3575 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003576 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003577 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003578 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3579 const std::vector<Record *> &ImplicitDefs) const;
3580
Daniel Sanders8ead1292018-06-15 23:13:43 +00003581 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3582 StringRef TypeIdentifier, StringRef ArgType,
Petar Avramovic09b88712020-09-14 10:39:25 +02003583 StringRef ArgName, StringRef AdditionalArgs,
3584 StringRef AdditionalDeclarations,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003585 std::function<bool(const Record *R)> Filter);
3586 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3587 StringRef ArgType,
3588 std::function<bool(const Record *R)> Filter);
3589 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003590
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003591 /// Analyze pattern \p P, returning a matcher for it if possible.
3592 /// Otherwise, return an Error explaining why we don't support it.
3593 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003594
3595 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003596
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003597 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3598 bool WithCoverage);
3599
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003600 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3601 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3602 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3603 /// If no register class is found, return None.
3604 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003605 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3606 TreePatternNode *SuperRegNode,
3607 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003608 Optional<CodeGenSubRegIndex *>
3609 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003610
3611 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3612 /// Return None if no such class exists.
3613 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003614 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003615 TreePatternNode *SubRegIdxNode);
3616
3617 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3618 Optional<const CodeGenRegisterClass *>
3619 getRegClassFromLeaf(TreePatternNode *Leaf);
3620
3621 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3622 /// otherwise.
3623 Optional<const CodeGenRegisterClass *>
3624 inferRegClassFromPattern(TreePatternNode *N);
3625
madhur134908351e802020-07-02 09:08:06 +00003626 // Add builtin predicates.
3627 Expected<InstructionMatcher &>
3628 addBuiltinPredicates(const Record *SrcGIEquivOrNull,
3629 const TreePredicateFn &Predicate,
3630 InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
3631
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003632public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003633 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003634 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003635 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003636 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003637 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003638 /// Output without optimization:
3639 /// \verbatim
3640 /// # R1
3641 /// # predicate A
3642 /// # predicate B
3643 /// ...
3644 /// # R2
3645 /// # predicate A // <-- effectively this is going to be checked twice.
3646 /// // Once in R1 and once in R2.
3647 /// # predicate C
3648 /// \endverbatim
3649 /// Output with optimization:
3650 /// \verbatim
3651 /// # Group1_2
3652 /// # predicate A // <-- Check is now shared.
3653 /// # R1
3654 /// # predicate B
3655 /// # R2
3656 /// # predicate C
3657 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003658 template <class GroupT>
3659 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003660 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003661 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003662};
3663
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003664void GlobalISelEmitter::gatherOpcodeValues() {
3665 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3666}
3667
3668void GlobalISelEmitter::gatherTypeIDValues() {
3669 LLTOperandMatcher::initTypeIDValuesMap();
3670}
3671
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003672void GlobalISelEmitter::gatherNodeEquivs() {
3673 assert(NodeEquivs.empty());
3674 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003675 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003676
3677 assert(ComplexPatternEquivs.empty());
3678 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3679 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3680 if (!SelDAGEquiv)
3681 continue;
3682 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3683 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003684
3685 assert(SDNodeXFormEquivs.empty());
3686 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3687 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3688 if (!SelDAGEquiv)
3689 continue;
3690 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3691 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003692}
3693
Daniel Sanders39690bd2017-10-15 02:41:12 +00003694Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003695 return NodeEquivs.lookup(N);
3696}
3697
Daniel Sandersf84bc372018-05-05 20:53:24 +00003698const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003699GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003700 if (N->getNumChildren() >= 1) {
3701 // setcc operation maps to two different G_* instructions based on the type.
3702 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3703 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3704 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3705 }
3706
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003707 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3708 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003709 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3710 Predicate.isSignExtLoad())
3711 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3712 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3713 Predicate.isZeroExtLoad())
3714 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3715 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003716
Daniel Sandersf84bc372018-05-05 20:53:24 +00003717 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3718}
3719
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003720GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003721 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003722 CGRegs(Target.getRegBank()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003723
3724//===- Emitter ------------------------------------------------------------===//
3725
Daniel Sandersc270c502017-03-30 09:36:33 +00003726Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003727GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003728 ArrayRef<Predicate> Predicates) {
3729 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003730 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003731 continue;
3732 declareSubtargetFeature(P.Def);
3733 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003734 }
3735
Daniel Sandersc270c502017-03-30 09:36:33 +00003736 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003737}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003738
madhur134908351e802020-07-02 09:08:06 +00003739Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
3740 const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
3741 InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
3742 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3743 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3744 SmallVector<unsigned, 4> ParsedAddrSpaces;
3745
3746 for (Init *Val : AddrSpaces->getValues()) {
3747 IntInit *IntVal = dyn_cast<IntInit>(Val);
3748 if (!IntVal)
3749 return failedImport("Address space is not an integer");
3750 ParsedAddrSpaces.push_back(IntVal->getValue());
3751 }
3752
3753 if (!ParsedAddrSpaces.empty()) {
3754 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3755 0, ParsedAddrSpaces);
3756 }
3757 }
3758
3759 int64_t MinAlign = Predicate.getMinAlignment();
3760 if (MinAlign > 0)
3761 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3762 }
3763
3764 // G_LOAD is used for both non-extending and any-extending loads.
3765 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3766 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3767 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3768 return InsnMatcher;
3769 }
3770 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3771 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3772 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3773 return InsnMatcher;
3774 }
3775
3776 if (Predicate.isStore()) {
3777 if (Predicate.isTruncStore()) {
3778 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3779 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3780 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3781 return InsnMatcher;
3782 }
3783 if (Predicate.isNonTruncStore()) {
3784 // We need to check the sizes match here otherwise we could incorrectly
3785 // match truncating stores with non-truncating ones.
3786 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3787 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3788 }
3789 }
3790
3791 // No check required. We already did it by swapping the opcode.
3792 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3793 Predicate.isSignExtLoad())
3794 return InsnMatcher;
3795
3796 // No check required. We already did it by swapping the opcode.
3797 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3798 Predicate.isZeroExtLoad())
3799 return InsnMatcher;
3800
3801 // No check required. G_STORE by itself is a non-extending store.
3802 if (Predicate.isNonTruncStore())
3803 return InsnMatcher;
3804
3805 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3806 if (Predicate.getMemoryVT() != nullptr) {
3807 Optional<LLTCodeGen> MemTyOrNone =
3808 MVTToLLT(getValueType(Predicate.getMemoryVT()));
3809
3810 if (!MemTyOrNone)
3811 return failedImport("MemVT could not be converted to LLT");
3812
3813 // MMO's work in bytes so we must take care of unusual types like i1
3814 // don't round down.
3815 unsigned MemSizeInBits =
3816 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3817
3818 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
3819 MemSizeInBits / 8);
3820 return InsnMatcher;
3821 }
3822 }
3823
3824 if (Predicate.isLoad() || Predicate.isStore()) {
3825 // No check required. A G_LOAD/G_STORE is an unindexed load.
3826 if (Predicate.isUnindexed())
3827 return InsnMatcher;
3828 }
3829
3830 if (Predicate.isAtomic()) {
3831 if (Predicate.isAtomicOrderingMonotonic()) {
3832 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
3833 return InsnMatcher;
3834 }
3835 if (Predicate.isAtomicOrderingAcquire()) {
3836 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3837 return InsnMatcher;
3838 }
3839 if (Predicate.isAtomicOrderingRelease()) {
3840 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3841 return InsnMatcher;
3842 }
3843 if (Predicate.isAtomicOrderingAcquireRelease()) {
3844 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3845 "AcquireRelease");
3846 return InsnMatcher;
3847 }
3848 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3849 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3850 "SequentiallyConsistent");
3851 return InsnMatcher;
3852 }
3853 }
3854
3855 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3856 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3857 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3858 return InsnMatcher;
3859 }
3860 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3861 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3862 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3863 return InsnMatcher;
3864 }
3865
3866 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3867 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3868 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3869 return InsnMatcher;
3870 }
3871 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3872 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3873 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3874 return InsnMatcher;
3875 }
3876 HasAddedMatcher = false;
3877 return InsnMatcher;
3878}
3879
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003880Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3881 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003882 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003883 Record *SrcGIEquivOrNull = nullptr;
3884 const CodeGenInstruction *SrcGIOrNull = nullptr;
3885
3886 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003887 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003888 return failedImport("Src pattern has multiple results");
3889
Florian Hahn6b1db822018-06-14 20:32:58 +00003890 if (Src->isLeaf()) {
3891 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003892 if (isa<IntInit>(SrcInit)) {
3893 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3894 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3895 } else
3896 return failedImport(
3897 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3898 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003899 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003900 if (!SrcGIEquivOrNull)
3901 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003902 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003903 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003904
3905 // The operators look good: match the opcode
3906 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3907 }
3908
3909 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003910 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003911 // Results don't have a name unless they are the root node. The caller will
3912 // set the name if appropriate.
3913 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3914 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3915 return failedImport(toString(std::move(Error)) +
3916 " for result of Src pattern operator");
3917 }
3918
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003919 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3920 const TreePredicateFn &Predicate = Call.Fn;
madhur134908351e802020-07-02 09:08:06 +00003921 bool HasAddedBuiltinMatcher = true;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003922 if (Predicate.isAlwaysTrue())
3923 continue;
3924
3925 if (Predicate.isImmediatePattern()) {
3926 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3927 continue;
3928 }
3929
madhur134908351e802020-07-02 09:08:06 +00003930 auto InsnMatcherOrError = addBuiltinPredicates(
3931 SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
3932 if (auto Error = InsnMatcherOrError.takeError())
3933 return std::move(Error);
Daniel Sandersd66e0902017-10-23 18:19:24 +00003934
Daniel Sanders8ead1292018-06-15 23:13:43 +00003935 if (Predicate.hasGISelPredicateCode()) {
Petar Avramovic09b88712020-09-14 10:39:25 +02003936 if (Predicate.usesOperands()) {
3937 assert(WaitingForNamedOperands == 0 &&
3938 "previous predicate didn't find all operands or "
3939 "nested predicate that uses operands");
3940 TreePattern *TP = Predicate.getOrigPatFragRecord();
3941 WaitingForNamedOperands = TP->getNumArgs();
3942 for (unsigned i = 0; i < WaitingForNamedOperands; ++i)
3943 StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(i))] = i;
3944 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00003945 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3946 continue;
3947 }
madhur134908351e802020-07-02 09:08:06 +00003948 if (!HasAddedBuiltinMatcher) {
3949 return failedImport("Src pattern child has predicate (" +
3950 explainPredicates(Src) + ")");
3951 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003952 }
Matt Arsenault53f21e02020-08-02 17:23:52 -04003953
3954 bool IsAtomic = false;
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003955 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3956 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003957 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
Matt Arsenault53f21e02020-08-02 17:23:52 -04003958 IsAtomic = true;
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003959 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3960 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3961 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003962
Florian Hahn6b1db822018-06-14 20:32:58 +00003963 if (Src->isLeaf()) {
3964 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003965 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003966 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003967 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003968 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3969 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003970 return failedImport(
3971 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003972 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003973 assert(SrcGIOrNull &&
3974 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003975 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3976 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3977 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003978 // here since we don't support ImmLeaf predicates yet. However, we still
3979 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3980 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3981 return InsnMatcher;
3982 }
3983
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003984 // Special case because the operand order is changed from setcc. The
3985 // predicate operand needs to be swapped from the last operand to the first
3986 // source.
3987
3988 unsigned NumChildren = Src->getNumChildren();
3989 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3990
3991 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3992 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3993 if (SrcChild->isLeaf()) {
3994 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3995 Record *CCDef = DI ? DI->getDef() : nullptr;
3996 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3997 return failedImport("Unable to handle CondCode");
3998
3999 OperandMatcher &OM =
4000 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
4001 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
4002 CCDef->getValueAsString("ICmpPredicate");
4003
4004 if (!PredType.empty()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01004005 OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
Matt Arsenault8ec5c102019-08-29 01:13:41 +00004006 // Process the other 2 operands normally.
4007 --NumChildren;
4008 }
4009 }
4010 }
4011
Matt Arsenault53f21e02020-08-02 17:23:52 -04004012 // Hack around an unfortunate mistake in how atomic store (and really
4013 // atomicrmw in general) operands were ordered. A ISD::STORE used the order
4014 // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
4015 // <pointer>, <stored value>. In GlobalISel there's just the one store
4016 // opcode, so we need to swap the operands here to get the right type check.
4017 if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
4018 assert(NumChildren == 2 && "wrong operands for atomic store");
4019
4020 TreePatternNode *PtrChild = Src->getChild(0);
4021 TreePatternNode *ValueChild = Src->getChild(1);
4022
4023 if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
4024 false, 1, TempOpIdx))
4025 return std::move(Error);
4026
4027 if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
4028 false, 0, TempOpIdx))
4029 return std::move(Error);
4030 return InsnMatcher;
4031 }
4032
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004033 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00004034 bool IsIntrinsic =
4035 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
4036 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
4037 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
4038 if (IsIntrinsic && !II)
4039 return failedImport("Expected IntInit containing intrinsic ID)");
4040
Matt Arsenault8ec5c102019-08-29 01:13:41 +00004041 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004042 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00004043
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004044 // We need to determine the meaning of a literal integer based on the
4045 // context. If this is a field required to be an immediate (such as an
4046 // immarg intrinsic argument), the required predicates are different than
4047 // a constant which may be materialized in a register. If we have an
4048 // argument that is required to be an immediate, we should not emit an LLT
4049 // type check, and should not be looking for a G_CONSTANT defined
4050 // register.
4051 bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
4052
Daniel Sandersa71f4542017-10-16 00:56:30 +00004053 // SelectionDAG allows pointers to be represented with iN since it doesn't
4054 // distinguish between pointers and integers but they are different types in GlobalISel.
4055 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004056 //
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00004057 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00004058
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00004059 if (IsIntrinsic) {
4060 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
4061 // following the defs is an intrinsic ID.
4062 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00004063 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00004064 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00004065 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00004066 continue;
4067 }
4068
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004069 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00004070 //
4071 // Note that we have to look at the i-1th parameter, because we don't
4072 // have the intrinsic ID in the intrinsic's parameter list.
4073 OperandIsAPointer |= II->isParamAPointer(i - 1);
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004074 OperandIsImmArg |= II->isParamImmArg(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00004075 }
4076
Daniel Sandersa71f4542017-10-16 00:56:30 +00004077 if (auto Error =
4078 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004079 OperandIsImmArg, OpIdx++, TempOpIdx))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004080 return std::move(Error);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004081 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00004082 }
4083
4084 return InsnMatcher;
4085}
4086
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004087Error GlobalISelEmitter::importComplexPatternOperandMatcher(
4088 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
4089 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
4090 if (ComplexPattern == ComplexPatternEquivs.end())
4091 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
4092 ") not mapped to GlobalISel");
4093
4094 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
4095 TempOpIdx++;
4096 return Error::success();
4097}
4098
Matt Arsenault3e45c702019-09-06 20:32:37 +00004099// Get the name to use for a pattern operand. For an anonymous physical register
4100// input, this should use the register name.
4101static StringRef getSrcChildName(const TreePatternNode *SrcChild,
4102 Record *&PhysReg) {
4103 StringRef SrcChildName = SrcChild->getName();
4104 if (SrcChildName.empty() && SrcChild->isLeaf()) {
4105 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4106 auto *ChildRec = ChildDefInit->getDef();
4107 if (ChildRec->isSubClassOf("Register")) {
4108 SrcChildName = ChildRec->getName();
4109 PhysReg = ChildRec;
4110 }
4111 }
4112 }
4113
4114 return SrcChildName;
4115}
4116
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004117Error GlobalISelEmitter::importChildMatcher(
4118 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
4119 const TreePatternNode *SrcChild, bool OperandIsAPointer,
4120 bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00004121
4122 Record *PhysReg = nullptr;
Petar Avramovic416346d2020-09-14 11:37:14 +02004123 std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg));
4124 if (!SrcChild->isLeaf() &&
4125 SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
4126 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
4127 // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
4128 std::string PatternName = std::string(SrcChild->getOperator()->getName());
4129 for (unsigned i = 0; i < SrcChild->getNumChildren(); ++i) {
4130 PatternName += ":";
4131 PatternName += SrcChild->getChild(i)->getName();
4132 }
4133 SrcChildName = PatternName;
4134 }
Matt Arsenault3e45c702019-09-06 20:32:37 +00004135
Benjamin Krameradcd0262020-01-28 20:23:46 +01004136 OperandMatcher &OM =
Petar Avramovic416346d2020-09-14 11:37:14 +02004137 PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
4138 : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004139 if (OM.isSameAsAnotherOperand())
4140 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004141
Florian Hahn6b1db822018-06-14 20:32:58 +00004142 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004143 if (ChildTypes.size() != 1)
4144 return failedImport("Src pattern child has multiple results");
4145
4146 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00004147 if (!SrcChild->isLeaf()) {
4148 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
4149 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004150 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4151 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00004152 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004153 }
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00004154 if (SrcChild->getOperator()->getName() == "timm") {
4155 OM.addPredicate<ImmOperandMatcher>();
4156 return Error::success();
4157 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00004158 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00004159 }
4160
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004161 // Immediate arguments have no meaningful type to check as they don't have
4162 // registers.
4163 if (!OperandIsImmArg) {
4164 if (auto Error =
4165 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
4166 return failedImport(toString(std::move(Error)) + " for Src operand (" +
4167 to_string(*SrcChild) + ")");
4168 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00004169
Daniel Sandersbee57392017-04-04 13:25:23 +00004170 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00004171 if (!SrcChild->isLeaf()) {
4172 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004173 // When a ComplexPattern is used as an operator, it should do the same
4174 // thing as when used as a leaf. However, the children of the operator
4175 // name the sub-operands that make up the complex operand and we must
4176 // prepare to reference them in the renderer too.
4177 unsigned RendererID = TempOpIdx;
4178 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00004179 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004180 return Error;
4181
Florian Hahn6b1db822018-06-14 20:32:58 +00004182 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
4183 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00004184 if (!SubOperand->getName().empty()) {
Petar Avramovic416346d2020-09-14 11:37:14 +02004185 if (auto Error = Rule.defineComplexSubOperand(
4186 SubOperand->getName(), SrcChild->getOperator(), RendererID, i,
4187 SrcChildName))
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00004188 return Error;
4189 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004190 }
4191
4192 return Error::success();
4193 }
4194
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004195 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004196 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004197 if (!MaybeInsnOperand.hasValue()) {
4198 // This isn't strictly true. If the user were to provide exactly the same
4199 // matchers as the original operand then we could allow it. However, it's
4200 // simpler to not permit the redundant specification.
4201 return failedImport("Nested instruction cannot be the same as another operand");
4202 }
4203
Daniel Sandersbee57392017-04-04 13:25:23 +00004204 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004205 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00004206 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004207 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00004208 if (auto Error = InsnMatcherOrError.takeError())
4209 return Error;
4210
4211 return Error::success();
4212 }
4213
Florian Hahn6b1db822018-06-14 20:32:58 +00004214 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00004215 return failedImport("Src pattern child has unsupported predicate");
4216
Daniel Sandersffc7d582017-03-29 15:37:18 +00004217 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00004218 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004219 if (OperandIsImmArg) {
4220 // Checks for argument directly in operand list
4221 OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
4222 } else {
4223 // Checks for materialized constant
4224 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
4225 }
Daniel Sandersc270c502017-03-30 09:36:33 +00004226 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004227 }
4228
4229 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00004230 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004231 auto *ChildRec = ChildDefInit->getDef();
4232
Petar Avramovic09b88712020-09-14 10:39:25 +02004233 if (WaitingForNamedOperands) {
4234 auto PA = SrcChild->getNamesAsPredicateArg().begin();
4235 std::string Name = getScopedName(PA->getScope(), PA->getIdentifier());
4236 OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name);
4237 --WaitingForNamedOperands;
4238 }
4239
Daniel Sandersffc7d582017-03-29 15:37:18 +00004240 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004241 if (ChildRec->isSubClassOf("RegisterClass") ||
4242 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004243 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004244 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00004245 return Error::success();
4246 }
4247
Matt Arsenault3e45c702019-09-06 20:32:37 +00004248 if (ChildRec->isSubClassOf("Register")) {
4249 // This just be emitted as a copy to the specific register.
4250 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
4251 const CodeGenRegisterClass *RC
4252 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
4253 if (!RC) {
4254 return failedImport(
4255 "Could not determine physical register class of pattern source");
4256 }
4257
4258 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
4259 return Error::success();
4260 }
4261
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004262 // Check for ValueType.
4263 if (ChildRec->isSubClassOf("ValueType")) {
4264 // We already added a type check as standard practice so this doesn't need
4265 // to do anything.
4266 return Error::success();
4267 }
4268
Daniel Sandersffc7d582017-03-29 15:37:18 +00004269 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004270 if (ChildRec->isSubClassOf("ComplexPattern"))
4271 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004272
Daniel Sandersd0656a32017-04-13 09:45:37 +00004273 if (ChildRec->isSubClassOf("ImmLeaf")) {
4274 return failedImport(
4275 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
4276 }
4277
Matt Arsenault03a592f2020-01-16 10:47:13 -05004278 // Place holder for SRCVALUE nodes. Nothing to do here.
4279 if (ChildRec->getName() == "srcvalue")
4280 return Error::success();
4281
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04004282 const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
4283 if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
4284 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4285 InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
4286 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4287
4288 ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
Matt Arsenault116affb2020-08-02 14:52:20 -04004289
4290 const CodeGenInstruction &BuildVector
4291 = Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
4292 const CodeGenInstruction &BuildVectorTrunc
4293 = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
4294
4295 // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
4296 // as an alternative.
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04004297 InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
Matt Arsenault116affb2020-08-02 14:52:20 -04004298 makeArrayRef({&BuildVector, &BuildVectorTrunc}));
Matt Arsenault5c5e6d92020-08-01 10:39:21 -04004299
4300 // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
4301 // theoretically not emit any opcode check, but getOpcodeMatcher currently
4302 // has to succeed.
4303 OperandMatcher &OM =
4304 InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
4305 if (auto Error =
4306 OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
4307 return failedImport(toString(std::move(Error)) +
4308 " for result of Src pattern operator");
4309
4310 InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
4311 ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
4312 : VectorSplatImmPredicateMatcher::AllZeros);
4313 return Error::success();
4314 }
4315
Daniel Sandersffc7d582017-03-29 15:37:18 +00004316 return failedImport(
4317 "Src pattern child def is an unsupported tablegen class");
4318 }
4319
4320 return failedImport("Src pattern child is an unsupported kind");
4321}
4322
Daniel Sanders7438b262017-10-31 23:03:18 +00004323Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4324 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004325 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00004326
Florian Hahn6b1db822018-06-14 20:32:58 +00004327 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004328 if (SubOperand.hasValue()) {
4329 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004330 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004331 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00004332 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004333 }
4334
Florian Hahn6b1db822018-06-14 20:32:58 +00004335 if (!DstChild->isLeaf()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004336 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4337 auto Child = DstChild->getChild(0);
4338 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00004339 if (I != SDNodeXFormEquivs.end()) {
Matt Arsenaultb4a64742020-01-08 12:53:15 -05004340 Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4341 if (XFormOpc->getName() == "timm") {
4342 // If this is a TargetConstant, there won't be a corresponding
4343 // instruction to transform. Instead, this will refer directly to an
4344 // operand in an instruction's operand list.
4345 DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4346 Child->getName());
4347 } else {
4348 DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4349 Child->getName());
4350 }
4351
Volkan Kelesf7f25682018-01-16 18:44:05 +00004352 return InsertPt;
4353 }
Florian Hahn6b1db822018-06-14 20:32:58 +00004354 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00004355 " has no custom renderer");
4356 }
4357
Daniel Sanders05540042017-08-08 10:44:31 +00004358 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4359 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004360 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4361 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004362 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004363 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004364 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004365 }
4366 }
Daniel Sanders05540042017-08-08 10:44:31 +00004367
4368 // Similarly, imm is an operator in TreePatternNode's view but must be
4369 // rendered as operands.
4370 // FIXME: The target should be able to choose sign-extended when appropriate
4371 // (e.g. on Mips).
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00004372 if (DstChild->getOperator()->getName() == "timm") {
4373 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4374 return InsertPt;
4375 } else if (DstChild->getOperator()->getName() == "imm") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004376 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004377 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00004378 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004379 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004380 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004381 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00004382 }
4383
Florian Hahn6b1db822018-06-14 20:32:58 +00004384 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
Matt Arsenault9c346462020-01-14 16:02:02 -05004385 auto OpTy = getInstResultType(DstChild);
4386 if (!OpTy)
4387 return OpTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004388
4389 unsigned TempRegID = Rule.allocateTempRegID();
4390 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
Matt Arsenault9c346462020-01-14 16:02:02 -05004391 InsertPt, *OpTy, TempRegID);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004392 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4393
4394 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4395 ++InsertPt, Rule, DstChild, TempRegID);
4396 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004397 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004398 return InsertPtOrError.get();
4399 }
4400
Florian Hahn6b1db822018-06-14 20:32:58 +00004401 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00004402 }
4403
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004404 // It could be a specific immediate in which case we should just check for
4405 // that immediate.
4406 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004407 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004408 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4409 return InsertPt;
4410 }
4411
Daniel Sandersffc7d582017-03-29 15:37:18 +00004412 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004413 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004414 auto *ChildRec = ChildDefInit->getDef();
4415
Florian Hahn6b1db822018-06-14 20:32:58 +00004416 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004417 if (ChildTypes.size() != 1)
4418 return failedImport("Dst pattern child has multiple results");
4419
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004420 Optional<LLTCodeGen> OpTyOrNone = None;
4421 if (ChildTypes.front().isMachineValueType())
4422 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004423 if (!OpTyOrNone)
4424 return failedImport("Dst operand has an unsupported type");
4425
4426 if (ChildRec->isSubClassOf("Register")) {
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02004427 DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00004428 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004429 }
4430
Daniel Sanders658541f2017-04-22 15:53:21 +00004431 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004432 ChildRec->isSubClassOf("RegisterOperand") ||
4433 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00004434 if (ChildRec->isSubClassOf("RegisterOperand") &&
4435 !ChildRec->isValueUnset("GIZeroRegister")) {
4436 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004437 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00004438 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00004439 }
4440
Florian Hahn6b1db822018-06-14 20:32:58 +00004441 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004442 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004443 }
4444
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004445 if (ChildRec->isSubClassOf("SubRegIndex")) {
4446 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4447 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4448 return InsertPt;
4449 }
4450
Daniel Sandersffc7d582017-03-29 15:37:18 +00004451 if (ChildRec->isSubClassOf("ComplexPattern")) {
4452 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4453 if (ComplexPattern == ComplexPatternEquivs.end())
4454 return failedImport(
4455 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4456
Florian Hahn6b1db822018-06-14 20:32:58 +00004457 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004458 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004459 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004460 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004461 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004462 }
4463
4464 return failedImport(
4465 "Dst pattern child def is an unsupported tablegen class");
4466 }
4467
4468 return failedImport("Dst pattern child is an unsupported kind");
4469}
4470
Daniel Sandersc270c502017-03-30 09:36:33 +00004471Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004472 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4473 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004474 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4475 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004476 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004477
Daniel Sanders7438b262017-10-31 23:03:18 +00004478 action_iterator InsertPt = InsertPtOrError.get();
4479 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004480
Matt Arsenault3e45c702019-09-06 20:32:37 +00004481 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4482 InsertPt = M.insertAction<BuildMIAction>(
4483 InsertPt, M.allocateOutputInsnID(),
4484 &Target.getInstruction(RK.getDef("COPY")));
4485 BuildMIAction &CopyToPhysRegMIBuilder =
4486 *static_cast<BuildMIAction *>(InsertPt->get());
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02004487 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target,
4488 PhysInput.first,
Matt Arsenault3e45c702019-09-06 20:32:37 +00004489 true);
4490 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4491 }
4492
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004493 if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
4494 .takeError())
4495 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004496
Daniel Sanders7438b262017-10-31 23:03:18 +00004497 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4498 .takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004499 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004500
4501 return DstMIBuilder;
4502}
4503
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004504Expected<action_iterator>
4505GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004506 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004507 unsigned TempRegID) {
4508 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4509
4510 // TODO: Assert there's exactly one result.
4511
4512 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004513 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004514
4515 BuildMIAction &DstMIBuilder =
4516 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4517
4518 // Assign the result to TempReg.
4519 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4520
Daniel Sanders08464522018-01-29 21:09:12 +00004521 InsertPtOrError =
4522 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004523 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004524 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004525
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004526 // We need to make sure that when we import an INSERT_SUBREG as a
4527 // subinstruction that it ends up being constrained to the correct super
4528 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004529 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4530 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004531 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4532 if (!SubClass)
4533 return failedImport(
4534 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004535 Optional<const CodeGenRegisterClass *> SuperClass =
4536 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4537 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004538 if (!SuperClass)
4539 return failedImport(
4540 "Cannot infer register class for INSERT_SUBREG operand #0");
4541 // The destination and the super register source of an INSERT_SUBREG must
4542 // be the same register class.
4543 M.insertAction<ConstrainOperandToRegClassAction>(
4544 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4545 M.insertAction<ConstrainOperandToRegClassAction>(
4546 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4547 M.insertAction<ConstrainOperandToRegClassAction>(
4548 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4549 return InsertPtOrError.get();
4550 }
4551
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004552 if (OpName == "EXTRACT_SUBREG") {
4553 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4554 // instructions, the result register class is controlled by the
4555 // subregisters of the operand. As a result, we must constrain the result
4556 // class rather than check that it's already the right one.
4557 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4558 if (!SuperClass)
4559 return failedImport(
4560 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4561
4562 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4563 if (!SubIdx)
4564 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4565
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004566 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004567 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4568 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4569 M.insertAction<ConstrainOperandToRegClassAction>(
4570 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4571 M.insertAction<ConstrainOperandToRegClassAction>(
4572 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4573
4574 // We're done with this pattern! It's eligible for GISel emission; return
4575 // it.
4576 return InsertPtOrError.get();
4577 }
4578
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004579 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4580 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004581 if (OpName == "SUBREG_TO_REG") {
4582 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4583 if (!SubClass)
4584 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004585 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004586 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4587 Dst->getChild(2));
4588 if (!SuperClass)
4589 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004590 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004591 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004592 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004593 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004594 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004595 return InsertPtOrError.get();
4596 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004597
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04004598 if (OpName == "REG_SEQUENCE") {
4599 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4600 M.insertAction<ConstrainOperandToRegClassAction>(
4601 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4602
4603 unsigned Num = Dst->getNumChildren();
4604 for (unsigned I = 1; I != Num; I += 2) {
4605 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4606
4607 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4608 if (!SubIdx)
4609 return failedImport("REG_SEQUENCE child is not a subreg index");
4610
4611 const auto SrcRCDstRCPair =
4612 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4613 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4614 M.insertAction<ConstrainOperandToRegClassAction>(
4615 InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4616 }
4617
4618 return InsertPtOrError.get();
4619 }
4620
Daniel Sanders08464522018-01-29 21:09:12 +00004621 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4622 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004623 return InsertPtOrError.get();
4624}
4625
Daniel Sanders7438b262017-10-31 23:03:18 +00004626Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004627 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4628 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004629 if (!DstOp->isSubClassOf("Instruction")) {
4630 if (DstOp->isSubClassOf("ValueType"))
4631 return failedImport(
4632 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004633 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004634 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004635 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004636
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004637 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004638 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004639 StringRef Name = DstI->TheDef->getName();
4640 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004641 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004642
Daniel Sanders198447a2017-11-01 00:29:47 +00004643 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4644 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004645}
4646
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004647Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
4648 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4649 const TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004650 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004651 const unsigned NumDefs = DstI->Operands.NumDefs;
4652 if (NumDefs == 0)
4653 return InsertPt;
4654
4655 DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
4656
Matt Arsenault930fc0b2020-07-27 20:29:53 -04004657 // Some instructions have multiple defs, but are missing a type entry
4658 // (e.g. s_cc_out operands).
4659 if (Dst->getExtTypes().size() < NumDefs)
4660 return failedImport("unhandled discarded def");
4661
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004662 // Patterns only handle a single result, so any result after the first is an
4663 // implicitly dead def.
4664 for (unsigned I = 1; I < NumDefs; ++I) {
4665 const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
4666 if (!ExtTy.isMachineValueType())
4667 return failedImport("unsupported typeset");
4668
4669 auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
4670 if (!OpTy)
4671 return failedImport("unsupported type");
4672
4673 unsigned TempRegID = M.allocateTempRegID();
4674 InsertPt =
4675 M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
4676 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004677 }
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004678
4679 return InsertPt;
Daniel Sandersdf258e32017-10-31 19:09:29 +00004680}
4681
Daniel Sanders7438b262017-10-31 23:03:18 +00004682Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4683 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004684 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004685 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004686 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004687
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004688 StringRef Name = OrigDstI->TheDef->getName();
4689 unsigned ExpectedDstINumUses = Dst->getNumChildren();
4690
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004691 // EXTRACT_SUBREG needs to use a subregister COPY.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004692 if (Name == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05004693 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4694 if (!SubRegInit)
4695 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004696
Matt Arsenault9c346462020-01-14 16:02:02 -05004697 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4698 TreePatternNode *ValChild = Dst->getChild(0);
4699 if (!ValChild->isLeaf()) {
4700 // We really have to handle the source instruction, and then insert a
4701 // copy from the subregister.
4702 auto ExtractSrcTy = getInstResultType(ValChild);
4703 if (!ExtractSrcTy)
4704 return ExtractSrcTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004705
Matt Arsenault9c346462020-01-14 16:02:02 -05004706 unsigned TempRegID = M.allocateTempRegID();
4707 InsertPt = M.insertAction<MakeTempRegisterAction>(
4708 InsertPt, *ExtractSrcTy, TempRegID);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004709
Matt Arsenault9c346462020-01-14 16:02:02 -05004710 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4711 ++InsertPt, M, ValChild, TempRegID);
4712 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004713 return std::move(Error);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004714
Matt Arsenault9c346462020-01-14 16:02:02 -05004715 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004716 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004717 }
4718
Matt Arsenault9c346462020-01-14 16:02:02 -05004719 // If this is a source operand, this is just a subregister copy.
4720 Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4721 if (!RCDef)
4722 return failedImport("EXTRACT_SUBREG child #0 could not "
4723 "be coerced to a register class");
4724
4725 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4726
4727 const auto SrcRCDstRCPair =
4728 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4729 if (SrcRCDstRCPair.hasValue()) {
4730 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4731 if (SrcRCDstRCPair->first != RC)
4732 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4733 }
4734
4735 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4736 SubIdx);
4737 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004738 }
4739
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004740 if (Name == "REG_SEQUENCE") {
4741 if (!Dst->getChild(0)->isLeaf())
4742 return failedImport("REG_SEQUENCE child #0 is not a leaf");
4743
4744 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4745 if (!RCDef)
4746 return failedImport("REG_SEQUENCE child #0 could not "
4747 "be coerced to a register class");
4748
4749 if ((ExpectedDstINumUses - 1) % 2 != 0)
4750 return failedImport("Malformed REG_SEQUENCE");
4751
4752 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4753 TreePatternNode *ValChild = Dst->getChild(I);
4754 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4755
4756 if (DefInit *SubRegInit =
4757 dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4758 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4759
4760 auto InsertPtOrError =
4761 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4762 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004763 return std::move(Error);
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004764 InsertPt = InsertPtOrError.get();
4765 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4766 }
4767 }
4768
4769 return InsertPt;
4770 }
4771
Daniel Sandersffc7d582017-03-29 15:37:18 +00004772 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004773 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004774 if (Name == "COPY_TO_REGCLASS") {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004775 DstINumUses--; // Ignore the class constraint.
4776 ExpectedDstINumUses--;
4777 }
4778
Matt Arsenault26f714f2019-10-21 21:39:42 -07004779 // NumResults - This is the number of results produced by the instruction in
4780 // the "outs" list.
4781 unsigned NumResults = OrigDstI->Operands.NumDefs;
4782
4783 // Number of operands we know the output instruction must have. If it is
4784 // variadic, we could have more operands.
4785 unsigned NumFixedOperands = DstI->Operands.size();
4786
4787 // Loop over all of the fixed operands of the instruction pattern, emitting
4788 // code to fill them all in. The node 'N' usually has number children equal to
4789 // the number of input operands of the instruction. However, in cases where
4790 // there are predicate operands for an instruction, we need to fill in the
4791 // 'execute always' values. Match up the node operands to the instruction
4792 // operands to do this.
Daniel Sanders0ed28822017-04-12 08:23:08 +00004793 unsigned Child = 0;
Matt Arsenault26f714f2019-10-21 21:39:42 -07004794
4795 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4796 // number of operands at the end of the list which have default values.
4797 // Those can come from the pattern if it provides enough arguments, or be
4798 // filled in with the default if the pattern hasn't provided them. But any
4799 // operand with a default value _before_ the last mandatory one will be
4800 // filled in with their defaults unconditionally.
4801 unsigned NonOverridableOperands = NumFixedOperands;
4802 while (NonOverridableOperands > NumResults &&
4803 CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4804 --NonOverridableOperands;
4805
Diana Picus382602f2017-05-17 08:57:28 +00004806 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004807 for (unsigned I = 0; I != DstINumUses; ++I) {
Matt Arsenault26f714f2019-10-21 21:39:42 -07004808 unsigned InstOpNo = DstI->Operands.NumDefs + I;
4809
4810 // Determine what to emit for this operand.
4811 Record *OperandNode = DstI->Operands[InstOpNo].Rec;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004812
Diana Picus382602f2017-05-17 08:57:28 +00004813 // If the operand has default values, introduce them now.
Matt Arsenault26f714f2019-10-21 21:39:42 -07004814 if (CGP.operandHasDefault(OperandNode) &&
4815 (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4816 // This is a predicate or optional def operand which the pattern has not
4817 // overridden, or which we aren't letting it override; emit the 'default
4818 // ops' operands.
4819
4820 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004821 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004822 if (auto Error = importDefaultOperandRenderers(
4823 InsertPt, M, DstMIBuilder, DefaultOps))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004824 return std::move(Error);
Diana Picus382602f2017-05-17 08:57:28 +00004825 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004826 continue;
4827 }
4828
Daniel Sanders7438b262017-10-31 23:03:18 +00004829 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004830 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004831 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004832 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004833 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004834 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004835 }
4836
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004837 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004838 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004839 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004840 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004841 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004842 " default ones");
4843
Daniel Sanders7438b262017-10-31 23:03:18 +00004844 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004845}
4846
Diana Picus382602f2017-05-17 08:57:28 +00004847Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004848 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4849 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004850 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004851 Optional<LLTCodeGen> OpTyOrNone = None;
4852
Diana Picus382602f2017-05-17 08:57:28 +00004853 // Look through ValueType operators.
4854 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4855 if (const DefInit *DefaultDagOperator =
4856 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004857 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004858 OpTyOrNone = MVTToLLT(getValueType(
4859 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004860 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004861 }
Diana Picus382602f2017-05-17 08:57:28 +00004862 }
4863 }
4864
4865 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004866 auto Def = DefaultDefOp->getDef();
4867 if (Def->getName() == "undef_tied_input") {
4868 unsigned TempRegID = M.allocateTempRegID();
4869 M.insertAction<MakeTempRegisterAction>(
4870 InsertPt, OpTyOrNone.getValue(), TempRegID);
4871 InsertPt = M.insertAction<BuildMIAction>(
4872 InsertPt, M.allocateOutputInsnID(),
4873 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4874 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4875 InsertPt->get());
4876 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4877 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4878 } else {
Gabriel Hjort Ã…kerlundc1020052020-09-18 10:08:32 +02004879 DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, Def);
Sjoerd Meijerde234842019-05-30 07:30:37 +00004880 }
Diana Picus382602f2017-05-17 08:57:28 +00004881 continue;
4882 }
4883
4884 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004885 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004886 continue;
4887 }
4888
4889 return failedImport("Could not add default op");
4890 }
4891
4892 return Error::success();
4893}
4894
Daniel Sandersc270c502017-03-30 09:36:33 +00004895Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004896 BuildMIAction &DstMIBuilder,
4897 const std::vector<Record *> &ImplicitDefs) const {
4898 if (!ImplicitDefs.empty())
4899 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004900 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004901}
4902
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004903Optional<const CodeGenRegisterClass *>
4904GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4905 assert(Leaf && "Expected node?");
4906 assert(Leaf->isLeaf() && "Expected leaf?");
4907 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4908 if (!RCRec)
4909 return None;
4910 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4911 if (!RC)
4912 return None;
4913 return RC;
4914}
4915
4916Optional<const CodeGenRegisterClass *>
4917GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4918 if (!N)
4919 return None;
4920
4921 if (N->isLeaf())
4922 return getRegClassFromLeaf(N);
4923
4924 // We don't have a leaf node, so we have to try and infer something. Check
4925 // that we have an instruction that we an infer something from.
4926
4927 // Only handle things that produce a single type.
4928 if (N->getNumTypes() != 1)
4929 return None;
4930 Record *OpRec = N->getOperator();
4931
4932 // We only want instructions.
4933 if (!OpRec->isSubClassOf("Instruction"))
4934 return None;
4935
4936 // Don't want to try and infer things when there could potentially be more
4937 // than one candidate register class.
4938 auto &Inst = Target.getInstruction(OpRec);
4939 if (Inst.Operands.NumDefs > 1)
4940 return None;
4941
4942 // Handle any special-case instructions which we can safely infer register
4943 // classes from.
4944 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004945 bool IsRegSequence = InstName == "REG_SEQUENCE";
4946 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004947 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4948 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004949 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004950 if (!RCChild->isLeaf())
4951 return None;
4952 return getRegClassFromLeaf(RCChild);
4953 }
Gabriel Hjort Ã…kerlund64b879a2020-10-05 10:28:50 +02004954 if (InstName == "INSERT_SUBREG") {
4955 TreePatternNode *Child0 = N->getChild(0);
4956 assert(Child0->getNumTypes() == 1 && "Unexpected number of types!");
4957 const TypeSetByHwMode &VTy = Child0->getExtType(0);
4958 return inferSuperRegisterClassForNode(VTy, Child0, N->getChild(2));
4959 }
4960 if (InstName == "EXTRACT_SUBREG") {
4961 assert(N->getNumTypes() == 1 && "Unexpected number of types!");
4962 const TypeSetByHwMode &VTy = N->getExtType(0);
4963 return inferSuperRegisterClass(VTy, N->getChild(1));
4964 }
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004965
4966 // Handle destination record types that we can safely infer a register class
4967 // from.
4968 const auto &DstIOperand = Inst.Operands[0];
4969 Record *DstIOpRec = DstIOperand.Rec;
4970 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4971 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4972 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4973 return &RC;
4974 }
4975
4976 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4977 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4978 return &RC;
4979 }
4980
4981 return None;
4982}
4983
4984Optional<const CodeGenRegisterClass *>
4985GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004986 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004987 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004988 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4989 if (!Ty.isValueTypeByHwMode(false))
4990 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004991 if (!SubRegIdxNode->isLeaf())
4992 return None;
4993 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4994 if (!SubRegInit)
4995 return None;
4996 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4997
4998 // Use the information we found above to find a minimal register class which
4999 // supports the subregister and type we want.
5000 auto RC =
5001 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
5002 if (!RC)
5003 return None;
5004 return *RC;
5005}
5006
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005007Optional<const CodeGenRegisterClass *>
5008GlobalISelEmitter::inferSuperRegisterClassForNode(
5009 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
5010 TreePatternNode *SubRegIdxNode) {
5011 assert(SuperRegNode && "Expected super register node!");
5012 // Check if we already have a defined register class for the super register
5013 // node. If we do, then we should preserve that rather than inferring anything
5014 // from the subregister index node. We can assume that whoever wrote the
5015 // pattern in the first place made sure that the super register and
5016 // subregister are compatible.
5017 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
5018 inferRegClassFromPattern(SuperRegNode))
5019 return *SuperRegisterClass;
5020 return inferSuperRegisterClass(Ty, SubRegIdxNode);
5021}
5022
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00005023Optional<CodeGenSubRegIndex *>
5024GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
5025 if (!SubRegIdxNode->isLeaf())
5026 return None;
5027
5028 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
5029 if (!SubRegInit)
5030 return None;
5031 return CGRegs.getSubRegIdx(SubRegInit->getDef());
5032}
5033
Daniel Sandersffc7d582017-03-29 15:37:18 +00005034Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005035 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005036 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00005037 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005038 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00005039 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
5040 " => " +
5041 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005042
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00005043 if (auto Error = importRulePredicates(M, P.getPredicates()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005044 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005045
5046 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00005047 TreePatternNode *Src = P.getSrcPattern();
5048 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005049
5050 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00005051 if (auto Err = isTrivialOperatorNode(Dst))
5052 return failedImport("Dst pattern root isn't a trivial operator (" +
5053 toString(std::move(Err)) + ")");
5054 if (auto Err = isTrivialOperatorNode(Src))
5055 return failedImport("Src pattern root isn't a trivial operator (" +
5056 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005057
Quentin Colombetaad20be2017-12-15 23:07:42 +00005058 // The different predicates and matchers created during
5059 // addInstructionMatcher use the RuleMatcher M to set up their
5060 // instruction ID (InsnVarID) that are going to be used when
5061 // M is going to be emitted.
5062 // However, the code doing the emission still relies on the IDs
5063 // returned during that process by the RuleMatcher when issuing
5064 // the recordInsn opcodes.
5065 // Because of that:
5066 // 1. The order in which we created the predicates
5067 // and such must be the same as the order in which we emit them,
5068 // and
5069 // 2. We need to reset the generation of the IDs in M somewhere between
5070 // addInstructionMatcher and emit
5071 //
5072 // FIXME: Long term, we don't want to have to rely on this implicit
5073 // naming being the same. One possible solution would be to have
5074 // explicit operator for operation capture and reference those.
5075 // The plus side is that it would expose opportunities to share
5076 // the capture accross rules. The downside is that it would
5077 // introduce a dependency between predicates (captures must happen
5078 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00005079 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00005080 unsigned TempOpIdx = 0;
5081 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00005082 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00005083 if (auto Error = InsnMatcherOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005084 return std::move(Error);
Daniel Sandersedd07842017-08-17 09:26:14 +00005085 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
5086
Florian Hahn6b1db822018-06-14 20:32:58 +00005087 if (Dst->isLeaf()) {
5088 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00005089
5090 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
5091 if (RCDef) {
5092 // We need to replace the def and all its uses with the specified
5093 // operand. However, we must also insert COPY's wherever needed.
5094 // For now, emit a copy and let the register allocator clean up.
5095 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
5096 const auto &DstIOperand = DstI.Operands[0];
5097
5098 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
5099 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00005100 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00005101 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
5102
Daniel Sanders198447a2017-11-01 00:29:47 +00005103 auto &DstMIBuilder =
5104 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
5105 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00005106 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00005107 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
5108
5109 // We're done with this pattern! It's eligible for GISel emission; return
5110 // it.
5111 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005112 return std::move(M);
Daniel Sandersedd07842017-08-17 09:26:14 +00005113 }
5114
Daniel Sanders452c8ae2017-05-23 19:33:16 +00005115 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00005116 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00005117
Daniel Sandersbee57392017-04-04 13:25:23 +00005118 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00005119 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005120 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005121 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005122
5123 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00005124 StringRef DstIName = DstI.TheDef->getName();
5125
Matt Arsenaultee3feef2020-07-13 08:59:38 -04005126 if (DstI.Operands.NumDefs < Src->getExtTypes().size())
5127 return failedImport("Src pattern result has more defs than dst MI (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00005128 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00005129 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005130
Daniel Sandersffc7d582017-03-29 15:37:18 +00005131 // The root of the match also has constraints on the register bank so that it
5132 // matches the result instruction.
5133 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00005134 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00005135 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00005136
Daniel Sanders066ebbf2017-02-24 15:43:30 +00005137 const auto &DstIOperand = DstI.Operands[OpIdx];
5138 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00005139 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00005140 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005141
5142 if (DstIOpRec == nullptr)
5143 return failedImport(
5144 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00005145 } else if (DstIName == "REG_SEQUENCE") {
5146 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
5147 if (DstIOpRec == nullptr)
5148 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
5149 } else if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05005150 auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
5151 if (!InferredClass)
5152 return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005153
Daniel Sanders32291982017-06-28 13:50:04 +00005154 // We can assume that a subregister is in the same bank as it's super
5155 // register.
Matt Arsenault9c346462020-01-14 16:02:02 -05005156 DstIOpRec = (*InferredClass)->getDef();
Matt Arsenault38fb3442019-09-04 16:19:34 +00005157 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005158 auto MaybeSuperClass = inferSuperRegisterClassForNode(
5159 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005160 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005161 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005162 "Cannot infer register class for INSERT_SUBREG operand #0");
5163 // Move to the next pattern here, because the register class we found
5164 // doesn't necessarily have a record associated with it. So, we can't
5165 // set DstIOpRec using this.
5166 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5167 OM.setSymbolicName(DstIOperand.Name);
5168 M.defineOperand(OM.getSymbolicName(), OM);
5169 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
5170 ++OpIdx;
5171 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00005172 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005173 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
5174 if (!MaybeRegClass)
5175 return failedImport(
5176 "Cannot infer register class for SUBREG_TO_REG operand #0");
5177 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5178 OM.setSymbolicName(DstIOperand.Name);
5179 M.defineOperand(OM.getSymbolicName(), OM);
5180 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
5181 ++OpIdx;
5182 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005183 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00005184 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005185 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00005186 return failedImport("Dst MI def isn't a register class" +
5187 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005188
Daniel Sandersffc7d582017-03-29 15:37:18 +00005189 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5190 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00005191 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00005192 OM.addPredicate<RegisterBankOperandMatcher>(
5193 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005194 ++OpIdx;
5195 }
5196
Matt Arsenault3e45c702019-09-06 20:32:37 +00005197 auto DstMIBuilderOrError =
5198 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00005199 if (auto Error = DstMIBuilderOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005200 return std::move(Error);
Daniel Sandersffc7d582017-03-29 15:37:18 +00005201 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005202
Daniel Sandersffc7d582017-03-29 15:37:18 +00005203 // Render the implicit defs.
5204 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00005205 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005206 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005207
Daniel Sandersa7b75262017-10-31 18:50:24 +00005208 DstMIBuilder.chooseInsnToMutate(M);
5209
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005210 // Constrain the registers to classes. This is normally derived from the
5211 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00005212 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005213 // COPY_TO_REGCLASS does not provide operand constraints itself but the
5214 // result is constrained to the class given by the second child.
5215 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00005216 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005217
5218 if (DstIOpRec == nullptr)
5219 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
5220
5221 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005222 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005223
5224 // We're done with this pattern! It's eligible for GISel emission; return
5225 // it.
5226 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005227 return std::move(M);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005228 }
5229
Matt Arsenault38fb3442019-09-04 16:19:34 +00005230 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00005231 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5232 if (!SuperClass)
5233 return failedImport(
5234 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005235
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00005236 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
5237 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00005238 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005239
Daniel Sanders320390b2017-06-28 15:16:03 +00005240 // It would be nice to leave this constraint implicit but we're required
5241 // to pick a register class so constrain the result to a register class
5242 // that can hold the correct MVT.
5243 //
5244 // FIXME: This may introduce an extra copy if the chosen class doesn't
5245 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00005246 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00005247 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005248
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05005249 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00005250 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Matt Arsenault9c346462020-01-14 16:02:02 -05005251 if (!SrcRCDstRCPair) {
5252 return failedImport("subreg index is incompatible "
5253 "with inferred reg class");
5254 }
5255
Daniel Sanders320390b2017-06-28 15:16:03 +00005256 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005257 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
5258 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
5259
5260 // We're done with this pattern! It's eligible for GISel emission; return
5261 // it.
5262 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005263 return std::move(M);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005264 }
5265
Matt Arsenault38fb3442019-09-04 16:19:34 +00005266 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005267 assert(Src->getExtTypes().size() == 1 &&
5268 "Expected Src of INSERT_SUBREG to have one result type");
5269 // We need to constrain the destination, a super regsister source, and a
5270 // subregister source.
5271 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5272 if (!SubClass)
5273 return failedImport(
5274 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005275 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005276 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
5277 if (!SuperClass)
5278 return failedImport(
5279 "Cannot infer register class for INSERT_SUBREG operand #0");
5280 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5281 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
5282 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5283 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005284 return std::move(M);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005285 }
5286
Matt Arsenault38fb3442019-09-04 16:19:34 +00005287 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005288 // We need to constrain the destination and subregister source.
5289 assert(Src->getExtTypes().size() == 1 &&
5290 "Expected Src of SUBREG_TO_REG to have one result type");
5291
5292 // Attempt to infer the subregister source from the first child. If it has
5293 // an explicitly given register class, we'll use that. Otherwise, we will
5294 // fail.
5295 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5296 if (!SubClass)
5297 return failedImport(
5298 "Cannot infer register class from SUBREG_TO_REG child #1");
5299 // We don't have a child to look at that might have a super register node.
5300 auto SuperClass =
5301 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
5302 if (!SuperClass)
5303 return failedImport(
5304 "Cannot infer register class for SUBREG_TO_REG operand #0");
5305 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5306 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5307 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005308 return std::move(M);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005309 }
5310
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04005311 if (DstIName == "REG_SEQUENCE") {
5312 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5313
5314 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5315
5316 unsigned Num = Dst->getNumChildren();
5317 for (unsigned I = 1; I != Num; I += 2) {
5318 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
5319
5320 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
5321 if (!SubIdx)
5322 return failedImport("REG_SEQUENCE child is not a subreg index");
5323
5324 const auto SrcRCDstRCPair =
5325 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5326
5327 M.addAction<ConstrainOperandToRegClassAction>(0, I,
5328 *SrcRCDstRCPair->second);
5329 }
5330
5331 ++NumPatternImported;
5332 return std::move(M);
5333 }
5334
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005335 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005336
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005337 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005338 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005339 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005340}
5341
Daniel Sanders649c5852017-10-13 20:42:18 +00005342// Emit imm predicate table and an enum to reference them with.
5343// The 'Predicate_' part of the name is redundant but eliminating it is more
5344// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00005345void GlobalISelEmitter::emitCxxPredicateFns(
5346 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
Petar Avramovic09b88712020-09-14 10:39:25 +02005347 StringRef ArgType, StringRef ArgName, StringRef AdditionalArgs,
5348 StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00005349 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005350 std::vector<const Record *> MatchedRecords;
5351 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
5352 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5353 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00005354 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00005355 Filter(Record);
5356 });
5357
Daniel Sanders11300ce2017-10-13 21:28:03 +00005358 if (!MatchedRecords.empty()) {
5359 OS << "// PatFrag predicates.\n"
5360 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00005361 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00005362 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5363 for (const auto *Record : MatchedRecords) {
5364 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5365 << EnumeratorSeparator;
5366 EnumeratorSeparator = ",\n";
5367 }
5368 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005369 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00005370
Daniel Sanders8ead1292018-06-15 23:13:43 +00005371 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5372 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
Petar Avramovic09b88712020-09-14 10:39:25 +02005373 << ArgName << AdditionalArgs <<") const {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005374 << AdditionalDeclarations;
5375 if (!AdditionalDeclarations.empty())
5376 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00005377 if (!MatchedRecords.empty())
5378 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005379 for (const auto *Record : MatchedRecords) {
5380 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
5381 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005382 << " " << Record->getValueAsString(CodeFieldName) << "\n"
5383 << " llvm_unreachable(\"" << CodeFieldName
5384 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005385 << " return false;\n"
5386 << " }\n";
5387 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00005388 if (!MatchedRecords.empty())
5389 OS << " }\n";
5390 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005391 << " return false;\n"
5392 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005393}
5394
Daniel Sanders8ead1292018-06-15 23:13:43 +00005395void GlobalISelEmitter::emitImmPredicateFns(
5396 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5397 std::function<bool(const Record *R)> Filter) {
5398 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
Petar Avramovic09b88712020-09-14 10:39:25 +02005399 "Imm", "", "", Filter);
Daniel Sanders8ead1292018-06-15 23:13:43 +00005400}
5401
5402void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5403 return emitCxxPredicateFns(
5404 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
Petar Avramovic09b88712020-09-14 10:39:25 +02005405 ", const std::array<const MachineOperand *, 3> &Operands",
Daniel Sanders8ead1292018-06-15 23:13:43 +00005406 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00005407 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5408 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00005409 [](const Record *R) { return true; });
5410}
5411
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005412template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005413std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005414 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005415 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5416
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005417 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005418 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005419 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5420 unsigned NumGroups = 0;
5421
5422 auto ProcessCurrentGroup = [&]() {
5423 if (CurrentGroup->empty())
5424 // An empty group is good to be reused:
5425 return;
5426
5427 // If the group isn't large enough to provide any benefit, move all the
5428 // added rules out of it and make sure to re-create the group to properly
5429 // re-initialize it:
5430 if (CurrentGroup->size() < 2)
5431 for (Matcher *M : CurrentGroup->matchers())
5432 OptRules.push_back(M);
5433 else {
5434 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005435 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005436 MatcherStorage.emplace_back(std::move(CurrentGroup));
5437 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005438 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005439 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005440 };
5441 for (Matcher *Rule : Rules) {
5442 // Greedily add as many matchers as possible to the current group:
5443 if (CurrentGroup->addMatcher(*Rule))
5444 continue;
5445
5446 ProcessCurrentGroup();
5447 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5448
5449 // Try to add the pending matcher to a newly created empty group:
5450 if (!CurrentGroup->addMatcher(*Rule))
5451 // If we couldn't add the matcher to an empty group, that group type
5452 // doesn't support that kind of matchers at all, so just skip it:
5453 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005454 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005455 ProcessCurrentGroup();
5456
Nicola Zaghen03d0b912018-05-23 15:09:29 +00005457 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005458 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005459 return OptRules;
5460}
5461
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005462MatchTable
5463GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00005464 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005465 std::vector<Matcher *> InputRules;
5466 for (Matcher &Rule : Rules)
5467 InputRules.push_back(&Rule);
5468
5469 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00005470 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005471
Roman Tereshin77013602018-05-22 16:54:27 +00005472 unsigned CurrentOrdering = 0;
5473 StringMap<unsigned> OpcodeOrder;
5474 for (RuleMatcher &Rule : Rules) {
5475 const StringRef Opcode = Rule.getOpcode();
5476 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5477 if (OpcodeOrder.count(Opcode) == 0)
5478 OpcodeOrder[Opcode] = CurrentOrdering++;
5479 }
5480
5481 std::stable_sort(InputRules.begin(), InputRules.end(),
5482 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5483 auto *L = static_cast<const RuleMatcher *>(A);
5484 auto *R = static_cast<const RuleMatcher *>(B);
5485 return std::make_tuple(OpcodeOrder[L->getOpcode()],
5486 L->getNumOperands()) <
5487 std::make_tuple(OpcodeOrder[R->getOpcode()],
5488 R->getNumOperands());
5489 });
5490
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005491 for (Matcher *Rule : InputRules)
5492 Rule->optimize();
5493
5494 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005495 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005496 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5497
5498 for (Matcher *Rule : OptRules)
5499 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005500
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005501 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5502
Roman Tereshinbeb39312018-05-02 20:15:11 +00005503 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005504}
5505
Roman Tereshinfedae332018-05-23 02:04:19 +00005506void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00005507 // Make sure we only sort by a specific predicate within a range of rules that
5508 // all have that predicate checked against a specific value (not a wildcard):
5509 auto F = Matchers.begin();
5510 auto T = F;
5511 auto E = Matchers.end();
5512 while (T != E) {
5513 while (T != E) {
5514 auto *R = static_cast<RuleMatcher *>(*T);
5515 if (!R->getFirstConditionAsRootType().get().isValid())
5516 break;
5517 ++T;
5518 }
5519 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5520 auto *L = static_cast<RuleMatcher *>(A);
5521 auto *R = static_cast<RuleMatcher *>(B);
5522 return L->getFirstConditionAsRootType() <
5523 R->getFirstConditionAsRootType();
5524 });
5525 if (T != E)
5526 F = ++T;
5527 }
Roman Tereshinfedae332018-05-23 02:04:19 +00005528 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5529 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00005530 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5531 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00005532}
5533
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005534void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00005535 if (!UseCoverageFile.empty()) {
5536 RuleCoverage = CodeGenCoverage();
5537 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5538 if (!RuleCoverageBufOrErr) {
5539 PrintWarning(SMLoc(), "Missing rule coverage data");
5540 RuleCoverage = None;
5541 } else {
5542 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5543 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5544 RuleCoverage = None;
5545 }
5546 }
5547 }
5548
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005549 // Track the run-time opcode values
5550 gatherOpcodeValues();
5551 // Track the run-time LLT ID values
5552 gatherTypeIDValues();
5553
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005554 // Track the GINodeEquiv definitions.
5555 gatherNodeEquivs();
5556
5557 emitSourceFileHeader(("Global Instruction Selector for the " +
5558 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005559 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005560 // Look through the SelectionDAG patterns we found, possibly emitting some.
5561 for (const PatternToMatch &Pat : CGP.ptms()) {
5562 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00005563
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005564 auto MatcherOrErr = runOnPattern(Pat);
5565
5566 // The pattern analysis can fail, indicating an unsupported pattern.
5567 // Report that if we've been asked to do so.
5568 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005569 if (WarnOnSkippedPatterns) {
5570 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005571 "Skipped pattern: " + toString(std::move(Err)));
5572 } else {
5573 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005574 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005575 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005576 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005577 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005578
Daniel Sandersf76f3152017-11-16 00:46:35 +00005579 if (RuleCoverage) {
5580 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5581 ++NumPatternsTested;
5582 else
5583 PrintWarning(Pat.getSrcRecord()->getLoc(),
5584 "Pattern is not covered by a test");
5585 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005586 Rules.push_back(std::move(MatcherOrErr.get()));
5587 }
5588
Volkan Kelesf7f25682018-01-16 18:44:05 +00005589 // Comparison function to order records by name.
5590 auto orderByName = [](const Record *A, const Record *B) {
5591 return A->getName() < B->getName();
5592 };
5593
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005594 std::vector<Record *> ComplexPredicates =
5595 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00005596 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005597
5598 std::vector<Record *> CustomRendererFns =
5599 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00005600 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005601
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005602 unsigned MaxTemporaries = 0;
5603 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00005604 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005605
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005606 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5607 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5608 << ";\n"
5609 << "using PredicateBitset = "
5610 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5611 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5612
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005613 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5614 << " mutable MatcherState State;\n"
5615 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00005616 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005617 << Target.getName()
5618 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005619
5620 << " typedef void(" << Target.getName()
5621 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
Matt Arsenaultb4a64742020-01-08 12:53:15 -05005622 "MachineInstr&, int) "
Volkan Kelesf7f25682018-01-16 18:44:05 +00005623 "const;\n"
5624 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5625 "CustomRendererFn> "
5626 "ISelInfo;\n";
5627 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005628 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005629 << " static " << Target.getName()
5630 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005631 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005632 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005633 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005634 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005635 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005636 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005637 << " const int64_t *getMatchTable() const override;\n"
Petar Avramovic09b88712020-09-14 10:39:25 +02005638 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI"
5639 ", const std::array<const MachineOperand *, 3> &Operands) "
Daniel Sanders8ead1292018-06-15 23:13:43 +00005640 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005641 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005642
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005643 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5644 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005645 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5646 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005647 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005648
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005649 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5650 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5651 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005652
5653 // Separate subtarget features by how often they must be recomputed.
5654 SubtargetFeatureInfoMap ModuleFeatures;
5655 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5656 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5657 [](const SubtargetFeatureInfoMap::value_type &X) {
5658 return !X.second.mustRecomputePerFunction();
5659 });
5660 SubtargetFeatureInfoMap FunctionFeatures;
5661 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5662 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5663 [](const SubtargetFeatureInfoMap::value_type &X) {
5664 return X.second.mustRecomputePerFunction();
5665 });
5666
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005667 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Matt Arsenaultf937b432020-01-08 19:49:30 -05005668 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005669 ModuleFeatures, OS);
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005670
Matt Arsenaultf937b432020-01-08 19:49:30 -05005671
5672 OS << "void " << Target.getName() << "InstructionSelector"
5673 "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5674 " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5675 "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5676 "}\n";
5677
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005678 if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5679 // TODO: Implement PGSO.
5680 OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5681 OS << " return MF->getFunction().hasOptSize();\n";
5682 OS << "}\n\n";
5683 }
5684
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005685 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5686 Target.getName(), "InstructionSelector",
5687 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5688 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005689
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005690 // Emit a table containing the LLT objects needed by the matcher and an enum
5691 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005692 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005693 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005694 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005695 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005696 OS << "// LLT Objects.\n"
5697 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005698 for (const auto &TypeObject : TypeObjects) {
5699 OS << " ";
5700 TypeObject.emitCxxEnumValue(OS);
5701 OS << ",\n";
5702 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005703 OS << "};\n";
5704 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005705 << "const static LLT TypeObjects[] = {\n";
5706 for (const auto &TypeObject : TypeObjects) {
5707 OS << " ";
5708 TypeObject.emitCxxConstructorCall(OS);
5709 OS << ",\n";
5710 }
5711 OS << "};\n\n";
5712
5713 // Emit a table containing the PredicateBitsets objects needed by the matcher
5714 // and an enum for the matcher to reference them with.
5715 std::vector<std::vector<Record *>> FeatureBitsets;
5716 for (auto &Rule : Rules)
5717 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005718 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5719 const std::vector<Record *> &B) {
5720 if (A.size() < B.size())
5721 return true;
5722 if (A.size() > B.size())
5723 return false;
Mark de Wevere8d448e2019-12-22 18:58:32 +01005724 for (auto Pair : zip(A, B)) {
Fangrui Song3507c6e2018-09-30 22:31:29 +00005725 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5726 return true;
5727 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005728 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005729 }
5730 return false;
5731 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005732 FeatureBitsets.erase(
5733 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5734 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005735 OS << "// Feature bitsets.\n"
5736 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005737 << " GIFBS_Invalid,\n";
5738 for (const auto &FeatureBitset : FeatureBitsets) {
5739 if (FeatureBitset.empty())
5740 continue;
5741 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5742 }
5743 OS << "};\n"
5744 << "const static PredicateBitset FeatureBitsets[] {\n"
5745 << " {}, // GIFBS_Invalid\n";
5746 for (const auto &FeatureBitset : FeatureBitsets) {
5747 if (FeatureBitset.empty())
5748 continue;
5749 OS << " {";
5750 for (const auto &Feature : FeatureBitset) {
5751 const auto &I = SubtargetFeatures.find(Feature);
5752 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5753 OS << I->second.getEnumBitName() << ", ";
5754 }
5755 OS << "},\n";
5756 }
5757 OS << "};\n\n";
5758
5759 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005760 OS << "// ComplexPattern predicates.\n"
5761 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005762 << " GICP_Invalid,\n";
5763 for (const auto &Record : ComplexPredicates)
5764 OS << " GICP_" << Record->getName() << ",\n";
5765 OS << "};\n"
5766 << "// See constructor for table contents\n\n";
5767
Daniel Sanders8ead1292018-06-15 23:13:43 +00005768 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005769 bool Unset;
5770 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5771 !R->getValueAsBit("IsAPInt");
5772 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005773 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005774 bool Unset;
5775 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5776 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005777 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005778 return R->getValueAsBit("IsAPInt");
5779 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005780 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005781 OS << "\n";
5782
5783 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5784 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5785 << " nullptr, // GICP_Invalid\n";
5786 for (const auto &Record : ComplexPredicates)
5787 OS << " &" << Target.getName()
5788 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5789 << ", // " << Record->getName() << "\n";
5790 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005791
Volkan Kelesf7f25682018-01-16 18:44:05 +00005792 OS << "// Custom renderers.\n"
5793 << "enum {\n"
5794 << " GICR_Invalid,\n";
5795 for (const auto &Record : CustomRendererFns)
5796 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5797 OS << "};\n";
5798
5799 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5800 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
Matt Arsenault0274ed92020-01-08 18:57:44 -05005801 << " nullptr, // GICR_Invalid\n";
Volkan Kelesf7f25682018-01-16 18:44:05 +00005802 for (const auto &Record : CustomRendererFns)
5803 OS << " &" << Target.getName()
5804 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5805 << ", // " << Record->getName() << "\n";
5806 OS << "};\n\n";
5807
Fangrui Songefd94c52019-04-23 14:51:27 +00005808 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005809 int ScoreA = RuleMatcherScores[A.getRuleID()];
5810 int ScoreB = RuleMatcherScores[B.getRuleID()];
5811 if (ScoreA > ScoreB)
5812 return true;
5813 if (ScoreB > ScoreA)
5814 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005815 if (A.isHigherPriorityThan(B)) {
5816 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5817 "and less important at "
5818 "the same time");
5819 return true;
5820 }
5821 return false;
5822 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005823
Roman Tereshin2df4c222018-05-02 20:07:15 +00005824 OS << "bool " << Target.getName()
5825 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5826 "&CoverageInfo) const {\n"
5827 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5828 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005829 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5830 << " NewMIVector OutMIs;\n"
5831 << " State.MIs.clear();\n"
5832 << " State.MIs.push_back(&I);\n\n"
5833 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5834 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5835 << ", CoverageInfo)) {\n"
5836 << " return true;\n"
5837 << " }\n\n"
5838 << " return false;\n"
5839 << "}\n\n";
5840
Roman Tereshinbeb39312018-05-02 20:15:11 +00005841 const MatchTable Table =
5842 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005843 OS << "const int64_t *" << Target.getName()
5844 << "InstructionSelector::getMatchTable() const {\n";
5845 Table.emitDeclaration(OS);
5846 OS << " return ";
5847 Table.emitUse(OS);
5848 OS << ";\n}\n";
5849 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005850
5851 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5852 << "PredicateBitset AvailableModuleFeatures;\n"
5853 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5854 << "PredicateBitset getAvailableFeatures() const {\n"
5855 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5856 << "}\n"
5857 << "PredicateBitset\n"
5858 << "computeAvailableModuleFeatures(const " << Target.getName()
5859 << "Subtarget *Subtarget) const;\n"
5860 << "PredicateBitset\n"
5861 << "computeAvailableFunctionFeatures(const " << Target.getName()
5862 << "Subtarget *Subtarget,\n"
5863 << " const MachineFunction *MF) const;\n"
Matt Arsenaultf937b432020-01-08 19:49:30 -05005864 << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005865 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5866
5867 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5868 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5869 << "AvailableFunctionFeatures()\n"
5870 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005871}
5872
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005873void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5874 if (SubtargetFeatures.count(Predicate) == 0)
5875 SubtargetFeatures.emplace(
5876 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5877}
5878
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005879void RuleMatcher::optimize() {
5880 for (auto &Item : InsnVariableIDs) {
5881 InstructionMatcher &InsnMatcher = *Item.first;
5882 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005883 // Complex Patterns are usually expensive and they relatively rarely fail
5884 // on their own: more often we end up throwing away all the work done by a
5885 // matching part of a complex pattern because some other part of the
5886 // enclosing pattern didn't match. All of this makes it beneficial to
5887 // delay complex patterns until the very end of the rule matching,
5888 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005889 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005890 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005891 EpilogueMatchers.emplace_back(std::move(OP));
5892 OM->eraseNullPredicates();
5893 }
5894 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005895 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005896 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5897 const std::unique_ptr<PredicateMatcher> &R) {
5898 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5899 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5900 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005901}
5902
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005903bool RuleMatcher::hasFirstCondition() const {
5904 if (insnmatchers_empty())
5905 return false;
5906 InstructionMatcher &Matcher = insnmatchers_front();
5907 if (!Matcher.predicates_empty())
5908 return true;
5909 for (auto &OM : Matcher.operands())
5910 for (auto &OP : OM->predicates())
5911 if (!isa<InstructionOperandMatcher>(OP))
5912 return true;
5913 return false;
5914}
5915
5916const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5917 assert(!insnmatchers_empty() &&
5918 "Trying to get a condition from an empty RuleMatcher");
5919
5920 InstructionMatcher &Matcher = insnmatchers_front();
5921 if (!Matcher.predicates_empty())
5922 return **Matcher.predicates_begin();
5923 // If there is no more predicate on the instruction itself, look at its
5924 // operands.
5925 for (auto &OM : Matcher.operands())
5926 for (auto &OP : OM->predicates())
5927 if (!isa<InstructionOperandMatcher>(OP))
5928 return *OP;
5929
5930 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5931 "no conditions");
5932}
5933
5934std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5935 assert(!insnmatchers_empty() &&
5936 "Trying to pop a condition from an empty RuleMatcher");
5937
5938 InstructionMatcher &Matcher = insnmatchers_front();
5939 if (!Matcher.predicates_empty())
5940 return Matcher.predicates_pop_front();
5941 // If there is no more predicate on the instruction itself, look at its
5942 // operands.
5943 for (auto &OM : Matcher.operands())
5944 for (auto &OP : OM->predicates())
5945 if (!isa<InstructionOperandMatcher>(OP)) {
5946 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5947 OM->eraseNullPredicates();
5948 return Result;
5949 }
5950
5951 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5952 "no conditions");
5953}
5954
5955bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005956 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005957
5958 if (empty()) {
5959 // Sharing predicates for nested instructions is not supported yet as we
5960 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5961 // only work on the original root instruction (InsnVarID == 0):
5962 if (Predicate.getInsnVarID() != 0)
5963 return false;
5964 // ... otherwise an empty group can handle any predicate with no specific
5965 // requirements:
5966 return true;
5967 }
5968
5969 const Matcher &Representative = **Matchers.begin();
5970 const auto &RepresentativeCondition = Representative.getFirstCondition();
5971 // ... if not empty, the group can only accomodate matchers with the exact
5972 // same first condition:
5973 return Predicate.isIdentical(RepresentativeCondition);
5974}
5975
5976bool GroupMatcher::addMatcher(Matcher &Candidate) {
5977 if (!Candidate.hasFirstCondition())
5978 return false;
5979
5980 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5981 if (!candidateConditionMatches(Predicate))
5982 return false;
5983
5984 Matchers.push_back(&Candidate);
5985 return true;
5986}
5987
5988void GroupMatcher::finalize() {
5989 assert(Conditions.empty() && "Already finalized?");
5990 if (empty())
5991 return;
5992
5993 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005994 for (;;) {
5995 // All the checks are expected to succeed during the first iteration:
5996 for (const auto &Rule : Matchers)
5997 if (!Rule->hasFirstCondition())
5998 return;
5999 const auto &FirstCondition = FirstRule.getFirstCondition();
6000 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6001 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
6002 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00006003
Roman Tereshin152fc162018-05-23 22:50:53 +00006004 Conditions.push_back(FirstRule.popFirstCondition());
6005 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6006 Matchers[I]->popFirstCondition();
6007 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00006008}
6009
6010void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00006011 unsigned LabelID = ~0U;
6012 if (!Conditions.empty()) {
6013 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00006014 Table << MatchTable::Opcode("GIM_Try", +1)
6015 << MatchTable::Comment("On fail goto")
6016 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00006017 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00006018 for (auto &Condition : Conditions)
6019 Condition->emitPredicateOpcodes(
6020 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
6021
6022 for (const auto &M : Matchers)
6023 M->emit(Table);
6024
6025 // Exit the group
6026 if (!Conditions.empty())
6027 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00006028 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00006029}
6030
Roman Tereshin0ee082f2018-05-22 19:37:59 +00006031bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00006032 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00006033}
6034
6035bool SwitchMatcher::candidateConditionMatches(
6036 const PredicateMatcher &Predicate) const {
6037
6038 if (empty()) {
6039 // Sharing predicates for nested instructions is not supported yet as we
6040 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
6041 // only work on the original root instruction (InsnVarID == 0):
6042 if (Predicate.getInsnVarID() != 0)
6043 return false;
6044 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
6045 // could fail as not all the types of conditions are supported:
6046 if (!isSupportedPredicateType(Predicate))
6047 return false;
6048 // ... or the condition might not have a proper implementation of
6049 // getValue() / isIdenticalDownToValue() yet:
6050 if (!Predicate.hasValue())
6051 return false;
6052 // ... otherwise an empty Switch can accomodate the condition with no
6053 // further requirements:
6054 return true;
6055 }
6056
6057 const Matcher &CaseRepresentative = **Matchers.begin();
6058 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
6059 // Switch-cases must share the same kind of condition and path to the value it
6060 // checks:
6061 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
6062 return false;
6063
6064 const auto Value = Predicate.getValue();
6065 // ... but be unique with respect to the actual value they check:
6066 return Values.count(Value) == 0;
6067}
6068
6069bool SwitchMatcher::addMatcher(Matcher &Candidate) {
6070 if (!Candidate.hasFirstCondition())
6071 return false;
6072
6073 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
6074 if (!candidateConditionMatches(Predicate))
6075 return false;
6076 const auto Value = Predicate.getValue();
6077 Values.insert(Value);
6078
6079 Matchers.push_back(&Candidate);
6080 return true;
6081}
6082
6083void SwitchMatcher::finalize() {
6084 assert(Condition == nullptr && "Already finalized");
6085 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6086 if (empty())
6087 return;
6088
6089 std::stable_sort(Matchers.begin(), Matchers.end(),
6090 [](const Matcher *L, const Matcher *R) {
6091 return L->getFirstCondition().getValue() <
6092 R->getFirstCondition().getValue();
6093 });
6094 Condition = Matchers[0]->popFirstCondition();
6095 for (unsigned I = 1, E = Values.size(); I < E; ++I)
6096 Matchers[I]->popFirstCondition();
6097}
6098
6099void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
6100 MatchTable &Table) {
6101 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
6102
6103 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
6104 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
6105 << MatchTable::IntValue(Condition->getInsnVarID());
6106 return;
6107 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00006108 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
6109 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
6110 << MatchTable::IntValue(Condition->getInsnVarID())
6111 << MatchTable::Comment("Op")
6112 << MatchTable::IntValue(Condition->getOpIdx());
6113 return;
6114 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00006115
6116 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
6117 "predicate type that is claimed to be supported");
6118}
6119
6120void SwitchMatcher::emit(MatchTable &Table) {
6121 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6122 if (empty())
6123 return;
6124 assert(Condition != nullptr &&
6125 "Broken SwitchMatcher, hasn't been finalized?");
6126
6127 std::vector<unsigned> LabelIDs(Values.size());
6128 std::generate(LabelIDs.begin(), LabelIDs.end(),
6129 [&Table]() { return Table.allocateLabelID(); });
6130 const unsigned Default = Table.allocateLabelID();
6131
6132 const int64_t LowerBound = Values.begin()->getRawValue();
6133 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
6134
6135 emitPredicateSpecificOpcodes(*Condition, Table);
6136
6137 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
6138 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
6139 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
6140
6141 int64_t J = LowerBound;
6142 auto VI = Values.begin();
6143 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6144 auto V = *VI++;
6145 while (J++ < V.getRawValue())
6146 Table << MatchTable::IntValue(0);
6147 V.turnIntoComment();
6148 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
6149 }
6150 Table << MatchTable::LineBreak;
6151
6152 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6153 Table << MatchTable::Label(LabelIDs[I]);
6154 Matchers[I]->emit(Table);
6155 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
6156 }
6157 Table << MatchTable::Label(Default);
6158}
6159
Roman Tereshinf1aa3482018-05-21 23:28:51 +00006160unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00006161
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00006162} // end anonymous namespace
6163
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006164//===----------------------------------------------------------------------===//
6165
6166namespace llvm {
6167void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
6168 GlobalISelEmitter(RK).run(OS);
6169}
6170} // End llvm namespace