blob: 2a7be0cb821d1d5bbe73ef1933e30710e3669290 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This tablegen backend emits code for use by the GlobalISel instruction
11/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12///
13/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14/// backend, filters out the ones that are unsupported, maps
15/// SelectionDAG-specific constructs to their GlobalISel counterpart
16/// (when applicable: MVT to LLT; SDNode to generic Instruction).
17///
18/// Not all patterns are supported: pass the tablegen invocation
19/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20/// as well as why.
21///
22/// The generated file defines a single method:
23/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24/// intended to be used in InstructionSelector::select as the first-step
25/// selector for the patterns that don't require complex C++.
26///
27/// FIXME: We'll probably want to eventually define a base
28/// "TargetGenInstructionSelector" class.
29///
30//===----------------------------------------------------------------------===//
31
32#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000033#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000034#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000035#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000036#include "llvm/ADT/Statistic.h"
Daniel Sandersf76f3152017-11-16 00:46:35 +000037#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000038#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000039#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000040#include "llvm/Support/LowLevelTypeImpl.h"
David Blaikie13e77db2018-03-23 23:58:25 +000041#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000046#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000047#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000055STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000056STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57
Daniel Sanders0848b232017-03-27 13:15:13 +000058cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060static cl::opt<bool> WarnOnSkippedPatterns(
61 "warn-on-skipped-patterns",
62 cl::desc("Explain why a pattern was skipped for inclusion "
63 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000064 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000065
Daniel Sandersf76f3152017-11-16 00:46:35 +000066static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
70
71static cl::opt<std::string> UseCoverageFile(
72 "gisel-coverage-file", cl::init(""),
73 cl::desc("Specify file to retrieve coverage information from"),
74 cl::cat(GlobalISelEmitterCat));
75
Quentin Colombetec76d9c2017-12-18 19:47:41 +000076static cl::opt<bool> OptimizeMatchTable(
77 "optimize-match-table",
78 cl::desc("Generate an optimized version of the match table"),
79 cl::init(true), cl::cat(GlobalISelEmitterCat));
80
Daniel Sandersbdfebb82017-03-15 20:18:38 +000081namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000082//===- Helper functions ---------------------------------------------------===//
83
Daniel Sanders11300ce2017-10-13 21:28:03 +000084/// Get the name of the enum value used to number the predicate function.
85std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000086 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000088 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000089 Predicate.getFnName();
90}
91
92/// Get the opcode used to check this predicate.
93std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000094 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000095}
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097/// This class stands in for LLT wherever we want to tablegen-erate an
98/// equivalent at compiler run-time.
99class LLTCodeGen {
100private:
101 LLT Ty;
102
103public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000104 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
110
111 emitCxxEnumValue(OS);
112 return OS.str();
113 }
114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
119 }
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
123 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
129 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000130 llvm_unreachable("Unhandled LLT");
131 }
132
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
137 }
138 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000141 return;
142 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
147 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 llvm_unreachable("Unhandled LLT");
149 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000150
151 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000152
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000153 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000156 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000161
162 if (Ty.isVector() != Other.Ty.isVector())
163 return Ty.isVector() < Other.Ty.isVector();
164 if (Ty.isScalar() != Other.Ty.isScalar())
165 return Ty.isScalar() < Other.Ty.isScalar();
166 if (Ty.isPointer() != Other.Ty.isPointer())
167 return Ty.isPointer() < Other.Ty.isPointer();
168
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
174
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000176 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000177
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000179};
180
Daniel Sandersf84bc372018-05-05 20:53:24 +0000181// Track all types that are used so we can emit the corresponding enum.
182std::set<LLTCodeGen> KnownTypes;
183
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000184class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000185/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000189
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000193
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000197}
198
Florian Hahn6b1db822018-06-14 20:32:58 +0000199static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000200 std::string Explanation = "";
201 StringRef Separator = "";
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
238
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
244
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
247 }
248
249 OS << ']';
250 }
251
Matt Arsenault52c26242019-07-31 00:14:43 +0000252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
255
Daniel Sanders76664652017-11-28 22:07:05 +0000256 if (P.isAtomicOrderingMonotonic())
257 Explanation += " monotonic";
258 if (P.isAtomicOrderingAcquire())
259 Explanation += " acquire";
260 if (P.isAtomicOrderingRelease())
261 Explanation += " release";
262 if (P.isAtomicOrderingAcquireRelease())
263 Explanation += " acq_rel";
264 if (P.isAtomicOrderingSequentiallyConsistent())
265 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000266 if (P.isAtomicOrderingAcquireOrStronger())
267 Explanation += " >=acquire";
268 if (P.isAtomicOrderingWeakerThanAcquire())
269 Explanation += " <acquire";
270 if (P.isAtomicOrderingReleaseOrStronger())
271 Explanation += " >=release";
272 if (P.isAtomicOrderingWeakerThanRelease())
273 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000274 }
275 return Explanation;
276}
277
Daniel Sandersd0656a32017-04-13 09:45:37 +0000278std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000281
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
289
Volkan Kelesf7f25682018-01-16 18:44:05 +0000290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
294
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000295 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000296}
297
298/// Helper function to let the emitter report skip reason error messages.
299static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
301}
302
Florian Hahn6b1db822018-06-14 20:32:58 +0000303static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000304 std::string Explanation = "";
305 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000306
307 bool HasUnsupportedPredicate = false;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
310
Daniel Sanders2c269f62017-08-24 09:11:20 +0000311 if (Predicate.isAlwaysTrue())
312 continue;
313
314 if (Predicate.isImmediatePattern())
315 continue;
316
Daniel Sandersf84bc372018-05-05 20:53:24 +0000317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000319 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320
Matt Arsenault02772492019-07-15 21:15:20 +0000321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sandersf84bc372018-05-05 20:53:24 +0000324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
326
Daniel Sanders76664652017-11-28 22:07:05 +0000327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
330 }
331
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
Matt Arsenault52c26242019-07-31 00:14:43 +0000336
337 if (Predicate.getMinAlignment() > 0)
338 continue;
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000339 }
340
Daniel Sanders76664652017-11-28 22:07:05 +0000341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
343
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000354 continue;
355
Daniel Sanders8ead1292018-06-15 23:13:43 +0000356 if (Predicate.hasGISelPredicateCode())
357 continue;
358
Daniel Sanders2c269f62017-08-24 09:11:20 +0000359 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000365 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000366 }
367
Volkan Kelesf7f25682018-01-16 18:44:05 +0000368 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000369 return Error::success();
370
371 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000372}
373
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000374static Record *getInitValueAsRegClass(Init *V) {
375 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377 return VDefInit->getDef()->getValueAsDef("RegClass");
378 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379 return VDefInit->getDef();
380 }
381 return nullptr;
382}
383
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000384std::string
385getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
390}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000391
392//===- MatchTable Helpers -------------------------------------------------===//
393
394class MatchTable;
395
396/// A record to be stored in a MatchTable.
397///
398/// This class represents any and all output that may be required to emit the
399/// MatchTable. Instances are most often configured to represent an opcode or
400/// value that will be emitted to the table with some formatting but it can also
401/// represent commas, comments, and other formatting instructions.
402struct MatchTableRecord {
403 enum RecordFlagsBits {
404 MTRF_None = 0x0,
405 /// Causes EmitStr to be formatted as comment when emitted.
406 MTRF_Comment = 0x1,
407 /// Causes the record value to be followed by a comma when emitted.
408 MTRF_CommaFollows = 0x2,
409 /// Causes the record value to be followed by a line break when emitted.
410 MTRF_LineBreakFollows = 0x4,
411 /// Indicates that the record defines a label and causes an additional
412 /// comment to be emitted containing the index of the label.
413 MTRF_Label = 0x8,
414 /// Causes the record to be emitted as the index of the label specified by
415 /// LabelID along with a comment indicating where that label is.
416 MTRF_JumpTarget = 0x10,
417 /// Causes the formatter to add a level of indentation before emitting the
418 /// record.
419 MTRF_Indent = 0x20,
420 /// Causes the formatter to remove a level of indentation after emitting the
421 /// record.
422 MTRF_Outdent = 0x40,
423 };
424
425 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426 /// reference or define.
427 unsigned LabelID;
428 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429 /// value, a label name.
430 std::string EmitStr;
431
432private:
433 /// The number of MatchTable elements described by this record. Comments are 0
434 /// while values are typically 1. Values >1 may occur when we need to emit
435 /// values that exceed the size of a MatchTable element.
436 unsigned NumElements;
437
438public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
441
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000442 /// The actual run-time value, if known
443 int64_t RawValue;
444
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
451
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000452 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
453 "This value is reserved for non-labels");
454 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000455 MatchTableRecord(const MatchTableRecord &Other) = default;
456 MatchTableRecord(MatchTableRecord &&Other) = default;
457
458 /// Useful if a Match Table Record gets optimized out
459 void turnIntoComment() {
460 Flags |= MTRF_Comment;
461 Flags &= ~MTRF_CommaFollows;
462 NumElements = 0;
463 }
464
465 /// For Jump Table generation purposes
466 bool operator<(const MatchTableRecord &Other) const {
467 return RawValue < Other.RawValue;
468 }
469 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000470
471 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
472 const MatchTable &Table) const;
473 unsigned size() const { return NumElements; }
474};
475
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000476class Matcher;
477
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000478/// Holds the contents of a generated MatchTable to enable formatting and the
479/// necessary index tracking needed to support GIM_Try.
480class MatchTable {
481 /// An unique identifier for the table. The generated table will be named
482 /// MatchTable${ID}.
483 unsigned ID;
484 /// The records that make up the table. Also includes comments describing the
485 /// values being emitted and line breaks to format it.
486 std::vector<MatchTableRecord> Contents;
487 /// The currently defined labels.
488 DenseMap<unsigned, unsigned> LabelMap;
489 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000490 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000491 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000492 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000493 /// Determines if the table should be instrumented for rule coverage tracking.
494 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000495
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000496public:
497 static MatchTableRecord LineBreak;
498 static MatchTableRecord Comment(StringRef Comment) {
499 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
500 }
501 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
502 unsigned ExtraFlags = 0;
503 if (IndentAdjust > 0)
504 ExtraFlags |= MatchTableRecord::MTRF_Indent;
505 if (IndentAdjust < 0)
506 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
507
508 return MatchTableRecord(None, Opcode, 1,
509 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
510 }
511 static MatchTableRecord NamedValue(StringRef NamedValue) {
512 return MatchTableRecord(None, NamedValue, 1,
513 MatchTableRecord::MTRF_CommaFollows);
514 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000515 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
516 return MatchTableRecord(None, NamedValue, 1,
517 MatchTableRecord::MTRF_CommaFollows, RawValue);
518 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000519 static MatchTableRecord NamedValue(StringRef Namespace,
520 StringRef NamedValue) {
521 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
522 MatchTableRecord::MTRF_CommaFollows);
523 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000524 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
525 int64_t RawValue) {
526 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
527 MatchTableRecord::MTRF_CommaFollows, RawValue);
528 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000529 static MatchTableRecord IntValue(int64_t IntValue) {
530 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
531 MatchTableRecord::MTRF_CommaFollows);
532 }
533 static MatchTableRecord Label(unsigned LabelID) {
534 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
535 MatchTableRecord::MTRF_Label |
536 MatchTableRecord::MTRF_Comment |
537 MatchTableRecord::MTRF_LineBreakFollows);
538 }
539 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000540 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000541 MatchTableRecord::MTRF_JumpTarget |
542 MatchTableRecord::MTRF_Comment |
543 MatchTableRecord::MTRF_CommaFollows);
544 }
545
Roman Tereshinbeb39312018-05-02 20:15:11 +0000546 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000547
Roman Tereshinbeb39312018-05-02 20:15:11 +0000548 MatchTable(bool WithCoverage, unsigned ID = 0)
549 : ID(ID), IsWithCoverage(WithCoverage) {}
550
551 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000552
553 void push_back(const MatchTableRecord &Value) {
554 if (Value.Flags & MatchTableRecord::MTRF_Label)
555 defineLabel(Value.LabelID);
556 Contents.push_back(Value);
557 CurrentSize += Value.size();
558 }
559
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000560 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000561
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000562 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000563 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000564 }
565
566 unsigned getLabelIndex(unsigned LabelID) const {
567 const auto I = LabelMap.find(LabelID);
568 assert(I != LabelMap.end() && "Use of undeclared label");
569 return I->second;
570 }
571
Daniel Sanders8e82af22017-07-27 11:03:45 +0000572 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
573
574 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000575 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000576 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000577 LineBreak.emit(OS, true, *this);
578 OS << std::string(Indentation, ' ');
579
580 for (auto I = Contents.begin(), E = Contents.end(); I != E;
581 ++I) {
582 bool LineBreakIsNext = false;
583 const auto &NextI = std::next(I);
584
585 if (NextI != E) {
586 if (NextI->EmitStr == "" &&
587 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
588 LineBreakIsNext = true;
589 }
590
591 if (I->Flags & MatchTableRecord::MTRF_Indent)
592 Indentation += 2;
593
594 I->emit(OS, LineBreakIsNext, *this);
595 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
596 OS << std::string(Indentation, ' ');
597
598 if (I->Flags & MatchTableRecord::MTRF_Outdent)
599 Indentation -= 2;
600 }
601 OS << "};\n";
602 }
603};
604
605MatchTableRecord MatchTable::LineBreak = {
606 None, "" /* Emit String */, 0 /* Elements */,
607 MatchTableRecord::MTRF_LineBreakFollows};
608
609void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
610 const MatchTable &Table) const {
611 bool UseLineComment =
612 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
613 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
614 UseLineComment = false;
615
616 if (Flags & MTRF_Comment)
617 OS << (UseLineComment ? "// " : "/*");
618
619 OS << EmitStr;
620 if (Flags & MTRF_Label)
621 OS << ": @" << Table.getLabelIndex(LabelID);
622
623 if (Flags & MTRF_Comment && !UseLineComment)
624 OS << "*/";
625
626 if (Flags & MTRF_JumpTarget) {
627 if (Flags & MTRF_Comment)
628 OS << " ";
629 OS << Table.getLabelIndex(LabelID);
630 }
631
632 if (Flags & MTRF_CommaFollows) {
633 OS << ",";
634 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
635 OS << " ";
636 }
637
638 if (Flags & MTRF_LineBreakFollows)
639 OS << "\n";
640}
641
642MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
643 Table.push_back(Value);
644 return Table;
645}
646
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000647//===- Matchers -----------------------------------------------------------===//
648
Daniel Sandersbee57392017-04-04 13:25:23 +0000649class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000650class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000651class PredicateMatcher;
652class RuleMatcher;
653
654class Matcher {
655public:
656 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000657 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000658 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000659
660 virtual bool hasFirstCondition() const = 0;
661 virtual const PredicateMatcher &getFirstCondition() const = 0;
662 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000663};
664
Roman Tereshinbeb39312018-05-02 20:15:11 +0000665MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
666 bool WithCoverage) {
667 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000668 for (Matcher *Rule : Rules)
669 Rule->emit(Table);
670
671 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
672}
673
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000674class GroupMatcher final : public Matcher {
675 /// Conditions that form a common prefix of all the matchers contained.
676 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
677
678 /// All the nested matchers, sharing a common prefix.
679 std::vector<Matcher *> Matchers;
680
681 /// An owning collection for any auxiliary matchers created while optimizing
682 /// nested matchers contained.
683 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000684
685public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000686 /// Add a matcher to the collection of nested matchers if it meets the
687 /// requirements, and return true. If it doesn't, do nothing and return false.
688 ///
689 /// Expected to preserve its argument, so it could be moved out later on.
690 bool addMatcher(Matcher &Candidate);
691
692 /// Mark the matcher as fully-built and ensure any invariants expected by both
693 /// optimize() and emit(...) methods. Generally, both sequences of calls
694 /// are expected to lead to a sensible result:
695 ///
696 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
697 /// addMatcher(...)*; finalize(); emit(...);
698 ///
699 /// or generally
700 ///
701 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
702 ///
703 /// Multiple calls to optimize() are expected to be handled gracefully, though
704 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
705 /// aren't generally supported. emit(...) is expected to be non-mutating and
706 /// producing the exact same results upon repeated calls.
707 ///
708 /// addMatcher() calls after the finalize() call are not supported.
709 ///
710 /// finalize() and optimize() are both allowed to mutate the contained
711 /// matchers, so moving them out after finalize() is not supported.
712 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000713 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000714 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000715
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000716 /// Could be used to move out the matchers added previously, unless finalize()
717 /// has been already called. If any of the matchers are moved out, the group
718 /// becomes safe to destroy, but not safe to re-use for anything else.
719 iterator_range<std::vector<Matcher *>::iterator> matchers() {
720 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000721 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000722 size_t size() const { return Matchers.size(); }
723 bool empty() const { return Matchers.empty(); }
724
725 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
726 assert(!Conditions.empty() &&
727 "Trying to pop a condition from a condition-less group");
728 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
729 Conditions.erase(Conditions.begin());
730 return P;
731 }
732 const PredicateMatcher &getFirstCondition() const override {
733 assert(!Conditions.empty() &&
734 "Trying to get a condition from a condition-less group");
735 return *Conditions.front();
736 }
737 bool hasFirstCondition() const override { return !Conditions.empty(); }
738
739private:
740 /// See if a candidate matcher could be added to this group solely by
741 /// analyzing its first condition.
742 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000743};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000744
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000745class SwitchMatcher : public Matcher {
746 /// All the nested matchers, representing distinct switch-cases. The first
747 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
748 /// matchers must share the same type and path to a value they check, in other
749 /// words, be isIdenticalDownToValue, but have different values they check
750 /// against.
751 std::vector<Matcher *> Matchers;
752
753 /// The representative condition, with a type and a path (InsnVarID and OpIdx
754 /// in most cases) shared by all the matchers contained.
755 std::unique_ptr<PredicateMatcher> Condition = nullptr;
756
757 /// Temporary set used to check that the case values don't repeat within the
758 /// same switch.
759 std::set<MatchTableRecord> Values;
760
761 /// An owning collection for any auxiliary matchers created while optimizing
762 /// nested matchers contained.
763 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
764
765public:
766 bool addMatcher(Matcher &Candidate);
767
768 void finalize();
769 void emit(MatchTable &Table) override;
770
771 iterator_range<std::vector<Matcher *>::iterator> matchers() {
772 return make_range(Matchers.begin(), Matchers.end());
773 }
774 size_t size() const { return Matchers.size(); }
775 bool empty() const { return Matchers.empty(); }
776
777 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
778 // SwitchMatcher doesn't have a common first condition for its cases, as all
779 // the cases only share a kind of a value (a type and a path to it) they
780 // match, but deliberately differ in the actual value they match.
781 llvm_unreachable("Trying to pop a condition from a condition-less group");
782 }
783 const PredicateMatcher &getFirstCondition() const override {
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
785 }
786 bool hasFirstCondition() const override { return false; }
787
788private:
789 /// See if the predicate type has a Switch-implementation for it.
790 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
791
792 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
793
794 /// emit()-helper
795 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
796 MatchTable &Table);
797};
798
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000799/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000800class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000801public:
Daniel Sanders08464522018-01-29 21:09:12 +0000802 using ActionList = std::list<std::unique_ptr<MatchAction>>;
803 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000804
805protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000806 /// A list of matchers that all need to succeed for the current rule to match.
807 /// FIXME: This currently supports a single match position but could be
808 /// extended to support multiple positions to support div/rem fusion or
809 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000810 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
811 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000812
813 /// A list of actions that need to be taken when all predicates in this rule
814 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000815 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000816
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000817 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000818
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000819 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000820 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000821
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000822 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000823
824 // The set of instruction matchers that have not yet been claimed for mutation
825 // by a BuildMI.
826 MutatableInsnSet MutatableInsns;
827
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000828 /// A map of named operands defined by the matchers that may be referenced by
829 /// the renderers.
830 StringMap<OperandMatcher *> DefinedOperands;
831
Matt Arsenault3e45c702019-09-06 20:32:37 +0000832 /// A map of anonymous physical register operands defined by the matchers that
833 /// may be referenced by the renderers.
834 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
835
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000836 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000837 unsigned NextInsnVarID;
838
Daniel Sanders198447a2017-11-01 00:29:47 +0000839 /// ID for the next output instruction allocated with allocateOutputInsnID()
840 unsigned NextOutputInsnID;
841
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000842 /// ID for the next temporary register ID allocated with allocateTempRegID()
843 unsigned NextTempRegID;
844
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000845 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000846 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000847
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000848 ArrayRef<SMLoc> SrcLoc;
849
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000850 typedef std::tuple<Record *, unsigned, unsigned>
851 DefinedComplexPatternSubOperand;
852 typedef StringMap<DefinedComplexPatternSubOperand>
853 DefinedComplexPatternSubOperandMap;
854 /// A map of Symbolic Names to ComplexPattern sub-operands.
855 DefinedComplexPatternSubOperandMap ComplexSubOperands;
856
Daniel Sandersf76f3152017-11-16 00:46:35 +0000857 uint64_t RuleID;
858 static uint64_t NextRuleID;
859
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000860public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000861 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000862 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000863 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000864 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
865 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000866 RuleMatcher(RuleMatcher &&Other) = default;
867 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000868
Daniel Sandersf76f3152017-11-16 00:46:35 +0000869 uint64_t getRuleID() const { return RuleID; }
870
Daniel Sanders05540042017-08-08 10:44:31 +0000871 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000872 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000873 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000874
875 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000876 template <class Kind, class... Args>
877 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000878
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000879 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000880 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
881
882 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000883 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
884 return InsnVariableIDs.begin();
885 }
886 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
887 return InsnVariableIDs.end();
888 }
889 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
890 defined_insn_vars() const {
891 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
892 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000893
Daniel Sandersa7b75262017-10-31 18:50:24 +0000894 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
895 return MutatableInsns.begin();
896 }
897 MutatableInsnSet::const_iterator mutatable_insns_end() const {
898 return MutatableInsns.end();
899 }
900 iterator_range<typename MutatableInsnSet::const_iterator>
901 mutatable_insns() const {
902 return make_range(mutatable_insns_begin(), mutatable_insns_end());
903 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000904 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000905 bool R = MutatableInsns.erase(InsnMatcher);
906 assert(R && "Reserving a mutatable insn that isn't available");
907 (void)R;
908 }
909
Daniel Sanders7438b262017-10-31 23:03:18 +0000910 action_iterator actions_begin() { return Actions.begin(); }
911 action_iterator actions_end() { return Actions.end(); }
912 iterator_range<action_iterator> actions() {
913 return make_range(actions_begin(), actions_end());
914 }
915
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000916 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
917
Matt Arsenault3e45c702019-09-06 20:32:37 +0000918 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
919
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000920 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
921 unsigned RendererID, unsigned SubOperandID) {
922 if (ComplexSubOperands.count(SymbolicName))
923 return failedImport(
924 "Complex suboperand referenced more than once (Operand: " +
925 SymbolicName + ")");
926
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000927 ComplexSubOperands[SymbolicName] =
928 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000929
930 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000931 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000932
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000933 Optional<DefinedComplexPatternSubOperand>
934 getComplexSubOperand(StringRef SymbolicName) const {
935 const auto &I = ComplexSubOperands.find(SymbolicName);
936 if (I == ComplexSubOperands.end())
937 return None;
938 return I->second;
939 }
940
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000941 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000942 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000943 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000944
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000945 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000946 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000947
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000948 /// Compare the priority of this object and B.
949 ///
950 /// Returns true if this object is more important than B.
951 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000952
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000953 /// Report the maximum number of temporary operands needed by the rule
954 /// matcher.
955 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000956
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000957 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
958 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000959 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000960 bool hasFirstCondition() const override;
961 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000962 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000963
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000964 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000965 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000966
967 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000968 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000969
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000970 iterator_range<MatchersTy::iterator> insnmatchers() {
971 return make_range(Matchers.begin(), Matchers.end());
972 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000973 bool insnmatchers_empty() const { return Matchers.empty(); }
974 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000975};
976
Daniel Sandersf76f3152017-11-16 00:46:35 +0000977uint64_t RuleMatcher::NextRuleID = 0;
978
Daniel Sanders7438b262017-10-31 23:03:18 +0000979using action_iterator = RuleMatcher::action_iterator;
980
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000981template <class PredicateTy> class PredicateListMatcher {
982private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000983 /// Template instantiations should specialize this to return a string to use
984 /// for the comment emitted when there are no predicates.
985 std::string getNoPredicateComment() const;
986
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000987protected:
988 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
989 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000990
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000991 /// Track if the list of predicates was manipulated by one of the optimization
992 /// methods.
993 bool Optimized = false;
994
995public:
996 /// Construct a new predicate and add it to the matcher.
997 template <class Kind, class... Args>
998 Optional<Kind *> addPredicate(Args &&... args);
999
1000 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001001 return Predicates.begin();
1002 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001003 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001004 return Predicates.end();
1005 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001006 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001007 return make_range(predicates_begin(), predicates_end());
1008 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001009 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001010 return Predicates.size();
1011 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001012 bool predicates_empty() const { return Predicates.empty(); }
1013
1014 std::unique_ptr<PredicateTy> predicates_pop_front() {
1015 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001016 Predicates.pop_front();
1017 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001018 return Front;
1019 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001020
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001021 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1022 Predicates.push_front(std::move(Predicate));
1023 }
1024
1025 void eraseNullPredicates() {
1026 const auto NewEnd =
1027 std::stable_partition(Predicates.begin(), Predicates.end(),
1028 std::logical_not<std::unique_ptr<PredicateTy>>());
1029 if (NewEnd != Predicates.begin()) {
1030 Predicates.erase(Predicates.begin(), NewEnd);
1031 Optimized = true;
1032 }
1033 }
1034
Daniel Sanders9d662d22017-07-06 10:06:12 +00001035 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001036 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001037 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1038 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001039 Table << MatchTable::Comment(getNoPredicateComment())
1040 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001041 return;
1042 }
1043
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001044 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001045 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001046 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001047};
1048
Quentin Colombet063d7982017-12-14 23:44:07 +00001049class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001050public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001051 /// This enum is used for RTTI and also defines the priority that is given to
1052 /// the predicate when generating the matcher code. Kinds with higher priority
1053 /// must be tested first.
1054 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001055 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1056 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1057 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001058 ///
1059 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1060 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001061 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001062 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001063 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001064 IPM_ImmPredicate,
1065 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;
1183 for (const LLTCodeGen LLTy : KnownTypes)
1184 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
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001343/// Generates code to check that an operand is a G_CONSTANT with a particular
1344/// int.
1345class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001346protected:
1347 int64_t Value;
1348
1349public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001350 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001351 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001352
Quentin Colombet893e0f12017-12-15 23:24:39 +00001353 bool isIdentical(const PredicateMatcher &B) const override {
1354 return OperandPredicateMatcher::isIdentical(B) &&
1355 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1356 }
1357
Quentin Colombet063d7982017-12-14 23:44:07 +00001358 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001359 return P->getKind() == OPM_Int;
1360 }
1361
Quentin Colombetaad20be2017-12-15 23:07:42 +00001362 void emitPredicateOpcodes(MatchTable &Table,
1363 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001364 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1365 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1366 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1367 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001368 }
1369};
1370
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001371/// Generates code to check that an operand is a raw int (where MO.isImm() or
1372/// MO.isCImm() is true).
1373class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1374protected:
1375 int64_t Value;
1376
1377public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001378 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001379 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1380 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001381
Quentin Colombet893e0f12017-12-15 23:24:39 +00001382 bool isIdentical(const PredicateMatcher &B) const override {
1383 return OperandPredicateMatcher::isIdentical(B) &&
1384 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1385 }
1386
Quentin Colombet063d7982017-12-14 23:44:07 +00001387 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001388 return P->getKind() == OPM_LiteralInt;
1389 }
1390
Quentin Colombetaad20be2017-12-15 23:07:42 +00001391 void emitPredicateOpcodes(MatchTable &Table,
1392 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001393 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1394 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1395 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1396 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001397 }
1398};
1399
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001400/// Generates code to check that an operand is an CmpInst predicate
1401class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1402protected:
1403 std::string PredName;
1404
1405public:
1406 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1407 std::string P)
1408 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1409
1410 bool isIdentical(const PredicateMatcher &B) const override {
1411 return OperandPredicateMatcher::isIdentical(B) &&
1412 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1413 }
1414
1415 static bool classof(const PredicateMatcher *P) {
1416 return P->getKind() == OPM_CmpPredicate;
1417 }
1418
1419 void emitPredicateOpcodes(MatchTable &Table,
1420 RuleMatcher &Rule) const override {
1421 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1422 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1423 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1424 << MatchTable::Comment("Predicate")
1425 << MatchTable::NamedValue("CmpInst", PredName)
1426 << MatchTable::LineBreak;
1427 }
1428};
1429
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001430/// Generates code to check that an operand is an intrinsic ID.
1431class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1432protected:
1433 const CodeGenIntrinsic *II;
1434
1435public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001436 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1437 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001438 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001439
Quentin Colombet893e0f12017-12-15 23:24:39 +00001440 bool isIdentical(const PredicateMatcher &B) const override {
1441 return OperandPredicateMatcher::isIdentical(B) &&
1442 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1443 }
1444
Quentin Colombet063d7982017-12-14 23:44:07 +00001445 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001446 return P->getKind() == OPM_IntrinsicID;
1447 }
1448
Quentin Colombetaad20be2017-12-15 23:07:42 +00001449 void emitPredicateOpcodes(MatchTable &Table,
1450 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001451 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1452 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1453 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1454 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1455 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001456 }
1457};
1458
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001459/// Generates code to check that a set of predicates match for a particular
1460/// operand.
1461class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1462protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001463 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001464 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001465 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001466
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001467 /// The index of the first temporary variable allocated to this operand. The
1468 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001469 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001470 unsigned AllocatedTemporariesBaseID;
1471
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001472public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001473 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001474 const std::string &SymbolicName,
1475 unsigned AllocatedTemporariesBaseID)
1476 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1477 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001478
1479 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1480 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001481 void setSymbolicName(StringRef Name) {
1482 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1483 SymbolicName = Name;
1484 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001485
1486 /// Construct a new operand predicate and add it to the matcher.
1487 template <class Kind, class... Args>
1488 Optional<Kind *> addPredicate(Args &&... args) {
1489 if (isSameAsAnotherOperand())
1490 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001491 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001492 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1493 return static_cast<Kind *>(Predicates.back().get());
1494 }
1495
1496 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001497 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001498
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001499 std::string getOperandExpr(unsigned InsnVarID) const {
1500 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1501 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001502 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001503
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001504 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1505
Daniel Sandersa71f4542017-10-16 00:56:30 +00001506 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001507 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001508
Daniel Sanders9d662d22017-07-06 10:06:12 +00001509 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001510 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001511 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1512 if (!Optimized) {
1513 std::string Comment;
1514 raw_string_ostream CommentOS(Comment);
1515 CommentOS << "MIs[" << getInsnVarID() << "] ";
1516 if (SymbolicName.empty())
1517 CommentOS << "Operand " << OpIdx;
1518 else
1519 CommentOS << SymbolicName;
1520 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1521 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001522
Quentin Colombetaad20be2017-12-15 23:07:42 +00001523 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001524 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001525
1526 /// Compare the priority of this object and B.
1527 ///
1528 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001529 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001530 // Operand matchers involving more predicates have higher priority.
1531 if (predicates_size() > B.predicates_size())
1532 return true;
1533 if (predicates_size() < B.predicates_size())
1534 return false;
1535
1536 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001537 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001538 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1539 return true;
1540 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1541 return false;
1542 }
1543
1544 return false;
1545 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001546
1547 /// Report the maximum number of temporary operands needed by the operand
1548 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001549 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001550 return std::accumulate(
1551 predicates().begin(), predicates().end(), 0,
1552 [](unsigned A,
1553 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001554 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001555 });
1556 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001557
1558 unsigned getAllocatedTemporariesBaseID() const {
1559 return AllocatedTemporariesBaseID;
1560 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001561
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001562 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001563 for (const auto &Predicate : predicates())
1564 if (isa<SameOperandMatcher>(Predicate))
1565 return true;
1566 return false;
1567 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001568};
1569
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001570Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001571 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001572 if (!VTy.isMachineValueType())
1573 return failedImport("unsupported typeset");
1574
1575 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1576 addPredicate<PointerToAnyOperandMatcher>(0);
1577 return Error::success();
1578 }
1579
1580 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1581 if (!OpTyOrNone)
1582 return failedImport("unsupported type");
1583
1584 if (OperandIsAPointer)
1585 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001586 else if (VTy.isPointer())
1587 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1588 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001589 else
1590 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1591 return Error::success();
1592}
1593
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001594unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1595 return Operand.getAllocatedTemporariesBaseID();
1596}
1597
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001598/// Generates code to check a predicate on an instruction.
1599///
1600/// Typical predicates include:
1601/// * The opcode of the instruction is a particular value.
1602/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001603class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001604public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001605 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1606 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001607 virtual ~InstructionPredicateMatcher() {}
1608
Daniel Sanders759ff412017-02-24 13:58:11 +00001609 /// Compare the priority of this object and B.
1610 ///
1611 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001612 virtual bool
1613 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001614 return Kind < B.Kind;
1615 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001616};
1617
Daniel Sanders2c269f62017-08-24 09:11:20 +00001618template <>
1619std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001620PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001621 return "No instruction predicates";
1622}
1623
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001624/// Generates code to check the opcode of an instruction.
1625class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1626protected:
1627 const CodeGenInstruction *I;
1628
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001629 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1630
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001631public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001632 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1633 OpcodeValues.clear();
1634
1635 unsigned OpcodeValue = 0;
1636 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1637 OpcodeValues[I] = OpcodeValue++;
1638 }
1639
Quentin Colombetaad20be2017-12-15 23:07:42 +00001640 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1641 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001642
Quentin Colombet063d7982017-12-14 23:44:07 +00001643 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001644 return P->getKind() == IPM_Opcode;
1645 }
1646
Quentin Colombet893e0f12017-12-15 23:24:39 +00001647 bool isIdentical(const PredicateMatcher &B) const override {
1648 return InstructionPredicateMatcher::isIdentical(B) &&
1649 I == cast<InstructionOpcodeMatcher>(&B)->I;
1650 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001651 MatchTableRecord getValue() const override {
1652 const auto VI = OpcodeValues.find(I);
1653 if (VI != OpcodeValues.end())
1654 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1655 VI->second);
1656 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1657 }
1658 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001659
Quentin Colombetaad20be2017-12-15 23:07:42 +00001660 void emitPredicateOpcodes(MatchTable &Table,
1661 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001662 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001663 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001664 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001665 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001666
1667 /// Compare the priority of this object and B.
1668 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001669 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001670 bool
1671 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001672 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1673 return true;
1674 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1675 return false;
1676
1677 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1678 // this is cosmetic at the moment, we may want to drive a similar ordering
1679 // using instruction frequency information to improve compile time.
1680 if (const InstructionOpcodeMatcher *BO =
1681 dyn_cast<InstructionOpcodeMatcher>(&B))
1682 return I->TheDef->getName() < BO->I->TheDef->getName();
1683
1684 return false;
1685 };
Daniel Sanders05540042017-08-08 10:44:31 +00001686
1687 bool isConstantInstruction() const {
1688 return I->TheDef->getName() == "G_CONSTANT";
1689 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001690
Roman Tereshin19da6672018-05-22 04:31:50 +00001691 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001692 unsigned getNumOperands() const { return I->Operands.size(); }
1693
1694 StringRef getOperandType(unsigned OpIdx) const {
1695 return I->Operands[OpIdx].OperandType;
1696 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001697};
1698
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001699DenseMap<const CodeGenInstruction *, unsigned>
1700 InstructionOpcodeMatcher::OpcodeValues;
1701
Roman Tereshin19da6672018-05-22 04:31:50 +00001702class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1703 unsigned NumOperands = 0;
1704
1705public:
1706 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1707 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1708 NumOperands(NumOperands) {}
1709
1710 static bool classof(const PredicateMatcher *P) {
1711 return P->getKind() == IPM_NumOperands;
1712 }
1713
1714 bool isIdentical(const PredicateMatcher &B) const override {
1715 return InstructionPredicateMatcher::isIdentical(B) &&
1716 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1717 }
1718
1719 void emitPredicateOpcodes(MatchTable &Table,
1720 RuleMatcher &Rule) const override {
1721 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1722 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1723 << MatchTable::Comment("Expected")
1724 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1725 }
1726};
1727
Daniel Sanders2c269f62017-08-24 09:11:20 +00001728/// Generates code to check that this instruction is a constant whose value
1729/// meets an immediate predicate.
1730///
1731/// Immediates are slightly odd since they are typically used like an operand
1732/// but are represented as an operator internally. We typically write simm8:$src
1733/// in a tablegen pattern, but this is just syntactic sugar for
1734/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1735/// that will be matched and the predicate (which is attached to the imm
1736/// operator) that will be tested. In SelectionDAG this describes a
1737/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1738///
1739/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1740/// this representation, the immediate could be tested with an
1741/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1742/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1743/// there are two implementation issues with producing that matcher
1744/// configuration from the SelectionDAG pattern:
1745/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1746/// were we to sink the immediate predicate to the operand we would have to
1747/// have two partial implementations of PatFrag support, one for immediates
1748/// and one for non-immediates.
1749/// * At the point we handle the predicate, the OperandMatcher hasn't been
1750/// created yet. If we were to sink the predicate to the OperandMatcher we
1751/// would also have to complicate (or duplicate) the code that descends and
1752/// creates matchers for the subtree.
1753/// Overall, it's simpler to handle it in the place it was found.
1754class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1755protected:
1756 TreePredicateFn Predicate;
1757
1758public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001759 InstructionImmPredicateMatcher(unsigned InsnVarID,
1760 const TreePredicateFn &Predicate)
1761 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1762 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001763
Quentin Colombet893e0f12017-12-15 23:24:39 +00001764 bool isIdentical(const PredicateMatcher &B) const override {
1765 return InstructionPredicateMatcher::isIdentical(B) &&
1766 Predicate.getOrigPatFragRecord() ==
1767 cast<InstructionImmPredicateMatcher>(&B)
1768 ->Predicate.getOrigPatFragRecord();
1769 }
1770
Quentin Colombet063d7982017-12-14 23:44:07 +00001771 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001772 return P->getKind() == IPM_ImmPredicate;
1773 }
1774
Quentin Colombetaad20be2017-12-15 23:07:42 +00001775 void emitPredicateOpcodes(MatchTable &Table,
1776 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001777 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001778 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1779 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001780 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001781 << MatchTable::LineBreak;
1782 }
1783};
1784
Daniel Sanders76664652017-11-28 22:07:05 +00001785/// Generates code to check that a memory instruction has a atomic ordering
1786/// MachineMemoryOperand.
1787class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001788public:
1789 enum AOComparator {
1790 AO_Exactly,
1791 AO_OrStronger,
1792 AO_WeakerThan,
1793 };
1794
1795protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001796 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001797 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001798
Daniel Sanders39690bd2017-10-15 02:41:12 +00001799public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001800 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001801 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001802 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1803 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001804
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001805 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001806 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001807 }
1808
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001809 bool isIdentical(const PredicateMatcher &B) const override {
1810 if (!InstructionPredicateMatcher::isIdentical(B))
1811 return false;
1812 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1813 return Order == R.Order && Comparator == R.Comparator;
1814 }
1815
Quentin Colombetaad20be2017-12-15 23:07:42 +00001816 void emitPredicateOpcodes(MatchTable &Table,
1817 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001818 StringRef Opcode = "GIM_CheckAtomicOrdering";
1819
1820 if (Comparator == AO_OrStronger)
1821 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1822 if (Comparator == AO_WeakerThan)
1823 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1824
1825 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1826 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001827 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001828 << MatchTable::LineBreak;
1829 }
1830};
1831
Daniel Sandersf84bc372018-05-05 20:53:24 +00001832/// Generates code to check that the size of an MMO is exactly N bytes.
1833class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1834protected:
1835 unsigned MMOIdx;
1836 uint64_t Size;
1837
1838public:
1839 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1840 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1841 MMOIdx(MMOIdx), Size(Size) {}
1842
1843 static bool classof(const PredicateMatcher *P) {
1844 return P->getKind() == IPM_MemoryLLTSize;
1845 }
1846 bool isIdentical(const PredicateMatcher &B) const override {
1847 return InstructionPredicateMatcher::isIdentical(B) &&
1848 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1849 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1850 }
1851
1852 void emitPredicateOpcodes(MatchTable &Table,
1853 RuleMatcher &Rule) const override {
1854 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1855 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1856 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1857 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1858 << MatchTable::LineBreak;
1859 }
1860};
1861
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001862class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1863protected:
1864 unsigned MMOIdx;
1865 SmallVector<unsigned, 4> AddrSpaces;
1866
1867public:
1868 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1869 ArrayRef<unsigned> AddrSpaces)
1870 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1871 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1872
1873 static bool classof(const PredicateMatcher *P) {
1874 return P->getKind() == IPM_MemoryAddressSpace;
1875 }
1876 bool isIdentical(const PredicateMatcher &B) const override {
1877 if (!InstructionPredicateMatcher::isIdentical(B))
1878 return false;
1879 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1880 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1881 }
1882
1883 void emitPredicateOpcodes(MatchTable &Table,
1884 RuleMatcher &Rule) const override {
1885 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1886 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1887 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1888 // Encode number of address spaces to expect.
1889 << MatchTable::Comment("NumAddrSpace")
1890 << MatchTable::IntValue(AddrSpaces.size());
1891 for (unsigned AS : AddrSpaces)
1892 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1893
1894 Table << MatchTable::LineBreak;
1895 }
1896};
1897
Matt Arsenault52c26242019-07-31 00:14:43 +00001898class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1899protected:
1900 unsigned MMOIdx;
1901 int MinAlign;
1902
1903public:
1904 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1905 int MinAlign)
1906 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1907 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1908 assert(MinAlign > 0);
1909 }
1910
1911 static bool classof(const PredicateMatcher *P) {
1912 return P->getKind() == IPM_MemoryAlignment;
1913 }
1914
1915 bool isIdentical(const PredicateMatcher &B) const override {
1916 if (!InstructionPredicateMatcher::isIdentical(B))
1917 return false;
1918 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1919 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1920 }
1921
1922 void emitPredicateOpcodes(MatchTable &Table,
1923 RuleMatcher &Rule) const override {
1924 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1925 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1926 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1927 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1928 << MatchTable::LineBreak;
1929 }
1930};
1931
Daniel Sandersf84bc372018-05-05 20:53:24 +00001932/// Generates code to check that the size of an MMO is less-than, equal-to, or
1933/// greater than a given LLT.
1934class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1935public:
1936 enum RelationKind {
1937 GreaterThan,
1938 EqualTo,
1939 LessThan,
1940 };
1941
1942protected:
1943 unsigned MMOIdx;
1944 RelationKind Relation;
1945 unsigned OpIdx;
1946
1947public:
1948 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1949 enum RelationKind Relation,
1950 unsigned OpIdx)
1951 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1952 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1953
1954 static bool classof(const PredicateMatcher *P) {
1955 return P->getKind() == IPM_MemoryVsLLTSize;
1956 }
1957 bool isIdentical(const PredicateMatcher &B) const override {
1958 return InstructionPredicateMatcher::isIdentical(B) &&
1959 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1960 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1961 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1962 }
1963
1964 void emitPredicateOpcodes(MatchTable &Table,
1965 RuleMatcher &Rule) const override {
1966 Table << MatchTable::Opcode(Relation == EqualTo
1967 ? "GIM_CheckMemorySizeEqualToLLT"
1968 : Relation == GreaterThan
1969 ? "GIM_CheckMemorySizeGreaterThanLLT"
1970 : "GIM_CheckMemorySizeLessThanLLT")
1971 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1972 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1973 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1974 << MatchTable::LineBreak;
1975 }
1976};
1977
Daniel Sanders8ead1292018-06-15 23:13:43 +00001978/// Generates code to check an arbitrary C++ instruction predicate.
1979class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1980protected:
1981 TreePredicateFn Predicate;
1982
1983public:
1984 GenericInstructionPredicateMatcher(unsigned InsnVarID,
1985 TreePredicateFn Predicate)
1986 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
1987 Predicate(Predicate) {}
1988
1989 static bool classof(const InstructionPredicateMatcher *P) {
1990 return P->getKind() == IPM_GenericPredicate;
1991 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00001992 bool isIdentical(const PredicateMatcher &B) const override {
1993 return InstructionPredicateMatcher::isIdentical(B) &&
1994 Predicate ==
1995 static_cast<const GenericInstructionPredicateMatcher &>(B)
1996 .Predicate;
1997 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00001998 void emitPredicateOpcodes(MatchTable &Table,
1999 RuleMatcher &Rule) const override {
2000 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2001 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2002 << MatchTable::Comment("FnId")
2003 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2004 << MatchTable::LineBreak;
2005 }
2006};
2007
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002008/// Generates code to check that a set of predicates and operands match for a
2009/// particular instruction.
2010///
2011/// Typical predicates include:
2012/// * Has a specific opcode.
2013/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002014class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002015protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002016 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002017
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002018 RuleMatcher &Rule;
2019
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002020 /// The operands to match. All rendered operands must be present even if the
2021 /// condition is always true.
2022 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002023 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002024
Daniel Sanders05540042017-08-08 10:44:31 +00002025 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002026 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002027
Matt Arsenault3e45c702019-09-06 20:32:37 +00002028 /// PhysRegInputs - List list has an entry for each explicitly specified
2029 /// physreg input to the pattern. The first elt is the Register node, the
2030 /// second is the recorded slot number the input pattern match saved it in.
2031 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2032
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002033public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002034 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002035 : Rule(Rule), SymbolicName(SymbolicName) {
2036 // We create a new instruction matcher.
2037 // Get a new ID for that instruction.
2038 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2039 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002040
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002041 /// Construct a new instruction predicate and add it to the matcher.
2042 template <class Kind, class... Args>
2043 Optional<Kind *> addPredicate(Args &&... args) {
2044 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002045 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002046 return static_cast<Kind *>(Predicates.back().get());
2047 }
2048
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002049 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002050
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002051 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002052
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002053 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002054 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2055 unsigned AllocatedTemporariesBaseID) {
2056 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2057 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002058 if (!SymbolicName.empty())
2059 Rule.defineOperand(SymbolicName, *Operands.back());
2060
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002061 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002062 }
2063
Daniel Sandersffc7d582017-03-29 15:37:18 +00002064 OperandMatcher &getOperand(unsigned OpIdx) {
2065 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002066 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002067 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002068 });
2069 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002070 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002071 llvm_unreachable("Failed to lookup operand");
2072 }
2073
Matt Arsenault3e45c702019-09-06 20:32:37 +00002074 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2075 unsigned TempOpIdx) {
2076 assert(SymbolicName.empty());
2077 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2078 Operands.emplace_back(OM);
2079 Rule.definePhysRegOperand(Reg, *OM);
2080 PhysRegInputs.emplace_back(Reg, OpIdx);
2081 return *OM;
2082 }
2083
2084 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2085 return PhysRegInputs;
2086 }
2087
Daniel Sanders05540042017-08-08 10:44:31 +00002088 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002089 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002090 OperandVec::iterator operands_begin() { return Operands.begin(); }
2091 OperandVec::iterator operands_end() { return Operands.end(); }
2092 iterator_range<OperandVec::iterator> operands() {
2093 return make_range(operands_begin(), operands_end());
2094 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002095 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2096 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002097 iterator_range<OperandVec::const_iterator> operands() const {
2098 return make_range(operands_begin(), operands_end());
2099 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002100 bool operands_empty() const { return Operands.empty(); }
2101
2102 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002103
Roman Tereshin19da6672018-05-22 04:31:50 +00002104 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002105
2106 /// Emit MatchTable opcodes that test whether the instruction named in
2107 /// InsnVarName matches all the predicates and all the operands.
2108 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002109 if (NumOperandsCheck)
2110 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2111 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002112
Quentin Colombetaad20be2017-12-15 23:07:42 +00002113 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002115 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002116 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002117 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002118
2119 /// Compare the priority of this object and B.
2120 ///
2121 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002122 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002123 // Instruction matchers involving more operands have higher priority.
2124 if (Operands.size() > B.Operands.size())
2125 return true;
2126 if (Operands.size() < B.Operands.size())
2127 return false;
2128
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002129 for (auto &&P : zip(predicates(), B.predicates())) {
2130 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2131 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2132 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002133 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002134 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002135 return false;
2136 }
2137
2138 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002139 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002140 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002141 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002142 return false;
2143 }
2144
2145 return false;
2146 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002147
2148 /// Report the maximum number of temporary operands needed by the instruction
2149 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002150 unsigned countRendererFns() {
2151 return std::accumulate(
2152 predicates().begin(), predicates().end(), 0,
2153 [](unsigned A,
2154 const std::unique_ptr<PredicateMatcher> &Predicate) {
2155 return A + Predicate->countRendererFns();
2156 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002157 std::accumulate(
2158 Operands.begin(), Operands.end(), 0,
2159 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002160 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002161 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002162 }
Daniel Sanders05540042017-08-08 10:44:31 +00002163
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002164 InstructionOpcodeMatcher &getOpcodeMatcher() {
2165 for (auto &P : predicates())
2166 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2167 return *OpMatcher;
2168 llvm_unreachable("Didn't find an opcode matcher");
2169 }
2170
2171 bool isConstantInstruction() {
2172 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002173 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002174
2175 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002176};
2177
Roman Tereshin19da6672018-05-22 04:31:50 +00002178StringRef RuleMatcher::getOpcode() const {
2179 return Matchers.front()->getOpcode();
2180}
2181
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002182unsigned RuleMatcher::getNumOperands() const {
2183 return Matchers.front()->getNumOperands();
2184}
2185
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002186LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2187 InstructionMatcher &InsnMatcher = *Matchers.front();
2188 if (!InsnMatcher.predicates_empty())
2189 if (const auto *TM =
2190 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2191 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2192 return TM->getTy();
2193 return {};
2194}
2195
Daniel Sandersbee57392017-04-04 13:25:23 +00002196/// Generates code to check that the operand is a register defined by an
2197/// instruction that matches the given instruction matcher.
2198///
2199/// For example, the pattern:
2200/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2201/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2202/// the:
2203/// (G_ADD $src1, $src2)
2204/// subpattern.
2205class InstructionOperandMatcher : public OperandPredicateMatcher {
2206protected:
2207 std::unique_ptr<InstructionMatcher> InsnMatcher;
2208
2209public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002210 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2211 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002212 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002213 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002214
Quentin Colombet063d7982017-12-14 23:44:07 +00002215 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002216 return P->getKind() == OPM_Instruction;
2217 }
2218
2219 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2220
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002221 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2222 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2223 Table << MatchTable::Opcode("GIM_RecordInsn")
2224 << MatchTable::Comment("DefineMI")
2225 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2226 << MatchTable::IntValue(getInsnVarID())
2227 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2228 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2229 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002230 }
2231
Quentin Colombetaad20be2017-12-15 23:07:42 +00002232 void emitPredicateOpcodes(MatchTable &Table,
2233 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002234 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002235 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002236 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002237
2238 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2239 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2240 return true;
2241 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2242 return false;
2243
2244 if (const InstructionOperandMatcher *BP =
2245 dyn_cast<InstructionOperandMatcher>(&B))
2246 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2247 return true;
2248 return false;
2249 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002250};
2251
Roman Tereshin19da6672018-05-22 04:31:50 +00002252void InstructionMatcher::optimize() {
2253 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2254 const auto &OpcMatcher = getOpcodeMatcher();
2255
2256 Stash.push_back(predicates_pop_front());
2257 if (Stash.back().get() == &OpcMatcher) {
2258 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2259 Stash.emplace_back(
2260 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2261 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002262
2263 for (auto &OM : Operands)
2264 for (auto &OP : OM->predicates())
2265 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2266 Stash.push_back(std::move(OP));
2267 OM->eraseNullPredicates();
2268 break;
2269 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002270 }
2271
2272 if (InsnVarID > 0) {
2273 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2274 for (auto &OP : Operands[0]->predicates())
2275 OP.reset();
2276 Operands[0]->eraseNullPredicates();
2277 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002278 for (auto &OM : Operands) {
2279 for (auto &OP : OM->predicates())
2280 if (isa<LLTOperandMatcher>(OP))
2281 Stash.push_back(std::move(OP));
2282 OM->eraseNullPredicates();
2283 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002284 while (!Stash.empty())
2285 prependPredicate(Stash.pop_back_val());
2286}
2287
Daniel Sanders43c882c2017-02-01 10:53:10 +00002288//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002289class OperandRenderer {
2290public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002291 enum RendererKind {
2292 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002293 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002294 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002295 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002296 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002297 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002298 OR_Imm,
2299 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002300 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002301 OR_ComplexPattern,
2302 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002303 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002304
2305protected:
2306 RendererKind Kind;
2307
2308public:
2309 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2310 virtual ~OperandRenderer() {}
2311
2312 RendererKind getKind() const { return Kind; }
2313
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002314 virtual void emitRenderOpcodes(MatchTable &Table,
2315 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002316};
2317
2318/// A CopyRenderer emits code to copy a single operand from an existing
2319/// instruction to the one being built.
2320class CopyRenderer : public OperandRenderer {
2321protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002322 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002323 /// The name of the operand.
2324 const StringRef SymbolicName;
2325
2326public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002327 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2328 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002329 SymbolicName(SymbolicName) {
2330 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2331 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002332
2333 static bool classof(const OperandRenderer *R) {
2334 return R->getKind() == OR_Copy;
2335 }
2336
2337 const StringRef getSymbolicName() const { return SymbolicName; }
2338
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002339 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002340 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002341 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002342 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2343 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2344 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002345 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002346 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002347 }
2348};
2349
Matt Arsenault3e45c702019-09-06 20:32:37 +00002350/// A CopyRenderer emits code to copy a virtual register to a specific physical
2351/// register.
2352class CopyPhysRegRenderer : public OperandRenderer {
2353protected:
2354 unsigned NewInsnID;
2355 Record *PhysReg;
2356
2357public:
2358 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2359 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2360 PhysReg(Reg) {
2361 assert(PhysReg);
2362 }
2363
2364 static bool classof(const OperandRenderer *R) {
2365 return R->getKind() == OR_CopyPhysReg;
2366 }
2367
2368 Record *getPhysReg() const { return PhysReg; }
2369
2370 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2371 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2372 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2373 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2374 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2375 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2376 << MatchTable::IntValue(Operand.getOpIdx())
2377 << MatchTable::Comment(PhysReg->getName())
2378 << MatchTable::LineBreak;
2379 }
2380};
2381
Daniel Sandersd66e0902017-10-23 18:19:24 +00002382/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2383/// existing instruction to the one being built. If the operand turns out to be
2384/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2385class CopyOrAddZeroRegRenderer : public OperandRenderer {
2386protected:
2387 unsigned NewInsnID;
2388 /// The name of the operand.
2389 const StringRef SymbolicName;
2390 const Record *ZeroRegisterDef;
2391
2392public:
2393 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002394 StringRef SymbolicName, Record *ZeroRegisterDef)
2395 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2396 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2397 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2398 }
2399
2400 static bool classof(const OperandRenderer *R) {
2401 return R->getKind() == OR_CopyOrAddZeroReg;
2402 }
2403
2404 const StringRef getSymbolicName() const { return SymbolicName; }
2405
2406 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2407 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2408 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2409 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2410 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2411 << MatchTable::Comment("OldInsnID")
2412 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002413 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002414 << MatchTable::NamedValue(
2415 (ZeroRegisterDef->getValue("Namespace")
2416 ? ZeroRegisterDef->getValueAsString("Namespace")
2417 : ""),
2418 ZeroRegisterDef->getName())
2419 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2420 }
2421};
2422
Daniel Sanders05540042017-08-08 10:44:31 +00002423/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2424/// an extended immediate operand.
2425class CopyConstantAsImmRenderer : public OperandRenderer {
2426protected:
2427 unsigned NewInsnID;
2428 /// The name of the operand.
2429 const std::string SymbolicName;
2430 bool Signed;
2431
2432public:
2433 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2434 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2435 SymbolicName(SymbolicName), Signed(true) {}
2436
2437 static bool classof(const OperandRenderer *R) {
2438 return R->getKind() == OR_CopyConstantAsImm;
2439 }
2440
2441 const StringRef getSymbolicName() const { return SymbolicName; }
2442
2443 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002444 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002445 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2446 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2447 : "GIR_CopyConstantAsUImm")
2448 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2449 << MatchTable::Comment("OldInsnID")
2450 << MatchTable::IntValue(OldInsnVarID)
2451 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2452 }
2453};
2454
Daniel Sanders11300ce2017-10-13 21:28:03 +00002455/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2456/// instruction to an extended immediate operand.
2457class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2458protected:
2459 unsigned NewInsnID;
2460 /// The name of the operand.
2461 const std::string SymbolicName;
2462
2463public:
2464 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2465 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2466 SymbolicName(SymbolicName) {}
2467
2468 static bool classof(const OperandRenderer *R) {
2469 return R->getKind() == OR_CopyFConstantAsFPImm;
2470 }
2471
2472 const StringRef getSymbolicName() const { return SymbolicName; }
2473
2474 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002475 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002476 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2477 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2478 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2479 << MatchTable::Comment("OldInsnID")
2480 << MatchTable::IntValue(OldInsnVarID)
2481 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2482 }
2483};
2484
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002485/// A CopySubRegRenderer emits code to copy a single register operand from an
2486/// existing instruction to the one being built and indicate that only a
2487/// subregister should be copied.
2488class CopySubRegRenderer : public OperandRenderer {
2489protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002490 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002491 /// The name of the operand.
2492 const StringRef SymbolicName;
2493 /// The subregister to extract.
2494 const CodeGenSubRegIndex *SubReg;
2495
2496public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002497 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2498 const CodeGenSubRegIndex *SubReg)
2499 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002500 SymbolicName(SymbolicName), SubReg(SubReg) {}
2501
2502 static bool classof(const OperandRenderer *R) {
2503 return R->getKind() == OR_CopySubReg;
2504 }
2505
2506 const StringRef getSymbolicName() const { return SymbolicName; }
2507
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002508 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002509 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002510 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002511 Table << MatchTable::Opcode("GIR_CopySubReg")
2512 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2513 << MatchTable::Comment("OldInsnID")
2514 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002515 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002516 << MatchTable::Comment("SubRegIdx")
2517 << MatchTable::IntValue(SubReg->EnumValue)
2518 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002519 }
2520};
2521
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002522/// Adds a specific physical register to the instruction being built.
2523/// This is typically useful for WZR/XZR on AArch64.
2524class AddRegisterRenderer : public OperandRenderer {
2525protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002526 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002527 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002528 bool IsDef;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002529
2530public:
Matt Arsenault3e45c702019-09-06 20:32:37 +00002531 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2532 bool IsDef = false)
2533 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2534 IsDef(IsDef) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002535
2536 static bool classof(const OperandRenderer *R) {
2537 return R->getKind() == OR_Register;
2538 }
2539
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002540 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2541 Table << MatchTable::Opcode("GIR_AddRegister")
2542 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2543 << MatchTable::NamedValue(
2544 (RegisterDef->getValue("Namespace")
2545 ? RegisterDef->getValueAsString("Namespace")
2546 : ""),
2547 RegisterDef->getName())
Matt Arsenault3e45c702019-09-06 20:32:37 +00002548 << MatchTable::Comment("AddRegisterRegFlags");
2549
2550 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2551 // really needed for a physical register reference. We can pack the
2552 // register and flags in a single field.
2553 if (IsDef)
2554 Table << MatchTable::NamedValue("RegState::Define");
2555 else
2556 Table << MatchTable::IntValue(0);
2557 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002558 }
2559};
2560
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002561/// Adds a specific temporary virtual register to the instruction being built.
2562/// This is used to chain instructions together when emitting multiple
2563/// instructions.
2564class TempRegRenderer : public OperandRenderer {
2565protected:
2566 unsigned InsnID;
2567 unsigned TempRegID;
2568 bool IsDef;
2569
2570public:
2571 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2572 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2573 IsDef(IsDef) {}
2574
2575 static bool classof(const OperandRenderer *R) {
2576 return R->getKind() == OR_TempRegister;
2577 }
2578
2579 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2580 Table << MatchTable::Opcode("GIR_AddTempRegister")
2581 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2582 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2583 << MatchTable::Comment("TempRegFlags");
2584 if (IsDef)
2585 Table << MatchTable::NamedValue("RegState::Define");
2586 else
2587 Table << MatchTable::IntValue(0);
2588 Table << MatchTable::LineBreak;
2589 }
2590};
2591
Daniel Sanders0ed28822017-04-12 08:23:08 +00002592/// Adds a specific immediate to the instruction being built.
2593class ImmRenderer : public OperandRenderer {
2594protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002595 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002596 int64_t Imm;
2597
2598public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002599 ImmRenderer(unsigned InsnID, int64_t Imm)
2600 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002601
2602 static bool classof(const OperandRenderer *R) {
2603 return R->getKind() == OR_Imm;
2604 }
2605
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002606 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2607 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2608 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2609 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002610 }
2611};
2612
Daniel Sanders2deea182017-04-22 15:11:04 +00002613/// Adds operands by calling a renderer function supplied by the ComplexPattern
2614/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002615class RenderComplexPatternOperand : public OperandRenderer {
2616private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002617 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002618 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002619 /// The name of the operand.
2620 const StringRef SymbolicName;
2621 /// The renderer number. This must be unique within a rule since it's used to
2622 /// identify a temporary variable to hold the renderer function.
2623 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002624 /// When provided, this is the suboperand of the ComplexPattern operand to
2625 /// render. Otherwise all the suboperands will be rendered.
2626 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002627
2628 unsigned getNumOperands() const {
2629 return TheDef.getValueAsDag("Operands")->getNumArgs();
2630 }
2631
2632public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002633 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002634 StringRef SymbolicName, unsigned RendererID,
2635 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002636 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002637 SymbolicName(SymbolicName), RendererID(RendererID),
2638 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002639
2640 static bool classof(const OperandRenderer *R) {
2641 return R->getKind() == OR_ComplexPattern;
2642 }
2643
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002644 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002645 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2646 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002647 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2648 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002649 << MatchTable::IntValue(RendererID);
2650 if (SubOperand.hasValue())
2651 Table << MatchTable::Comment("SubOperand")
2652 << MatchTable::IntValue(SubOperand.getValue());
2653 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002654 }
2655};
2656
Volkan Kelesf7f25682018-01-16 18:44:05 +00002657class CustomRenderer : public OperandRenderer {
2658protected:
2659 unsigned InsnID;
2660 const Record &Renderer;
2661 /// The name of the operand.
2662 const std::string SymbolicName;
2663
2664public:
2665 CustomRenderer(unsigned InsnID, const Record &Renderer,
2666 StringRef SymbolicName)
2667 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2668 SymbolicName(SymbolicName) {}
2669
2670 static bool classof(const OperandRenderer *R) {
2671 return R->getKind() == OR_Custom;
2672 }
2673
2674 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002675 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002676 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2677 Table << MatchTable::Opcode("GIR_CustomRenderer")
2678 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2679 << MatchTable::Comment("OldInsnID")
2680 << MatchTable::IntValue(OldInsnVarID)
2681 << MatchTable::Comment("Renderer")
2682 << MatchTable::NamedValue(
2683 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2684 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2685 }
2686};
2687
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002688/// An action taken when all Matcher predicates succeeded for a parent rule.
2689///
2690/// Typical actions include:
2691/// * Changing the opcode of an instruction.
2692/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002693class MatchAction {
2694public:
2695 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002696
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002697 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002698 virtual void emitActionOpcodes(MatchTable &Table,
2699 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002700};
2701
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002702/// Generates a comment describing the matched rule being acted upon.
2703class DebugCommentAction : public MatchAction {
2704private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002705 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002706
2707public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002708 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002709
Daniel Sandersa7b75262017-10-31 18:50:24 +00002710 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002711 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002712 }
2713};
2714
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002715/// Generates code to build an instruction or mutate an existing instruction
2716/// into the desired instruction when this is possible.
2717class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002718private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002719 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002720 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002721 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002722 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2723
2724 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002725 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2726 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002727 return false;
2728
Daniel Sandersa7b75262017-10-31 18:50:24 +00002729 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002730 return false;
2731
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002732 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002733 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002734 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002735 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002736 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002737 return false;
2738 } else
2739 return false;
2740 }
2741
2742 return true;
2743 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002744
Daniel Sanders43c882c2017-02-01 10:53:10 +00002745public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002746 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2747 : InsnID(InsnID), I(I), Matched(nullptr) {}
2748
Daniel Sanders08464522018-01-29 21:09:12 +00002749 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002750 const CodeGenInstruction *getCGI() const { return I; }
2751
Daniel Sandersa7b75262017-10-31 18:50:24 +00002752 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002753 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002754 if (canMutate(Rule, MutateCandidate)) {
2755 // Take the first one we're offered that we're able to mutate.
2756 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2757 Matched = MutateCandidate;
2758 return;
2759 }
2760 }
2761 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002762
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002763 template <class Kind, class... Args>
2764 Kind &addRenderer(Args&&... args) {
2765 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002766 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002767 return *static_cast<Kind *>(OperandRenderers.back().get());
2768 }
2769
Daniel Sandersa7b75262017-10-31 18:50:24 +00002770 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2771 if (Matched) {
2772 assert(canMutate(Rule, Matched) &&
2773 "Arranged to mutate an insn that isn't mutatable");
2774
2775 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002776 Table << MatchTable::Opcode("GIR_MutateOpcode")
2777 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2778 << MatchTable::Comment("RecycleInsnID")
2779 << MatchTable::IntValue(RecycleInsnID)
2780 << MatchTable::Comment("Opcode")
2781 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2782 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002783
2784 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002785 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002786 auto Namespace = Def->getValue("Namespace")
2787 ? Def->getValueAsString("Namespace")
2788 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002789 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2790 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2791 << MatchTable::NamedValue(Namespace, Def->getName())
2792 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002793 }
2794 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002795 auto Namespace = Use->getValue("Namespace")
2796 ? Use->getValueAsString("Namespace")
2797 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002798 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2799 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2800 << MatchTable::NamedValue(Namespace, Use->getName())
2801 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002802 }
2803 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002804 return;
2805 }
2806
2807 // TODO: Simple permutation looks like it could be almost as common as
2808 // mutation due to commutative operations.
2809
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002810 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2811 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2812 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2813 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002814 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002815 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002816
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002817 if (I->mayLoad || I->mayStore) {
2818 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2819 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2820 << MatchTable::Comment("MergeInsnID's");
2821 // Emit the ID's for all the instructions that are matched by this rule.
2822 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2823 // some other means of having a memoperand. Also limit this to
2824 // emitted instructions that expect to have a memoperand too. For
2825 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2826 // sign-extend instructions shouldn't put the memoperand on the
2827 // sign-extend since it has no effect there.
2828 std::vector<unsigned> MergeInsnIDs;
2829 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2830 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002831 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002832 for (const auto &MergeInsnID : MergeInsnIDs)
2833 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002834 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2835 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002836 }
2837
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002838 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2839 // better for combines. Particularly when there are multiple match
2840 // roots.
2841 if (InsnID == 0)
2842 Table << MatchTable::Opcode("GIR_EraseFromParent")
2843 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2844 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002845 }
2846};
2847
2848/// Generates code to constrain the operands of an output instruction to the
2849/// register classes specified by the definition of that instruction.
2850class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002851 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002852
2853public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002854 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002855
Daniel Sandersa7b75262017-10-31 18:50:24 +00002856 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002857 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2858 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2859 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002860 }
2861};
2862
2863/// Generates code to constrain the specified operand of an output instruction
2864/// to the specified register class.
2865class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002866 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002867 unsigned OpIdx;
2868 const CodeGenRegisterClass &RC;
2869
2870public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002871 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002872 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002873 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002874
Daniel Sandersa7b75262017-10-31 18:50:24 +00002875 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002876 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2877 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2878 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2879 << MatchTable::Comment("RC " + RC.getName())
2880 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002881 }
2882};
2883
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002884/// Generates code to create a temporary register which can be used to chain
2885/// instructions together.
2886class MakeTempRegisterAction : public MatchAction {
2887private:
2888 LLTCodeGen Ty;
2889 unsigned TempRegID;
2890
2891public:
2892 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2893 : Ty(Ty), TempRegID(TempRegID) {}
2894
2895 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2896 Table << MatchTable::Opcode("GIR_MakeTempReg")
2897 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2898 << MatchTable::Comment("TypeID")
2899 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2900 << MatchTable::LineBreak;
2901 }
2902};
2903
Daniel Sanders05540042017-08-08 10:44:31 +00002904InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002905 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002906 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002907 return *Matchers.back();
2908}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002909
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002910void RuleMatcher::addRequiredFeature(Record *Feature) {
2911 RequiredFeatures.push_back(Feature);
2912}
2913
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002914const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2915 return RequiredFeatures;
2916}
2917
Daniel Sanders7438b262017-10-31 23:03:18 +00002918// Emplaces an action of the specified Kind at the end of the action list.
2919//
2920// Returns a reference to the newly created action.
2921//
2922// Like std::vector::emplace_back(), may invalidate all iterators if the new
2923// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2924// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002925template <class Kind, class... Args>
2926Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002927 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002928 return *static_cast<Kind *>(Actions.back().get());
2929}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002930
Daniel Sanders7438b262017-10-31 23:03:18 +00002931// Emplaces an action of the specified Kind before the given insertion point.
2932//
2933// Returns an iterator pointing at the newly created instruction.
2934//
2935// Like std::vector::insert(), may invalidate all iterators if the new size
2936// exceeds the capacity. Otherwise, only invalidates the iterators from the
2937// insertion point onwards.
2938template <class Kind, class... Args>
2939action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2940 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002941 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002942 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002943}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002944
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002945unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002946 unsigned NewInsnVarID = NextInsnVarID++;
2947 InsnVariableIDs[&Matcher] = NewInsnVarID;
2948 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002949}
2950
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002951unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002952 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2953 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002954 return I->second;
2955 llvm_unreachable("Matched Insn was not captured in a local variable");
2956}
2957
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002958void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2959 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2960 DefinedOperands[SymbolicName] = &OM;
2961 return;
2962 }
2963
2964 // If the operand is already defined, then we must ensure both references in
2965 // the matcher have the exact same node.
2966 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2967}
2968
Matt Arsenault3e45c702019-09-06 20:32:37 +00002969void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
2970 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
2971 PhysRegOperands[Reg] = &OM;
2972 return;
2973 }
2974}
2975
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002976InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00002977RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2978 for (const auto &I : InsnVariableIDs)
2979 if (I.first->getSymbolicName() == SymbolicName)
2980 return *I.first;
2981 llvm_unreachable(
2982 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2983}
2984
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002985const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00002986RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
2987 const auto &I = PhysRegOperands.find(Reg);
2988
2989 if (I == PhysRegOperands.end()) {
2990 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
2991 " was not declared in matcher");
2992 }
2993
2994 return *I->second;
2995}
2996
2997const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002998RuleMatcher::getOperandMatcher(StringRef Name) const {
2999 const auto &I = DefinedOperands.find(Name);
3000
3001 if (I == DefinedOperands.end())
3002 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3003
3004 return *I->second;
3005}
3006
Daniel Sanders8e82af22017-07-27 11:03:45 +00003007void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003008 if (Matchers.empty())
3009 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003010
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003011 // The representation supports rules that require multiple roots such as:
3012 // %ptr(p0) = ...
3013 // %elt0(s32) = G_LOAD %ptr
3014 // %1(p0) = G_ADD %ptr, 4
3015 // %elt1(s32) = G_LOAD p0 %1
3016 // which could be usefully folded into:
3017 // %ptr(p0) = ...
3018 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3019 // on some targets but we don't need to make use of that yet.
3020 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003021
Daniel Sanders8e82af22017-07-27 11:03:45 +00003022 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003023 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003024 << MatchTable::Comment("On fail goto")
3025 << MatchTable::JumpTarget(LabelID)
3026 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003027 << MatchTable::LineBreak;
3028
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003029 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003030 Table << MatchTable::Opcode("GIM_CheckFeatures")
3031 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3032 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003033 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003034
Quentin Colombetaad20be2017-12-15 23:07:42 +00003035 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003036
Daniel Sandersbee57392017-04-04 13:25:23 +00003037 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003038 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003039 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003040 SmallVector<unsigned, 2> InsnIDs;
3041 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003042 // Skip the root node since it isn't moving anywhere. Everything else is
3043 // sinking to meet it.
3044 if (Pair.first == Matchers.front().get())
3045 continue;
3046
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003047 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003048 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003049 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003050
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003051 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003052 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003053 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3054 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3055 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003056
3057 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3058 // account for unsafe cases.
3059 //
3060 // Example:
3061 // MI1--> %0 = ...
3062 // %1 = ... %0
3063 // MI0--> %2 = ... %0
3064 // It's not safe to erase MI1. We currently handle this by not
3065 // erasing %0 (even when it's dead).
3066 //
3067 // Example:
3068 // MI1--> %0 = load volatile @a
3069 // %1 = load volatile @a
3070 // MI0--> %2 = ... %0
3071 // It's not safe to sink %0's def past %1. We currently handle
3072 // this by rejecting all loads.
3073 //
3074 // Example:
3075 // MI1--> %0 = load @a
3076 // %1 = store @a
3077 // MI0--> %2 = ... %0
3078 // It's not safe to sink %0's def past %1. We currently handle
3079 // this by rejecting all loads.
3080 //
3081 // Example:
3082 // G_CONDBR %cond, @BB1
3083 // BB0:
3084 // MI1--> %0 = load @a
3085 // G_BR @BB1
3086 // BB1:
3087 // MI0--> %2 = ... %0
3088 // It's not always safe to sink %0 across control flow. In this
3089 // case it may introduce a memory fault. We currentl handle this
3090 // by rejecting all loads.
3091 }
3092 }
3093
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003094 for (const auto &PM : EpilogueMatchers)
3095 PM->emitPredicateOpcodes(Table, *this);
3096
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003097 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003098 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003099
Roman Tereshinbeb39312018-05-02 20:15:11 +00003100 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003101 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3102 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003103 else
3104 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3105 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003107 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003108 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003109 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003110}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003111
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003112bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3113 // Rules involving more match roots have higher priority.
3114 if (Matchers.size() > B.Matchers.size())
3115 return true;
3116 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003117 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003118
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003119 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
3120 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3121 return true;
3122 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3123 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003124 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003125
3126 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003127}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003128
Daniel Sanders2deea182017-04-22 15:11:04 +00003129unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003130 return std::accumulate(
3131 Matchers.begin(), Matchers.end(), 0,
3132 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003133 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003134 });
3135}
3136
Daniel Sanders05540042017-08-08 10:44:31 +00003137bool OperandPredicateMatcher::isHigherPriorityThan(
3138 const OperandPredicateMatcher &B) const {
3139 // Generally speaking, an instruction is more important than an Int or a
3140 // LiteralInt because it can cover more nodes but theres an exception to
3141 // this. G_CONSTANT's are less important than either of those two because they
3142 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003143
3144 const InstructionOperandMatcher *AOM =
3145 dyn_cast<InstructionOperandMatcher>(this);
3146 const InstructionOperandMatcher *BOM =
3147 dyn_cast<InstructionOperandMatcher>(&B);
3148 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3149 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3150
3151 if (AOM && BOM) {
3152 // The relative priorities between a G_CONSTANT and any other instruction
3153 // don't actually matter but this code is needed to ensure a strict weak
3154 // ordering. This is particularly important on Windows where the rules will
3155 // be incorrectly sorted without it.
3156 if (AIsConstantInsn != BIsConstantInsn)
3157 return AIsConstantInsn < BIsConstantInsn;
3158 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003159 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003160
3161 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3162 return false;
3163 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3164 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003165
3166 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003167}
Daniel Sanders05540042017-08-08 10:44:31 +00003168
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003169void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003170 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003171 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003172 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003173 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003174
3175 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3176 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3177 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3178 << MatchTable::Comment("OtherMI")
3179 << MatchTable::IntValue(OtherInsnVarID)
3180 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003181 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003182 << MatchTable::LineBreak;
3183}
3184
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003185//===- GlobalISelEmitter class --------------------------------------------===//
3186
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003187class GlobalISelEmitter {
3188public:
3189 explicit GlobalISelEmitter(RecordKeeper &RK);
3190 void run(raw_ostream &OS);
3191
3192private:
3193 const RecordKeeper &RK;
3194 const CodeGenDAGPatterns CGP;
3195 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003196 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003197
Daniel Sanders39690bd2017-10-15 02:41:12 +00003198 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003199 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3200 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003201 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003202 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003203
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003204 /// Keep track of the equivalence between ComplexPattern's and
3205 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3206 /// GIComplexPatternEquiv.
3207 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3208
Volkan Kelesf7f25682018-01-16 18:44:05 +00003209 /// Keep track of the equivalence between SDNodeXForm's and
3210 /// GICustomOperandRenderer. Map entries are specified by subclassing
3211 /// GISDNodeXFormEquiv.
3212 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3213
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003214 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3215 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3216 DenseMap<uint64_t, int> RuleMatcherScores;
3217
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003218 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003219 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003220
Daniel Sandersf76f3152017-11-16 00:46:35 +00003221 // Rule coverage information.
3222 Optional<CodeGenCoverage> RuleCoverage;
3223
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003224 void gatherOpcodeValues();
3225 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003226 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003227
Daniel Sanders39690bd2017-10-15 02:41:12 +00003228 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003229 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003230 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003231
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003232 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003233 Expected<InstructionMatcher &>
3234 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3235 InstructionMatcher &InsnMatcher,
3236 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003237 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3238 unsigned &TempOpIdx) const;
3239 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003240 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003241 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003242 unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003243
Matt Arsenault3e45c702019-09-06 20:32:37 +00003244 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3245 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3246 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003247 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003248 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003249 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003250 Expected<action_iterator>
3251 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003252 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003253 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003254
Daniel Sanders7438b262017-10-31 23:03:18 +00003255 Expected<action_iterator>
3256 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3257 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003258 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003259 Expected<action_iterator>
3260 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3261 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003262 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003263 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3264 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003265 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003266 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003267 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3268 const std::vector<Record *> &ImplicitDefs) const;
3269
Daniel Sanders8ead1292018-06-15 23:13:43 +00003270 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3271 StringRef TypeIdentifier, StringRef ArgType,
3272 StringRef ArgName, StringRef AdditionalDeclarations,
3273 std::function<bool(const Record *R)> Filter);
3274 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3275 StringRef ArgType,
3276 std::function<bool(const Record *R)> Filter);
3277 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003278
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003279 /// Analyze pattern \p P, returning a matcher for it if possible.
3280 /// Otherwise, return an Error explaining why we don't support it.
3281 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003282
3283 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003284
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003285 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3286 bool WithCoverage);
3287
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003288 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3289 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3290 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3291 /// If no register class is found, return None.
3292 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003293 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3294 TreePatternNode *SuperRegNode,
3295 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003296 Optional<CodeGenSubRegIndex *>
3297 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003298
3299 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3300 /// Return None if no such class exists.
3301 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003302 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003303 TreePatternNode *SubRegIdxNode);
3304
3305 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3306 Optional<const CodeGenRegisterClass *>
3307 getRegClassFromLeaf(TreePatternNode *Leaf);
3308
3309 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3310 /// otherwise.
3311 Optional<const CodeGenRegisterClass *>
3312 inferRegClassFromPattern(TreePatternNode *N);
3313
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003314public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003315 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003316 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003317 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003318 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003319 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003320 /// Output without optimization:
3321 /// \verbatim
3322 /// # R1
3323 /// # predicate A
3324 /// # predicate B
3325 /// ...
3326 /// # R2
3327 /// # predicate A // <-- effectively this is going to be checked twice.
3328 /// // Once in R1 and once in R2.
3329 /// # predicate C
3330 /// \endverbatim
3331 /// Output with optimization:
3332 /// \verbatim
3333 /// # Group1_2
3334 /// # predicate A // <-- Check is now shared.
3335 /// # R1
3336 /// # predicate B
3337 /// # R2
3338 /// # predicate C
3339 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003340 template <class GroupT>
3341 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003342 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003343 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003344};
3345
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003346void GlobalISelEmitter::gatherOpcodeValues() {
3347 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3348}
3349
3350void GlobalISelEmitter::gatherTypeIDValues() {
3351 LLTOperandMatcher::initTypeIDValuesMap();
3352}
3353
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003354void GlobalISelEmitter::gatherNodeEquivs() {
3355 assert(NodeEquivs.empty());
3356 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003357 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003358
3359 assert(ComplexPatternEquivs.empty());
3360 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3361 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3362 if (!SelDAGEquiv)
3363 continue;
3364 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3365 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003366
3367 assert(SDNodeXFormEquivs.empty());
3368 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3369 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3370 if (!SelDAGEquiv)
3371 continue;
3372 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3373 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003374}
3375
Daniel Sanders39690bd2017-10-15 02:41:12 +00003376Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003377 return NodeEquivs.lookup(N);
3378}
3379
Daniel Sandersf84bc372018-05-05 20:53:24 +00003380const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003381GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003382 if (N->getNumChildren() >= 1) {
3383 // setcc operation maps to two different G_* instructions based on the type.
3384 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3385 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3386 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3387 }
3388
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003389 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3390 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003391 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3392 Predicate.isSignExtLoad())
3393 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3394 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3395 Predicate.isZeroExtLoad())
3396 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3397 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003398
Daniel Sandersf84bc372018-05-05 20:53:24 +00003399 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3400}
3401
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003402GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003403 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3404 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003405
3406//===- Emitter ------------------------------------------------------------===//
3407
Daniel Sandersc270c502017-03-30 09:36:33 +00003408Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003409GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003410 ArrayRef<Predicate> Predicates) {
3411 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003412 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003413 continue;
3414 declareSubtargetFeature(P.Def);
3415 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003416 }
3417
Daniel Sandersc270c502017-03-30 09:36:33 +00003418 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003419}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003420
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003421Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3422 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003423 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003424 Record *SrcGIEquivOrNull = nullptr;
3425 const CodeGenInstruction *SrcGIOrNull = nullptr;
3426
3427 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003428 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003429 return failedImport("Src pattern has multiple results");
3430
Florian Hahn6b1db822018-06-14 20:32:58 +00003431 if (Src->isLeaf()) {
3432 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003433 if (isa<IntInit>(SrcInit)) {
3434 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3435 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3436 } else
3437 return failedImport(
3438 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3439 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003440 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003441 if (!SrcGIEquivOrNull)
3442 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003443 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003444 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003445
3446 // The operators look good: match the opcode
3447 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3448 }
3449
3450 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003451 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003452 // Results don't have a name unless they are the root node. The caller will
3453 // set the name if appropriate.
3454 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3455 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3456 return failedImport(toString(std::move(Error)) +
3457 " for result of Src pattern operator");
3458 }
3459
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003460 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3461 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003462 if (Predicate.isAlwaysTrue())
3463 continue;
3464
3465 if (Predicate.isImmediatePattern()) {
3466 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3467 continue;
3468 }
3469
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003470 // An address space check is needed in all contexts if there is one.
3471 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3472 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3473 SmallVector<unsigned, 4> ParsedAddrSpaces;
3474
3475 for (Init *Val : AddrSpaces->getValues()) {
3476 IntInit *IntVal = dyn_cast<IntInit>(Val);
3477 if (!IntVal)
3478 return failedImport("Address space is not an integer");
3479 ParsedAddrSpaces.push_back(IntVal->getValue());
3480 }
3481
3482 if (!ParsedAddrSpaces.empty()) {
3483 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3484 0, ParsedAddrSpaces);
3485 }
3486 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003487
3488 int64_t MinAlign = Predicate.getMinAlignment();
3489 if (MinAlign > 0)
3490 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003491 }
3492
3493 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003494 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3495 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3496 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3497 continue;
3498 }
3499 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3500 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3501 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3502 continue;
3503 }
3504
Amara Emerson52e6d522019-08-02 23:33:13 +00003505 if (Predicate.isStore()) {
3506 if (Predicate.isTruncStore()) {
3507 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3508 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3509 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3510 continue;
3511 }
3512 if (Predicate.isNonTruncStore()) {
3513 // We need to check the sizes match here otherwise we could incorrectly
3514 // match truncating stores with non-truncating ones.
3515 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3516 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3517 }
Matt Arsenault02772492019-07-15 21:15:20 +00003518 }
3519
Daniel Sandersf84bc372018-05-05 20:53:24 +00003520 // No check required. We already did it by swapping the opcode.
3521 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3522 Predicate.isSignExtLoad())
3523 continue;
3524
3525 // No check required. We already did it by swapping the opcode.
3526 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3527 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003528 continue;
3529
Daniel Sandersd66e0902017-10-23 18:19:24 +00003530 // No check required. G_STORE by itself is a non-extending store.
3531 if (Predicate.isNonTruncStore())
3532 continue;
3533
Daniel Sanders76664652017-11-28 22:07:05 +00003534 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3535 if (Predicate.getMemoryVT() != nullptr) {
3536 Optional<LLTCodeGen> MemTyOrNone =
3537 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003538
Daniel Sanders76664652017-11-28 22:07:05 +00003539 if (!MemTyOrNone)
3540 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003541
Daniel Sandersf84bc372018-05-05 20:53:24 +00003542 // MMO's work in bytes so we must take care of unusual types like i1
3543 // don't round down.
3544 unsigned MemSizeInBits =
3545 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3546
3547 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3548 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003549 continue;
3550 }
3551 }
3552
3553 if (Predicate.isLoad() || Predicate.isStore()) {
3554 // No check required. A G_LOAD/G_STORE is an unindexed load.
3555 if (Predicate.isUnindexed())
3556 continue;
3557 }
3558
3559 if (Predicate.isAtomic()) {
3560 if (Predicate.isAtomicOrderingMonotonic()) {
3561 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3562 "Monotonic");
3563 continue;
3564 }
3565 if (Predicate.isAtomicOrderingAcquire()) {
3566 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3567 continue;
3568 }
3569 if (Predicate.isAtomicOrderingRelease()) {
3570 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3571 continue;
3572 }
3573 if (Predicate.isAtomicOrderingAcquireRelease()) {
3574 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3575 "AcquireRelease");
3576 continue;
3577 }
3578 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3579 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3580 "SequentiallyConsistent");
3581 continue;
3582 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003583
3584 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3585 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3586 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3587 continue;
3588 }
3589 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3590 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3591 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3592 continue;
3593 }
3594
3595 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3596 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3597 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3598 continue;
3599 }
3600 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3601 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3602 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3603 continue;
3604 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003605 }
3606
Daniel Sanders8ead1292018-06-15 23:13:43 +00003607 if (Predicate.hasGISelPredicateCode()) {
3608 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3609 continue;
3610 }
3611
Daniel Sanders2c269f62017-08-24 09:11:20 +00003612 return failedImport("Src pattern child has predicate (" +
3613 explainPredicates(Src) + ")");
3614 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003615 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3616 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003617 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3618 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3619 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3620 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003621
Florian Hahn6b1db822018-06-14 20:32:58 +00003622 if (Src->isLeaf()) {
3623 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003624 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003625 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003626 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003627 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3628 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003629 return failedImport(
3630 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003631 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003632 assert(SrcGIOrNull &&
3633 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003634 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3635 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3636 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003637 // here since we don't support ImmLeaf predicates yet. However, we still
3638 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3639 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3640 return InsnMatcher;
3641 }
3642
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003643 // Special case because the operand order is changed from setcc. The
3644 // predicate operand needs to be swapped from the last operand to the first
3645 // source.
3646
3647 unsigned NumChildren = Src->getNumChildren();
3648 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3649
3650 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3651 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3652 if (SrcChild->isLeaf()) {
3653 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3654 Record *CCDef = DI ? DI->getDef() : nullptr;
3655 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3656 return failedImport("Unable to handle CondCode");
3657
3658 OperandMatcher &OM =
3659 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3660 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3661 CCDef->getValueAsString("ICmpPredicate");
3662
3663 if (!PredType.empty()) {
3664 OM.addPredicate<CmpPredicateOperandMatcher>(PredType);
3665 // Process the other 2 operands normally.
3666 --NumChildren;
3667 }
3668 }
3669 }
3670
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003671 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003672 bool IsIntrinsic =
3673 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3674 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3675 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3676 if (IsIntrinsic && !II)
3677 return failedImport("Expected IntInit containing intrinsic ID)");
3678
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003679 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003680 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003681
Daniel Sandersa71f4542017-10-16 00:56:30 +00003682 // SelectionDAG allows pointers to be represented with iN since it doesn't
3683 // distinguish between pointers and integers but they are different types in GlobalISel.
3684 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003685 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003686
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003687 if (IsIntrinsic) {
3688 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3689 // following the defs is an intrinsic ID.
3690 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003691 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003692 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003693 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003694 continue;
3695 }
3696
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003697 // We have to check intrinsics for llvm_anyptr_ty parameters.
3698 //
3699 // Note that we have to look at the i-1th parameter, because we don't
3700 // have the intrinsic ID in the intrinsic's parameter list.
3701 OperandIsAPointer |= II->isParamAPointer(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003702 }
3703
Daniel Sandersa71f4542017-10-16 00:56:30 +00003704 if (auto Error =
3705 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3706 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003707 return std::move(Error);
3708 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003709 }
3710
3711 return InsnMatcher;
3712}
3713
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003714Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3715 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3716 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3717 if (ComplexPattern == ComplexPatternEquivs.end())
3718 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3719 ") not mapped to GlobalISel");
3720
3721 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3722 TempOpIdx++;
3723 return Error::success();
3724}
3725
Matt Arsenault3e45c702019-09-06 20:32:37 +00003726// Get the name to use for a pattern operand. For an anonymous physical register
3727// input, this should use the register name.
3728static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3729 Record *&PhysReg) {
3730 StringRef SrcChildName = SrcChild->getName();
3731 if (SrcChildName.empty() && SrcChild->isLeaf()) {
3732 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3733 auto *ChildRec = ChildDefInit->getDef();
3734 if (ChildRec->isSubClassOf("Register")) {
3735 SrcChildName = ChildRec->getName();
3736 PhysReg = ChildRec;
3737 }
3738 }
3739 }
3740
3741 return SrcChildName;
3742}
3743
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003744Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3745 InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003746 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003747 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003748 unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003749 unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00003750
3751 Record *PhysReg = nullptr;
3752 StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3753
3754 OperandMatcher &OM = PhysReg ?
3755 InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx) :
3756 InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003757 if (OM.isSameAsAnotherOperand())
3758 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003759
Florian Hahn6b1db822018-06-14 20:32:58 +00003760 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003761 if (ChildTypes.size() != 1)
3762 return failedImport("Src pattern child has multiple results");
3763
3764 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003765 if (!SrcChild->isLeaf()) {
3766 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3767 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003768 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3769 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003770 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003771 }
3772 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003773 }
3774
Daniel Sandersa71f4542017-10-16 00:56:30 +00003775 if (auto Error =
3776 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3777 return failedImport(toString(std::move(Error)) + " for Src operand (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003778 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003779
Daniel Sandersbee57392017-04-04 13:25:23 +00003780 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003781 if (!SrcChild->isLeaf()) {
3782 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003783 // When a ComplexPattern is used as an operator, it should do the same
3784 // thing as when used as a leaf. However, the children of the operator
3785 // name the sub-operands that make up the complex operand and we must
3786 // prepare to reference them in the renderer too.
3787 unsigned RendererID = TempOpIdx;
3788 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003789 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003790 return Error;
3791
Florian Hahn6b1db822018-06-14 20:32:58 +00003792 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3793 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003794 if (!SubOperand->getName().empty()) {
3795 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3796 SrcChild->getOperator(),
3797 RendererID, i))
3798 return Error;
3799 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003800 }
3801
3802 return Error::success();
3803 }
3804
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003805 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003806 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003807 if (!MaybeInsnOperand.hasValue()) {
3808 // This isn't strictly true. If the user were to provide exactly the same
3809 // matchers as the original operand then we could allow it. However, it's
3810 // simpler to not permit the redundant specification.
3811 return failedImport("Nested instruction cannot be the same as another operand");
3812 }
3813
Daniel Sandersbee57392017-04-04 13:25:23 +00003814 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003815 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003816 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003817 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003818 if (auto Error = InsnMatcherOrError.takeError())
3819 return Error;
3820
3821 return Error::success();
3822 }
3823
Florian Hahn6b1db822018-06-14 20:32:58 +00003824 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003825 return failedImport("Src pattern child has unsupported predicate");
3826
Daniel Sandersffc7d582017-03-29 15:37:18 +00003827 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003828 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003829 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003830 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003831 }
3832
3833 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003834 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003835 auto *ChildRec = ChildDefInit->getDef();
3836
3837 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003838 if (ChildRec->isSubClassOf("RegisterClass") ||
3839 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003840 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003841 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003842 return Error::success();
3843 }
3844
Matt Arsenault3e45c702019-09-06 20:32:37 +00003845 if (ChildRec->isSubClassOf("Register")) {
3846 // This just be emitted as a copy to the specific register.
3847 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
3848 const CodeGenRegisterClass *RC
3849 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
3850 if (!RC) {
3851 return failedImport(
3852 "Could not determine physical register class of pattern source");
3853 }
3854
3855 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
3856 return Error::success();
3857 }
3858
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003859 // Check for ValueType.
3860 if (ChildRec->isSubClassOf("ValueType")) {
3861 // We already added a type check as standard practice so this doesn't need
3862 // to do anything.
3863 return Error::success();
3864 }
3865
Daniel Sandersffc7d582017-03-29 15:37:18 +00003866 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003867 if (ChildRec->isSubClassOf("ComplexPattern"))
3868 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003869
Daniel Sandersd0656a32017-04-13 09:45:37 +00003870 if (ChildRec->isSubClassOf("ImmLeaf")) {
3871 return failedImport(
3872 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3873 }
3874
Daniel Sandersffc7d582017-03-29 15:37:18 +00003875 return failedImport(
3876 "Src pattern child def is an unsupported tablegen class");
3877 }
3878
3879 return failedImport("Src pattern child is an unsupported kind");
3880}
3881
Daniel Sanders7438b262017-10-31 23:03:18 +00003882Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3883 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003884 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003885
Florian Hahn6b1db822018-06-14 20:32:58 +00003886 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003887 if (SubOperand.hasValue()) {
3888 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003889 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003890 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003891 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003892 }
3893
Florian Hahn6b1db822018-06-14 20:32:58 +00003894 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003895
Florian Hahn6b1db822018-06-14 20:32:58 +00003896 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3897 auto Child = DstChild->getChild(0);
3898 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003899 if (I != SDNodeXFormEquivs.end()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003900 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003901 return InsertPt;
3902 }
Florian Hahn6b1db822018-06-14 20:32:58 +00003903 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00003904 " has no custom renderer");
3905 }
3906
Daniel Sanders05540042017-08-08 10:44:31 +00003907 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3908 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003909 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3910 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003911 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003912 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003913 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003914 }
3915 }
Daniel Sanders05540042017-08-08 10:44:31 +00003916
3917 // Similarly, imm is an operator in TreePatternNode's view but must be
3918 // rendered as operands.
3919 // FIXME: The target should be able to choose sign-extended when appropriate
3920 // (e.g. on Mips).
Florian Hahn6b1db822018-06-14 20:32:58 +00003921 if (DstChild->getOperator()->getName() == "imm") {
3922 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003923 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00003924 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00003925 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003926 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003927 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003928 }
3929
Florian Hahn6b1db822018-06-14 20:32:58 +00003930 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3931 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003932 if (ChildTypes.size() != 1)
3933 return failedImport("Dst pattern child has multiple results");
3934
3935 Optional<LLTCodeGen> OpTyOrNone = None;
3936 if (ChildTypes.front().isMachineValueType())
3937 OpTyOrNone =
3938 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3939 if (!OpTyOrNone)
3940 return failedImport("Dst operand has an unsupported type");
3941
3942 unsigned TempRegID = Rule.allocateTempRegID();
3943 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3944 InsertPt, OpTyOrNone.getValue(), TempRegID);
3945 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3946
3947 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3948 ++InsertPt, Rule, DstChild, TempRegID);
3949 if (auto Error = InsertPtOrError.takeError())
3950 return std::move(Error);
3951 return InsertPtOrError.get();
3952 }
3953
Florian Hahn6b1db822018-06-14 20:32:58 +00003954 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003955 }
3956
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003957 // It could be a specific immediate in which case we should just check for
3958 // that immediate.
3959 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003960 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003961 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3962 return InsertPt;
3963 }
3964
Daniel Sandersffc7d582017-03-29 15:37:18 +00003965 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003966 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003967 auto *ChildRec = ChildDefInit->getDef();
3968
Florian Hahn6b1db822018-06-14 20:32:58 +00003969 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003970 if (ChildTypes.size() != 1)
3971 return failedImport("Dst pattern child has multiple results");
3972
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003973 Optional<LLTCodeGen> OpTyOrNone = None;
3974 if (ChildTypes.front().isMachineValueType())
3975 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003976 if (!OpTyOrNone)
3977 return failedImport("Dst operand has an unsupported type");
3978
3979 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003980 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003981 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003982 }
3983
Daniel Sanders658541f2017-04-22 15:53:21 +00003984 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003985 ChildRec->isSubClassOf("RegisterOperand") ||
3986 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003987 if (ChildRec->isSubClassOf("RegisterOperand") &&
3988 !ChildRec->isValueUnset("GIZeroRegister")) {
3989 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003990 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003991 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003992 }
3993
Florian Hahn6b1db822018-06-14 20:32:58 +00003994 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003995 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003996 }
3997
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003998 if (ChildRec->isSubClassOf("SubRegIndex")) {
3999 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4000 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4001 return InsertPt;
4002 }
4003
Daniel Sandersffc7d582017-03-29 15:37:18 +00004004 if (ChildRec->isSubClassOf("ComplexPattern")) {
4005 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4006 if (ComplexPattern == ComplexPatternEquivs.end())
4007 return failedImport(
4008 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4009
Florian Hahn6b1db822018-06-14 20:32:58 +00004010 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004011 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004012 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004013 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004014 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004015 }
4016
4017 return failedImport(
4018 "Dst pattern child def is an unsupported tablegen class");
4019 }
4020
4021 return failedImport("Dst pattern child is an unsupported kind");
4022}
4023
Daniel Sandersc270c502017-03-30 09:36:33 +00004024Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004025 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4026 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004027 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4028 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004029 return std::move(Error);
4030
Daniel Sanders7438b262017-10-31 23:03:18 +00004031 action_iterator InsertPt = InsertPtOrError.get();
4032 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004033
Matt Arsenault3e45c702019-09-06 20:32:37 +00004034 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4035 InsertPt = M.insertAction<BuildMIAction>(
4036 InsertPt, M.allocateOutputInsnID(),
4037 &Target.getInstruction(RK.getDef("COPY")));
4038 BuildMIAction &CopyToPhysRegMIBuilder =
4039 *static_cast<BuildMIAction *>(InsertPt->get());
4040 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4041 true);
4042 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4043 }
4044
Daniel Sandersdf258e32017-10-31 19:09:29 +00004045 importExplicitDefRenderers(DstMIBuilder);
4046
Daniel Sanders7438b262017-10-31 23:03:18 +00004047 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4048 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004049 return std::move(Error);
4050
4051 return DstMIBuilder;
4052}
4053
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004054Expected<action_iterator>
4055GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004056 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004057 unsigned TempRegID) {
4058 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4059
4060 // TODO: Assert there's exactly one result.
4061
4062 if (auto Error = InsertPtOrError.takeError())
4063 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004064
4065 BuildMIAction &DstMIBuilder =
4066 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4067
4068 // Assign the result to TempReg.
4069 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4070
Daniel Sanders08464522018-01-29 21:09:12 +00004071 InsertPtOrError =
4072 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004073 if (auto Error = InsertPtOrError.takeError())
4074 return std::move(Error);
4075
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004076 // We need to make sure that when we import an INSERT_SUBREG as a
4077 // subinstruction that it ends up being constrained to the correct super
4078 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004079 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4080 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004081 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4082 if (!SubClass)
4083 return failedImport(
4084 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004085 Optional<const CodeGenRegisterClass *> SuperClass =
4086 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4087 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004088 if (!SuperClass)
4089 return failedImport(
4090 "Cannot infer register class for INSERT_SUBREG operand #0");
4091 // The destination and the super register source of an INSERT_SUBREG must
4092 // be the same register class.
4093 M.insertAction<ConstrainOperandToRegClassAction>(
4094 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4095 M.insertAction<ConstrainOperandToRegClassAction>(
4096 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4097 M.insertAction<ConstrainOperandToRegClassAction>(
4098 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4099 return InsertPtOrError.get();
4100 }
4101
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004102 if (OpName == "EXTRACT_SUBREG") {
4103 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4104 // instructions, the result register class is controlled by the
4105 // subregisters of the operand. As a result, we must constrain the result
4106 // class rather than check that it's already the right one.
4107 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4108 if (!SuperClass)
4109 return failedImport(
4110 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4111
4112 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4113 if (!SubIdx)
4114 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4115
4116 const auto &SrcRCDstRCPair =
4117 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4118 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4119 M.insertAction<ConstrainOperandToRegClassAction>(
4120 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4121 M.insertAction<ConstrainOperandToRegClassAction>(
4122 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4123
4124 // We're done with this pattern! It's eligible for GISel emission; return
4125 // it.
4126 return InsertPtOrError.get();
4127 }
4128
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004129 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4130 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004131 if (OpName == "SUBREG_TO_REG") {
4132 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4133 if (!SubClass)
4134 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004135 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004136 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4137 Dst->getChild(2));
4138 if (!SuperClass)
4139 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004140 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004141 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004142 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004143 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004144 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004145 return InsertPtOrError.get();
4146 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004147
Daniel Sanders08464522018-01-29 21:09:12 +00004148 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4149 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004150 return InsertPtOrError.get();
4151}
4152
Daniel Sanders7438b262017-10-31 23:03:18 +00004153Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004154 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4155 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004156 if (!DstOp->isSubClassOf("Instruction")) {
4157 if (DstOp->isSubClassOf("ValueType"))
4158 return failedImport(
4159 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004160 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004161 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004162 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004163
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004164 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004165 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004166 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004167 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00004168 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004169 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004170 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
4171 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004172
Daniel Sanders198447a2017-11-01 00:29:47 +00004173 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4174 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004175}
4176
4177void GlobalISelEmitter::importExplicitDefRenderers(
4178 BuildMIAction &DstMIBuilder) {
4179 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004180 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
4181 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00004182 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004183 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00004184}
4185
Daniel Sanders7438b262017-10-31 23:03:18 +00004186Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4187 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004188 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004189 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004190 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004191
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004192 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004193 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004194 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004195 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4196
Daniel Sanders32291982017-06-28 13:50:04 +00004197 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004198 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
4199 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004200 if (!RCDef)
4201 return failedImport("EXTRACT_SUBREG child #0 could not "
4202 "be coerced to a register class");
4203
4204 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004205 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4206
4207 const auto &SrcRCDstRCPair =
4208 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4209 if (SrcRCDstRCPair.hasValue()) {
4210 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4211 if (SrcRCDstRCPair->first != RC)
4212 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4213 }
4214
Florian Hahn6b1db822018-06-14 20:32:58 +00004215 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00004216 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004217 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004218 }
4219
4220 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4221 }
4222
Daniel Sandersffc7d582017-03-29 15:37:18 +00004223 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004224 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Florian Hahn6b1db822018-06-14 20:32:58 +00004225 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sandersdf258e32017-10-31 19:09:29 +00004226 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
4227 DstINumUses--; // Ignore the class constraint.
4228 ExpectedDstINumUses--;
4229 }
4230
Daniel Sanders0ed28822017-04-12 08:23:08 +00004231 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00004232 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004233 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004234 const CGIOperandList::OperandInfo &DstIOperand =
4235 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004236
Diana Picus382602f2017-05-17 08:57:28 +00004237 // If the operand has default values, introduce them now.
4238 // FIXME: Until we have a decent test case that dictates we should do
4239 // otherwise, we're going to assume that operands with default values cannot
4240 // be specified in the patterns. Therefore, adding them will not cause us to
4241 // end up with too many rendered operands.
4242 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00004243 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004244 if (auto Error = importDefaultOperandRenderers(
4245 InsertPt, M, DstMIBuilder, DefaultOps))
Diana Picus382602f2017-05-17 08:57:28 +00004246 return std::move(Error);
4247 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004248 continue;
4249 }
4250
Daniel Sanders7438b262017-10-31 23:03:18 +00004251 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004252 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004253 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00004254 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004255 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004256 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004257 }
4258
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004259 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004260 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004261 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004262 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004263 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004264 " default ones");
4265
Daniel Sanders7438b262017-10-31 23:03:18 +00004266 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004267}
4268
Diana Picus382602f2017-05-17 08:57:28 +00004269Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004270 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4271 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004272 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004273 Optional<LLTCodeGen> OpTyOrNone = None;
4274
Diana Picus382602f2017-05-17 08:57:28 +00004275 // Look through ValueType operators.
4276 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4277 if (const DefInit *DefaultDagOperator =
4278 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004279 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004280 OpTyOrNone = MVTToLLT(getValueType(
4281 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004282 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004283 }
Diana Picus382602f2017-05-17 08:57:28 +00004284 }
4285 }
4286
4287 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004288 auto Def = DefaultDefOp->getDef();
4289 if (Def->getName() == "undef_tied_input") {
4290 unsigned TempRegID = M.allocateTempRegID();
4291 M.insertAction<MakeTempRegisterAction>(
4292 InsertPt, OpTyOrNone.getValue(), TempRegID);
4293 InsertPt = M.insertAction<BuildMIAction>(
4294 InsertPt, M.allocateOutputInsnID(),
4295 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4296 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4297 InsertPt->get());
4298 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4299 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4300 } else {
4301 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4302 }
Diana Picus382602f2017-05-17 08:57:28 +00004303 continue;
4304 }
4305
4306 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004307 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004308 continue;
4309 }
4310
4311 return failedImport("Could not add default op");
4312 }
4313
4314 return Error::success();
4315}
4316
Daniel Sandersc270c502017-03-30 09:36:33 +00004317Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004318 BuildMIAction &DstMIBuilder,
4319 const std::vector<Record *> &ImplicitDefs) const {
4320 if (!ImplicitDefs.empty())
4321 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004322 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004323}
4324
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004325Optional<const CodeGenRegisterClass *>
4326GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4327 assert(Leaf && "Expected node?");
4328 assert(Leaf->isLeaf() && "Expected leaf?");
4329 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4330 if (!RCRec)
4331 return None;
4332 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4333 if (!RC)
4334 return None;
4335 return RC;
4336}
4337
4338Optional<const CodeGenRegisterClass *>
4339GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4340 if (!N)
4341 return None;
4342
4343 if (N->isLeaf())
4344 return getRegClassFromLeaf(N);
4345
4346 // We don't have a leaf node, so we have to try and infer something. Check
4347 // that we have an instruction that we an infer something from.
4348
4349 // Only handle things that produce a single type.
4350 if (N->getNumTypes() != 1)
4351 return None;
4352 Record *OpRec = N->getOperator();
4353
4354 // We only want instructions.
4355 if (!OpRec->isSubClassOf("Instruction"))
4356 return None;
4357
4358 // Don't want to try and infer things when there could potentially be more
4359 // than one candidate register class.
4360 auto &Inst = Target.getInstruction(OpRec);
4361 if (Inst.Operands.NumDefs > 1)
4362 return None;
4363
4364 // Handle any special-case instructions which we can safely infer register
4365 // classes from.
4366 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004367 bool IsRegSequence = InstName == "REG_SEQUENCE";
4368 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004369 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4370 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004371 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004372 if (!RCChild->isLeaf())
4373 return None;
4374 return getRegClassFromLeaf(RCChild);
4375 }
4376
4377 // Handle destination record types that we can safely infer a register class
4378 // from.
4379 const auto &DstIOperand = Inst.Operands[0];
4380 Record *DstIOpRec = DstIOperand.Rec;
4381 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4382 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4383 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4384 return &RC;
4385 }
4386
4387 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4388 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4389 return &RC;
4390 }
4391
4392 return None;
4393}
4394
4395Optional<const CodeGenRegisterClass *>
4396GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004397 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004398 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004399 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4400 if (!Ty.isValueTypeByHwMode(false))
4401 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004402 if (!SubRegIdxNode->isLeaf())
4403 return None;
4404 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4405 if (!SubRegInit)
4406 return None;
4407 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4408
4409 // Use the information we found above to find a minimal register class which
4410 // supports the subregister and type we want.
4411 auto RC =
4412 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4413 if (!RC)
4414 return None;
4415 return *RC;
4416}
4417
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004418Optional<const CodeGenRegisterClass *>
4419GlobalISelEmitter::inferSuperRegisterClassForNode(
4420 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4421 TreePatternNode *SubRegIdxNode) {
4422 assert(SuperRegNode && "Expected super register node!");
4423 // Check if we already have a defined register class for the super register
4424 // node. If we do, then we should preserve that rather than inferring anything
4425 // from the subregister index node. We can assume that whoever wrote the
4426 // pattern in the first place made sure that the super register and
4427 // subregister are compatible.
4428 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4429 inferRegClassFromPattern(SuperRegNode))
4430 return *SuperRegisterClass;
4431 return inferSuperRegisterClass(Ty, SubRegIdxNode);
4432}
4433
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004434Optional<CodeGenSubRegIndex *>
4435GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4436 if (!SubRegIdxNode->isLeaf())
4437 return None;
4438
4439 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4440 if (!SubRegInit)
4441 return None;
4442 return CGRegs.getSubRegIdx(SubRegInit->getDef());
4443}
4444
Daniel Sandersffc7d582017-03-29 15:37:18 +00004445Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004446 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004447 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004448 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004449 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004450 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4451 " => " +
4452 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004453
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004454 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004455 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004456
4457 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004458 TreePatternNode *Src = P.getSrcPattern();
4459 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004460
4461 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004462 if (auto Err = isTrivialOperatorNode(Dst))
4463 return failedImport("Dst pattern root isn't a trivial operator (" +
4464 toString(std::move(Err)) + ")");
4465 if (auto Err = isTrivialOperatorNode(Src))
4466 return failedImport("Src pattern root isn't a trivial operator (" +
4467 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004468
Quentin Colombetaad20be2017-12-15 23:07:42 +00004469 // The different predicates and matchers created during
4470 // addInstructionMatcher use the RuleMatcher M to set up their
4471 // instruction ID (InsnVarID) that are going to be used when
4472 // M is going to be emitted.
4473 // However, the code doing the emission still relies on the IDs
4474 // returned during that process by the RuleMatcher when issuing
4475 // the recordInsn opcodes.
4476 // Because of that:
4477 // 1. The order in which we created the predicates
4478 // and such must be the same as the order in which we emit them,
4479 // and
4480 // 2. We need to reset the generation of the IDs in M somewhere between
4481 // addInstructionMatcher and emit
4482 //
4483 // FIXME: Long term, we don't want to have to rely on this implicit
4484 // naming being the same. One possible solution would be to have
4485 // explicit operator for operation capture and reference those.
4486 // The plus side is that it would expose opportunities to share
4487 // the capture accross rules. The downside is that it would
4488 // introduce a dependency between predicates (captures must happen
4489 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004490 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004491 unsigned TempOpIdx = 0;
4492 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004493 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004494 if (auto Error = InsnMatcherOrError.takeError())
4495 return std::move(Error);
4496 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4497
Florian Hahn6b1db822018-06-14 20:32:58 +00004498 if (Dst->isLeaf()) {
4499 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004500
4501 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4502 if (RCDef) {
4503 // We need to replace the def and all its uses with the specified
4504 // operand. However, we must also insert COPY's wherever needed.
4505 // For now, emit a copy and let the register allocator clean up.
4506 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4507 const auto &DstIOperand = DstI.Operands[0];
4508
4509 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4510 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004511 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004512 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4513
Daniel Sanders198447a2017-11-01 00:29:47 +00004514 auto &DstMIBuilder =
4515 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4516 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004517 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004518 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4519
4520 // We're done with this pattern! It's eligible for GISel emission; return
4521 // it.
4522 ++NumPatternImported;
4523 return std::move(M);
4524 }
4525
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004526 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004527 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004528
Daniel Sandersbee57392017-04-04 13:25:23 +00004529 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004530 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004531 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004532 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004533
4534 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004535 StringRef DstIName = DstI.TheDef->getName();
4536
Florian Hahn6b1db822018-06-14 20:32:58 +00004537 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00004538 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004539 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004540 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004541
Daniel Sandersffc7d582017-03-29 15:37:18 +00004542 // The root of the match also has constraints on the register bank so that it
4543 // matches the result instruction.
4544 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004545 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004546 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004547
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004548 const auto &DstIOperand = DstI.Operands[OpIdx];
4549 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004550 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004551 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004552
4553 if (DstIOpRec == nullptr)
4554 return failedImport(
4555 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004556 } else if (DstIName == "REG_SEQUENCE") {
4557 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4558 if (DstIOpRec == nullptr)
4559 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4560 } else if (DstIName == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004561 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004562 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
4563
Daniel Sanders32291982017-06-28 13:50:04 +00004564 // We can assume that a subregister is in the same bank as it's super
4565 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00004566 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004567
4568 if (DstIOpRec == nullptr)
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004569 return failedImport("EXTRACT_SUBREG operand #0 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004570 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004571 auto MaybeSuperClass = inferSuperRegisterClassForNode(
4572 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004573 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004574 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004575 "Cannot infer register class for INSERT_SUBREG operand #0");
4576 // Move to the next pattern here, because the register class we found
4577 // doesn't necessarily have a record associated with it. So, we can't
4578 // set DstIOpRec using this.
4579 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4580 OM.setSymbolicName(DstIOperand.Name);
4581 M.defineOperand(OM.getSymbolicName(), OM);
4582 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4583 ++OpIdx;
4584 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004585 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004586 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
4587 if (!MaybeRegClass)
4588 return failedImport(
4589 "Cannot infer register class for SUBREG_TO_REG operand #0");
4590 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4591 OM.setSymbolicName(DstIOperand.Name);
4592 M.defineOperand(OM.getSymbolicName(), OM);
4593 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
4594 ++OpIdx;
4595 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004596 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004597 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004598 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004599 return failedImport("Dst MI def isn't a register class" +
4600 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004601
Daniel Sandersffc7d582017-03-29 15:37:18 +00004602 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4603 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004604 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004605 OM.addPredicate<RegisterBankOperandMatcher>(
4606 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004607 ++OpIdx;
4608 }
4609
Matt Arsenault3e45c702019-09-06 20:32:37 +00004610 auto DstMIBuilderOrError =
4611 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004612 if (auto Error = DstMIBuilderOrError.takeError())
4613 return std::move(Error);
4614 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004615
Daniel Sandersffc7d582017-03-29 15:37:18 +00004616 // Render the implicit defs.
4617 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004618 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004619 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004620
Daniel Sandersa7b75262017-10-31 18:50:24 +00004621 DstMIBuilder.chooseInsnToMutate(M);
4622
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004623 // Constrain the registers to classes. This is normally derived from the
4624 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004625 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004626 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4627 // result is constrained to the class given by the second child.
4628 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004629 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004630
4631 if (DstIOpRec == nullptr)
4632 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4633
4634 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004635 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004636
4637 // We're done with this pattern! It's eligible for GISel emission; return
4638 // it.
4639 ++NumPatternImported;
4640 return std::move(M);
4641 }
4642
Matt Arsenault38fb3442019-09-04 16:19:34 +00004643 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004644 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4645 if (!SuperClass)
4646 return failedImport(
4647 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004648
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004649 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4650 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00004651 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004652
Daniel Sanders320390b2017-06-28 15:16:03 +00004653 // It would be nice to leave this constraint implicit but we're required
4654 // to pick a register class so constrain the result to a register class
4655 // that can hold the correct MVT.
4656 //
4657 // FIXME: This may introduce an extra copy if the chosen class doesn't
4658 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004659 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004660 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004661
Daniel Sanders320390b2017-06-28 15:16:03 +00004662 const auto &SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004663 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Daniel Sanders320390b2017-06-28 15:16:03 +00004664 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004665 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4666 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4667
4668 // We're done with this pattern! It's eligible for GISel emission; return
4669 // it.
4670 ++NumPatternImported;
4671 return std::move(M);
4672 }
4673
Matt Arsenault38fb3442019-09-04 16:19:34 +00004674 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004675 assert(Src->getExtTypes().size() == 1 &&
4676 "Expected Src of INSERT_SUBREG to have one result type");
4677 // We need to constrain the destination, a super regsister source, and a
4678 // subregister source.
4679 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4680 if (!SubClass)
4681 return failedImport(
4682 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004683 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004684 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4685 if (!SuperClass)
4686 return failedImport(
4687 "Cannot infer register class for INSERT_SUBREG operand #0");
4688 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4689 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4690 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4691 ++NumPatternImported;
4692 return std::move(M);
4693 }
4694
Matt Arsenault38fb3442019-09-04 16:19:34 +00004695 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004696 // We need to constrain the destination and subregister source.
4697 assert(Src->getExtTypes().size() == 1 &&
4698 "Expected Src of SUBREG_TO_REG to have one result type");
4699
4700 // Attempt to infer the subregister source from the first child. If it has
4701 // an explicitly given register class, we'll use that. Otherwise, we will
4702 // fail.
4703 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4704 if (!SubClass)
4705 return failedImport(
4706 "Cannot infer register class from SUBREG_TO_REG child #1");
4707 // We don't have a child to look at that might have a super register node.
4708 auto SuperClass =
4709 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
4710 if (!SuperClass)
4711 return failedImport(
4712 "Cannot infer register class for SUBREG_TO_REG operand #0");
4713 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4714 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4715 ++NumPatternImported;
4716 return std::move(M);
4717 }
4718
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004719 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004720
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004721 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004722 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004723 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004724}
4725
Daniel Sanders649c5852017-10-13 20:42:18 +00004726// Emit imm predicate table and an enum to reference them with.
4727// The 'Predicate_' part of the name is redundant but eliminating it is more
4728// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004729void GlobalISelEmitter::emitCxxPredicateFns(
4730 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4731 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004732 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004733 std::vector<const Record *> MatchedRecords;
4734 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4735 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4736 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004737 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004738 Filter(Record);
4739 });
4740
Daniel Sanders11300ce2017-10-13 21:28:03 +00004741 if (!MatchedRecords.empty()) {
4742 OS << "// PatFrag predicates.\n"
4743 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004744 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004745 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4746 for (const auto *Record : MatchedRecords) {
4747 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4748 << EnumeratorSeparator;
4749 EnumeratorSeparator = ",\n";
4750 }
4751 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004752 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004753
Daniel Sanders8ead1292018-06-15 23:13:43 +00004754 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4755 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4756 << ArgName << ") const {\n"
4757 << AdditionalDeclarations;
4758 if (!AdditionalDeclarations.empty())
4759 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004760 if (!MatchedRecords.empty())
4761 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004762 for (const auto *Record : MatchedRecords) {
4763 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4764 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004765 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4766 << " llvm_unreachable(\"" << CodeFieldName
4767 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004768 << " return false;\n"
4769 << " }\n";
4770 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004771 if (!MatchedRecords.empty())
4772 OS << " }\n";
4773 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004774 << " return false;\n"
4775 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004776}
4777
Daniel Sanders8ead1292018-06-15 23:13:43 +00004778void GlobalISelEmitter::emitImmPredicateFns(
4779 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4780 std::function<bool(const Record *R)> Filter) {
4781 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4782 "Imm", "", Filter);
4783}
4784
4785void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4786 return emitCxxPredicateFns(
4787 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4788 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00004789 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4790 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00004791 [](const Record *R) { return true; });
4792}
4793
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004794template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004795std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004796 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004797 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4798
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004799 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004800 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004801 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4802 unsigned NumGroups = 0;
4803
4804 auto ProcessCurrentGroup = [&]() {
4805 if (CurrentGroup->empty())
4806 // An empty group is good to be reused:
4807 return;
4808
4809 // If the group isn't large enough to provide any benefit, move all the
4810 // added rules out of it and make sure to re-create the group to properly
4811 // re-initialize it:
4812 if (CurrentGroup->size() < 2)
4813 for (Matcher *M : CurrentGroup->matchers())
4814 OptRules.push_back(M);
4815 else {
4816 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004817 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004818 MatcherStorage.emplace_back(std::move(CurrentGroup));
4819 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004820 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004821 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004822 };
4823 for (Matcher *Rule : Rules) {
4824 // Greedily add as many matchers as possible to the current group:
4825 if (CurrentGroup->addMatcher(*Rule))
4826 continue;
4827
4828 ProcessCurrentGroup();
4829 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4830
4831 // Try to add the pending matcher to a newly created empty group:
4832 if (!CurrentGroup->addMatcher(*Rule))
4833 // If we couldn't add the matcher to an empty group, that group type
4834 // doesn't support that kind of matchers at all, so just skip it:
4835 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004836 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004837 ProcessCurrentGroup();
4838
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004839 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004840 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004841 return OptRules;
4842}
4843
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004844MatchTable
4845GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004846 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004847 std::vector<Matcher *> InputRules;
4848 for (Matcher &Rule : Rules)
4849 InputRules.push_back(&Rule);
4850
4851 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004852 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004853
Roman Tereshin77013602018-05-22 16:54:27 +00004854 unsigned CurrentOrdering = 0;
4855 StringMap<unsigned> OpcodeOrder;
4856 for (RuleMatcher &Rule : Rules) {
4857 const StringRef Opcode = Rule.getOpcode();
4858 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4859 if (OpcodeOrder.count(Opcode) == 0)
4860 OpcodeOrder[Opcode] = CurrentOrdering++;
4861 }
4862
4863 std::stable_sort(InputRules.begin(), InputRules.end(),
4864 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4865 auto *L = static_cast<const RuleMatcher *>(A);
4866 auto *R = static_cast<const RuleMatcher *>(B);
4867 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4868 L->getNumOperands()) <
4869 std::make_tuple(OpcodeOrder[R->getOpcode()],
4870 R->getNumOperands());
4871 });
4872
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004873 for (Matcher *Rule : InputRules)
4874 Rule->optimize();
4875
4876 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004877 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004878 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4879
4880 for (Matcher *Rule : OptRules)
4881 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004882
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004883 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4884
Roman Tereshinbeb39312018-05-02 20:15:11 +00004885 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004886}
4887
Roman Tereshinfedae332018-05-23 02:04:19 +00004888void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004889 // Make sure we only sort by a specific predicate within a range of rules that
4890 // all have that predicate checked against a specific value (not a wildcard):
4891 auto F = Matchers.begin();
4892 auto T = F;
4893 auto E = Matchers.end();
4894 while (T != E) {
4895 while (T != E) {
4896 auto *R = static_cast<RuleMatcher *>(*T);
4897 if (!R->getFirstConditionAsRootType().get().isValid())
4898 break;
4899 ++T;
4900 }
4901 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4902 auto *L = static_cast<RuleMatcher *>(A);
4903 auto *R = static_cast<RuleMatcher *>(B);
4904 return L->getFirstConditionAsRootType() <
4905 R->getFirstConditionAsRootType();
4906 });
4907 if (T != E)
4908 F = ++T;
4909 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004910 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4911 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004912 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4913 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004914}
4915
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004916void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004917 if (!UseCoverageFile.empty()) {
4918 RuleCoverage = CodeGenCoverage();
4919 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4920 if (!RuleCoverageBufOrErr) {
4921 PrintWarning(SMLoc(), "Missing rule coverage data");
4922 RuleCoverage = None;
4923 } else {
4924 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4925 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4926 RuleCoverage = None;
4927 }
4928 }
4929 }
4930
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004931 // Track the run-time opcode values
4932 gatherOpcodeValues();
4933 // Track the run-time LLT ID values
4934 gatherTypeIDValues();
4935
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004936 // Track the GINodeEquiv definitions.
4937 gatherNodeEquivs();
4938
4939 emitSourceFileHeader(("Global Instruction Selector for the " +
4940 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004941 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004942 // Look through the SelectionDAG patterns we found, possibly emitting some.
4943 for (const PatternToMatch &Pat : CGP.ptms()) {
4944 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00004945
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004946 auto MatcherOrErr = runOnPattern(Pat);
4947
4948 // The pattern analysis can fail, indicating an unsupported pattern.
4949 // Report that if we've been asked to do so.
4950 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004951 if (WarnOnSkippedPatterns) {
4952 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004953 "Skipped pattern: " + toString(std::move(Err)));
4954 } else {
4955 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004956 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004957 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004958 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004959 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004960
Daniel Sandersf76f3152017-11-16 00:46:35 +00004961 if (RuleCoverage) {
4962 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4963 ++NumPatternsTested;
4964 else
4965 PrintWarning(Pat.getSrcRecord()->getLoc(),
4966 "Pattern is not covered by a test");
4967 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004968 Rules.push_back(std::move(MatcherOrErr.get()));
4969 }
4970
Volkan Kelesf7f25682018-01-16 18:44:05 +00004971 // Comparison function to order records by name.
4972 auto orderByName = [](const Record *A, const Record *B) {
4973 return A->getName() < B->getName();
4974 };
4975
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004976 std::vector<Record *> ComplexPredicates =
4977 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00004978 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004979
4980 std::vector<Record *> CustomRendererFns =
4981 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00004982 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004983
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004984 unsigned MaxTemporaries = 0;
4985 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00004986 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004987
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004988 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4989 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4990 << ";\n"
4991 << "using PredicateBitset = "
4992 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4993 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4994
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004995 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4996 << " mutable MatcherState State;\n"
4997 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00004998 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004999 << Target.getName()
5000 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005001
5002 << " typedef void(" << Target.getName()
5003 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5004 "MachineInstr&) "
5005 "const;\n"
5006 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5007 "CustomRendererFn> "
5008 "ISelInfo;\n";
5009 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005010 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005011 << " static " << Target.getName()
5012 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005013 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005014 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005015 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005016 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005017 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005018 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005019 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005020 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5021 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005022 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005023
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005024 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5025 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005026 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5027 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005028 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005029
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005030 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5031 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5032 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005033
5034 // Separate subtarget features by how often they must be recomputed.
5035 SubtargetFeatureInfoMap ModuleFeatures;
5036 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5037 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5038 [](const SubtargetFeatureInfoMap::value_type &X) {
5039 return !X.second.mustRecomputePerFunction();
5040 });
5041 SubtargetFeatureInfoMap FunctionFeatures;
5042 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5043 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5044 [](const SubtargetFeatureInfoMap::value_type &X) {
5045 return X.second.mustRecomputePerFunction();
5046 });
5047
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005048 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005049 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5050 ModuleFeatures, OS);
5051 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5052 Target.getName(), "InstructionSelector",
5053 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5054 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005055
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005056 // Emit a table containing the LLT objects needed by the matcher and an enum
5057 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005058 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005059 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005060 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005061 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005062 OS << "// LLT Objects.\n"
5063 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005064 for (const auto &TypeObject : TypeObjects) {
5065 OS << " ";
5066 TypeObject.emitCxxEnumValue(OS);
5067 OS << ",\n";
5068 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005069 OS << "};\n";
5070 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005071 << "const static LLT TypeObjects[] = {\n";
5072 for (const auto &TypeObject : TypeObjects) {
5073 OS << " ";
5074 TypeObject.emitCxxConstructorCall(OS);
5075 OS << ",\n";
5076 }
5077 OS << "};\n\n";
5078
5079 // Emit a table containing the PredicateBitsets objects needed by the matcher
5080 // and an enum for the matcher to reference them with.
5081 std::vector<std::vector<Record *>> FeatureBitsets;
5082 for (auto &Rule : Rules)
5083 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005084 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5085 const std::vector<Record *> &B) {
5086 if (A.size() < B.size())
5087 return true;
5088 if (A.size() > B.size())
5089 return false;
5090 for (const auto &Pair : zip(A, B)) {
5091 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5092 return true;
5093 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005094 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005095 }
5096 return false;
5097 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005098 FeatureBitsets.erase(
5099 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5100 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005101 OS << "// Feature bitsets.\n"
5102 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005103 << " GIFBS_Invalid,\n";
5104 for (const auto &FeatureBitset : FeatureBitsets) {
5105 if (FeatureBitset.empty())
5106 continue;
5107 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5108 }
5109 OS << "};\n"
5110 << "const static PredicateBitset FeatureBitsets[] {\n"
5111 << " {}, // GIFBS_Invalid\n";
5112 for (const auto &FeatureBitset : FeatureBitsets) {
5113 if (FeatureBitset.empty())
5114 continue;
5115 OS << " {";
5116 for (const auto &Feature : FeatureBitset) {
5117 const auto &I = SubtargetFeatures.find(Feature);
5118 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5119 OS << I->second.getEnumBitName() << ", ";
5120 }
5121 OS << "},\n";
5122 }
5123 OS << "};\n\n";
5124
5125 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005126 OS << "// ComplexPattern predicates.\n"
5127 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005128 << " GICP_Invalid,\n";
5129 for (const auto &Record : ComplexPredicates)
5130 OS << " GICP_" << Record->getName() << ",\n";
5131 OS << "};\n"
5132 << "// See constructor for table contents\n\n";
5133
Daniel Sanders8ead1292018-06-15 23:13:43 +00005134 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005135 bool Unset;
5136 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5137 !R->getValueAsBit("IsAPInt");
5138 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005139 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005140 bool Unset;
5141 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5142 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005143 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005144 return R->getValueAsBit("IsAPInt");
5145 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005146 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005147 OS << "\n";
5148
5149 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5150 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5151 << " nullptr, // GICP_Invalid\n";
5152 for (const auto &Record : ComplexPredicates)
5153 OS << " &" << Target.getName()
5154 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5155 << ", // " << Record->getName() << "\n";
5156 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005157
Volkan Kelesf7f25682018-01-16 18:44:05 +00005158 OS << "// Custom renderers.\n"
5159 << "enum {\n"
5160 << " GICR_Invalid,\n";
5161 for (const auto &Record : CustomRendererFns)
5162 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5163 OS << "};\n";
5164
5165 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5166 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5167 << " nullptr, // GICP_Invalid\n";
5168 for (const auto &Record : CustomRendererFns)
5169 OS << " &" << Target.getName()
5170 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5171 << ", // " << Record->getName() << "\n";
5172 OS << "};\n\n";
5173
Fangrui Songefd94c52019-04-23 14:51:27 +00005174 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005175 int ScoreA = RuleMatcherScores[A.getRuleID()];
5176 int ScoreB = RuleMatcherScores[B.getRuleID()];
5177 if (ScoreA > ScoreB)
5178 return true;
5179 if (ScoreB > ScoreA)
5180 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005181 if (A.isHigherPriorityThan(B)) {
5182 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5183 "and less important at "
5184 "the same time");
5185 return true;
5186 }
5187 return false;
5188 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005189
Roman Tereshin2df4c222018-05-02 20:07:15 +00005190 OS << "bool " << Target.getName()
5191 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5192 "&CoverageInfo) const {\n"
5193 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5194 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5195 << " // FIXME: This should be computed on a per-function basis rather "
5196 "than per-insn.\n"
5197 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
5198 "&MF);\n"
5199 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5200 << " NewMIVector OutMIs;\n"
5201 << " State.MIs.clear();\n"
5202 << " State.MIs.push_back(&I);\n\n"
5203 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5204 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5205 << ", CoverageInfo)) {\n"
5206 << " return true;\n"
5207 << " }\n\n"
5208 << " return false;\n"
5209 << "}\n\n";
5210
Roman Tereshinbeb39312018-05-02 20:15:11 +00005211 const MatchTable Table =
5212 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005213 OS << "const int64_t *" << Target.getName()
5214 << "InstructionSelector::getMatchTable() const {\n";
5215 Table.emitDeclaration(OS);
5216 OS << " return ";
5217 Table.emitUse(OS);
5218 OS << ";\n}\n";
5219 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005220
5221 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5222 << "PredicateBitset AvailableModuleFeatures;\n"
5223 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5224 << "PredicateBitset getAvailableFeatures() const {\n"
5225 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5226 << "}\n"
5227 << "PredicateBitset\n"
5228 << "computeAvailableModuleFeatures(const " << Target.getName()
5229 << "Subtarget *Subtarget) const;\n"
5230 << "PredicateBitset\n"
5231 << "computeAvailableFunctionFeatures(const " << Target.getName()
5232 << "Subtarget *Subtarget,\n"
5233 << " const MachineFunction *MF) const;\n"
5234 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5235
5236 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5237 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5238 << "AvailableFunctionFeatures()\n"
5239 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005240}
5241
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005242void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5243 if (SubtargetFeatures.count(Predicate) == 0)
5244 SubtargetFeatures.emplace(
5245 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5246}
5247
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005248void RuleMatcher::optimize() {
5249 for (auto &Item : InsnVariableIDs) {
5250 InstructionMatcher &InsnMatcher = *Item.first;
5251 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005252 // Complex Patterns are usually expensive and they relatively rarely fail
5253 // on their own: more often we end up throwing away all the work done by a
5254 // matching part of a complex pattern because some other part of the
5255 // enclosing pattern didn't match. All of this makes it beneficial to
5256 // delay complex patterns until the very end of the rule matching,
5257 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005258 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005259 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005260 EpilogueMatchers.emplace_back(std::move(OP));
5261 OM->eraseNullPredicates();
5262 }
5263 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005264 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005265 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5266 const std::unique_ptr<PredicateMatcher> &R) {
5267 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5268 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5269 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005270}
5271
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005272bool RuleMatcher::hasFirstCondition() const {
5273 if (insnmatchers_empty())
5274 return false;
5275 InstructionMatcher &Matcher = insnmatchers_front();
5276 if (!Matcher.predicates_empty())
5277 return true;
5278 for (auto &OM : Matcher.operands())
5279 for (auto &OP : OM->predicates())
5280 if (!isa<InstructionOperandMatcher>(OP))
5281 return true;
5282 return false;
5283}
5284
5285const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5286 assert(!insnmatchers_empty() &&
5287 "Trying to get a condition from an empty RuleMatcher");
5288
5289 InstructionMatcher &Matcher = insnmatchers_front();
5290 if (!Matcher.predicates_empty())
5291 return **Matcher.predicates_begin();
5292 // If there is no more predicate on the instruction itself, look at its
5293 // operands.
5294 for (auto &OM : Matcher.operands())
5295 for (auto &OP : OM->predicates())
5296 if (!isa<InstructionOperandMatcher>(OP))
5297 return *OP;
5298
5299 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5300 "no conditions");
5301}
5302
5303std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5304 assert(!insnmatchers_empty() &&
5305 "Trying to pop a condition from an empty RuleMatcher");
5306
5307 InstructionMatcher &Matcher = insnmatchers_front();
5308 if (!Matcher.predicates_empty())
5309 return Matcher.predicates_pop_front();
5310 // If there is no more predicate on the instruction itself, look at its
5311 // operands.
5312 for (auto &OM : Matcher.operands())
5313 for (auto &OP : OM->predicates())
5314 if (!isa<InstructionOperandMatcher>(OP)) {
5315 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5316 OM->eraseNullPredicates();
5317 return Result;
5318 }
5319
5320 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5321 "no conditions");
5322}
5323
5324bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005325 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005326
5327 if (empty()) {
5328 // Sharing predicates for nested instructions is not supported yet as we
5329 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5330 // only work on the original root instruction (InsnVarID == 0):
5331 if (Predicate.getInsnVarID() != 0)
5332 return false;
5333 // ... otherwise an empty group can handle any predicate with no specific
5334 // requirements:
5335 return true;
5336 }
5337
5338 const Matcher &Representative = **Matchers.begin();
5339 const auto &RepresentativeCondition = Representative.getFirstCondition();
5340 // ... if not empty, the group can only accomodate matchers with the exact
5341 // same first condition:
5342 return Predicate.isIdentical(RepresentativeCondition);
5343}
5344
5345bool GroupMatcher::addMatcher(Matcher &Candidate) {
5346 if (!Candidate.hasFirstCondition())
5347 return false;
5348
5349 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5350 if (!candidateConditionMatches(Predicate))
5351 return false;
5352
5353 Matchers.push_back(&Candidate);
5354 return true;
5355}
5356
5357void GroupMatcher::finalize() {
5358 assert(Conditions.empty() && "Already finalized?");
5359 if (empty())
5360 return;
5361
5362 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005363 for (;;) {
5364 // All the checks are expected to succeed during the first iteration:
5365 for (const auto &Rule : Matchers)
5366 if (!Rule->hasFirstCondition())
5367 return;
5368 const auto &FirstCondition = FirstRule.getFirstCondition();
5369 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5370 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5371 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005372
Roman Tereshin152fc162018-05-23 22:50:53 +00005373 Conditions.push_back(FirstRule.popFirstCondition());
5374 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5375 Matchers[I]->popFirstCondition();
5376 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005377}
5378
5379void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005380 unsigned LabelID = ~0U;
5381 if (!Conditions.empty()) {
5382 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005383 Table << MatchTable::Opcode("GIM_Try", +1)
5384 << MatchTable::Comment("On fail goto")
5385 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005386 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005387 for (auto &Condition : Conditions)
5388 Condition->emitPredicateOpcodes(
5389 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5390
5391 for (const auto &M : Matchers)
5392 M->emit(Table);
5393
5394 // Exit the group
5395 if (!Conditions.empty())
5396 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005397 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005398}
5399
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005400bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005401 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005402}
5403
5404bool SwitchMatcher::candidateConditionMatches(
5405 const PredicateMatcher &Predicate) const {
5406
5407 if (empty()) {
5408 // Sharing predicates for nested instructions is not supported yet as we
5409 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5410 // only work on the original root instruction (InsnVarID == 0):
5411 if (Predicate.getInsnVarID() != 0)
5412 return false;
5413 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5414 // could fail as not all the types of conditions are supported:
5415 if (!isSupportedPredicateType(Predicate))
5416 return false;
5417 // ... or the condition might not have a proper implementation of
5418 // getValue() / isIdenticalDownToValue() yet:
5419 if (!Predicate.hasValue())
5420 return false;
5421 // ... otherwise an empty Switch can accomodate the condition with no
5422 // further requirements:
5423 return true;
5424 }
5425
5426 const Matcher &CaseRepresentative = **Matchers.begin();
5427 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5428 // Switch-cases must share the same kind of condition and path to the value it
5429 // checks:
5430 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5431 return false;
5432
5433 const auto Value = Predicate.getValue();
5434 // ... but be unique with respect to the actual value they check:
5435 return Values.count(Value) == 0;
5436}
5437
5438bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5439 if (!Candidate.hasFirstCondition())
5440 return false;
5441
5442 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5443 if (!candidateConditionMatches(Predicate))
5444 return false;
5445 const auto Value = Predicate.getValue();
5446 Values.insert(Value);
5447
5448 Matchers.push_back(&Candidate);
5449 return true;
5450}
5451
5452void SwitchMatcher::finalize() {
5453 assert(Condition == nullptr && "Already finalized");
5454 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5455 if (empty())
5456 return;
5457
5458 std::stable_sort(Matchers.begin(), Matchers.end(),
5459 [](const Matcher *L, const Matcher *R) {
5460 return L->getFirstCondition().getValue() <
5461 R->getFirstCondition().getValue();
5462 });
5463 Condition = Matchers[0]->popFirstCondition();
5464 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5465 Matchers[I]->popFirstCondition();
5466}
5467
5468void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5469 MatchTable &Table) {
5470 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5471
5472 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5473 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5474 << MatchTable::IntValue(Condition->getInsnVarID());
5475 return;
5476 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005477 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5478 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5479 << MatchTable::IntValue(Condition->getInsnVarID())
5480 << MatchTable::Comment("Op")
5481 << MatchTable::IntValue(Condition->getOpIdx());
5482 return;
5483 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005484
5485 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5486 "predicate type that is claimed to be supported");
5487}
5488
5489void SwitchMatcher::emit(MatchTable &Table) {
5490 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5491 if (empty())
5492 return;
5493 assert(Condition != nullptr &&
5494 "Broken SwitchMatcher, hasn't been finalized?");
5495
5496 std::vector<unsigned> LabelIDs(Values.size());
5497 std::generate(LabelIDs.begin(), LabelIDs.end(),
5498 [&Table]() { return Table.allocateLabelID(); });
5499 const unsigned Default = Table.allocateLabelID();
5500
5501 const int64_t LowerBound = Values.begin()->getRawValue();
5502 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5503
5504 emitPredicateSpecificOpcodes(*Condition, Table);
5505
5506 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5507 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5508 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5509
5510 int64_t J = LowerBound;
5511 auto VI = Values.begin();
5512 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5513 auto V = *VI++;
5514 while (J++ < V.getRawValue())
5515 Table << MatchTable::IntValue(0);
5516 V.turnIntoComment();
5517 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5518 }
5519 Table << MatchTable::LineBreak;
5520
5521 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5522 Table << MatchTable::Label(LabelIDs[I]);
5523 Matchers[I]->emit(Table);
5524 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5525 }
5526 Table << MatchTable::Label(Default);
5527}
5528
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005529unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005530
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005531} // end anonymous namespace
5532
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005533//===----------------------------------------------------------------------===//
5534
5535namespace llvm {
5536void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5537 GlobalISelEmitter(RK).run(OS);
5538}
5539} // End llvm namespace