blob: 026f9ad349444ecd0427ed0a7e7c37f45c2c63b4 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This tablegen backend emits code for use by the GlobalISel instruction
11/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12///
13/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14/// backend, filters out the ones that are unsupported, maps
15/// SelectionDAG-specific constructs to their GlobalISel counterpart
16/// (when applicable: MVT to LLT; SDNode to generic Instruction).
17///
18/// Not all patterns are supported: pass the tablegen invocation
19/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20/// as well as why.
21///
22/// The generated file defines a single method:
23/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24/// intended to be used in InstructionSelector::select as the first-step
25/// selector for the patterns that don't require complex C++.
26///
27/// FIXME: We'll probably want to eventually define a base
28/// "TargetGenInstructionSelector" class.
29///
30//===----------------------------------------------------------------------===//
31
32#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000033#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000034#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000035#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000036#include "llvm/ADT/Statistic.h"
Daniel Sandersf76f3152017-11-16 00:46:35 +000037#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000038#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000039#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000040#include "llvm/Support/LowLevelTypeImpl.h"
David Blaikie13e77db2018-03-23 23:58:25 +000041#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000046#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000047#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000055STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000056STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57
Daniel Sanders0848b232017-03-27 13:15:13 +000058cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060static cl::opt<bool> WarnOnSkippedPatterns(
61 "warn-on-skipped-patterns",
62 cl::desc("Explain why a pattern was skipped for inclusion "
63 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000064 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000065
Daniel Sandersf76f3152017-11-16 00:46:35 +000066static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
70
71static cl::opt<std::string> UseCoverageFile(
72 "gisel-coverage-file", cl::init(""),
73 cl::desc("Specify file to retrieve coverage information from"),
74 cl::cat(GlobalISelEmitterCat));
75
Quentin Colombetec76d9c2017-12-18 19:47:41 +000076static cl::opt<bool> OptimizeMatchTable(
77 "optimize-match-table",
78 cl::desc("Generate an optimized version of the match table"),
79 cl::init(true), cl::cat(GlobalISelEmitterCat));
80
Daniel Sandersbdfebb82017-03-15 20:18:38 +000081namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000082//===- Helper functions ---------------------------------------------------===//
83
Daniel Sanders11300ce2017-10-13 21:28:03 +000084/// Get the name of the enum value used to number the predicate function.
85std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000086 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000088 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000089 Predicate.getFnName();
90}
91
92/// Get the opcode used to check this predicate.
93std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000094 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000095}
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097/// This class stands in for LLT wherever we want to tablegen-erate an
98/// equivalent at compiler run-time.
99class LLTCodeGen {
100private:
101 LLT Ty;
102
103public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000104 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
110
111 emitCxxEnumValue(OS);
112 return OS.str();
113 }
114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
119 }
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
123 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
129 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000130 llvm_unreachable("Unhandled LLT");
131 }
132
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
137 }
138 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000141 return;
142 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
147 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 llvm_unreachable("Unhandled LLT");
149 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000150
151 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000152
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000153 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000156 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000161
162 if (Ty.isVector() != Other.Ty.isVector())
163 return Ty.isVector() < Other.Ty.isVector();
164 if (Ty.isScalar() != Other.Ty.isScalar())
165 return Ty.isScalar() < Other.Ty.isScalar();
166 if (Ty.isPointer() != Other.Ty.isPointer())
167 return Ty.isPointer() < Other.Ty.isPointer();
168
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
174
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000176 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000177
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000179};
180
Daniel Sandersf84bc372018-05-05 20:53:24 +0000181// Track all types that are used so we can emit the corresponding enum.
182std::set<LLTCodeGen> KnownTypes;
183
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000184class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000185/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000189
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000193
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000197}
198
Florian Hahn6b1db822018-06-14 20:32:58 +0000199static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000200 std::string Explanation = "";
201 StringRef Separator = "";
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
238
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
244
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
247 }
248
249 OS << ']';
250 }
251
Matt Arsenault52c26242019-07-31 00:14:43 +0000252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
255
Daniel Sanders76664652017-11-28 22:07:05 +0000256 if (P.isAtomicOrderingMonotonic())
257 Explanation += " monotonic";
258 if (P.isAtomicOrderingAcquire())
259 Explanation += " acquire";
260 if (P.isAtomicOrderingRelease())
261 Explanation += " release";
262 if (P.isAtomicOrderingAcquireRelease())
263 Explanation += " acq_rel";
264 if (P.isAtomicOrderingSequentiallyConsistent())
265 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000266 if (P.isAtomicOrderingAcquireOrStronger())
267 Explanation += " >=acquire";
268 if (P.isAtomicOrderingWeakerThanAcquire())
269 Explanation += " <acquire";
270 if (P.isAtomicOrderingReleaseOrStronger())
271 Explanation += " >=release";
272 if (P.isAtomicOrderingWeakerThanRelease())
273 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000274 }
275 return Explanation;
276}
277
Daniel Sandersd0656a32017-04-13 09:45:37 +0000278std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000281
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
289
Volkan Kelesf7f25682018-01-16 18:44:05 +0000290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
294
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000295 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000296}
297
298/// Helper function to let the emitter report skip reason error messages.
299static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
301}
302
Florian Hahn6b1db822018-06-14 20:32:58 +0000303static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000304 std::string Explanation = "";
305 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000306
307 bool HasUnsupportedPredicate = false;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
310
Daniel Sanders2c269f62017-08-24 09:11:20 +0000311 if (Predicate.isAlwaysTrue())
312 continue;
313
314 if (Predicate.isImmediatePattern())
315 continue;
316
Daniel Sandersf84bc372018-05-05 20:53:24 +0000317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000319 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320
Matt Arsenault02772492019-07-15 21:15:20 +0000321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sandersf84bc372018-05-05 20:53:24 +0000324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
326
Daniel Sanders76664652017-11-28 22:07:05 +0000327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
330 }
331
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
Matt Arsenault52c26242019-07-31 00:14:43 +0000336
337 if (Predicate.getMinAlignment() > 0)
338 continue;
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000339 }
340
Daniel Sanders76664652017-11-28 22:07:05 +0000341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
343
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000354 continue;
355
Daniel Sanders8ead1292018-06-15 23:13:43 +0000356 if (Predicate.hasGISelPredicateCode())
357 continue;
358
Daniel Sanders2c269f62017-08-24 09:11:20 +0000359 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000365 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000366 }
367
Volkan Kelesf7f25682018-01-16 18:44:05 +0000368 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000369 return Error::success();
370
371 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000372}
373
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000374static Record *getInitValueAsRegClass(Init *V) {
375 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377 return VDefInit->getDef()->getValueAsDef("RegClass");
378 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379 return VDefInit->getDef();
380 }
381 return nullptr;
382}
383
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000384std::string
385getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
390}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000391
392//===- MatchTable Helpers -------------------------------------------------===//
393
394class MatchTable;
395
396/// A record to be stored in a MatchTable.
397///
398/// This class represents any and all output that may be required to emit the
399/// MatchTable. Instances are most often configured to represent an opcode or
400/// value that will be emitted to the table with some formatting but it can also
401/// represent commas, comments, and other formatting instructions.
402struct MatchTableRecord {
403 enum RecordFlagsBits {
404 MTRF_None = 0x0,
405 /// Causes EmitStr to be formatted as comment when emitted.
406 MTRF_Comment = 0x1,
407 /// Causes the record value to be followed by a comma when emitted.
408 MTRF_CommaFollows = 0x2,
409 /// Causes the record value to be followed by a line break when emitted.
410 MTRF_LineBreakFollows = 0x4,
411 /// Indicates that the record defines a label and causes an additional
412 /// comment to be emitted containing the index of the label.
413 MTRF_Label = 0x8,
414 /// Causes the record to be emitted as the index of the label specified by
415 /// LabelID along with a comment indicating where that label is.
416 MTRF_JumpTarget = 0x10,
417 /// Causes the formatter to add a level of indentation before emitting the
418 /// record.
419 MTRF_Indent = 0x20,
420 /// Causes the formatter to remove a level of indentation after emitting the
421 /// record.
422 MTRF_Outdent = 0x40,
423 };
424
425 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426 /// reference or define.
427 unsigned LabelID;
428 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429 /// value, a label name.
430 std::string EmitStr;
431
432private:
433 /// The number of MatchTable elements described by this record. Comments are 0
434 /// while values are typically 1. Values >1 may occur when we need to emit
435 /// values that exceed the size of a MatchTable element.
436 unsigned NumElements;
437
438public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
441
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000442 /// The actual run-time value, if known
443 int64_t RawValue;
444
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000451 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
452 "This value is reserved for non-labels");
453 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000454 MatchTableRecord(const MatchTableRecord &Other) = default;
455 MatchTableRecord(MatchTableRecord &&Other) = default;
456
457 /// Useful if a Match Table Record gets optimized out
458 void turnIntoComment() {
459 Flags |= MTRF_Comment;
460 Flags &= ~MTRF_CommaFollows;
461 NumElements = 0;
462 }
463
464 /// For Jump Table generation purposes
465 bool operator<(const MatchTableRecord &Other) const {
466 return RawValue < Other.RawValue;
467 }
468 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000469
470 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
471 const MatchTable &Table) const;
472 unsigned size() const { return NumElements; }
473};
474
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000475class Matcher;
476
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000477/// Holds the contents of a generated MatchTable to enable formatting and the
478/// necessary index tracking needed to support GIM_Try.
479class MatchTable {
480 /// An unique identifier for the table. The generated table will be named
481 /// MatchTable${ID}.
482 unsigned ID;
483 /// The records that make up the table. Also includes comments describing the
484 /// values being emitted and line breaks to format it.
485 std::vector<MatchTableRecord> Contents;
486 /// The currently defined labels.
487 DenseMap<unsigned, unsigned> LabelMap;
488 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000489 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000490 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000491 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000492 /// Determines if the table should be instrumented for rule coverage tracking.
493 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000494
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000495public:
496 static MatchTableRecord LineBreak;
497 static MatchTableRecord Comment(StringRef Comment) {
498 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
499 }
500 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
501 unsigned ExtraFlags = 0;
502 if (IndentAdjust > 0)
503 ExtraFlags |= MatchTableRecord::MTRF_Indent;
504 if (IndentAdjust < 0)
505 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
506
507 return MatchTableRecord(None, Opcode, 1,
508 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
509 }
510 static MatchTableRecord NamedValue(StringRef NamedValue) {
511 return MatchTableRecord(None, NamedValue, 1,
512 MatchTableRecord::MTRF_CommaFollows);
513 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000514 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
515 return MatchTableRecord(None, NamedValue, 1,
516 MatchTableRecord::MTRF_CommaFollows, RawValue);
517 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000518 static MatchTableRecord NamedValue(StringRef Namespace,
519 StringRef NamedValue) {
520 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
521 MatchTableRecord::MTRF_CommaFollows);
522 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000523 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
524 int64_t RawValue) {
525 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
526 MatchTableRecord::MTRF_CommaFollows, RawValue);
527 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000528 static MatchTableRecord IntValue(int64_t IntValue) {
529 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
530 MatchTableRecord::MTRF_CommaFollows);
531 }
532 static MatchTableRecord Label(unsigned LabelID) {
533 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
534 MatchTableRecord::MTRF_Label |
535 MatchTableRecord::MTRF_Comment |
536 MatchTableRecord::MTRF_LineBreakFollows);
537 }
538 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000539 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000540 MatchTableRecord::MTRF_JumpTarget |
541 MatchTableRecord::MTRF_Comment |
542 MatchTableRecord::MTRF_CommaFollows);
543 }
544
Roman Tereshinbeb39312018-05-02 20:15:11 +0000545 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000546
Roman Tereshinbeb39312018-05-02 20:15:11 +0000547 MatchTable(bool WithCoverage, unsigned ID = 0)
548 : ID(ID), IsWithCoverage(WithCoverage) {}
549
550 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000551
552 void push_back(const MatchTableRecord &Value) {
553 if (Value.Flags & MatchTableRecord::MTRF_Label)
554 defineLabel(Value.LabelID);
555 Contents.push_back(Value);
556 CurrentSize += Value.size();
557 }
558
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000559 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000560
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000561 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000562 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000563 }
564
565 unsigned getLabelIndex(unsigned LabelID) const {
566 const auto I = LabelMap.find(LabelID);
567 assert(I != LabelMap.end() && "Use of undeclared label");
568 return I->second;
569 }
570
Daniel Sanders8e82af22017-07-27 11:03:45 +0000571 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
572
573 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000574 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000575 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000576 LineBreak.emit(OS, true, *this);
577 OS << std::string(Indentation, ' ');
578
579 for (auto I = Contents.begin(), E = Contents.end(); I != E;
580 ++I) {
581 bool LineBreakIsNext = false;
582 const auto &NextI = std::next(I);
583
584 if (NextI != E) {
585 if (NextI->EmitStr == "" &&
586 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
587 LineBreakIsNext = true;
588 }
589
590 if (I->Flags & MatchTableRecord::MTRF_Indent)
591 Indentation += 2;
592
593 I->emit(OS, LineBreakIsNext, *this);
594 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
595 OS << std::string(Indentation, ' ');
596
597 if (I->Flags & MatchTableRecord::MTRF_Outdent)
598 Indentation -= 2;
599 }
600 OS << "};\n";
601 }
602};
603
604MatchTableRecord MatchTable::LineBreak = {
605 None, "" /* Emit String */, 0 /* Elements */,
606 MatchTableRecord::MTRF_LineBreakFollows};
607
608void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
609 const MatchTable &Table) const {
610 bool UseLineComment =
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000611 LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000612 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
613 UseLineComment = false;
614
615 if (Flags & MTRF_Comment)
616 OS << (UseLineComment ? "// " : "/*");
617
618 OS << EmitStr;
619 if (Flags & MTRF_Label)
620 OS << ": @" << Table.getLabelIndex(LabelID);
621
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000622 if ((Flags & MTRF_Comment) && !UseLineComment)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000623 OS << "*/";
624
625 if (Flags & MTRF_JumpTarget) {
626 if (Flags & MTRF_Comment)
627 OS << " ";
628 OS << Table.getLabelIndex(LabelID);
629 }
630
631 if (Flags & MTRF_CommaFollows) {
632 OS << ",";
633 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
634 OS << " ";
635 }
636
637 if (Flags & MTRF_LineBreakFollows)
638 OS << "\n";
639}
640
641MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
642 Table.push_back(Value);
643 return Table;
644}
645
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000646//===- Matchers -----------------------------------------------------------===//
647
Daniel Sandersbee57392017-04-04 13:25:23 +0000648class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000649class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000650class PredicateMatcher;
651class RuleMatcher;
652
653class Matcher {
654public:
655 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000656 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000657 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000658
659 virtual bool hasFirstCondition() const = 0;
660 virtual const PredicateMatcher &getFirstCondition() const = 0;
661 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000662};
663
Roman Tereshinbeb39312018-05-02 20:15:11 +0000664MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
665 bool WithCoverage) {
666 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000667 for (Matcher *Rule : Rules)
668 Rule->emit(Table);
669
670 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
671}
672
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000673class GroupMatcher final : public Matcher {
674 /// Conditions that form a common prefix of all the matchers contained.
675 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
676
677 /// All the nested matchers, sharing a common prefix.
678 std::vector<Matcher *> Matchers;
679
680 /// An owning collection for any auxiliary matchers created while optimizing
681 /// nested matchers contained.
682 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000683
684public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000685 /// Add a matcher to the collection of nested matchers if it meets the
686 /// requirements, and return true. If it doesn't, do nothing and return false.
687 ///
688 /// Expected to preserve its argument, so it could be moved out later on.
689 bool addMatcher(Matcher &Candidate);
690
691 /// Mark the matcher as fully-built and ensure any invariants expected by both
692 /// optimize() and emit(...) methods. Generally, both sequences of calls
693 /// are expected to lead to a sensible result:
694 ///
695 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
696 /// addMatcher(...)*; finalize(); emit(...);
697 ///
698 /// or generally
699 ///
700 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
701 ///
702 /// Multiple calls to optimize() are expected to be handled gracefully, though
703 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
704 /// aren't generally supported. emit(...) is expected to be non-mutating and
705 /// producing the exact same results upon repeated calls.
706 ///
707 /// addMatcher() calls after the finalize() call are not supported.
708 ///
709 /// finalize() and optimize() are both allowed to mutate the contained
710 /// matchers, so moving them out after finalize() is not supported.
711 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000712 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000713 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000714
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000715 /// Could be used to move out the matchers added previously, unless finalize()
716 /// has been already called. If any of the matchers are moved out, the group
717 /// becomes safe to destroy, but not safe to re-use for anything else.
718 iterator_range<std::vector<Matcher *>::iterator> matchers() {
719 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000720 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000721 size_t size() const { return Matchers.size(); }
722 bool empty() const { return Matchers.empty(); }
723
724 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
725 assert(!Conditions.empty() &&
726 "Trying to pop a condition from a condition-less group");
727 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
728 Conditions.erase(Conditions.begin());
729 return P;
730 }
731 const PredicateMatcher &getFirstCondition() const override {
732 assert(!Conditions.empty() &&
733 "Trying to get a condition from a condition-less group");
734 return *Conditions.front();
735 }
736 bool hasFirstCondition() const override { return !Conditions.empty(); }
737
738private:
739 /// See if a candidate matcher could be added to this group solely by
740 /// analyzing its first condition.
741 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000742};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000743
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000744class SwitchMatcher : public Matcher {
745 /// All the nested matchers, representing distinct switch-cases. The first
746 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
747 /// matchers must share the same type and path to a value they check, in other
748 /// words, be isIdenticalDownToValue, but have different values they check
749 /// against.
750 std::vector<Matcher *> Matchers;
751
752 /// The representative condition, with a type and a path (InsnVarID and OpIdx
753 /// in most cases) shared by all the matchers contained.
754 std::unique_ptr<PredicateMatcher> Condition = nullptr;
755
756 /// Temporary set used to check that the case values don't repeat within the
757 /// same switch.
758 std::set<MatchTableRecord> Values;
759
760 /// An owning collection for any auxiliary matchers created while optimizing
761 /// nested matchers contained.
762 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
763
764public:
765 bool addMatcher(Matcher &Candidate);
766
767 void finalize();
768 void emit(MatchTable &Table) override;
769
770 iterator_range<std::vector<Matcher *>::iterator> matchers() {
771 return make_range(Matchers.begin(), Matchers.end());
772 }
773 size_t size() const { return Matchers.size(); }
774 bool empty() const { return Matchers.empty(); }
775
776 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
777 // SwitchMatcher doesn't have a common first condition for its cases, as all
778 // the cases only share a kind of a value (a type and a path to it) they
779 // match, but deliberately differ in the actual value they match.
780 llvm_unreachable("Trying to pop a condition from a condition-less group");
781 }
782 const PredicateMatcher &getFirstCondition() const override {
783 llvm_unreachable("Trying to pop a condition from a condition-less group");
784 }
785 bool hasFirstCondition() const override { return false; }
786
787private:
788 /// See if the predicate type has a Switch-implementation for it.
789 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
790
791 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
792
793 /// emit()-helper
794 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
795 MatchTable &Table);
796};
797
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000798/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000799class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000800public:
Daniel Sanders08464522018-01-29 21:09:12 +0000801 using ActionList = std::list<std::unique_ptr<MatchAction>>;
802 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000803
804protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000805 /// A list of matchers that all need to succeed for the current rule to match.
806 /// FIXME: This currently supports a single match position but could be
807 /// extended to support multiple positions to support div/rem fusion or
808 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000809 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
810 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000811
812 /// A list of actions that need to be taken when all predicates in this rule
813 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000814 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000815
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000816 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000817
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000818 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000819 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000820
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000821 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000822
823 // The set of instruction matchers that have not yet been claimed for mutation
824 // by a BuildMI.
825 MutatableInsnSet MutatableInsns;
826
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000827 /// A map of named operands defined by the matchers that may be referenced by
828 /// the renderers.
829 StringMap<OperandMatcher *> DefinedOperands;
830
Matt Arsenault3e45c702019-09-06 20:32:37 +0000831 /// A map of anonymous physical register operands defined by the matchers that
832 /// may be referenced by the renderers.
833 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
834
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000835 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000836 unsigned NextInsnVarID;
837
Daniel Sanders198447a2017-11-01 00:29:47 +0000838 /// ID for the next output instruction allocated with allocateOutputInsnID()
839 unsigned NextOutputInsnID;
840
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000841 /// ID for the next temporary register ID allocated with allocateTempRegID()
842 unsigned NextTempRegID;
843
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000844 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000845 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000846
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000847 ArrayRef<SMLoc> SrcLoc;
848
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000849 typedef std::tuple<Record *, unsigned, unsigned>
850 DefinedComplexPatternSubOperand;
851 typedef StringMap<DefinedComplexPatternSubOperand>
852 DefinedComplexPatternSubOperandMap;
853 /// A map of Symbolic Names to ComplexPattern sub-operands.
854 DefinedComplexPatternSubOperandMap ComplexSubOperands;
855
Daniel Sandersf76f3152017-11-16 00:46:35 +0000856 uint64_t RuleID;
857 static uint64_t NextRuleID;
858
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000859public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000860 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000861 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000862 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000863 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
864 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000865 RuleMatcher(RuleMatcher &&Other) = default;
866 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000867
Daniel Sandersf76f3152017-11-16 00:46:35 +0000868 uint64_t getRuleID() const { return RuleID; }
869
Daniel Sanders05540042017-08-08 10:44:31 +0000870 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000871 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000872 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000873
874 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000875 template <class Kind, class... Args>
876 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000877
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000878 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000879 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
880
881 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000882 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
883 return InsnVariableIDs.begin();
884 }
885 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
886 return InsnVariableIDs.end();
887 }
888 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
889 defined_insn_vars() const {
890 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
891 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000892
Daniel Sandersa7b75262017-10-31 18:50:24 +0000893 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
894 return MutatableInsns.begin();
895 }
896 MutatableInsnSet::const_iterator mutatable_insns_end() const {
897 return MutatableInsns.end();
898 }
899 iterator_range<typename MutatableInsnSet::const_iterator>
900 mutatable_insns() const {
901 return make_range(mutatable_insns_begin(), mutatable_insns_end());
902 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000903 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000904 bool R = MutatableInsns.erase(InsnMatcher);
905 assert(R && "Reserving a mutatable insn that isn't available");
906 (void)R;
907 }
908
Daniel Sanders7438b262017-10-31 23:03:18 +0000909 action_iterator actions_begin() { return Actions.begin(); }
910 action_iterator actions_end() { return Actions.end(); }
911 iterator_range<action_iterator> actions() {
912 return make_range(actions_begin(), actions_end());
913 }
914
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000915 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
916
Matt Arsenault3e45c702019-09-06 20:32:37 +0000917 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
918
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000919 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
920 unsigned RendererID, unsigned SubOperandID) {
921 if (ComplexSubOperands.count(SymbolicName))
922 return failedImport(
923 "Complex suboperand referenced more than once (Operand: " +
924 SymbolicName + ")");
925
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000926 ComplexSubOperands[SymbolicName] =
927 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000928
929 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000930 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000931
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000932 Optional<DefinedComplexPatternSubOperand>
933 getComplexSubOperand(StringRef SymbolicName) const {
934 const auto &I = ComplexSubOperands.find(SymbolicName);
935 if (I == ComplexSubOperands.end())
936 return None;
937 return I->second;
938 }
939
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000940 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000941 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000942 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000943
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000944 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000945 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000946
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000947 /// Compare the priority of this object and B.
948 ///
949 /// Returns true if this object is more important than B.
950 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000951
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000952 /// Report the maximum number of temporary operands needed by the rule
953 /// matcher.
954 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000955
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000956 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
957 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000958 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000959 bool hasFirstCondition() const override;
960 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000961 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000962
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000963 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000964 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000965
966 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000967 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000968
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000969 iterator_range<MatchersTy::iterator> insnmatchers() {
970 return make_range(Matchers.begin(), Matchers.end());
971 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000972 bool insnmatchers_empty() const { return Matchers.empty(); }
973 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000974};
975
Daniel Sandersf76f3152017-11-16 00:46:35 +0000976uint64_t RuleMatcher::NextRuleID = 0;
977
Daniel Sanders7438b262017-10-31 23:03:18 +0000978using action_iterator = RuleMatcher::action_iterator;
979
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000980template <class PredicateTy> class PredicateListMatcher {
981private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000982 /// Template instantiations should specialize this to return a string to use
983 /// for the comment emitted when there are no predicates.
984 std::string getNoPredicateComment() const;
985
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000986protected:
987 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
988 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000989
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000990 /// Track if the list of predicates was manipulated by one of the optimization
991 /// methods.
992 bool Optimized = false;
993
994public:
995 /// Construct a new predicate and add it to the matcher.
996 template <class Kind, class... Args>
997 Optional<Kind *> addPredicate(Args &&... args);
998
999 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001000 return Predicates.begin();
1001 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001002 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001003 return Predicates.end();
1004 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001005 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001006 return make_range(predicates_begin(), predicates_end());
1007 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001008 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001009 return Predicates.size();
1010 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001011 bool predicates_empty() const { return Predicates.empty(); }
1012
1013 std::unique_ptr<PredicateTy> predicates_pop_front() {
1014 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001015 Predicates.pop_front();
1016 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001017 return Front;
1018 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001019
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001020 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1021 Predicates.push_front(std::move(Predicate));
1022 }
1023
1024 void eraseNullPredicates() {
1025 const auto NewEnd =
1026 std::stable_partition(Predicates.begin(), Predicates.end(),
1027 std::logical_not<std::unique_ptr<PredicateTy>>());
1028 if (NewEnd != Predicates.begin()) {
1029 Predicates.erase(Predicates.begin(), NewEnd);
1030 Optimized = true;
1031 }
1032 }
1033
Daniel Sanders9d662d22017-07-06 10:06:12 +00001034 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001035 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001036 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1037 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001038 Table << MatchTable::Comment(getNoPredicateComment())
1039 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001040 return;
1041 }
1042
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001043 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001044 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001045 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001046};
1047
Quentin Colombet063d7982017-12-14 23:44:07 +00001048class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001049public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001050 /// This enum is used for RTTI and also defines the priority that is given to
1051 /// the predicate when generating the matcher code. Kinds with higher priority
1052 /// must be tested first.
1053 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001054 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1055 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1056 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001057 ///
1058 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1059 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001060 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001061 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001062 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001063 IPM_ImmPredicate,
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001064 IPM_Imm,
Quentin Colombet063d7982017-12-14 23:44:07 +00001065 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001066 IPM_MemoryLLTSize,
1067 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001068 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001069 IPM_MemoryAlignment,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001070 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001071 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001072 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001073 OPM_IntrinsicID,
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001074 OPM_CmpPredicate,
Daniel Sanders05540042017-08-08 10:44:31 +00001075 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001076 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001077 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001078 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001079 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001080 OPM_RegBank,
1081 OPM_MBB,
1082 };
1083
1084protected:
1085 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001086 unsigned InsnVarID;
1087 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001088
1089public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001090 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1091 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001092
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001093 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001094 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001095
Quentin Colombet063d7982017-12-14 23:44:07 +00001096 virtual ~PredicateMatcher() = default;
1097 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001098 virtual void emitPredicateOpcodes(MatchTable &Table,
1099 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001100
Daniel Sanders759ff412017-02-24 13:58:11 +00001101 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001102
1103 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001104 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1105 OpIdx == B.OpIdx;
1106 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001107
1108 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1109 return hasValue() && PredicateMatcher::isIdentical(B);
1110 }
1111
1112 virtual MatchTableRecord getValue() const {
1113 assert(hasValue() && "Can not get a value of a value-less predicate!");
1114 llvm_unreachable("Not implemented yet");
1115 }
1116 virtual bool hasValue() const { return false; }
1117
1118 /// Report the maximum number of temporary operands needed by the predicate
1119 /// matcher.
1120 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001121};
1122
1123/// Generates code to check a predicate of an operand.
1124///
1125/// Typical predicates include:
1126/// * Operand is a particular register.
1127/// * Operand is assigned a particular register bank.
1128/// * Operand is an MBB.
1129class OperandPredicateMatcher : public PredicateMatcher {
1130public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001131 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1132 unsigned OpIdx)
1133 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001134 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001135
Daniel Sanders759ff412017-02-24 13:58:11 +00001136 /// Compare the priority of this object and B.
1137 ///
1138 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001139 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001140};
1141
Daniel Sanders2c269f62017-08-24 09:11:20 +00001142template <>
1143std::string
1144PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1145 return "No operand predicates";
1146}
1147
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001148/// Generates code to check that a register operand is defined by the same exact
1149/// one as another.
1150class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001151 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001152
1153public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001154 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001155 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1156 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001157
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001158 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001159 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001160 }
1161
Quentin Colombetaad20be2017-12-15 23:07:42 +00001162 void emitPredicateOpcodes(MatchTable &Table,
1163 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001164
1165 bool isIdentical(const PredicateMatcher &B) const override {
1166 return OperandPredicateMatcher::isIdentical(B) &&
1167 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1168 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001169};
1170
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001171/// Generates code to check that an operand is a particular LLT.
1172class LLTOperandMatcher : public OperandPredicateMatcher {
1173protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001174 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001175
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001176public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001177 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1178
1179 static void initTypeIDValuesMap() {
1180 TypeIDValues.clear();
1181
1182 unsigned ID = 0;
Mark de Wevere8d448e2019-12-22 18:58:32 +01001183 for (const LLTCodeGen &LLTy : KnownTypes)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001184 TypeIDValues[LLTy] = ID++;
1185 }
1186
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001187 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001188 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001189 KnownTypes.insert(Ty);
1190 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001191
Quentin Colombet063d7982017-12-14 23:44:07 +00001192 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001193 return P->getKind() == OPM_LLT;
1194 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001195 bool isIdentical(const PredicateMatcher &B) const override {
1196 return OperandPredicateMatcher::isIdentical(B) &&
1197 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1198 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001199 MatchTableRecord getValue() const override {
1200 const auto VI = TypeIDValues.find(Ty);
1201 if (VI == TypeIDValues.end())
1202 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1203 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1204 }
1205 bool hasValue() const override {
1206 if (TypeIDValues.size() != KnownTypes.size())
1207 initTypeIDValuesMap();
1208 return TypeIDValues.count(Ty);
1209 }
1210
1211 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001212
Quentin Colombetaad20be2017-12-15 23:07:42 +00001213 void emitPredicateOpcodes(MatchTable &Table,
1214 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001215 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1216 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1217 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001218 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001219 }
1220};
1221
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001222std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1223
Daniel Sandersa71f4542017-10-16 00:56:30 +00001224/// Generates code to check that an operand is a pointer to any address space.
1225///
1226/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1227/// result, iN is used to describe a pointer of N bits to any address space and
1228/// PatFrag predicates are typically used to constrain the address space. There's
1229/// no reliable means to derive the missing type information from the pattern so
1230/// imported rules must test the components of a pointer separately.
1231///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001232/// If SizeInBits is zero, then the pointer size will be obtained from the
1233/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001234class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1235protected:
1236 unsigned SizeInBits;
1237
1238public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001239 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1240 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001241 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1242 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001243
1244 static bool classof(const OperandPredicateMatcher *P) {
1245 return P->getKind() == OPM_PointerToAny;
1246 }
1247
Quentin Colombetaad20be2017-12-15 23:07:42 +00001248 void emitPredicateOpcodes(MatchTable &Table,
1249 RuleMatcher &Rule) const override {
1250 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1251 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1252 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1253 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001254 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1255 }
1256};
1257
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001258/// Generates code to check that an operand is a particular target constant.
1259class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1260protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001261 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001262 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001263
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001264 unsigned getAllocatedTemporariesBaseID() const;
1265
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001266public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001267 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1268
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001269 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1270 const OperandMatcher &Operand,
1271 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001272 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1273 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001274
Quentin Colombet063d7982017-12-14 23:44:07 +00001275 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001276 return P->getKind() == OPM_ComplexPattern;
1277 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001278
Quentin Colombetaad20be2017-12-15 23:07:42 +00001279 void emitPredicateOpcodes(MatchTable &Table,
1280 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001281 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001282 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1283 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1284 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1285 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1286 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1287 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001288 }
1289
Daniel Sanders2deea182017-04-22 15:11:04 +00001290 unsigned countRendererFns() const override {
1291 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001292 }
1293};
1294
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001295/// Generates code to check that an operand is in a particular register bank.
1296class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1297protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001298 const CodeGenRegisterClass &RC;
1299
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001300public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001301 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1302 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001303 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001304
Quentin Colombet893e0f12017-12-15 23:24:39 +00001305 bool isIdentical(const PredicateMatcher &B) const override {
1306 return OperandPredicateMatcher::isIdentical(B) &&
1307 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1308 }
1309
Quentin Colombet063d7982017-12-14 23:44:07 +00001310 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001311 return P->getKind() == OPM_RegBank;
1312 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001313
Quentin Colombetaad20be2017-12-15 23:07:42 +00001314 void emitPredicateOpcodes(MatchTable &Table,
1315 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001316 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1317 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1318 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1319 << MatchTable::Comment("RC")
1320 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1321 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001322 }
1323};
1324
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001325/// Generates code to check that an operand is a basic block.
1326class MBBOperandMatcher : public OperandPredicateMatcher {
1327public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001328 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1329 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001330
Quentin Colombet063d7982017-12-14 23:44:07 +00001331 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001332 return P->getKind() == OPM_MBB;
1333 }
1334
Quentin Colombetaad20be2017-12-15 23:07:42 +00001335 void emitPredicateOpcodes(MatchTable &Table,
1336 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001337 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1338 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1339 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001340 }
1341};
1342
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001343class ImmOperandMatcher : public OperandPredicateMatcher {
1344public:
1345 ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1346 : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1347
1348 static bool classof(const PredicateMatcher *P) {
1349 return P->getKind() == IPM_Imm;
1350 }
1351
1352 void emitPredicateOpcodes(MatchTable &Table,
1353 RuleMatcher &Rule) const override {
1354 Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1355 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1356 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1357 }
1358};
1359
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001360/// Generates code to check that an operand is a G_CONSTANT with a particular
1361/// int.
1362class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001363protected:
1364 int64_t Value;
1365
1366public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001367 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001368 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001369
Quentin Colombet893e0f12017-12-15 23:24:39 +00001370 bool isIdentical(const PredicateMatcher &B) const override {
1371 return OperandPredicateMatcher::isIdentical(B) &&
1372 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1373 }
1374
Quentin Colombet063d7982017-12-14 23:44:07 +00001375 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001376 return P->getKind() == OPM_Int;
1377 }
1378
Quentin Colombetaad20be2017-12-15 23:07:42 +00001379 void emitPredicateOpcodes(MatchTable &Table,
1380 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001381 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1382 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1383 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1384 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001385 }
1386};
1387
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001388/// Generates code to check that an operand is a raw int (where MO.isImm() or
1389/// MO.isCImm() is true).
1390class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1391protected:
1392 int64_t Value;
1393
1394public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001395 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001396 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1397 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001398
Quentin Colombet893e0f12017-12-15 23:24:39 +00001399 bool isIdentical(const PredicateMatcher &B) const override {
1400 return OperandPredicateMatcher::isIdentical(B) &&
1401 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1402 }
1403
Quentin Colombet063d7982017-12-14 23:44:07 +00001404 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001405 return P->getKind() == OPM_LiteralInt;
1406 }
1407
Quentin Colombetaad20be2017-12-15 23:07:42 +00001408 void emitPredicateOpcodes(MatchTable &Table,
1409 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001410 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1411 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1412 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1413 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001414 }
1415};
1416
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001417/// Generates code to check that an operand is an CmpInst predicate
1418class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1419protected:
1420 std::string PredName;
1421
1422public:
1423 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1424 std::string P)
1425 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1426
1427 bool isIdentical(const PredicateMatcher &B) const override {
1428 return OperandPredicateMatcher::isIdentical(B) &&
1429 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1430 }
1431
1432 static bool classof(const PredicateMatcher *P) {
1433 return P->getKind() == OPM_CmpPredicate;
1434 }
1435
1436 void emitPredicateOpcodes(MatchTable &Table,
1437 RuleMatcher &Rule) const override {
1438 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1439 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1440 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1441 << MatchTable::Comment("Predicate")
1442 << MatchTable::NamedValue("CmpInst", PredName)
1443 << MatchTable::LineBreak;
1444 }
1445};
1446
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001447/// Generates code to check that an operand is an intrinsic ID.
1448class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1449protected:
1450 const CodeGenIntrinsic *II;
1451
1452public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001453 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1454 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001455 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001456
Quentin Colombet893e0f12017-12-15 23:24:39 +00001457 bool isIdentical(const PredicateMatcher &B) const override {
1458 return OperandPredicateMatcher::isIdentical(B) &&
1459 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1460 }
1461
Quentin Colombet063d7982017-12-14 23:44:07 +00001462 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001463 return P->getKind() == OPM_IntrinsicID;
1464 }
1465
Quentin Colombetaad20be2017-12-15 23:07:42 +00001466 void emitPredicateOpcodes(MatchTable &Table,
1467 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001468 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1469 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1470 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1471 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1472 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001473 }
1474};
1475
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001476/// Generates code to check that a set of predicates match for a particular
1477/// operand.
1478class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1479protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001480 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001481 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001482 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001483
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001484 /// The index of the first temporary variable allocated to this operand. The
1485 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001486 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001487 unsigned AllocatedTemporariesBaseID;
1488
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001489public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001490 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001491 const std::string &SymbolicName,
1492 unsigned AllocatedTemporariesBaseID)
1493 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1494 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001495
1496 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1497 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001498 void setSymbolicName(StringRef Name) {
1499 assert(SymbolicName.empty() && "Operand already has a symbolic name");
Benjamin Krameradcd0262020-01-28 20:23:46 +01001500 SymbolicName = std::string(Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001501 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001502
1503 /// Construct a new operand predicate and add it to the matcher.
1504 template <class Kind, class... Args>
1505 Optional<Kind *> addPredicate(Args &&... args) {
1506 if (isSameAsAnotherOperand())
1507 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001508 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001509 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1510 return static_cast<Kind *>(Predicates.back().get());
1511 }
1512
1513 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001514 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001515
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001516 std::string getOperandExpr(unsigned InsnVarID) const {
1517 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1518 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001519 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001520
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001521 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1522
Daniel Sandersa71f4542017-10-16 00:56:30 +00001523 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001524 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001525
Daniel Sanders9d662d22017-07-06 10:06:12 +00001526 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001527 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001528 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1529 if (!Optimized) {
1530 std::string Comment;
1531 raw_string_ostream CommentOS(Comment);
1532 CommentOS << "MIs[" << getInsnVarID() << "] ";
1533 if (SymbolicName.empty())
1534 CommentOS << "Operand " << OpIdx;
1535 else
1536 CommentOS << SymbolicName;
1537 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1538 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001539
Quentin Colombetaad20be2017-12-15 23:07:42 +00001540 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001541 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001542
1543 /// Compare the priority of this object and B.
1544 ///
1545 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001546 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001547 // Operand matchers involving more predicates have higher priority.
1548 if (predicates_size() > B.predicates_size())
1549 return true;
1550 if (predicates_size() < B.predicates_size())
1551 return false;
1552
1553 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001554 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001555 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1556 return true;
1557 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1558 return false;
1559 }
1560
1561 return false;
1562 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001563
1564 /// Report the maximum number of temporary operands needed by the operand
1565 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001566 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001567 return std::accumulate(
1568 predicates().begin(), predicates().end(), 0,
1569 [](unsigned A,
1570 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001571 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001572 });
1573 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001574
1575 unsigned getAllocatedTemporariesBaseID() const {
1576 return AllocatedTemporariesBaseID;
1577 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001578
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001579 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001580 for (const auto &Predicate : predicates())
1581 if (isa<SameOperandMatcher>(Predicate))
1582 return true;
1583 return false;
1584 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001585};
1586
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001587Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001588 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001589 if (!VTy.isMachineValueType())
1590 return failedImport("unsupported typeset");
1591
1592 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1593 addPredicate<PointerToAnyOperandMatcher>(0);
1594 return Error::success();
1595 }
1596
1597 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1598 if (!OpTyOrNone)
1599 return failedImport("unsupported type");
1600
1601 if (OperandIsAPointer)
1602 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001603 else if (VTy.isPointer())
1604 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1605 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001606 else
1607 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1608 return Error::success();
1609}
1610
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001611unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1612 return Operand.getAllocatedTemporariesBaseID();
1613}
1614
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001615/// Generates code to check a predicate on an instruction.
1616///
1617/// Typical predicates include:
1618/// * The opcode of the instruction is a particular value.
1619/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001620class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001621public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001622 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1623 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001624 virtual ~InstructionPredicateMatcher() {}
1625
Daniel Sanders759ff412017-02-24 13:58:11 +00001626 /// Compare the priority of this object and B.
1627 ///
1628 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001629 virtual bool
1630 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001631 return Kind < B.Kind;
1632 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001633};
1634
Daniel Sanders2c269f62017-08-24 09:11:20 +00001635template <>
1636std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001637PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001638 return "No instruction predicates";
1639}
1640
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001641/// Generates code to check the opcode of an instruction.
1642class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1643protected:
1644 const CodeGenInstruction *I;
1645
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001646 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1647
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001648public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001649 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1650 OpcodeValues.clear();
1651
1652 unsigned OpcodeValue = 0;
1653 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1654 OpcodeValues[I] = OpcodeValue++;
1655 }
1656
Quentin Colombetaad20be2017-12-15 23:07:42 +00001657 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1658 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001659
Quentin Colombet063d7982017-12-14 23:44:07 +00001660 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001661 return P->getKind() == IPM_Opcode;
1662 }
1663
Quentin Colombet893e0f12017-12-15 23:24:39 +00001664 bool isIdentical(const PredicateMatcher &B) const override {
1665 return InstructionPredicateMatcher::isIdentical(B) &&
1666 I == cast<InstructionOpcodeMatcher>(&B)->I;
1667 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001668 MatchTableRecord getValue() const override {
1669 const auto VI = OpcodeValues.find(I);
1670 if (VI != OpcodeValues.end())
1671 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1672 VI->second);
1673 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1674 }
1675 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001676
Quentin Colombetaad20be2017-12-15 23:07:42 +00001677 void emitPredicateOpcodes(MatchTable &Table,
1678 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001679 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001680 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001681 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001682 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001683
1684 /// Compare the priority of this object and B.
1685 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001686 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001687 bool
1688 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001689 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1690 return true;
1691 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1692 return false;
1693
1694 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1695 // this is cosmetic at the moment, we may want to drive a similar ordering
1696 // using instruction frequency information to improve compile time.
1697 if (const InstructionOpcodeMatcher *BO =
1698 dyn_cast<InstructionOpcodeMatcher>(&B))
1699 return I->TheDef->getName() < BO->I->TheDef->getName();
1700
1701 return false;
1702 };
Daniel Sanders05540042017-08-08 10:44:31 +00001703
1704 bool isConstantInstruction() const {
1705 return I->TheDef->getName() == "G_CONSTANT";
1706 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001707
Roman Tereshin19da6672018-05-22 04:31:50 +00001708 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshin6082a062019-10-30 20:58:46 -07001709 bool isVariadicNumOperands() const { return I->Operands.isVariadic; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001710
1711 StringRef getOperandType(unsigned OpIdx) const {
1712 return I->Operands[OpIdx].OperandType;
1713 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001714};
1715
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001716DenseMap<const CodeGenInstruction *, unsigned>
1717 InstructionOpcodeMatcher::OpcodeValues;
1718
Roman Tereshin19da6672018-05-22 04:31:50 +00001719class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1720 unsigned NumOperands = 0;
1721
1722public:
1723 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1724 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1725 NumOperands(NumOperands) {}
1726
1727 static bool classof(const PredicateMatcher *P) {
1728 return P->getKind() == IPM_NumOperands;
1729 }
1730
1731 bool isIdentical(const PredicateMatcher &B) const override {
1732 return InstructionPredicateMatcher::isIdentical(B) &&
1733 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1734 }
1735
1736 void emitPredicateOpcodes(MatchTable &Table,
1737 RuleMatcher &Rule) const override {
1738 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1739 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1740 << MatchTable::Comment("Expected")
1741 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1742 }
1743};
1744
Daniel Sanders2c269f62017-08-24 09:11:20 +00001745/// Generates code to check that this instruction is a constant whose value
1746/// meets an immediate predicate.
1747///
1748/// Immediates are slightly odd since they are typically used like an operand
1749/// but are represented as an operator internally. We typically write simm8:$src
1750/// in a tablegen pattern, but this is just syntactic sugar for
1751/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1752/// that will be matched and the predicate (which is attached to the imm
1753/// operator) that will be tested. In SelectionDAG this describes a
1754/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1755///
1756/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1757/// this representation, the immediate could be tested with an
1758/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1759/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1760/// there are two implementation issues with producing that matcher
1761/// configuration from the SelectionDAG pattern:
1762/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1763/// were we to sink the immediate predicate to the operand we would have to
1764/// have two partial implementations of PatFrag support, one for immediates
1765/// and one for non-immediates.
1766/// * At the point we handle the predicate, the OperandMatcher hasn't been
1767/// created yet. If we were to sink the predicate to the OperandMatcher we
1768/// would also have to complicate (or duplicate) the code that descends and
1769/// creates matchers for the subtree.
1770/// Overall, it's simpler to handle it in the place it was found.
1771class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1772protected:
1773 TreePredicateFn Predicate;
1774
1775public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001776 InstructionImmPredicateMatcher(unsigned InsnVarID,
1777 const TreePredicateFn &Predicate)
1778 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1779 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001780
Quentin Colombet893e0f12017-12-15 23:24:39 +00001781 bool isIdentical(const PredicateMatcher &B) const override {
1782 return InstructionPredicateMatcher::isIdentical(B) &&
1783 Predicate.getOrigPatFragRecord() ==
1784 cast<InstructionImmPredicateMatcher>(&B)
1785 ->Predicate.getOrigPatFragRecord();
1786 }
1787
Quentin Colombet063d7982017-12-14 23:44:07 +00001788 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001789 return P->getKind() == IPM_ImmPredicate;
1790 }
1791
Quentin Colombetaad20be2017-12-15 23:07:42 +00001792 void emitPredicateOpcodes(MatchTable &Table,
1793 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001794 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001795 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1796 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001797 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001798 << MatchTable::LineBreak;
1799 }
1800};
1801
Daniel Sanders76664652017-11-28 22:07:05 +00001802/// Generates code to check that a memory instruction has a atomic ordering
1803/// MachineMemoryOperand.
1804class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001805public:
1806 enum AOComparator {
1807 AO_Exactly,
1808 AO_OrStronger,
1809 AO_WeakerThan,
1810 };
1811
1812protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001813 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001814 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001815
Daniel Sanders39690bd2017-10-15 02:41:12 +00001816public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001817 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001818 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001819 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1820 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001821
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001822 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001823 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001824 }
1825
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001826 bool isIdentical(const PredicateMatcher &B) const override {
1827 if (!InstructionPredicateMatcher::isIdentical(B))
1828 return false;
1829 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1830 return Order == R.Order && Comparator == R.Comparator;
1831 }
1832
Quentin Colombetaad20be2017-12-15 23:07:42 +00001833 void emitPredicateOpcodes(MatchTable &Table,
1834 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001835 StringRef Opcode = "GIM_CheckAtomicOrdering";
1836
1837 if (Comparator == AO_OrStronger)
1838 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1839 if (Comparator == AO_WeakerThan)
1840 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1841
1842 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1843 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001844 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001845 << MatchTable::LineBreak;
1846 }
1847};
1848
Daniel Sandersf84bc372018-05-05 20:53:24 +00001849/// Generates code to check that the size of an MMO is exactly N bytes.
1850class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1851protected:
1852 unsigned MMOIdx;
1853 uint64_t Size;
1854
1855public:
1856 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1857 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1858 MMOIdx(MMOIdx), Size(Size) {}
1859
1860 static bool classof(const PredicateMatcher *P) {
1861 return P->getKind() == IPM_MemoryLLTSize;
1862 }
1863 bool isIdentical(const PredicateMatcher &B) const override {
1864 return InstructionPredicateMatcher::isIdentical(B) &&
1865 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1866 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1867 }
1868
1869 void emitPredicateOpcodes(MatchTable &Table,
1870 RuleMatcher &Rule) const override {
1871 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1872 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1873 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1874 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1875 << MatchTable::LineBreak;
1876 }
1877};
1878
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001879class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1880protected:
1881 unsigned MMOIdx;
1882 SmallVector<unsigned, 4> AddrSpaces;
1883
1884public:
1885 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1886 ArrayRef<unsigned> AddrSpaces)
1887 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1888 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1889
1890 static bool classof(const PredicateMatcher *P) {
1891 return P->getKind() == IPM_MemoryAddressSpace;
1892 }
1893 bool isIdentical(const PredicateMatcher &B) const override {
1894 if (!InstructionPredicateMatcher::isIdentical(B))
1895 return false;
1896 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1897 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1898 }
1899
1900 void emitPredicateOpcodes(MatchTable &Table,
1901 RuleMatcher &Rule) const override {
1902 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1903 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1904 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1905 // Encode number of address spaces to expect.
1906 << MatchTable::Comment("NumAddrSpace")
1907 << MatchTable::IntValue(AddrSpaces.size());
1908 for (unsigned AS : AddrSpaces)
1909 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1910
1911 Table << MatchTable::LineBreak;
1912 }
1913};
1914
Matt Arsenault52c26242019-07-31 00:14:43 +00001915class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1916protected:
1917 unsigned MMOIdx;
1918 int MinAlign;
1919
1920public:
1921 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1922 int MinAlign)
1923 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1924 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1925 assert(MinAlign > 0);
1926 }
1927
1928 static bool classof(const PredicateMatcher *P) {
1929 return P->getKind() == IPM_MemoryAlignment;
1930 }
1931
1932 bool isIdentical(const PredicateMatcher &B) const override {
1933 if (!InstructionPredicateMatcher::isIdentical(B))
1934 return false;
1935 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1936 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1937 }
1938
1939 void emitPredicateOpcodes(MatchTable &Table,
1940 RuleMatcher &Rule) const override {
1941 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1942 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1943 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1944 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1945 << MatchTable::LineBreak;
1946 }
1947};
1948
Daniel Sandersf84bc372018-05-05 20:53:24 +00001949/// Generates code to check that the size of an MMO is less-than, equal-to, or
1950/// greater than a given LLT.
1951class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1952public:
1953 enum RelationKind {
1954 GreaterThan,
1955 EqualTo,
1956 LessThan,
1957 };
1958
1959protected:
1960 unsigned MMOIdx;
1961 RelationKind Relation;
1962 unsigned OpIdx;
1963
1964public:
1965 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1966 enum RelationKind Relation,
1967 unsigned OpIdx)
1968 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1969 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1970
1971 static bool classof(const PredicateMatcher *P) {
1972 return P->getKind() == IPM_MemoryVsLLTSize;
1973 }
1974 bool isIdentical(const PredicateMatcher &B) const override {
1975 return InstructionPredicateMatcher::isIdentical(B) &&
1976 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1977 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1978 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1979 }
1980
1981 void emitPredicateOpcodes(MatchTable &Table,
1982 RuleMatcher &Rule) const override {
1983 Table << MatchTable::Opcode(Relation == EqualTo
1984 ? "GIM_CheckMemorySizeEqualToLLT"
1985 : Relation == GreaterThan
1986 ? "GIM_CheckMemorySizeGreaterThanLLT"
1987 : "GIM_CheckMemorySizeLessThanLLT")
1988 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1989 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1990 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1991 << MatchTable::LineBreak;
1992 }
1993};
1994
Daniel Sanders8ead1292018-06-15 23:13:43 +00001995/// Generates code to check an arbitrary C++ instruction predicate.
1996class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1997protected:
1998 TreePredicateFn Predicate;
1999
2000public:
2001 GenericInstructionPredicateMatcher(unsigned InsnVarID,
2002 TreePredicateFn Predicate)
2003 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2004 Predicate(Predicate) {}
2005
2006 static bool classof(const InstructionPredicateMatcher *P) {
2007 return P->getKind() == IPM_GenericPredicate;
2008 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00002009 bool isIdentical(const PredicateMatcher &B) const override {
2010 return InstructionPredicateMatcher::isIdentical(B) &&
2011 Predicate ==
2012 static_cast<const GenericInstructionPredicateMatcher &>(B)
2013 .Predicate;
2014 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00002015 void emitPredicateOpcodes(MatchTable &Table,
2016 RuleMatcher &Rule) const override {
2017 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2018 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2019 << MatchTable::Comment("FnId")
2020 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2021 << MatchTable::LineBreak;
2022 }
2023};
2024
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002025/// Generates code to check that a set of predicates and operands match for a
2026/// particular instruction.
2027///
2028/// Typical predicates include:
2029/// * Has a specific opcode.
2030/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002031class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002032protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002033 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002034
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002035 RuleMatcher &Rule;
2036
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002037 /// The operands to match. All rendered operands must be present even if the
2038 /// condition is always true.
2039 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002040 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002041
Daniel Sanders05540042017-08-08 10:44:31 +00002042 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002043 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002044
Matt Arsenault3e45c702019-09-06 20:32:37 +00002045 /// PhysRegInputs - List list has an entry for each explicitly specified
2046 /// physreg input to the pattern. The first elt is the Register node, the
2047 /// second is the recorded slot number the input pattern match saved it in.
2048 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2049
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002050public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002051 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002052 : Rule(Rule), SymbolicName(SymbolicName) {
2053 // We create a new instruction matcher.
2054 // Get a new ID for that instruction.
2055 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2056 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002057
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002058 /// Construct a new instruction predicate and add it to the matcher.
2059 template <class Kind, class... Args>
2060 Optional<Kind *> addPredicate(Args &&... args) {
2061 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002062 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002063 return static_cast<Kind *>(Predicates.back().get());
2064 }
2065
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002066 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002067
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002068 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002069
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002070 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002071 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2072 unsigned AllocatedTemporariesBaseID) {
2073 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2074 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002075 if (!SymbolicName.empty())
2076 Rule.defineOperand(SymbolicName, *Operands.back());
2077
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002078 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002079 }
2080
Daniel Sandersffc7d582017-03-29 15:37:18 +00002081 OperandMatcher &getOperand(unsigned OpIdx) {
2082 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002083 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002084 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002085 });
2086 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002087 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002088 llvm_unreachable("Failed to lookup operand");
2089 }
2090
Matt Arsenault3e45c702019-09-06 20:32:37 +00002091 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2092 unsigned TempOpIdx) {
2093 assert(SymbolicName.empty());
2094 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2095 Operands.emplace_back(OM);
2096 Rule.definePhysRegOperand(Reg, *OM);
2097 PhysRegInputs.emplace_back(Reg, OpIdx);
2098 return *OM;
2099 }
2100
2101 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2102 return PhysRegInputs;
2103 }
2104
Daniel Sanders05540042017-08-08 10:44:31 +00002105 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002106 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002107 OperandVec::iterator operands_begin() { return Operands.begin(); }
2108 OperandVec::iterator operands_end() { return Operands.end(); }
2109 iterator_range<OperandVec::iterator> operands() {
2110 return make_range(operands_begin(), operands_end());
2111 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002112 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2113 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002114 iterator_range<OperandVec::const_iterator> operands() const {
2115 return make_range(operands_begin(), operands_end());
2116 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002117 bool operands_empty() const { return Operands.empty(); }
2118
2119 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002120
Roman Tereshin19da6672018-05-22 04:31:50 +00002121 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002122
2123 /// Emit MatchTable opcodes that test whether the instruction named in
2124 /// InsnVarName matches all the predicates and all the operands.
2125 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002126 if (NumOperandsCheck)
2127 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2128 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002129
Quentin Colombetaad20be2017-12-15 23:07:42 +00002130 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002131
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002132 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002133 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002134 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002135
2136 /// Compare the priority of this object and B.
2137 ///
2138 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002139 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002140 // Instruction matchers involving more operands have higher priority.
2141 if (Operands.size() > B.Operands.size())
2142 return true;
2143 if (Operands.size() < B.Operands.size())
2144 return false;
2145
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002146 for (auto &&P : zip(predicates(), B.predicates())) {
2147 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2148 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2149 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002150 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002151 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002152 return false;
2153 }
2154
Mark de Wevere8d448e2019-12-22 18:58:32 +01002155 for (auto Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002156 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002157 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002158 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002159 return false;
2160 }
2161
2162 return false;
2163 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002164
2165 /// Report the maximum number of temporary operands needed by the instruction
2166 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002167 unsigned countRendererFns() {
2168 return std::accumulate(
2169 predicates().begin(), predicates().end(), 0,
2170 [](unsigned A,
2171 const std::unique_ptr<PredicateMatcher> &Predicate) {
2172 return A + Predicate->countRendererFns();
2173 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002174 std::accumulate(
2175 Operands.begin(), Operands.end(), 0,
2176 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002177 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002178 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002179 }
Daniel Sanders05540042017-08-08 10:44:31 +00002180
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002181 InstructionOpcodeMatcher &getOpcodeMatcher() {
2182 for (auto &P : predicates())
2183 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2184 return *OpMatcher;
2185 llvm_unreachable("Didn't find an opcode matcher");
2186 }
2187
2188 bool isConstantInstruction() {
2189 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002190 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002191
2192 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002193};
2194
Roman Tereshin19da6672018-05-22 04:31:50 +00002195StringRef RuleMatcher::getOpcode() const {
2196 return Matchers.front()->getOpcode();
2197}
2198
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002199unsigned RuleMatcher::getNumOperands() const {
2200 return Matchers.front()->getNumOperands();
2201}
2202
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002203LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2204 InstructionMatcher &InsnMatcher = *Matchers.front();
2205 if (!InsnMatcher.predicates_empty())
2206 if (const auto *TM =
2207 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2208 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2209 return TM->getTy();
2210 return {};
2211}
2212
Daniel Sandersbee57392017-04-04 13:25:23 +00002213/// Generates code to check that the operand is a register defined by an
2214/// instruction that matches the given instruction matcher.
2215///
2216/// For example, the pattern:
2217/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2218/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2219/// the:
2220/// (G_ADD $src1, $src2)
2221/// subpattern.
2222class InstructionOperandMatcher : public OperandPredicateMatcher {
2223protected:
2224 std::unique_ptr<InstructionMatcher> InsnMatcher;
2225
2226public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002227 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2228 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002229 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002230 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002231
Quentin Colombet063d7982017-12-14 23:44:07 +00002232 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002233 return P->getKind() == OPM_Instruction;
2234 }
2235
2236 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2237
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002238 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2239 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2240 Table << MatchTable::Opcode("GIM_RecordInsn")
2241 << MatchTable::Comment("DefineMI")
2242 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2243 << MatchTable::IntValue(getInsnVarID())
2244 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2245 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2246 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002247 }
2248
Quentin Colombetaad20be2017-12-15 23:07:42 +00002249 void emitPredicateOpcodes(MatchTable &Table,
2250 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002251 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002252 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002253 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002254
2255 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2256 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2257 return true;
2258 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2259 return false;
2260
2261 if (const InstructionOperandMatcher *BP =
2262 dyn_cast<InstructionOperandMatcher>(&B))
2263 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2264 return true;
2265 return false;
2266 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002267};
2268
Roman Tereshin19da6672018-05-22 04:31:50 +00002269void InstructionMatcher::optimize() {
2270 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2271 const auto &OpcMatcher = getOpcodeMatcher();
2272
2273 Stash.push_back(predicates_pop_front());
2274 if (Stash.back().get() == &OpcMatcher) {
Roman Tereshin6082a062019-10-30 20:58:46 -07002275 if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
Roman Tereshin19da6672018-05-22 04:31:50 +00002276 Stash.emplace_back(
2277 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2278 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002279
2280 for (auto &OM : Operands)
2281 for (auto &OP : OM->predicates())
2282 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2283 Stash.push_back(std::move(OP));
2284 OM->eraseNullPredicates();
2285 break;
2286 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002287 }
2288
2289 if (InsnVarID > 0) {
2290 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2291 for (auto &OP : Operands[0]->predicates())
2292 OP.reset();
2293 Operands[0]->eraseNullPredicates();
2294 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002295 for (auto &OM : Operands) {
2296 for (auto &OP : OM->predicates())
2297 if (isa<LLTOperandMatcher>(OP))
2298 Stash.push_back(std::move(OP));
2299 OM->eraseNullPredicates();
2300 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002301 while (!Stash.empty())
2302 prependPredicate(Stash.pop_back_val());
2303}
2304
Daniel Sanders43c882c2017-02-01 10:53:10 +00002305//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002306class OperandRenderer {
2307public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002308 enum RendererKind {
2309 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002310 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002311 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002312 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002313 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002314 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002315 OR_Imm,
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002316 OR_SubRegIndex,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002317 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002318 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002319 OR_ComplexPattern,
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002320 OR_Custom,
2321 OR_CustomOperand
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002322 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002323
2324protected:
2325 RendererKind Kind;
2326
2327public:
2328 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2329 virtual ~OperandRenderer() {}
2330
2331 RendererKind getKind() const { return Kind; }
2332
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002333 virtual void emitRenderOpcodes(MatchTable &Table,
2334 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002335};
2336
2337/// A CopyRenderer emits code to copy a single operand from an existing
2338/// instruction to the one being built.
2339class CopyRenderer : public OperandRenderer {
2340protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002341 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002342 /// The name of the operand.
2343 const StringRef SymbolicName;
2344
2345public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002346 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2347 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002348 SymbolicName(SymbolicName) {
2349 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2350 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002351
2352 static bool classof(const OperandRenderer *R) {
2353 return R->getKind() == OR_Copy;
2354 }
2355
2356 const StringRef getSymbolicName() const { return SymbolicName; }
2357
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002358 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002359 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002360 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002361 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2362 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2363 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002364 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002365 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002366 }
2367};
2368
Matt Arsenault3e45c702019-09-06 20:32:37 +00002369/// A CopyRenderer emits code to copy a virtual register to a specific physical
2370/// register.
2371class CopyPhysRegRenderer : public OperandRenderer {
2372protected:
2373 unsigned NewInsnID;
2374 Record *PhysReg;
2375
2376public:
2377 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2378 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2379 PhysReg(Reg) {
2380 assert(PhysReg);
2381 }
2382
2383 static bool classof(const OperandRenderer *R) {
2384 return R->getKind() == OR_CopyPhysReg;
2385 }
2386
2387 Record *getPhysReg() const { return PhysReg; }
2388
2389 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2390 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2391 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2392 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2393 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2394 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2395 << MatchTable::IntValue(Operand.getOpIdx())
2396 << MatchTable::Comment(PhysReg->getName())
2397 << MatchTable::LineBreak;
2398 }
2399};
2400
Daniel Sandersd66e0902017-10-23 18:19:24 +00002401/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2402/// existing instruction to the one being built. If the operand turns out to be
2403/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2404class CopyOrAddZeroRegRenderer : public OperandRenderer {
2405protected:
2406 unsigned NewInsnID;
2407 /// The name of the operand.
2408 const StringRef SymbolicName;
2409 const Record *ZeroRegisterDef;
2410
2411public:
2412 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002413 StringRef SymbolicName, Record *ZeroRegisterDef)
2414 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2415 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2416 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2417 }
2418
2419 static bool classof(const OperandRenderer *R) {
2420 return R->getKind() == OR_CopyOrAddZeroReg;
2421 }
2422
2423 const StringRef getSymbolicName() const { return SymbolicName; }
2424
2425 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2426 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2427 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2428 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2429 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2430 << MatchTable::Comment("OldInsnID")
2431 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002432 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002433 << MatchTable::NamedValue(
2434 (ZeroRegisterDef->getValue("Namespace")
2435 ? ZeroRegisterDef->getValueAsString("Namespace")
2436 : ""),
2437 ZeroRegisterDef->getName())
2438 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2439 }
2440};
2441
Daniel Sanders05540042017-08-08 10:44:31 +00002442/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2443/// an extended immediate operand.
2444class CopyConstantAsImmRenderer : public OperandRenderer {
2445protected:
2446 unsigned NewInsnID;
2447 /// The name of the operand.
2448 const std::string SymbolicName;
2449 bool Signed;
2450
2451public:
2452 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2453 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2454 SymbolicName(SymbolicName), Signed(true) {}
2455
2456 static bool classof(const OperandRenderer *R) {
2457 return R->getKind() == OR_CopyConstantAsImm;
2458 }
2459
2460 const StringRef getSymbolicName() const { return SymbolicName; }
2461
2462 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002463 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002464 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2465 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2466 : "GIR_CopyConstantAsUImm")
2467 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2468 << MatchTable::Comment("OldInsnID")
2469 << MatchTable::IntValue(OldInsnVarID)
2470 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2471 }
2472};
2473
Daniel Sanders11300ce2017-10-13 21:28:03 +00002474/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2475/// instruction to an extended immediate operand.
2476class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2477protected:
2478 unsigned NewInsnID;
2479 /// The name of the operand.
2480 const std::string SymbolicName;
2481
2482public:
2483 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2484 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2485 SymbolicName(SymbolicName) {}
2486
2487 static bool classof(const OperandRenderer *R) {
2488 return R->getKind() == OR_CopyFConstantAsFPImm;
2489 }
2490
2491 const StringRef getSymbolicName() const { return SymbolicName; }
2492
2493 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002494 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002495 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2496 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2497 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2498 << MatchTable::Comment("OldInsnID")
2499 << MatchTable::IntValue(OldInsnVarID)
2500 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2501 }
2502};
2503
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002504/// A CopySubRegRenderer emits code to copy a single register operand from an
2505/// existing instruction to the one being built and indicate that only a
2506/// subregister should be copied.
2507class CopySubRegRenderer : public OperandRenderer {
2508protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002509 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002510 /// The name of the operand.
2511 const StringRef SymbolicName;
2512 /// The subregister to extract.
2513 const CodeGenSubRegIndex *SubReg;
2514
2515public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002516 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2517 const CodeGenSubRegIndex *SubReg)
2518 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002519 SymbolicName(SymbolicName), SubReg(SubReg) {}
2520
2521 static bool classof(const OperandRenderer *R) {
2522 return R->getKind() == OR_CopySubReg;
2523 }
2524
2525 const StringRef getSymbolicName() const { return SymbolicName; }
2526
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002527 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002528 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002529 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002530 Table << MatchTable::Opcode("GIR_CopySubReg")
2531 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2532 << MatchTable::Comment("OldInsnID")
2533 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002534 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002535 << MatchTable::Comment("SubRegIdx")
2536 << MatchTable::IntValue(SubReg->EnumValue)
2537 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002538 }
2539};
2540
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002541/// Adds a specific physical register to the instruction being built.
2542/// This is typically useful for WZR/XZR on AArch64.
2543class AddRegisterRenderer : public OperandRenderer {
2544protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002545 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002546 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002547 bool IsDef;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002548
2549public:
Matt Arsenault3e45c702019-09-06 20:32:37 +00002550 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2551 bool IsDef = false)
2552 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2553 IsDef(IsDef) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002554
2555 static bool classof(const OperandRenderer *R) {
2556 return R->getKind() == OR_Register;
2557 }
2558
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002559 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2560 Table << MatchTable::Opcode("GIR_AddRegister")
2561 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2562 << MatchTable::NamedValue(
2563 (RegisterDef->getValue("Namespace")
2564 ? RegisterDef->getValueAsString("Namespace")
2565 : ""),
2566 RegisterDef->getName())
Matt Arsenault3e45c702019-09-06 20:32:37 +00002567 << MatchTable::Comment("AddRegisterRegFlags");
2568
2569 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2570 // really needed for a physical register reference. We can pack the
2571 // register and flags in a single field.
2572 if (IsDef)
2573 Table << MatchTable::NamedValue("RegState::Define");
2574 else
2575 Table << MatchTable::IntValue(0);
2576 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002577 }
2578};
2579
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002580/// Adds a specific temporary virtual register to the instruction being built.
2581/// This is used to chain instructions together when emitting multiple
2582/// instructions.
2583class TempRegRenderer : public OperandRenderer {
2584protected:
2585 unsigned InsnID;
2586 unsigned TempRegID;
Matt Arsenault9c346462020-01-14 16:02:02 -05002587 const CodeGenSubRegIndex *SubRegIdx;
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002588 bool IsDef;
2589
2590public:
Matt Arsenault9c346462020-01-14 16:02:02 -05002591 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
2592 const CodeGenSubRegIndex *SubReg = nullptr)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002593 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
Matt Arsenault9c346462020-01-14 16:02:02 -05002594 SubRegIdx(SubReg), IsDef(IsDef) {}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002595
2596 static bool classof(const OperandRenderer *R) {
2597 return R->getKind() == OR_TempRegister;
2598 }
2599
2600 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Matt Arsenault9c346462020-01-14 16:02:02 -05002601 if (SubRegIdx) {
2602 assert(!IsDef);
2603 Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2604 } else
2605 Table << MatchTable::Opcode("GIR_AddTempRegister");
2606
2607 Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002608 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2609 << MatchTable::Comment("TempRegFlags");
Matt Arsenault9c346462020-01-14 16:02:02 -05002610
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002611 if (IsDef)
2612 Table << MatchTable::NamedValue("RegState::Define");
2613 else
2614 Table << MatchTable::IntValue(0);
Matt Arsenault9c346462020-01-14 16:02:02 -05002615
2616 if (SubRegIdx)
2617 Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002618 Table << MatchTable::LineBreak;
2619 }
2620};
2621
Daniel Sanders0ed28822017-04-12 08:23:08 +00002622/// Adds a specific immediate to the instruction being built.
2623class ImmRenderer : public OperandRenderer {
2624protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002625 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002626 int64_t Imm;
2627
2628public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002629 ImmRenderer(unsigned InsnID, int64_t Imm)
2630 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002631
2632 static bool classof(const OperandRenderer *R) {
2633 return R->getKind() == OR_Imm;
2634 }
2635
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002636 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2637 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2638 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2639 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002640 }
2641};
2642
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002643/// Adds an enum value for a subreg index to the instruction being built.
2644class SubRegIndexRenderer : public OperandRenderer {
2645protected:
2646 unsigned InsnID;
2647 const CodeGenSubRegIndex *SubRegIdx;
2648
2649public:
2650 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2651 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2652
2653 static bool classof(const OperandRenderer *R) {
2654 return R->getKind() == OR_SubRegIndex;
2655 }
2656
2657 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2658 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2659 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2660 << MatchTable::IntValue(SubRegIdx->EnumValue)
2661 << MatchTable::LineBreak;
2662 }
2663};
2664
Daniel Sanders2deea182017-04-22 15:11:04 +00002665/// Adds operands by calling a renderer function supplied by the ComplexPattern
2666/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002667class RenderComplexPatternOperand : public OperandRenderer {
2668private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002669 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002670 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002671 /// The name of the operand.
2672 const StringRef SymbolicName;
2673 /// The renderer number. This must be unique within a rule since it's used to
2674 /// identify a temporary variable to hold the renderer function.
2675 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002676 /// When provided, this is the suboperand of the ComplexPattern operand to
2677 /// render. Otherwise all the suboperands will be rendered.
2678 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002679
2680 unsigned getNumOperands() const {
2681 return TheDef.getValueAsDag("Operands")->getNumArgs();
2682 }
2683
2684public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002685 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002686 StringRef SymbolicName, unsigned RendererID,
2687 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002688 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002689 SymbolicName(SymbolicName), RendererID(RendererID),
2690 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002691
2692 static bool classof(const OperandRenderer *R) {
2693 return R->getKind() == OR_ComplexPattern;
2694 }
2695
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002696 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002697 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2698 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002699 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2700 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002701 << MatchTable::IntValue(RendererID);
2702 if (SubOperand.hasValue())
2703 Table << MatchTable::Comment("SubOperand")
2704 << MatchTable::IntValue(SubOperand.getValue());
2705 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002706 }
2707};
2708
Volkan Kelesf7f25682018-01-16 18:44:05 +00002709class CustomRenderer : public OperandRenderer {
2710protected:
2711 unsigned InsnID;
2712 const Record &Renderer;
2713 /// The name of the operand.
2714 const std::string SymbolicName;
2715
2716public:
2717 CustomRenderer(unsigned InsnID, const Record &Renderer,
2718 StringRef SymbolicName)
2719 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2720 SymbolicName(SymbolicName) {}
2721
2722 static bool classof(const OperandRenderer *R) {
2723 return R->getKind() == OR_Custom;
2724 }
2725
2726 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002727 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002728 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2729 Table << MatchTable::Opcode("GIR_CustomRenderer")
2730 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2731 << MatchTable::Comment("OldInsnID")
2732 << MatchTable::IntValue(OldInsnVarID)
2733 << MatchTable::Comment("Renderer")
2734 << MatchTable::NamedValue(
2735 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2736 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2737 }
2738};
2739
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002740class CustomOperandRenderer : public OperandRenderer {
2741protected:
2742 unsigned InsnID;
2743 const Record &Renderer;
2744 /// The name of the operand.
2745 const std::string SymbolicName;
2746
2747public:
2748 CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2749 StringRef SymbolicName)
2750 : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2751 SymbolicName(SymbolicName) {}
2752
2753 static bool classof(const OperandRenderer *R) {
2754 return R->getKind() == OR_CustomOperand;
2755 }
2756
2757 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2758 const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2759 Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2760 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2761 << MatchTable::Comment("OldInsnID")
2762 << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2763 << MatchTable::Comment("OpIdx")
2764 << MatchTable::IntValue(OpdMatcher.getOpIdx())
2765 << MatchTable::Comment("OperandRenderer")
2766 << MatchTable::NamedValue(
2767 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2768 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2769 }
2770};
2771
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002772/// An action taken when all Matcher predicates succeeded for a parent rule.
2773///
2774/// Typical actions include:
2775/// * Changing the opcode of an instruction.
2776/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002777class MatchAction {
2778public:
2779 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002780
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002781 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002782 virtual void emitActionOpcodes(MatchTable &Table,
2783 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002784};
2785
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002786/// Generates a comment describing the matched rule being acted upon.
2787class DebugCommentAction : public MatchAction {
2788private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002789 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002790
2791public:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002792 DebugCommentAction(StringRef S) : S(std::string(S)) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002793
Daniel Sandersa7b75262017-10-31 18:50:24 +00002794 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002795 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002796 }
2797};
2798
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002799/// Generates code to build an instruction or mutate an existing instruction
2800/// into the desired instruction when this is possible.
2801class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002802private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002803 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002804 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002805 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002806 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2807
2808 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002809 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2810 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002811 return false;
2812
Daniel Sandersa7b75262017-10-31 18:50:24 +00002813 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002814 return false;
2815
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002816 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002817 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002818 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002819 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002820 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002821 return false;
2822 } else
2823 return false;
2824 }
2825
2826 return true;
2827 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002828
Daniel Sanders43c882c2017-02-01 10:53:10 +00002829public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002830 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2831 : InsnID(InsnID), I(I), Matched(nullptr) {}
2832
Daniel Sanders08464522018-01-29 21:09:12 +00002833 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002834 const CodeGenInstruction *getCGI() const { return I; }
2835
Daniel Sandersa7b75262017-10-31 18:50:24 +00002836 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002837 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002838 if (canMutate(Rule, MutateCandidate)) {
2839 // Take the first one we're offered that we're able to mutate.
2840 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2841 Matched = MutateCandidate;
2842 return;
2843 }
2844 }
2845 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002846
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002847 template <class Kind, class... Args>
2848 Kind &addRenderer(Args&&... args) {
2849 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002850 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002851 return *static_cast<Kind *>(OperandRenderers.back().get());
2852 }
2853
Daniel Sandersa7b75262017-10-31 18:50:24 +00002854 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2855 if (Matched) {
2856 assert(canMutate(Rule, Matched) &&
2857 "Arranged to mutate an insn that isn't mutatable");
2858
2859 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002860 Table << MatchTable::Opcode("GIR_MutateOpcode")
2861 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2862 << MatchTable::Comment("RecycleInsnID")
2863 << MatchTable::IntValue(RecycleInsnID)
2864 << MatchTable::Comment("Opcode")
2865 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2866 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002867
2868 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002869 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002870 auto Namespace = Def->getValue("Namespace")
2871 ? Def->getValueAsString("Namespace")
2872 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002873 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2874 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2875 << MatchTable::NamedValue(Namespace, Def->getName())
2876 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002877 }
2878 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002879 auto Namespace = Use->getValue("Namespace")
2880 ? Use->getValueAsString("Namespace")
2881 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002882 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2883 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2884 << MatchTable::NamedValue(Namespace, Use->getName())
2885 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002886 }
2887 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002888 return;
2889 }
2890
2891 // TODO: Simple permutation looks like it could be almost as common as
2892 // mutation due to commutative operations.
2893
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002894 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2895 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2896 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2897 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002898 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002899 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002900
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002901 if (I->mayLoad || I->mayStore) {
2902 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2903 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2904 << MatchTable::Comment("MergeInsnID's");
2905 // Emit the ID's for all the instructions that are matched by this rule.
2906 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2907 // some other means of having a memoperand. Also limit this to
2908 // emitted instructions that expect to have a memoperand too. For
2909 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2910 // sign-extend instructions shouldn't put the memoperand on the
2911 // sign-extend since it has no effect there.
2912 std::vector<unsigned> MergeInsnIDs;
2913 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2914 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002915 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002916 for (const auto &MergeInsnID : MergeInsnIDs)
2917 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002918 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2919 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002920 }
2921
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002922 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2923 // better for combines. Particularly when there are multiple match
2924 // roots.
2925 if (InsnID == 0)
2926 Table << MatchTable::Opcode("GIR_EraseFromParent")
2927 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2928 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002929 }
2930};
2931
2932/// Generates code to constrain the operands of an output instruction to the
2933/// register classes specified by the definition of that instruction.
2934class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002935 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002936
2937public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002938 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002939
Daniel Sandersa7b75262017-10-31 18:50:24 +00002940 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002941 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2942 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2943 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002944 }
2945};
2946
2947/// Generates code to constrain the specified operand of an output instruction
2948/// to the specified register class.
2949class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002950 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002951 unsigned OpIdx;
2952 const CodeGenRegisterClass &RC;
2953
2954public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002955 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002956 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002957 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002958
Daniel Sandersa7b75262017-10-31 18:50:24 +00002959 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002960 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2961 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2962 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2963 << MatchTable::Comment("RC " + RC.getName())
2964 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002965 }
2966};
2967
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002968/// Generates code to create a temporary register which can be used to chain
2969/// instructions together.
2970class MakeTempRegisterAction : public MatchAction {
2971private:
2972 LLTCodeGen Ty;
2973 unsigned TempRegID;
2974
2975public:
2976 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002977 : Ty(Ty), TempRegID(TempRegID) {
2978 KnownTypes.insert(Ty);
2979 }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002980
2981 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2982 Table << MatchTable::Opcode("GIR_MakeTempReg")
2983 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2984 << MatchTable::Comment("TypeID")
2985 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2986 << MatchTable::LineBreak;
2987 }
2988};
2989
Daniel Sanders05540042017-08-08 10:44:31 +00002990InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002991 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002992 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002993 return *Matchers.back();
2994}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002995
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002996void RuleMatcher::addRequiredFeature(Record *Feature) {
2997 RequiredFeatures.push_back(Feature);
2998}
2999
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003000const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3001 return RequiredFeatures;
3002}
3003
Daniel Sanders7438b262017-10-31 23:03:18 +00003004// Emplaces an action of the specified Kind at the end of the action list.
3005//
3006// Returns a reference to the newly created action.
3007//
3008// Like std::vector::emplace_back(), may invalidate all iterators if the new
3009// size exceeds the capacity. Otherwise, only invalidates the past-the-end
3010// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003011template <class Kind, class... Args>
3012Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003013 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003014 return *static_cast<Kind *>(Actions.back().get());
3015}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003016
Daniel Sanders7438b262017-10-31 23:03:18 +00003017// Emplaces an action of the specified Kind before the given insertion point.
3018//
3019// Returns an iterator pointing at the newly created instruction.
3020//
3021// Like std::vector::insert(), may invalidate all iterators if the new size
3022// exceeds the capacity. Otherwise, only invalidates the iterators from the
3023// insertion point onwards.
3024template <class Kind, class... Args>
3025action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3026 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003027 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003028 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00003029}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003030
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003031unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003032 unsigned NewInsnVarID = NextInsnVarID++;
3033 InsnVariableIDs[&Matcher] = NewInsnVarID;
3034 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003035}
3036
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003037unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003038 const auto &I = InsnVariableIDs.find(&InsnMatcher);
3039 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003040 return I->second;
3041 llvm_unreachable("Matched Insn was not captured in a local variable");
3042}
3043
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003044void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3045 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3046 DefinedOperands[SymbolicName] = &OM;
3047 return;
3048 }
3049
3050 // If the operand is already defined, then we must ensure both references in
3051 // the matcher have the exact same node.
3052 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3053}
3054
Matt Arsenault3e45c702019-09-06 20:32:37 +00003055void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3056 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3057 PhysRegOperands[Reg] = &OM;
3058 return;
3059 }
3060}
3061
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003062InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00003063RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3064 for (const auto &I : InsnVariableIDs)
3065 if (I.first->getSymbolicName() == SymbolicName)
3066 return *I.first;
3067 llvm_unreachable(
3068 ("Failed to lookup instruction " + SymbolicName).str().c_str());
3069}
3070
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003071const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00003072RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3073 const auto &I = PhysRegOperands.find(Reg);
3074
3075 if (I == PhysRegOperands.end()) {
3076 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3077 " was not declared in matcher");
3078 }
3079
3080 return *I->second;
3081}
3082
3083const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003084RuleMatcher::getOperandMatcher(StringRef Name) const {
3085 const auto &I = DefinedOperands.find(Name);
3086
3087 if (I == DefinedOperands.end())
3088 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3089
3090 return *I->second;
3091}
3092
Daniel Sanders8e82af22017-07-27 11:03:45 +00003093void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003094 if (Matchers.empty())
3095 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003096
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003097 // The representation supports rules that require multiple roots such as:
3098 // %ptr(p0) = ...
3099 // %elt0(s32) = G_LOAD %ptr
3100 // %1(p0) = G_ADD %ptr, 4
3101 // %elt1(s32) = G_LOAD p0 %1
3102 // which could be usefully folded into:
3103 // %ptr(p0) = ...
3104 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3105 // on some targets but we don't need to make use of that yet.
3106 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003107
Daniel Sanders8e82af22017-07-27 11:03:45 +00003108 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003109 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003110 << MatchTable::Comment("On fail goto")
3111 << MatchTable::JumpTarget(LabelID)
3112 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003113 << MatchTable::LineBreak;
3114
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003115 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003116 Table << MatchTable::Opcode("GIM_CheckFeatures")
3117 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3118 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003119 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003120
Quentin Colombetaad20be2017-12-15 23:07:42 +00003121 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003122
Daniel Sandersbee57392017-04-04 13:25:23 +00003123 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003124 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003125 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003126 SmallVector<unsigned, 2> InsnIDs;
3127 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003128 // Skip the root node since it isn't moving anywhere. Everything else is
3129 // sinking to meet it.
3130 if (Pair.first == Matchers.front().get())
3131 continue;
3132
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003133 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003134 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003135 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003136
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003137 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003138 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003139 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3140 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3141 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003142
3143 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3144 // account for unsafe cases.
3145 //
3146 // Example:
3147 // MI1--> %0 = ...
3148 // %1 = ... %0
3149 // MI0--> %2 = ... %0
3150 // It's not safe to erase MI1. We currently handle this by not
3151 // erasing %0 (even when it's dead).
3152 //
3153 // Example:
3154 // MI1--> %0 = load volatile @a
3155 // %1 = load volatile @a
3156 // MI0--> %2 = ... %0
3157 // It's not safe to sink %0's def past %1. We currently handle
3158 // this by rejecting all loads.
3159 //
3160 // Example:
3161 // MI1--> %0 = load @a
3162 // %1 = store @a
3163 // MI0--> %2 = ... %0
3164 // It's not safe to sink %0's def past %1. We currently handle
3165 // this by rejecting all loads.
3166 //
3167 // Example:
3168 // G_CONDBR %cond, @BB1
3169 // BB0:
3170 // MI1--> %0 = load @a
3171 // G_BR @BB1
3172 // BB1:
3173 // MI0--> %2 = ... %0
3174 // It's not always safe to sink %0 across control flow. In this
3175 // case it may introduce a memory fault. We currentl handle this
3176 // by rejecting all loads.
3177 }
3178 }
3179
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003180 for (const auto &PM : EpilogueMatchers)
3181 PM->emitPredicateOpcodes(Table, *this);
3182
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003183 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003184 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003185
Roman Tereshinbeb39312018-05-02 20:15:11 +00003186 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003187 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3188 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003189 else
3190 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3191 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003192
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003193 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003194 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003195 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003196}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003197
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003198bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3199 // Rules involving more match roots have higher priority.
3200 if (Matchers.size() > B.Matchers.size())
3201 return true;
3202 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003203 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003204
Mark de Wevere8d448e2019-12-22 18:58:32 +01003205 for (auto Matcher : zip(Matchers, B.Matchers)) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003206 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3207 return true;
3208 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3209 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003210 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003211
3212 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003213}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003214
Daniel Sanders2deea182017-04-22 15:11:04 +00003215unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003216 return std::accumulate(
3217 Matchers.begin(), Matchers.end(), 0,
3218 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003219 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003220 });
3221}
3222
Daniel Sanders05540042017-08-08 10:44:31 +00003223bool OperandPredicateMatcher::isHigherPriorityThan(
3224 const OperandPredicateMatcher &B) const {
3225 // Generally speaking, an instruction is more important than an Int or a
3226 // LiteralInt because it can cover more nodes but theres an exception to
3227 // this. G_CONSTANT's are less important than either of those two because they
3228 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003229
3230 const InstructionOperandMatcher *AOM =
3231 dyn_cast<InstructionOperandMatcher>(this);
3232 const InstructionOperandMatcher *BOM =
3233 dyn_cast<InstructionOperandMatcher>(&B);
3234 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3235 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3236
3237 if (AOM && BOM) {
3238 // The relative priorities between a G_CONSTANT and any other instruction
3239 // don't actually matter but this code is needed to ensure a strict weak
3240 // ordering. This is particularly important on Windows where the rules will
3241 // be incorrectly sorted without it.
3242 if (AIsConstantInsn != BIsConstantInsn)
3243 return AIsConstantInsn < BIsConstantInsn;
3244 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003245 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003246
3247 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3248 return false;
3249 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3250 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003251
3252 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003253}
Daniel Sanders05540042017-08-08 10:44:31 +00003254
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003255void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003256 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003257 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003258 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003259 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003260
3261 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3262 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3263 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3264 << MatchTable::Comment("OtherMI")
3265 << MatchTable::IntValue(OtherInsnVarID)
3266 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003267 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003268 << MatchTable::LineBreak;
3269}
3270
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003271//===- GlobalISelEmitter class --------------------------------------------===//
3272
Matt Arsenault9c346462020-01-14 16:02:02 -05003273static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3274 ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3275 if (ChildTypes.size() != 1)
3276 return failedImport("Dst pattern child has multiple results");
3277
3278 Optional<LLTCodeGen> MaybeOpTy;
3279 if (ChildTypes.front().isMachineValueType()) {
3280 MaybeOpTy =
3281 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3282 }
3283
3284 if (!MaybeOpTy)
3285 return failedImport("Dst operand has an unsupported type");
3286 return *MaybeOpTy;
3287}
3288
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003289class GlobalISelEmitter {
3290public:
3291 explicit GlobalISelEmitter(RecordKeeper &RK);
3292 void run(raw_ostream &OS);
3293
3294private:
3295 const RecordKeeper &RK;
3296 const CodeGenDAGPatterns CGP;
3297 const CodeGenTarget &Target;
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003298 CodeGenRegBank &CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003299
Daniel Sanders39690bd2017-10-15 02:41:12 +00003300 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003301 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3302 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003303 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003304 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003305
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003306 /// Keep track of the equivalence between ComplexPattern's and
3307 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3308 /// GIComplexPatternEquiv.
3309 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3310
Volkan Kelesf7f25682018-01-16 18:44:05 +00003311 /// Keep track of the equivalence between SDNodeXForm's and
3312 /// GICustomOperandRenderer. Map entries are specified by subclassing
3313 /// GISDNodeXFormEquiv.
3314 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3315
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003316 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3317 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3318 DenseMap<uint64_t, int> RuleMatcherScores;
3319
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003320 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003321 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003322
Daniel Sandersf76f3152017-11-16 00:46:35 +00003323 // Rule coverage information.
3324 Optional<CodeGenCoverage> RuleCoverage;
3325
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003326 void gatherOpcodeValues();
3327 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003328 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003329
Daniel Sanders39690bd2017-10-15 02:41:12 +00003330 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003331 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003332 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003333
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003334 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003335 Expected<InstructionMatcher &>
3336 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3337 InstructionMatcher &InsnMatcher,
3338 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003339 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3340 unsigned &TempOpIdx) const;
3341 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003342 const TreePatternNode *SrcChild,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003343 bool OperandIsAPointer, bool OperandIsImmArg,
3344 unsigned OpIdx, unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003345
Matt Arsenault3e45c702019-09-06 20:32:37 +00003346 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3347 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3348 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003349 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003350 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003351 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003352 Expected<action_iterator>
3353 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003354 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003355 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003356
Daniel Sanders7438b262017-10-31 23:03:18 +00003357 Expected<action_iterator>
3358 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3359 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003360 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003361 Expected<action_iterator>
3362 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3363 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003364 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003365 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3366 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003367 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003368 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003369 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3370 const std::vector<Record *> &ImplicitDefs) const;
3371
Daniel Sanders8ead1292018-06-15 23:13:43 +00003372 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3373 StringRef TypeIdentifier, StringRef ArgType,
3374 StringRef ArgName, StringRef AdditionalDeclarations,
3375 std::function<bool(const Record *R)> Filter);
3376 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3377 StringRef ArgType,
3378 std::function<bool(const Record *R)> Filter);
3379 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003380
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003381 /// Analyze pattern \p P, returning a matcher for it if possible.
3382 /// Otherwise, return an Error explaining why we don't support it.
3383 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003384
3385 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003386
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003387 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3388 bool WithCoverage);
3389
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003390 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3391 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3392 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3393 /// If no register class is found, return None.
3394 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003395 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3396 TreePatternNode *SuperRegNode,
3397 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003398 Optional<CodeGenSubRegIndex *>
3399 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003400
3401 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3402 /// Return None if no such class exists.
3403 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003404 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003405 TreePatternNode *SubRegIdxNode);
3406
3407 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3408 Optional<const CodeGenRegisterClass *>
3409 getRegClassFromLeaf(TreePatternNode *Leaf);
3410
3411 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3412 /// otherwise.
3413 Optional<const CodeGenRegisterClass *>
3414 inferRegClassFromPattern(TreePatternNode *N);
3415
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003416public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003417 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003418 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003419 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003420 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003421 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003422 /// Output without optimization:
3423 /// \verbatim
3424 /// # R1
3425 /// # predicate A
3426 /// # predicate B
3427 /// ...
3428 /// # R2
3429 /// # predicate A // <-- effectively this is going to be checked twice.
3430 /// // Once in R1 and once in R2.
3431 /// # predicate C
3432 /// \endverbatim
3433 /// Output with optimization:
3434 /// \verbatim
3435 /// # Group1_2
3436 /// # predicate A // <-- Check is now shared.
3437 /// # R1
3438 /// # predicate B
3439 /// # R2
3440 /// # predicate C
3441 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003442 template <class GroupT>
3443 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003444 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003445 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003446};
3447
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003448void GlobalISelEmitter::gatherOpcodeValues() {
3449 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3450}
3451
3452void GlobalISelEmitter::gatherTypeIDValues() {
3453 LLTOperandMatcher::initTypeIDValuesMap();
3454}
3455
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003456void GlobalISelEmitter::gatherNodeEquivs() {
3457 assert(NodeEquivs.empty());
3458 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003459 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003460
3461 assert(ComplexPatternEquivs.empty());
3462 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3463 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3464 if (!SelDAGEquiv)
3465 continue;
3466 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3467 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003468
3469 assert(SDNodeXFormEquivs.empty());
3470 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3471 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3472 if (!SelDAGEquiv)
3473 continue;
3474 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3475 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003476}
3477
Daniel Sanders39690bd2017-10-15 02:41:12 +00003478Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003479 return NodeEquivs.lookup(N);
3480}
3481
Daniel Sandersf84bc372018-05-05 20:53:24 +00003482const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003483GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003484 if (N->getNumChildren() >= 1) {
3485 // setcc operation maps to two different G_* instructions based on the type.
3486 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3487 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3488 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3489 }
3490
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003491 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3492 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003493 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3494 Predicate.isSignExtLoad())
3495 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3496 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3497 Predicate.isZeroExtLoad())
3498 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3499 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003500
Daniel Sandersf84bc372018-05-05 20:53:24 +00003501 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3502}
3503
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003504GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003505 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003506 CGRegs(Target.getRegBank()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003507
3508//===- Emitter ------------------------------------------------------------===//
3509
Daniel Sandersc270c502017-03-30 09:36:33 +00003510Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003511GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003512 ArrayRef<Predicate> Predicates) {
3513 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003514 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003515 continue;
3516 declareSubtargetFeature(P.Def);
3517 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003518 }
3519
Daniel Sandersc270c502017-03-30 09:36:33 +00003520 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003521}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003522
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003523Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3524 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003525 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003526 Record *SrcGIEquivOrNull = nullptr;
3527 const CodeGenInstruction *SrcGIOrNull = nullptr;
3528
3529 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003530 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003531 return failedImport("Src pattern has multiple results");
3532
Florian Hahn6b1db822018-06-14 20:32:58 +00003533 if (Src->isLeaf()) {
3534 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003535 if (isa<IntInit>(SrcInit)) {
3536 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3537 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3538 } else
3539 return failedImport(
3540 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3541 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003542 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003543 if (!SrcGIEquivOrNull)
3544 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003545 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003546 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003547
3548 // The operators look good: match the opcode
3549 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3550 }
3551
3552 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003553 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003554 // Results don't have a name unless they are the root node. The caller will
3555 // set the name if appropriate.
3556 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3557 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3558 return failedImport(toString(std::move(Error)) +
3559 " for result of Src pattern operator");
3560 }
3561
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003562 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3563 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003564 if (Predicate.isAlwaysTrue())
3565 continue;
3566
3567 if (Predicate.isImmediatePattern()) {
3568 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3569 continue;
3570 }
3571
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003572 // An address space check is needed in all contexts if there is one.
3573 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3574 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3575 SmallVector<unsigned, 4> ParsedAddrSpaces;
3576
3577 for (Init *Val : AddrSpaces->getValues()) {
3578 IntInit *IntVal = dyn_cast<IntInit>(Val);
3579 if (!IntVal)
3580 return failedImport("Address space is not an integer");
3581 ParsedAddrSpaces.push_back(IntVal->getValue());
3582 }
3583
3584 if (!ParsedAddrSpaces.empty()) {
3585 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3586 0, ParsedAddrSpaces);
3587 }
3588 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003589
3590 int64_t MinAlign = Predicate.getMinAlignment();
3591 if (MinAlign > 0)
3592 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003593 }
3594
3595 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003596 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3597 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3598 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3599 continue;
3600 }
3601 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3602 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3603 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3604 continue;
3605 }
3606
Amara Emerson52e6d522019-08-02 23:33:13 +00003607 if (Predicate.isStore()) {
3608 if (Predicate.isTruncStore()) {
3609 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3610 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3611 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3612 continue;
3613 }
3614 if (Predicate.isNonTruncStore()) {
3615 // We need to check the sizes match here otherwise we could incorrectly
3616 // match truncating stores with non-truncating ones.
3617 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3618 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3619 }
Matt Arsenault02772492019-07-15 21:15:20 +00003620 }
3621
Daniel Sandersf84bc372018-05-05 20:53:24 +00003622 // No check required. We already did it by swapping the opcode.
3623 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3624 Predicate.isSignExtLoad())
3625 continue;
3626
3627 // No check required. We already did it by swapping the opcode.
3628 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3629 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003630 continue;
3631
Daniel Sandersd66e0902017-10-23 18:19:24 +00003632 // No check required. G_STORE by itself is a non-extending store.
3633 if (Predicate.isNonTruncStore())
3634 continue;
3635
Daniel Sanders76664652017-11-28 22:07:05 +00003636 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3637 if (Predicate.getMemoryVT() != nullptr) {
3638 Optional<LLTCodeGen> MemTyOrNone =
3639 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003640
Daniel Sanders76664652017-11-28 22:07:05 +00003641 if (!MemTyOrNone)
3642 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003643
Daniel Sandersf84bc372018-05-05 20:53:24 +00003644 // MMO's work in bytes so we must take care of unusual types like i1
3645 // don't round down.
3646 unsigned MemSizeInBits =
3647 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3648
3649 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3650 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003651 continue;
3652 }
3653 }
3654
3655 if (Predicate.isLoad() || Predicate.isStore()) {
3656 // No check required. A G_LOAD/G_STORE is an unindexed load.
3657 if (Predicate.isUnindexed())
3658 continue;
3659 }
3660
3661 if (Predicate.isAtomic()) {
3662 if (Predicate.isAtomicOrderingMonotonic()) {
3663 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3664 "Monotonic");
3665 continue;
3666 }
3667 if (Predicate.isAtomicOrderingAcquire()) {
3668 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3669 continue;
3670 }
3671 if (Predicate.isAtomicOrderingRelease()) {
3672 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3673 continue;
3674 }
3675 if (Predicate.isAtomicOrderingAcquireRelease()) {
3676 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3677 "AcquireRelease");
3678 continue;
3679 }
3680 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3681 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3682 "SequentiallyConsistent");
3683 continue;
3684 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003685
3686 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3687 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3688 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3689 continue;
3690 }
3691 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3692 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3693 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3694 continue;
3695 }
3696
3697 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3698 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3699 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3700 continue;
3701 }
3702 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3703 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3704 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3705 continue;
3706 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003707 }
3708
Daniel Sanders8ead1292018-06-15 23:13:43 +00003709 if (Predicate.hasGISelPredicateCode()) {
3710 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3711 continue;
3712 }
3713
Daniel Sanders2c269f62017-08-24 09:11:20 +00003714 return failedImport("Src pattern child has predicate (" +
3715 explainPredicates(Src) + ")");
3716 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003717 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3718 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003719 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3720 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3721 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3722 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003723
Florian Hahn6b1db822018-06-14 20:32:58 +00003724 if (Src->isLeaf()) {
3725 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003726 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003727 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003728 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003729 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3730 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003731 return failedImport(
3732 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003733 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003734 assert(SrcGIOrNull &&
3735 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003736 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3737 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3738 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003739 // here since we don't support ImmLeaf predicates yet. However, we still
3740 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3741 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3742 return InsnMatcher;
3743 }
3744
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003745 // Special case because the operand order is changed from setcc. The
3746 // predicate operand needs to be swapped from the last operand to the first
3747 // source.
3748
3749 unsigned NumChildren = Src->getNumChildren();
3750 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3751
3752 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3753 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3754 if (SrcChild->isLeaf()) {
3755 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3756 Record *CCDef = DI ? DI->getDef() : nullptr;
3757 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3758 return failedImport("Unable to handle CondCode");
3759
3760 OperandMatcher &OM =
3761 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3762 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3763 CCDef->getValueAsString("ICmpPredicate");
3764
3765 if (!PredType.empty()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003766 OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003767 // Process the other 2 operands normally.
3768 --NumChildren;
3769 }
3770 }
3771 }
3772
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003773 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003774 bool IsIntrinsic =
3775 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3776 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3777 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3778 if (IsIntrinsic && !II)
3779 return failedImport("Expected IntInit containing intrinsic ID)");
3780
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003781 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003782 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003783
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003784 // We need to determine the meaning of a literal integer based on the
3785 // context. If this is a field required to be an immediate (such as an
3786 // immarg intrinsic argument), the required predicates are different than
3787 // a constant which may be materialized in a register. If we have an
3788 // argument that is required to be an immediate, we should not emit an LLT
3789 // type check, and should not be looking for a G_CONSTANT defined
3790 // register.
3791 bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
3792
Daniel Sandersa71f4542017-10-16 00:56:30 +00003793 // SelectionDAG allows pointers to be represented with iN since it doesn't
3794 // distinguish between pointers and integers but they are different types in GlobalISel.
3795 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003796 //
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003797 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003798
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003799 if (IsIntrinsic) {
3800 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3801 // following the defs is an intrinsic ID.
3802 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003803 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003804 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003805 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003806 continue;
3807 }
3808
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003809 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003810 //
3811 // Note that we have to look at the i-1th parameter, because we don't
3812 // have the intrinsic ID in the intrinsic's parameter list.
3813 OperandIsAPointer |= II->isParamAPointer(i - 1);
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003814 OperandIsImmArg |= II->isParamImmArg(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003815 }
3816
Daniel Sandersa71f4542017-10-16 00:56:30 +00003817 if (auto Error =
3818 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003819 OperandIsImmArg, OpIdx++, TempOpIdx))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08003820 return std::move(Error);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003821 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003822 }
3823
3824 return InsnMatcher;
3825}
3826
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003827Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3828 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3829 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3830 if (ComplexPattern == ComplexPatternEquivs.end())
3831 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3832 ") not mapped to GlobalISel");
3833
3834 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3835 TempOpIdx++;
3836 return Error::success();
3837}
3838
Matt Arsenault3e45c702019-09-06 20:32:37 +00003839// Get the name to use for a pattern operand. For an anonymous physical register
3840// input, this should use the register name.
3841static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3842 Record *&PhysReg) {
3843 StringRef SrcChildName = SrcChild->getName();
3844 if (SrcChildName.empty() && SrcChild->isLeaf()) {
3845 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3846 auto *ChildRec = ChildDefInit->getDef();
3847 if (ChildRec->isSubClassOf("Register")) {
3848 SrcChildName = ChildRec->getName();
3849 PhysReg = ChildRec;
3850 }
3851 }
3852 }
3853
3854 return SrcChildName;
3855}
3856
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003857Error GlobalISelEmitter::importChildMatcher(
3858 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3859 const TreePatternNode *SrcChild, bool OperandIsAPointer,
3860 bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00003861
3862 Record *PhysReg = nullptr;
3863 StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3864
Benjamin Krameradcd0262020-01-28 20:23:46 +01003865 OperandMatcher &OM =
3866 PhysReg
3867 ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
3868 : InsnMatcher.addOperand(OpIdx, std::string(SrcChildName), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003869 if (OM.isSameAsAnotherOperand())
3870 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003871
Florian Hahn6b1db822018-06-14 20:32:58 +00003872 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003873 if (ChildTypes.size() != 1)
3874 return failedImport("Src pattern child has multiple results");
3875
3876 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003877 if (!SrcChild->isLeaf()) {
3878 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3879 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003880 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3881 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003882 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003883 }
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00003884 if (SrcChild->getOperator()->getName() == "timm") {
3885 OM.addPredicate<ImmOperandMatcher>();
3886 return Error::success();
3887 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003888 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003889 }
3890
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003891 // Immediate arguments have no meaningful type to check as they don't have
3892 // registers.
3893 if (!OperandIsImmArg) {
3894 if (auto Error =
3895 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3896 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3897 to_string(*SrcChild) + ")");
3898 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003899
Daniel Sandersbee57392017-04-04 13:25:23 +00003900 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003901 if (!SrcChild->isLeaf()) {
3902 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003903 // When a ComplexPattern is used as an operator, it should do the same
3904 // thing as when used as a leaf. However, the children of the operator
3905 // name the sub-operands that make up the complex operand and we must
3906 // prepare to reference them in the renderer too.
3907 unsigned RendererID = TempOpIdx;
3908 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003909 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003910 return Error;
3911
Florian Hahn6b1db822018-06-14 20:32:58 +00003912 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3913 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003914 if (!SubOperand->getName().empty()) {
3915 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3916 SrcChild->getOperator(),
3917 RendererID, i))
3918 return Error;
3919 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003920 }
3921
3922 return Error::success();
3923 }
3924
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003925 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003926 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003927 if (!MaybeInsnOperand.hasValue()) {
3928 // This isn't strictly true. If the user were to provide exactly the same
3929 // matchers as the original operand then we could allow it. However, it's
3930 // simpler to not permit the redundant specification.
3931 return failedImport("Nested instruction cannot be the same as another operand");
3932 }
3933
Daniel Sandersbee57392017-04-04 13:25:23 +00003934 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003935 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003936 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003937 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003938 if (auto Error = InsnMatcherOrError.takeError())
3939 return Error;
3940
3941 return Error::success();
3942 }
3943
Florian Hahn6b1db822018-06-14 20:32:58 +00003944 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003945 return failedImport("Src pattern child has unsupported predicate");
3946
Daniel Sandersffc7d582017-03-29 15:37:18 +00003947 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003948 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003949 if (OperandIsImmArg) {
3950 // Checks for argument directly in operand list
3951 OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
3952 } else {
3953 // Checks for materialized constant
3954 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
3955 }
Daniel Sandersc270c502017-03-30 09:36:33 +00003956 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003957 }
3958
3959 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003960 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003961 auto *ChildRec = ChildDefInit->getDef();
3962
3963 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003964 if (ChildRec->isSubClassOf("RegisterClass") ||
3965 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003966 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003967 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003968 return Error::success();
3969 }
3970
Matt Arsenault3e45c702019-09-06 20:32:37 +00003971 if (ChildRec->isSubClassOf("Register")) {
3972 // This just be emitted as a copy to the specific register.
3973 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
3974 const CodeGenRegisterClass *RC
3975 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
3976 if (!RC) {
3977 return failedImport(
3978 "Could not determine physical register class of pattern source");
3979 }
3980
3981 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
3982 return Error::success();
3983 }
3984
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003985 // Check for ValueType.
3986 if (ChildRec->isSubClassOf("ValueType")) {
3987 // We already added a type check as standard practice so this doesn't need
3988 // to do anything.
3989 return Error::success();
3990 }
3991
Daniel Sandersffc7d582017-03-29 15:37:18 +00003992 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003993 if (ChildRec->isSubClassOf("ComplexPattern"))
3994 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003995
Daniel Sandersd0656a32017-04-13 09:45:37 +00003996 if (ChildRec->isSubClassOf("ImmLeaf")) {
3997 return failedImport(
3998 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3999 }
4000
Matt Arsenault03a592f2020-01-16 10:47:13 -05004001 // Place holder for SRCVALUE nodes. Nothing to do here.
4002 if (ChildRec->getName() == "srcvalue")
4003 return Error::success();
4004
Daniel Sandersffc7d582017-03-29 15:37:18 +00004005 return failedImport(
4006 "Src pattern child def is an unsupported tablegen class");
4007 }
4008
4009 return failedImport("Src pattern child is an unsupported kind");
4010}
4011
Daniel Sanders7438b262017-10-31 23:03:18 +00004012Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4013 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004014 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00004015
Florian Hahn6b1db822018-06-14 20:32:58 +00004016 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004017 if (SubOperand.hasValue()) {
4018 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004019 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004020 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00004021 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004022 }
4023
Florian Hahn6b1db822018-06-14 20:32:58 +00004024 if (!DstChild->isLeaf()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004025 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4026 auto Child = DstChild->getChild(0);
4027 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00004028 if (I != SDNodeXFormEquivs.end()) {
Matt Arsenaultb4a64742020-01-08 12:53:15 -05004029 Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4030 if (XFormOpc->getName() == "timm") {
4031 // If this is a TargetConstant, there won't be a corresponding
4032 // instruction to transform. Instead, this will refer directly to an
4033 // operand in an instruction's operand list.
4034 DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4035 Child->getName());
4036 } else {
4037 DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4038 Child->getName());
4039 }
4040
Volkan Kelesf7f25682018-01-16 18:44:05 +00004041 return InsertPt;
4042 }
Florian Hahn6b1db822018-06-14 20:32:58 +00004043 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00004044 " has no custom renderer");
4045 }
4046
Daniel Sanders05540042017-08-08 10:44:31 +00004047 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4048 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004049 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4050 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004051 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004052 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004053 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004054 }
4055 }
Daniel Sanders05540042017-08-08 10:44:31 +00004056
4057 // Similarly, imm is an operator in TreePatternNode's view but must be
4058 // rendered as operands.
4059 // FIXME: The target should be able to choose sign-extended when appropriate
4060 // (e.g. on Mips).
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00004061 if (DstChild->getOperator()->getName() == "timm") {
4062 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4063 return InsertPt;
4064 } else if (DstChild->getOperator()->getName() == "imm") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004065 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004066 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00004067 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004068 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004069 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004070 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00004071 }
4072
Florian Hahn6b1db822018-06-14 20:32:58 +00004073 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
Matt Arsenault9c346462020-01-14 16:02:02 -05004074 auto OpTy = getInstResultType(DstChild);
4075 if (!OpTy)
4076 return OpTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004077
4078 unsigned TempRegID = Rule.allocateTempRegID();
4079 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
Matt Arsenault9c346462020-01-14 16:02:02 -05004080 InsertPt, *OpTy, TempRegID);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004081 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4082
4083 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4084 ++InsertPt, Rule, DstChild, TempRegID);
4085 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004086 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004087 return InsertPtOrError.get();
4088 }
4089
Florian Hahn6b1db822018-06-14 20:32:58 +00004090 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00004091 }
4092
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004093 // It could be a specific immediate in which case we should just check for
4094 // that immediate.
4095 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004096 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004097 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4098 return InsertPt;
4099 }
4100
Daniel Sandersffc7d582017-03-29 15:37:18 +00004101 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004102 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004103 auto *ChildRec = ChildDefInit->getDef();
4104
Florian Hahn6b1db822018-06-14 20:32:58 +00004105 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004106 if (ChildTypes.size() != 1)
4107 return failedImport("Dst pattern child has multiple results");
4108
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004109 Optional<LLTCodeGen> OpTyOrNone = None;
4110 if (ChildTypes.front().isMachineValueType())
4111 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004112 if (!OpTyOrNone)
4113 return failedImport("Dst operand has an unsupported type");
4114
4115 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004116 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00004117 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004118 }
4119
Daniel Sanders658541f2017-04-22 15:53:21 +00004120 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004121 ChildRec->isSubClassOf("RegisterOperand") ||
4122 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00004123 if (ChildRec->isSubClassOf("RegisterOperand") &&
4124 !ChildRec->isValueUnset("GIZeroRegister")) {
4125 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004126 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00004127 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00004128 }
4129
Florian Hahn6b1db822018-06-14 20:32:58 +00004130 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004131 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004132 }
4133
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004134 if (ChildRec->isSubClassOf("SubRegIndex")) {
4135 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4136 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4137 return InsertPt;
4138 }
4139
Daniel Sandersffc7d582017-03-29 15:37:18 +00004140 if (ChildRec->isSubClassOf("ComplexPattern")) {
4141 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4142 if (ComplexPattern == ComplexPatternEquivs.end())
4143 return failedImport(
4144 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4145
Florian Hahn6b1db822018-06-14 20:32:58 +00004146 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004147 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004148 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004149 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004150 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004151 }
4152
4153 return failedImport(
4154 "Dst pattern child def is an unsupported tablegen class");
4155 }
4156
4157 return failedImport("Dst pattern child is an unsupported kind");
4158}
4159
Daniel Sandersc270c502017-03-30 09:36:33 +00004160Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004161 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4162 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004163 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4164 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004165 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004166
Daniel Sanders7438b262017-10-31 23:03:18 +00004167 action_iterator InsertPt = InsertPtOrError.get();
4168 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004169
Matt Arsenault3e45c702019-09-06 20:32:37 +00004170 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4171 InsertPt = M.insertAction<BuildMIAction>(
4172 InsertPt, M.allocateOutputInsnID(),
4173 &Target.getInstruction(RK.getDef("COPY")));
4174 BuildMIAction &CopyToPhysRegMIBuilder =
4175 *static_cast<BuildMIAction *>(InsertPt->get());
4176 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4177 true);
4178 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4179 }
4180
Daniel Sandersdf258e32017-10-31 19:09:29 +00004181 importExplicitDefRenderers(DstMIBuilder);
4182
Daniel Sanders7438b262017-10-31 23:03:18 +00004183 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4184 .takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004185 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004186
4187 return DstMIBuilder;
4188}
4189
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004190Expected<action_iterator>
4191GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004192 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004193 unsigned TempRegID) {
4194 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4195
4196 // TODO: Assert there's exactly one result.
4197
4198 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004199 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004200
4201 BuildMIAction &DstMIBuilder =
4202 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4203
4204 // Assign the result to TempReg.
4205 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4206
Daniel Sanders08464522018-01-29 21:09:12 +00004207 InsertPtOrError =
4208 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004209 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004210 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004211
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004212 // We need to make sure that when we import an INSERT_SUBREG as a
4213 // subinstruction that it ends up being constrained to the correct super
4214 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004215 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4216 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004217 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4218 if (!SubClass)
4219 return failedImport(
4220 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004221 Optional<const CodeGenRegisterClass *> SuperClass =
4222 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4223 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004224 if (!SuperClass)
4225 return failedImport(
4226 "Cannot infer register class for INSERT_SUBREG operand #0");
4227 // The destination and the super register source of an INSERT_SUBREG must
4228 // be the same register class.
4229 M.insertAction<ConstrainOperandToRegClassAction>(
4230 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4231 M.insertAction<ConstrainOperandToRegClassAction>(
4232 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4233 M.insertAction<ConstrainOperandToRegClassAction>(
4234 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4235 return InsertPtOrError.get();
4236 }
4237
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004238 if (OpName == "EXTRACT_SUBREG") {
4239 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4240 // instructions, the result register class is controlled by the
4241 // subregisters of the operand. As a result, we must constrain the result
4242 // class rather than check that it's already the right one.
4243 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4244 if (!SuperClass)
4245 return failedImport(
4246 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4247
4248 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4249 if (!SubIdx)
4250 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4251
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004252 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004253 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4254 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4255 M.insertAction<ConstrainOperandToRegClassAction>(
4256 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4257 M.insertAction<ConstrainOperandToRegClassAction>(
4258 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4259
4260 // We're done with this pattern! It's eligible for GISel emission; return
4261 // it.
4262 return InsertPtOrError.get();
4263 }
4264
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004265 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4266 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004267 if (OpName == "SUBREG_TO_REG") {
4268 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4269 if (!SubClass)
4270 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004271 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004272 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4273 Dst->getChild(2));
4274 if (!SuperClass)
4275 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004276 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004277 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004278 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004279 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004280 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004281 return InsertPtOrError.get();
4282 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004283
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04004284 if (OpName == "REG_SEQUENCE") {
4285 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4286 M.insertAction<ConstrainOperandToRegClassAction>(
4287 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4288
4289 unsigned Num = Dst->getNumChildren();
4290 for (unsigned I = 1; I != Num; I += 2) {
4291 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4292
4293 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4294 if (!SubIdx)
4295 return failedImport("REG_SEQUENCE child is not a subreg index");
4296
4297 const auto SrcRCDstRCPair =
4298 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4299 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4300 M.insertAction<ConstrainOperandToRegClassAction>(
4301 InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4302 }
4303
4304 return InsertPtOrError.get();
4305 }
4306
Daniel Sanders08464522018-01-29 21:09:12 +00004307 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4308 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004309 return InsertPtOrError.get();
4310}
4311
Daniel Sanders7438b262017-10-31 23:03:18 +00004312Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004313 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4314 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004315 if (!DstOp->isSubClassOf("Instruction")) {
4316 if (DstOp->isSubClassOf("ValueType"))
4317 return failedImport(
4318 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004319 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004320 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004321 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004322
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004323 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004324 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004325 StringRef Name = DstI->TheDef->getName();
4326 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004327 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004328
Daniel Sanders198447a2017-11-01 00:29:47 +00004329 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4330 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004331}
4332
4333void GlobalISelEmitter::importExplicitDefRenderers(
4334 BuildMIAction &DstMIBuilder) {
4335 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004336 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
4337 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00004338 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004339 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00004340}
4341
Daniel Sanders7438b262017-10-31 23:03:18 +00004342Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4343 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004344 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004345 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004346 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004347
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004348 StringRef Name = OrigDstI->TheDef->getName();
4349 unsigned ExpectedDstINumUses = Dst->getNumChildren();
4350
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004351 // EXTRACT_SUBREG needs to use a subregister COPY.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004352 if (Name == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05004353 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4354 if (!SubRegInit)
4355 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004356
Matt Arsenault9c346462020-01-14 16:02:02 -05004357 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4358 TreePatternNode *ValChild = Dst->getChild(0);
4359 if (!ValChild->isLeaf()) {
4360 // We really have to handle the source instruction, and then insert a
4361 // copy from the subregister.
4362 auto ExtractSrcTy = getInstResultType(ValChild);
4363 if (!ExtractSrcTy)
4364 return ExtractSrcTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004365
Matt Arsenault9c346462020-01-14 16:02:02 -05004366 unsigned TempRegID = M.allocateTempRegID();
4367 InsertPt = M.insertAction<MakeTempRegisterAction>(
4368 InsertPt, *ExtractSrcTy, TempRegID);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004369
Matt Arsenault9c346462020-01-14 16:02:02 -05004370 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4371 ++InsertPt, M, ValChild, TempRegID);
4372 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004373 return std::move(Error);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004374
Matt Arsenault9c346462020-01-14 16:02:02 -05004375 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004376 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004377 }
4378
Matt Arsenault9c346462020-01-14 16:02:02 -05004379 // If this is a source operand, this is just a subregister copy.
4380 Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4381 if (!RCDef)
4382 return failedImport("EXTRACT_SUBREG child #0 could not "
4383 "be coerced to a register class");
4384
4385 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4386
4387 const auto SrcRCDstRCPair =
4388 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4389 if (SrcRCDstRCPair.hasValue()) {
4390 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4391 if (SrcRCDstRCPair->first != RC)
4392 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4393 }
4394
4395 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4396 SubIdx);
4397 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004398 }
4399
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004400 if (Name == "REG_SEQUENCE") {
4401 if (!Dst->getChild(0)->isLeaf())
4402 return failedImport("REG_SEQUENCE child #0 is not a leaf");
4403
4404 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4405 if (!RCDef)
4406 return failedImport("REG_SEQUENCE child #0 could not "
4407 "be coerced to a register class");
4408
4409 if ((ExpectedDstINumUses - 1) % 2 != 0)
4410 return failedImport("Malformed REG_SEQUENCE");
4411
4412 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4413 TreePatternNode *ValChild = Dst->getChild(I);
4414 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4415
4416 if (DefInit *SubRegInit =
4417 dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4418 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4419
4420 auto InsertPtOrError =
4421 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4422 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004423 return std::move(Error);
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004424 InsertPt = InsertPtOrError.get();
4425 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4426 }
4427 }
4428
4429 return InsertPt;
4430 }
4431
Daniel Sandersffc7d582017-03-29 15:37:18 +00004432 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004433 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004434 if (Name == "COPY_TO_REGCLASS") {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004435 DstINumUses--; // Ignore the class constraint.
4436 ExpectedDstINumUses--;
4437 }
4438
Matt Arsenault26f714f2019-10-21 21:39:42 -07004439 // NumResults - This is the number of results produced by the instruction in
4440 // the "outs" list.
4441 unsigned NumResults = OrigDstI->Operands.NumDefs;
4442
4443 // Number of operands we know the output instruction must have. If it is
4444 // variadic, we could have more operands.
4445 unsigned NumFixedOperands = DstI->Operands.size();
4446
4447 // Loop over all of the fixed operands of the instruction pattern, emitting
4448 // code to fill them all in. The node 'N' usually has number children equal to
4449 // the number of input operands of the instruction. However, in cases where
4450 // there are predicate operands for an instruction, we need to fill in the
4451 // 'execute always' values. Match up the node operands to the instruction
4452 // operands to do this.
Daniel Sanders0ed28822017-04-12 08:23:08 +00004453 unsigned Child = 0;
Matt Arsenault26f714f2019-10-21 21:39:42 -07004454
4455 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4456 // number of operands at the end of the list which have default values.
4457 // Those can come from the pattern if it provides enough arguments, or be
4458 // filled in with the default if the pattern hasn't provided them. But any
4459 // operand with a default value _before_ the last mandatory one will be
4460 // filled in with their defaults unconditionally.
4461 unsigned NonOverridableOperands = NumFixedOperands;
4462 while (NonOverridableOperands > NumResults &&
4463 CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4464 --NonOverridableOperands;
4465
Diana Picus382602f2017-05-17 08:57:28 +00004466 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004467 for (unsigned I = 0; I != DstINumUses; ++I) {
Matt Arsenault26f714f2019-10-21 21:39:42 -07004468 unsigned InstOpNo = DstI->Operands.NumDefs + I;
4469
4470 // Determine what to emit for this operand.
4471 Record *OperandNode = DstI->Operands[InstOpNo].Rec;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004472
Diana Picus382602f2017-05-17 08:57:28 +00004473 // If the operand has default values, introduce them now.
Matt Arsenault26f714f2019-10-21 21:39:42 -07004474 if (CGP.operandHasDefault(OperandNode) &&
4475 (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4476 // This is a predicate or optional def operand which the pattern has not
4477 // overridden, or which we aren't letting it override; emit the 'default
4478 // ops' operands.
4479
4480 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004481 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004482 if (auto Error = importDefaultOperandRenderers(
4483 InsertPt, M, DstMIBuilder, DefaultOps))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004484 return std::move(Error);
Diana Picus382602f2017-05-17 08:57:28 +00004485 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004486 continue;
4487 }
4488
Daniel Sanders7438b262017-10-31 23:03:18 +00004489 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004490 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004491 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004492 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004493 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004494 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004495 }
4496
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004497 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004498 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004499 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004500 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004501 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004502 " default ones");
4503
Daniel Sanders7438b262017-10-31 23:03:18 +00004504 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004505}
4506
Diana Picus382602f2017-05-17 08:57:28 +00004507Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004508 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4509 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004510 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004511 Optional<LLTCodeGen> OpTyOrNone = None;
4512
Diana Picus382602f2017-05-17 08:57:28 +00004513 // Look through ValueType operators.
4514 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4515 if (const DefInit *DefaultDagOperator =
4516 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004517 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004518 OpTyOrNone = MVTToLLT(getValueType(
4519 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004520 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004521 }
Diana Picus382602f2017-05-17 08:57:28 +00004522 }
4523 }
4524
4525 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004526 auto Def = DefaultDefOp->getDef();
4527 if (Def->getName() == "undef_tied_input") {
4528 unsigned TempRegID = M.allocateTempRegID();
4529 M.insertAction<MakeTempRegisterAction>(
4530 InsertPt, OpTyOrNone.getValue(), TempRegID);
4531 InsertPt = M.insertAction<BuildMIAction>(
4532 InsertPt, M.allocateOutputInsnID(),
4533 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4534 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4535 InsertPt->get());
4536 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4537 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4538 } else {
4539 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4540 }
Diana Picus382602f2017-05-17 08:57:28 +00004541 continue;
4542 }
4543
4544 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004545 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004546 continue;
4547 }
4548
4549 return failedImport("Could not add default op");
4550 }
4551
4552 return Error::success();
4553}
4554
Daniel Sandersc270c502017-03-30 09:36:33 +00004555Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004556 BuildMIAction &DstMIBuilder,
4557 const std::vector<Record *> &ImplicitDefs) const {
4558 if (!ImplicitDefs.empty())
4559 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004560 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004561}
4562
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004563Optional<const CodeGenRegisterClass *>
4564GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4565 assert(Leaf && "Expected node?");
4566 assert(Leaf->isLeaf() && "Expected leaf?");
4567 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4568 if (!RCRec)
4569 return None;
4570 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4571 if (!RC)
4572 return None;
4573 return RC;
4574}
4575
4576Optional<const CodeGenRegisterClass *>
4577GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4578 if (!N)
4579 return None;
4580
4581 if (N->isLeaf())
4582 return getRegClassFromLeaf(N);
4583
4584 // We don't have a leaf node, so we have to try and infer something. Check
4585 // that we have an instruction that we an infer something from.
4586
4587 // Only handle things that produce a single type.
4588 if (N->getNumTypes() != 1)
4589 return None;
4590 Record *OpRec = N->getOperator();
4591
4592 // We only want instructions.
4593 if (!OpRec->isSubClassOf("Instruction"))
4594 return None;
4595
4596 // Don't want to try and infer things when there could potentially be more
4597 // than one candidate register class.
4598 auto &Inst = Target.getInstruction(OpRec);
4599 if (Inst.Operands.NumDefs > 1)
4600 return None;
4601
4602 // Handle any special-case instructions which we can safely infer register
4603 // classes from.
4604 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004605 bool IsRegSequence = InstName == "REG_SEQUENCE";
4606 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004607 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4608 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004609 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004610 if (!RCChild->isLeaf())
4611 return None;
4612 return getRegClassFromLeaf(RCChild);
4613 }
4614
4615 // Handle destination record types that we can safely infer a register class
4616 // from.
4617 const auto &DstIOperand = Inst.Operands[0];
4618 Record *DstIOpRec = DstIOperand.Rec;
4619 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4620 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4621 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4622 return &RC;
4623 }
4624
4625 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4626 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4627 return &RC;
4628 }
4629
4630 return None;
4631}
4632
4633Optional<const CodeGenRegisterClass *>
4634GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004635 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004636 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004637 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4638 if (!Ty.isValueTypeByHwMode(false))
4639 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004640 if (!SubRegIdxNode->isLeaf())
4641 return None;
4642 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4643 if (!SubRegInit)
4644 return None;
4645 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4646
4647 // Use the information we found above to find a minimal register class which
4648 // supports the subregister and type we want.
4649 auto RC =
4650 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4651 if (!RC)
4652 return None;
4653 return *RC;
4654}
4655
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004656Optional<const CodeGenRegisterClass *>
4657GlobalISelEmitter::inferSuperRegisterClassForNode(
4658 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4659 TreePatternNode *SubRegIdxNode) {
4660 assert(SuperRegNode && "Expected super register node!");
4661 // Check if we already have a defined register class for the super register
4662 // node. If we do, then we should preserve that rather than inferring anything
4663 // from the subregister index node. We can assume that whoever wrote the
4664 // pattern in the first place made sure that the super register and
4665 // subregister are compatible.
4666 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4667 inferRegClassFromPattern(SuperRegNode))
4668 return *SuperRegisterClass;
4669 return inferSuperRegisterClass(Ty, SubRegIdxNode);
4670}
4671
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004672Optional<CodeGenSubRegIndex *>
4673GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4674 if (!SubRegIdxNode->isLeaf())
4675 return None;
4676
4677 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4678 if (!SubRegInit)
4679 return None;
4680 return CGRegs.getSubRegIdx(SubRegInit->getDef());
4681}
4682
Daniel Sandersffc7d582017-03-29 15:37:18 +00004683Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004684 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004685 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004686 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004687 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004688 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4689 " => " +
4690 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004691
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004692 if (auto Error = importRulePredicates(M, P.getPredicates()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004693 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004694
4695 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004696 TreePatternNode *Src = P.getSrcPattern();
4697 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004698
4699 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004700 if (auto Err = isTrivialOperatorNode(Dst))
4701 return failedImport("Dst pattern root isn't a trivial operator (" +
4702 toString(std::move(Err)) + ")");
4703 if (auto Err = isTrivialOperatorNode(Src))
4704 return failedImport("Src pattern root isn't a trivial operator (" +
4705 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004706
Quentin Colombetaad20be2017-12-15 23:07:42 +00004707 // The different predicates and matchers created during
4708 // addInstructionMatcher use the RuleMatcher M to set up their
4709 // instruction ID (InsnVarID) that are going to be used when
4710 // M is going to be emitted.
4711 // However, the code doing the emission still relies on the IDs
4712 // returned during that process by the RuleMatcher when issuing
4713 // the recordInsn opcodes.
4714 // Because of that:
4715 // 1. The order in which we created the predicates
4716 // and such must be the same as the order in which we emit them,
4717 // and
4718 // 2. We need to reset the generation of the IDs in M somewhere between
4719 // addInstructionMatcher and emit
4720 //
4721 // FIXME: Long term, we don't want to have to rely on this implicit
4722 // naming being the same. One possible solution would be to have
4723 // explicit operator for operation capture and reference those.
4724 // The plus side is that it would expose opportunities to share
4725 // the capture accross rules. The downside is that it would
4726 // introduce a dependency between predicates (captures must happen
4727 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004728 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004729 unsigned TempOpIdx = 0;
4730 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004731 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004732 if (auto Error = InsnMatcherOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004733 return std::move(Error);
Daniel Sandersedd07842017-08-17 09:26:14 +00004734 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4735
Florian Hahn6b1db822018-06-14 20:32:58 +00004736 if (Dst->isLeaf()) {
4737 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004738
4739 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4740 if (RCDef) {
4741 // We need to replace the def and all its uses with the specified
4742 // operand. However, we must also insert COPY's wherever needed.
4743 // For now, emit a copy and let the register allocator clean up.
4744 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4745 const auto &DstIOperand = DstI.Operands[0];
4746
4747 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4748 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004749 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004750 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4751
Daniel Sanders198447a2017-11-01 00:29:47 +00004752 auto &DstMIBuilder =
4753 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4754 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004755 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004756 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4757
4758 // We're done with this pattern! It's eligible for GISel emission; return
4759 // it.
4760 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004761 return std::move(M);
Daniel Sandersedd07842017-08-17 09:26:14 +00004762 }
4763
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004764 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004765 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004766
Daniel Sandersbee57392017-04-04 13:25:23 +00004767 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004768 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004769 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004770 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004771
4772 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004773 StringRef DstIName = DstI.TheDef->getName();
4774
Florian Hahn6b1db822018-06-14 20:32:58 +00004775 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00004776 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004777 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004778 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004779
Daniel Sandersffc7d582017-03-29 15:37:18 +00004780 // The root of the match also has constraints on the register bank so that it
4781 // matches the result instruction.
4782 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004783 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004784 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004785
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004786 const auto &DstIOperand = DstI.Operands[OpIdx];
4787 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004788 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004789 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004790
4791 if (DstIOpRec == nullptr)
4792 return failedImport(
4793 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004794 } else if (DstIName == "REG_SEQUENCE") {
4795 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4796 if (DstIOpRec == nullptr)
4797 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4798 } else if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05004799 auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
4800 if (!InferredClass)
4801 return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004802
Daniel Sanders32291982017-06-28 13:50:04 +00004803 // We can assume that a subregister is in the same bank as it's super
4804 // register.
Matt Arsenault9c346462020-01-14 16:02:02 -05004805 DstIOpRec = (*InferredClass)->getDef();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004806 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004807 auto MaybeSuperClass = inferSuperRegisterClassForNode(
4808 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004809 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004810 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004811 "Cannot infer register class for INSERT_SUBREG operand #0");
4812 // Move to the next pattern here, because the register class we found
4813 // doesn't necessarily have a record associated with it. So, we can't
4814 // set DstIOpRec using this.
4815 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4816 OM.setSymbolicName(DstIOperand.Name);
4817 M.defineOperand(OM.getSymbolicName(), OM);
4818 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4819 ++OpIdx;
4820 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004821 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004822 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
4823 if (!MaybeRegClass)
4824 return failedImport(
4825 "Cannot infer register class for SUBREG_TO_REG operand #0");
4826 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4827 OM.setSymbolicName(DstIOperand.Name);
4828 M.defineOperand(OM.getSymbolicName(), OM);
4829 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
4830 ++OpIdx;
4831 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004832 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004833 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004834 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004835 return failedImport("Dst MI def isn't a register class" +
4836 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004837
Daniel Sandersffc7d582017-03-29 15:37:18 +00004838 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4839 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004840 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004841 OM.addPredicate<RegisterBankOperandMatcher>(
4842 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004843 ++OpIdx;
4844 }
4845
Matt Arsenault3e45c702019-09-06 20:32:37 +00004846 auto DstMIBuilderOrError =
4847 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004848 if (auto Error = DstMIBuilderOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004849 return std::move(Error);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004850 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004851
Daniel Sandersffc7d582017-03-29 15:37:18 +00004852 // Render the implicit defs.
4853 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004854 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004855 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004856
Daniel Sandersa7b75262017-10-31 18:50:24 +00004857 DstMIBuilder.chooseInsnToMutate(M);
4858
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004859 // Constrain the registers to classes. This is normally derived from the
4860 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004861 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004862 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4863 // result is constrained to the class given by the second child.
4864 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004865 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004866
4867 if (DstIOpRec == nullptr)
4868 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4869
4870 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004871 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004872
4873 // We're done with this pattern! It's eligible for GISel emission; return
4874 // it.
4875 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004876 return std::move(M);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004877 }
4878
Matt Arsenault38fb3442019-09-04 16:19:34 +00004879 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004880 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4881 if (!SuperClass)
4882 return failedImport(
4883 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004884
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004885 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4886 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00004887 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004888
Daniel Sanders320390b2017-06-28 15:16:03 +00004889 // It would be nice to leave this constraint implicit but we're required
4890 // to pick a register class so constrain the result to a register class
4891 // that can hold the correct MVT.
4892 //
4893 // FIXME: This may introduce an extra copy if the chosen class doesn't
4894 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004895 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004896 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004897
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004898 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004899 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Matt Arsenault9c346462020-01-14 16:02:02 -05004900 if (!SrcRCDstRCPair) {
4901 return failedImport("subreg index is incompatible "
4902 "with inferred reg class");
4903 }
4904
Daniel Sanders320390b2017-06-28 15:16:03 +00004905 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004906 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4907 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4908
4909 // We're done with this pattern! It's eligible for GISel emission; return
4910 // it.
4911 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004912 return std::move(M);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004913 }
4914
Matt Arsenault38fb3442019-09-04 16:19:34 +00004915 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004916 assert(Src->getExtTypes().size() == 1 &&
4917 "Expected Src of INSERT_SUBREG to have one result type");
4918 // We need to constrain the destination, a super regsister source, and a
4919 // subregister source.
4920 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4921 if (!SubClass)
4922 return failedImport(
4923 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004924 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004925 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4926 if (!SuperClass)
4927 return failedImport(
4928 "Cannot infer register class for INSERT_SUBREG operand #0");
4929 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4930 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4931 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4932 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004933 return std::move(M);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004934 }
4935
Matt Arsenault38fb3442019-09-04 16:19:34 +00004936 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004937 // We need to constrain the destination and subregister source.
4938 assert(Src->getExtTypes().size() == 1 &&
4939 "Expected Src of SUBREG_TO_REG to have one result type");
4940
4941 // Attempt to infer the subregister source from the first child. If it has
4942 // an explicitly given register class, we'll use that. Otherwise, we will
4943 // fail.
4944 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4945 if (!SubClass)
4946 return failedImport(
4947 "Cannot infer register class from SUBREG_TO_REG child #1");
4948 // We don't have a child to look at that might have a super register node.
4949 auto SuperClass =
4950 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
4951 if (!SuperClass)
4952 return failedImport(
4953 "Cannot infer register class for SUBREG_TO_REG operand #0");
4954 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4955 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4956 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004957 return std::move(M);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004958 }
4959
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04004960 if (DstIName == "REG_SEQUENCE") {
4961 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4962
4963 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4964
4965 unsigned Num = Dst->getNumChildren();
4966 for (unsigned I = 1; I != Num; I += 2) {
4967 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4968
4969 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4970 if (!SubIdx)
4971 return failedImport("REG_SEQUENCE child is not a subreg index");
4972
4973 const auto SrcRCDstRCPair =
4974 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4975
4976 M.addAction<ConstrainOperandToRegClassAction>(0, I,
4977 *SrcRCDstRCPair->second);
4978 }
4979
4980 ++NumPatternImported;
4981 return std::move(M);
4982 }
4983
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004984 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004985
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004986 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004987 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004988 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004989}
4990
Daniel Sanders649c5852017-10-13 20:42:18 +00004991// Emit imm predicate table and an enum to reference them with.
4992// The 'Predicate_' part of the name is redundant but eliminating it is more
4993// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004994void GlobalISelEmitter::emitCxxPredicateFns(
4995 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4996 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004997 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004998 std::vector<const Record *> MatchedRecords;
4999 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
5000 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5001 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00005002 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00005003 Filter(Record);
5004 });
5005
Daniel Sanders11300ce2017-10-13 21:28:03 +00005006 if (!MatchedRecords.empty()) {
5007 OS << "// PatFrag predicates.\n"
5008 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00005009 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00005010 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5011 for (const auto *Record : MatchedRecords) {
5012 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5013 << EnumeratorSeparator;
5014 EnumeratorSeparator = ",\n";
5015 }
5016 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005017 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00005018
Daniel Sanders8ead1292018-06-15 23:13:43 +00005019 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5020 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
5021 << ArgName << ") const {\n"
5022 << AdditionalDeclarations;
5023 if (!AdditionalDeclarations.empty())
5024 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00005025 if (!MatchedRecords.empty())
5026 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005027 for (const auto *Record : MatchedRecords) {
5028 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
5029 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005030 << " " << Record->getValueAsString(CodeFieldName) << "\n"
5031 << " llvm_unreachable(\"" << CodeFieldName
5032 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005033 << " return false;\n"
5034 << " }\n";
5035 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00005036 if (!MatchedRecords.empty())
5037 OS << " }\n";
5038 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005039 << " return false;\n"
5040 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005041}
5042
Daniel Sanders8ead1292018-06-15 23:13:43 +00005043void GlobalISelEmitter::emitImmPredicateFns(
5044 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5045 std::function<bool(const Record *R)> Filter) {
5046 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
5047 "Imm", "", Filter);
5048}
5049
5050void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5051 return emitCxxPredicateFns(
5052 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
5053 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00005054 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5055 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00005056 [](const Record *R) { return true; });
5057}
5058
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005059template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005060std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005061 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005062 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5063
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005064 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005065 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005066 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5067 unsigned NumGroups = 0;
5068
5069 auto ProcessCurrentGroup = [&]() {
5070 if (CurrentGroup->empty())
5071 // An empty group is good to be reused:
5072 return;
5073
5074 // If the group isn't large enough to provide any benefit, move all the
5075 // added rules out of it and make sure to re-create the group to properly
5076 // re-initialize it:
5077 if (CurrentGroup->size() < 2)
5078 for (Matcher *M : CurrentGroup->matchers())
5079 OptRules.push_back(M);
5080 else {
5081 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005082 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005083 MatcherStorage.emplace_back(std::move(CurrentGroup));
5084 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005085 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005086 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005087 };
5088 for (Matcher *Rule : Rules) {
5089 // Greedily add as many matchers as possible to the current group:
5090 if (CurrentGroup->addMatcher(*Rule))
5091 continue;
5092
5093 ProcessCurrentGroup();
5094 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5095
5096 // Try to add the pending matcher to a newly created empty group:
5097 if (!CurrentGroup->addMatcher(*Rule))
5098 // If we couldn't add the matcher to an empty group, that group type
5099 // doesn't support that kind of matchers at all, so just skip it:
5100 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005101 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005102 ProcessCurrentGroup();
5103
Nicola Zaghen03d0b912018-05-23 15:09:29 +00005104 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005105 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005106 return OptRules;
5107}
5108
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005109MatchTable
5110GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00005111 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005112 std::vector<Matcher *> InputRules;
5113 for (Matcher &Rule : Rules)
5114 InputRules.push_back(&Rule);
5115
5116 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00005117 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005118
Roman Tereshin77013602018-05-22 16:54:27 +00005119 unsigned CurrentOrdering = 0;
5120 StringMap<unsigned> OpcodeOrder;
5121 for (RuleMatcher &Rule : Rules) {
5122 const StringRef Opcode = Rule.getOpcode();
5123 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5124 if (OpcodeOrder.count(Opcode) == 0)
5125 OpcodeOrder[Opcode] = CurrentOrdering++;
5126 }
5127
5128 std::stable_sort(InputRules.begin(), InputRules.end(),
5129 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5130 auto *L = static_cast<const RuleMatcher *>(A);
5131 auto *R = static_cast<const RuleMatcher *>(B);
5132 return std::make_tuple(OpcodeOrder[L->getOpcode()],
5133 L->getNumOperands()) <
5134 std::make_tuple(OpcodeOrder[R->getOpcode()],
5135 R->getNumOperands());
5136 });
5137
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005138 for (Matcher *Rule : InputRules)
5139 Rule->optimize();
5140
5141 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005142 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005143 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5144
5145 for (Matcher *Rule : OptRules)
5146 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005147
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005148 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5149
Roman Tereshinbeb39312018-05-02 20:15:11 +00005150 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005151}
5152
Roman Tereshinfedae332018-05-23 02:04:19 +00005153void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00005154 // Make sure we only sort by a specific predicate within a range of rules that
5155 // all have that predicate checked against a specific value (not a wildcard):
5156 auto F = Matchers.begin();
5157 auto T = F;
5158 auto E = Matchers.end();
5159 while (T != E) {
5160 while (T != E) {
5161 auto *R = static_cast<RuleMatcher *>(*T);
5162 if (!R->getFirstConditionAsRootType().get().isValid())
5163 break;
5164 ++T;
5165 }
5166 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5167 auto *L = static_cast<RuleMatcher *>(A);
5168 auto *R = static_cast<RuleMatcher *>(B);
5169 return L->getFirstConditionAsRootType() <
5170 R->getFirstConditionAsRootType();
5171 });
5172 if (T != E)
5173 F = ++T;
5174 }
Roman Tereshinfedae332018-05-23 02:04:19 +00005175 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5176 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00005177 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5178 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00005179}
5180
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005181void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00005182 if (!UseCoverageFile.empty()) {
5183 RuleCoverage = CodeGenCoverage();
5184 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5185 if (!RuleCoverageBufOrErr) {
5186 PrintWarning(SMLoc(), "Missing rule coverage data");
5187 RuleCoverage = None;
5188 } else {
5189 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5190 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5191 RuleCoverage = None;
5192 }
5193 }
5194 }
5195
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005196 // Track the run-time opcode values
5197 gatherOpcodeValues();
5198 // Track the run-time LLT ID values
5199 gatherTypeIDValues();
5200
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005201 // Track the GINodeEquiv definitions.
5202 gatherNodeEquivs();
5203
5204 emitSourceFileHeader(("Global Instruction Selector for the " +
5205 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005206 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005207 // Look through the SelectionDAG patterns we found, possibly emitting some.
5208 for (const PatternToMatch &Pat : CGP.ptms()) {
5209 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00005210
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005211 auto MatcherOrErr = runOnPattern(Pat);
5212
5213 // The pattern analysis can fail, indicating an unsupported pattern.
5214 // Report that if we've been asked to do so.
5215 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005216 if (WarnOnSkippedPatterns) {
5217 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005218 "Skipped pattern: " + toString(std::move(Err)));
5219 } else {
5220 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005221 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005222 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005223 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005224 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005225
Daniel Sandersf76f3152017-11-16 00:46:35 +00005226 if (RuleCoverage) {
5227 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5228 ++NumPatternsTested;
5229 else
5230 PrintWarning(Pat.getSrcRecord()->getLoc(),
5231 "Pattern is not covered by a test");
5232 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005233 Rules.push_back(std::move(MatcherOrErr.get()));
5234 }
5235
Volkan Kelesf7f25682018-01-16 18:44:05 +00005236 // Comparison function to order records by name.
5237 auto orderByName = [](const Record *A, const Record *B) {
5238 return A->getName() < B->getName();
5239 };
5240
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005241 std::vector<Record *> ComplexPredicates =
5242 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00005243 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005244
5245 std::vector<Record *> CustomRendererFns =
5246 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00005247 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005248
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005249 unsigned MaxTemporaries = 0;
5250 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00005251 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005252
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005253 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5254 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5255 << ";\n"
5256 << "using PredicateBitset = "
5257 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5258 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5259
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005260 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5261 << " mutable MatcherState State;\n"
5262 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00005263 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005264 << Target.getName()
5265 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005266
5267 << " typedef void(" << Target.getName()
5268 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
Matt Arsenaultb4a64742020-01-08 12:53:15 -05005269 "MachineInstr&, int) "
Volkan Kelesf7f25682018-01-16 18:44:05 +00005270 "const;\n"
5271 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5272 "CustomRendererFn> "
5273 "ISelInfo;\n";
5274 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005275 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005276 << " static " << Target.getName()
5277 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005278 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005279 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005280 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005281 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005282 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005283 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005284 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005285 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5286 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005287 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005288
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005289 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5290 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005291 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5292 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005293 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005294
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005295 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5296 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5297 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005298
5299 // Separate subtarget features by how often they must be recomputed.
5300 SubtargetFeatureInfoMap ModuleFeatures;
5301 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5302 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5303 [](const SubtargetFeatureInfoMap::value_type &X) {
5304 return !X.second.mustRecomputePerFunction();
5305 });
5306 SubtargetFeatureInfoMap FunctionFeatures;
5307 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5308 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5309 [](const SubtargetFeatureInfoMap::value_type &X) {
5310 return X.second.mustRecomputePerFunction();
5311 });
5312
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005313 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Matt Arsenaultf937b432020-01-08 19:49:30 -05005314 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005315 ModuleFeatures, OS);
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005316
Matt Arsenaultf937b432020-01-08 19:49:30 -05005317
5318 OS << "void " << Target.getName() << "InstructionSelector"
5319 "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5320 " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5321 "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5322 "}\n";
5323
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005324 if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5325 // TODO: Implement PGSO.
5326 OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5327 OS << " return MF->getFunction().hasOptSize();\n";
5328 OS << "}\n\n";
5329 }
5330
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005331 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5332 Target.getName(), "InstructionSelector",
5333 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5334 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005335
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005336 // Emit a table containing the LLT objects needed by the matcher and an enum
5337 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005338 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005339 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005340 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005341 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005342 OS << "// LLT Objects.\n"
5343 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005344 for (const auto &TypeObject : TypeObjects) {
5345 OS << " ";
5346 TypeObject.emitCxxEnumValue(OS);
5347 OS << ",\n";
5348 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005349 OS << "};\n";
5350 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005351 << "const static LLT TypeObjects[] = {\n";
5352 for (const auto &TypeObject : TypeObjects) {
5353 OS << " ";
5354 TypeObject.emitCxxConstructorCall(OS);
5355 OS << ",\n";
5356 }
5357 OS << "};\n\n";
5358
5359 // Emit a table containing the PredicateBitsets objects needed by the matcher
5360 // and an enum for the matcher to reference them with.
5361 std::vector<std::vector<Record *>> FeatureBitsets;
5362 for (auto &Rule : Rules)
5363 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005364 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5365 const std::vector<Record *> &B) {
5366 if (A.size() < B.size())
5367 return true;
5368 if (A.size() > B.size())
5369 return false;
Mark de Wevere8d448e2019-12-22 18:58:32 +01005370 for (auto Pair : zip(A, B)) {
Fangrui Song3507c6e2018-09-30 22:31:29 +00005371 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5372 return true;
5373 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005374 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005375 }
5376 return false;
5377 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005378 FeatureBitsets.erase(
5379 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5380 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005381 OS << "// Feature bitsets.\n"
5382 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005383 << " GIFBS_Invalid,\n";
5384 for (const auto &FeatureBitset : FeatureBitsets) {
5385 if (FeatureBitset.empty())
5386 continue;
5387 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5388 }
5389 OS << "};\n"
5390 << "const static PredicateBitset FeatureBitsets[] {\n"
5391 << " {}, // GIFBS_Invalid\n";
5392 for (const auto &FeatureBitset : FeatureBitsets) {
5393 if (FeatureBitset.empty())
5394 continue;
5395 OS << " {";
5396 for (const auto &Feature : FeatureBitset) {
5397 const auto &I = SubtargetFeatures.find(Feature);
5398 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5399 OS << I->second.getEnumBitName() << ", ";
5400 }
5401 OS << "},\n";
5402 }
5403 OS << "};\n\n";
5404
5405 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005406 OS << "// ComplexPattern predicates.\n"
5407 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005408 << " GICP_Invalid,\n";
5409 for (const auto &Record : ComplexPredicates)
5410 OS << " GICP_" << Record->getName() << ",\n";
5411 OS << "};\n"
5412 << "// See constructor for table contents\n\n";
5413
Daniel Sanders8ead1292018-06-15 23:13:43 +00005414 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005415 bool Unset;
5416 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5417 !R->getValueAsBit("IsAPInt");
5418 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005419 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005420 bool Unset;
5421 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5422 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005423 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005424 return R->getValueAsBit("IsAPInt");
5425 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005426 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005427 OS << "\n";
5428
5429 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5430 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5431 << " nullptr, // GICP_Invalid\n";
5432 for (const auto &Record : ComplexPredicates)
5433 OS << " &" << Target.getName()
5434 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5435 << ", // " << Record->getName() << "\n";
5436 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005437
Volkan Kelesf7f25682018-01-16 18:44:05 +00005438 OS << "// Custom renderers.\n"
5439 << "enum {\n"
5440 << " GICR_Invalid,\n";
5441 for (const auto &Record : CustomRendererFns)
5442 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5443 OS << "};\n";
5444
5445 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5446 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
Matt Arsenault0274ed92020-01-08 18:57:44 -05005447 << " nullptr, // GICR_Invalid\n";
Volkan Kelesf7f25682018-01-16 18:44:05 +00005448 for (const auto &Record : CustomRendererFns)
5449 OS << " &" << Target.getName()
5450 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5451 << ", // " << Record->getName() << "\n";
5452 OS << "};\n\n";
5453
Fangrui Songefd94c52019-04-23 14:51:27 +00005454 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005455 int ScoreA = RuleMatcherScores[A.getRuleID()];
5456 int ScoreB = RuleMatcherScores[B.getRuleID()];
5457 if (ScoreA > ScoreB)
5458 return true;
5459 if (ScoreB > ScoreA)
5460 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005461 if (A.isHigherPriorityThan(B)) {
5462 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5463 "and less important at "
5464 "the same time");
5465 return true;
5466 }
5467 return false;
5468 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005469
Roman Tereshin2df4c222018-05-02 20:07:15 +00005470 OS << "bool " << Target.getName()
5471 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5472 "&CoverageInfo) const {\n"
5473 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5474 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005475 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5476 << " NewMIVector OutMIs;\n"
5477 << " State.MIs.clear();\n"
5478 << " State.MIs.push_back(&I);\n\n"
5479 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5480 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5481 << ", CoverageInfo)) {\n"
5482 << " return true;\n"
5483 << " }\n\n"
5484 << " return false;\n"
5485 << "}\n\n";
5486
Roman Tereshinbeb39312018-05-02 20:15:11 +00005487 const MatchTable Table =
5488 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005489 OS << "const int64_t *" << Target.getName()
5490 << "InstructionSelector::getMatchTable() const {\n";
5491 Table.emitDeclaration(OS);
5492 OS << " return ";
5493 Table.emitUse(OS);
5494 OS << ";\n}\n";
5495 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005496
5497 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5498 << "PredicateBitset AvailableModuleFeatures;\n"
5499 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5500 << "PredicateBitset getAvailableFeatures() const {\n"
5501 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5502 << "}\n"
5503 << "PredicateBitset\n"
5504 << "computeAvailableModuleFeatures(const " << Target.getName()
5505 << "Subtarget *Subtarget) const;\n"
5506 << "PredicateBitset\n"
5507 << "computeAvailableFunctionFeatures(const " << Target.getName()
5508 << "Subtarget *Subtarget,\n"
5509 << " const MachineFunction *MF) const;\n"
Matt Arsenaultf937b432020-01-08 19:49:30 -05005510 << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005511 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5512
5513 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5514 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5515 << "AvailableFunctionFeatures()\n"
5516 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005517}
5518
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005519void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5520 if (SubtargetFeatures.count(Predicate) == 0)
5521 SubtargetFeatures.emplace(
5522 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5523}
5524
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005525void RuleMatcher::optimize() {
5526 for (auto &Item : InsnVariableIDs) {
5527 InstructionMatcher &InsnMatcher = *Item.first;
5528 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005529 // Complex Patterns are usually expensive and they relatively rarely fail
5530 // on their own: more often we end up throwing away all the work done by a
5531 // matching part of a complex pattern because some other part of the
5532 // enclosing pattern didn't match. All of this makes it beneficial to
5533 // delay complex patterns until the very end of the rule matching,
5534 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005535 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005536 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005537 EpilogueMatchers.emplace_back(std::move(OP));
5538 OM->eraseNullPredicates();
5539 }
5540 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005541 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005542 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5543 const std::unique_ptr<PredicateMatcher> &R) {
5544 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5545 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5546 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005547}
5548
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005549bool RuleMatcher::hasFirstCondition() const {
5550 if (insnmatchers_empty())
5551 return false;
5552 InstructionMatcher &Matcher = insnmatchers_front();
5553 if (!Matcher.predicates_empty())
5554 return true;
5555 for (auto &OM : Matcher.operands())
5556 for (auto &OP : OM->predicates())
5557 if (!isa<InstructionOperandMatcher>(OP))
5558 return true;
5559 return false;
5560}
5561
5562const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5563 assert(!insnmatchers_empty() &&
5564 "Trying to get a condition from an empty RuleMatcher");
5565
5566 InstructionMatcher &Matcher = insnmatchers_front();
5567 if (!Matcher.predicates_empty())
5568 return **Matcher.predicates_begin();
5569 // If there is no more predicate on the instruction itself, look at its
5570 // operands.
5571 for (auto &OM : Matcher.operands())
5572 for (auto &OP : OM->predicates())
5573 if (!isa<InstructionOperandMatcher>(OP))
5574 return *OP;
5575
5576 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5577 "no conditions");
5578}
5579
5580std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5581 assert(!insnmatchers_empty() &&
5582 "Trying to pop a condition from an empty RuleMatcher");
5583
5584 InstructionMatcher &Matcher = insnmatchers_front();
5585 if (!Matcher.predicates_empty())
5586 return Matcher.predicates_pop_front();
5587 // If there is no more predicate on the instruction itself, look at its
5588 // operands.
5589 for (auto &OM : Matcher.operands())
5590 for (auto &OP : OM->predicates())
5591 if (!isa<InstructionOperandMatcher>(OP)) {
5592 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5593 OM->eraseNullPredicates();
5594 return Result;
5595 }
5596
5597 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5598 "no conditions");
5599}
5600
5601bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005602 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005603
5604 if (empty()) {
5605 // Sharing predicates for nested instructions is not supported yet as we
5606 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5607 // only work on the original root instruction (InsnVarID == 0):
5608 if (Predicate.getInsnVarID() != 0)
5609 return false;
5610 // ... otherwise an empty group can handle any predicate with no specific
5611 // requirements:
5612 return true;
5613 }
5614
5615 const Matcher &Representative = **Matchers.begin();
5616 const auto &RepresentativeCondition = Representative.getFirstCondition();
5617 // ... if not empty, the group can only accomodate matchers with the exact
5618 // same first condition:
5619 return Predicate.isIdentical(RepresentativeCondition);
5620}
5621
5622bool GroupMatcher::addMatcher(Matcher &Candidate) {
5623 if (!Candidate.hasFirstCondition())
5624 return false;
5625
5626 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5627 if (!candidateConditionMatches(Predicate))
5628 return false;
5629
5630 Matchers.push_back(&Candidate);
5631 return true;
5632}
5633
5634void GroupMatcher::finalize() {
5635 assert(Conditions.empty() && "Already finalized?");
5636 if (empty())
5637 return;
5638
5639 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005640 for (;;) {
5641 // All the checks are expected to succeed during the first iteration:
5642 for (const auto &Rule : Matchers)
5643 if (!Rule->hasFirstCondition())
5644 return;
5645 const auto &FirstCondition = FirstRule.getFirstCondition();
5646 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5647 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5648 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005649
Roman Tereshin152fc162018-05-23 22:50:53 +00005650 Conditions.push_back(FirstRule.popFirstCondition());
5651 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5652 Matchers[I]->popFirstCondition();
5653 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005654}
5655
5656void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005657 unsigned LabelID = ~0U;
5658 if (!Conditions.empty()) {
5659 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005660 Table << MatchTable::Opcode("GIM_Try", +1)
5661 << MatchTable::Comment("On fail goto")
5662 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005663 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005664 for (auto &Condition : Conditions)
5665 Condition->emitPredicateOpcodes(
5666 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5667
5668 for (const auto &M : Matchers)
5669 M->emit(Table);
5670
5671 // Exit the group
5672 if (!Conditions.empty())
5673 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005674 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005675}
5676
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005677bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005678 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005679}
5680
5681bool SwitchMatcher::candidateConditionMatches(
5682 const PredicateMatcher &Predicate) const {
5683
5684 if (empty()) {
5685 // Sharing predicates for nested instructions is not supported yet as we
5686 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5687 // only work on the original root instruction (InsnVarID == 0):
5688 if (Predicate.getInsnVarID() != 0)
5689 return false;
5690 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5691 // could fail as not all the types of conditions are supported:
5692 if (!isSupportedPredicateType(Predicate))
5693 return false;
5694 // ... or the condition might not have a proper implementation of
5695 // getValue() / isIdenticalDownToValue() yet:
5696 if (!Predicate.hasValue())
5697 return false;
5698 // ... otherwise an empty Switch can accomodate the condition with no
5699 // further requirements:
5700 return true;
5701 }
5702
5703 const Matcher &CaseRepresentative = **Matchers.begin();
5704 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5705 // Switch-cases must share the same kind of condition and path to the value it
5706 // checks:
5707 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5708 return false;
5709
5710 const auto Value = Predicate.getValue();
5711 // ... but be unique with respect to the actual value they check:
5712 return Values.count(Value) == 0;
5713}
5714
5715bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5716 if (!Candidate.hasFirstCondition())
5717 return false;
5718
5719 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5720 if (!candidateConditionMatches(Predicate))
5721 return false;
5722 const auto Value = Predicate.getValue();
5723 Values.insert(Value);
5724
5725 Matchers.push_back(&Candidate);
5726 return true;
5727}
5728
5729void SwitchMatcher::finalize() {
5730 assert(Condition == nullptr && "Already finalized");
5731 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5732 if (empty())
5733 return;
5734
5735 std::stable_sort(Matchers.begin(), Matchers.end(),
5736 [](const Matcher *L, const Matcher *R) {
5737 return L->getFirstCondition().getValue() <
5738 R->getFirstCondition().getValue();
5739 });
5740 Condition = Matchers[0]->popFirstCondition();
5741 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5742 Matchers[I]->popFirstCondition();
5743}
5744
5745void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5746 MatchTable &Table) {
5747 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5748
5749 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5750 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5751 << MatchTable::IntValue(Condition->getInsnVarID());
5752 return;
5753 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005754 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5755 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5756 << MatchTable::IntValue(Condition->getInsnVarID())
5757 << MatchTable::Comment("Op")
5758 << MatchTable::IntValue(Condition->getOpIdx());
5759 return;
5760 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005761
5762 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5763 "predicate type that is claimed to be supported");
5764}
5765
5766void SwitchMatcher::emit(MatchTable &Table) {
5767 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5768 if (empty())
5769 return;
5770 assert(Condition != nullptr &&
5771 "Broken SwitchMatcher, hasn't been finalized?");
5772
5773 std::vector<unsigned> LabelIDs(Values.size());
5774 std::generate(LabelIDs.begin(), LabelIDs.end(),
5775 [&Table]() { return Table.allocateLabelID(); });
5776 const unsigned Default = Table.allocateLabelID();
5777
5778 const int64_t LowerBound = Values.begin()->getRawValue();
5779 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5780
5781 emitPredicateSpecificOpcodes(*Condition, Table);
5782
5783 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5784 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5785 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5786
5787 int64_t J = LowerBound;
5788 auto VI = Values.begin();
5789 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5790 auto V = *VI++;
5791 while (J++ < V.getRawValue())
5792 Table << MatchTable::IntValue(0);
5793 V.turnIntoComment();
5794 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5795 }
5796 Table << MatchTable::LineBreak;
5797
5798 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5799 Table << MatchTable::Label(LabelIDs[I]);
5800 Matchers[I]->emit(Table);
5801 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5802 }
5803 Table << MatchTable::Label(Default);
5804}
5805
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005806unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005807
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005808} // end anonymous namespace
5809
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005810//===----------------------------------------------------------------------===//
5811
5812namespace llvm {
5813void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5814 GlobalISelEmitter(RK).run(OS);
5815}
5816} // End llvm namespace