[llvm-objdump] - Remove one overload of reportError. NFCI.
[llvm-complete.git] / utils / TableGen / GlobalISelEmitter.cpp
blob0fb6a9c95e61e0916dc8268465df978ebc892bf2
1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 // 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
6 //
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 //===----------------------------------------------------------------------===//
32 #include "CodeGenDAGPatterns.h"
33 #include "SubtargetFeatureInfo.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CodeGenCoverage.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/LowLevelTypeImpl.h"
41 #include "llvm/Support/MachineValueType.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <numeric>
47 #include <string>
48 using namespace llvm;
50 #define DEBUG_TYPE "gisel-emitter"
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
56 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
58 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60 static 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"),
64 cl::init(false), cl::cat(GlobalISelEmitterCat));
66 static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
71 static 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));
76 static 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));
81 namespace {
82 //===- Helper functions ---------------------------------------------------===//
84 /// Get the name of the enum value used to number the predicate function.
85 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
86 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
88 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
89 Predicate.getFnName();
92 /// Get the opcode used to check this predicate.
93 std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
94 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
97 /// This class stands in for LLT wherever we want to tablegen-erate an
98 /// equivalent at compiler run-time.
99 class LLTCodeGen {
100 private:
101 LLT Ty;
103 public:
104 LLTCodeGen() = default;
105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
111 emitCxxEnumValue(OS);
112 return OS.str();
115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
130 llvm_unreachable("Unhandled LLT");
133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
138 if (Ty.isVector()) {
139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
141 return;
143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
148 llvm_unreachable("Unhandled LLT");
151 const LLT &get() const { return Ty; }
153 /// This ordering is used for std::unique() and llvm::sort(). There's no
154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
156 bool operator<(const LLTCodeGen &Other) const {
157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
159 if (!Ty.isValid())
160 return false;
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();
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
181 // Track all types that are used so we can emit the corresponding enum.
182 std::set<LLTCodeGen> KnownTypes;
184 class InstructionMatcher;
185 /// 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, ...).
187 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
188 MVT VT(SVT);
190 if (VT.isVector() && VT.getVectorNumElements() != 1)
191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
199 static std::string explainPredicates(const TreePatternNode *N) {
200 std::string Explanation = "";
201 StringRef Separator = "";
202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
206 Separator = ", ";
208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
213 if (P.isUnindexed())
214 Explanation += " unindexed";
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";
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
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();
235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
249 OS << ']';
252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
256 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";
266 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";
275 return Explanation;
278 std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
295 return (" (Operator " + Operator->getName() + " not understood)").str();
298 /// Helper function to let the emitter report skip reason error messages.
299 static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
303 static Error isTrivialOperatorNode(const TreePatternNode *N) {
304 std::string Explanation = "";
305 std::string Separator = "";
307 bool HasUnsupportedPredicate = false;
308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
311 if (Predicate.isAlwaysTrue())
312 continue;
314 if (Predicate.isImmediatePattern())
315 continue;
317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
319 continue;
321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
322 continue;
324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
337 if (Predicate.getMinAlignment() > 0)
338 continue;
341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
354 continue;
356 if (Predicate.hasGISelPredicateCode())
357 continue;
359 HasUnsupportedPredicate = true;
360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
365 break;
368 if (!HasUnsupportedPredicate)
369 return Error::success();
371 return failedImport(Explanation);
374 static 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();
381 return nullptr;
384 std::string
385 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
392 //===- MatchTable Helpers -------------------------------------------------===//
394 class MatchTable;
396 /// A record to be stored in a MatchTable.
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.
402 struct 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,
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;
432 private:
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;
438 public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
442 /// The actual run-time value, if known
443 int64_t RawValue;
445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
452 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
453 "This value is reserved for non-labels");
455 MatchTableRecord(const MatchTableRecord &Other) = default;
456 MatchTableRecord(MatchTableRecord &&Other) = default;
458 /// Useful if a Match Table Record gets optimized out
459 void turnIntoComment() {
460 Flags |= MTRF_Comment;
461 Flags &= ~MTRF_CommaFollows;
462 NumElements = 0;
465 /// For Jump Table generation purposes
466 bool operator<(const MatchTableRecord &Other) const {
467 return RawValue < Other.RawValue;
469 int64_t getRawValue() const { return RawValue; }
471 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
472 const MatchTable &Table) const;
473 unsigned size() const { return NumElements; }
476 class Matcher;
478 /// Holds the contents of a generated MatchTable to enable formatting and the
479 /// necessary index tracking needed to support GIM_Try.
480 class 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.
490 unsigned CurrentSize = 0;
491 /// A unique identifier for a MatchTable label.
492 unsigned CurrentLabelID = 0;
493 /// Determines if the table should be instrumented for rule coverage tracking.
494 bool IsWithCoverage;
496 public:
497 static MatchTableRecord LineBreak;
498 static MatchTableRecord Comment(StringRef Comment) {
499 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
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;
508 return MatchTableRecord(None, Opcode, 1,
509 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
511 static MatchTableRecord NamedValue(StringRef NamedValue) {
512 return MatchTableRecord(None, NamedValue, 1,
513 MatchTableRecord::MTRF_CommaFollows);
515 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
516 return MatchTableRecord(None, NamedValue, 1,
517 MatchTableRecord::MTRF_CommaFollows, RawValue);
519 static MatchTableRecord NamedValue(StringRef Namespace,
520 StringRef NamedValue) {
521 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
522 MatchTableRecord::MTRF_CommaFollows);
524 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
525 int64_t RawValue) {
526 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
527 MatchTableRecord::MTRF_CommaFollows, RawValue);
529 static MatchTableRecord IntValue(int64_t IntValue) {
530 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
531 MatchTableRecord::MTRF_CommaFollows);
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);
539 static MatchTableRecord JumpTarget(unsigned LabelID) {
540 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
541 MatchTableRecord::MTRF_JumpTarget |
542 MatchTableRecord::MTRF_Comment |
543 MatchTableRecord::MTRF_CommaFollows);
546 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
548 MatchTable(bool WithCoverage, unsigned ID = 0)
549 : ID(ID), IsWithCoverage(WithCoverage) {}
551 bool isWithCoverage() const { return IsWithCoverage; }
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();
560 unsigned allocateLabelID() { return CurrentLabelID++; }
562 void defineLabel(unsigned LabelID) {
563 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
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;
572 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
574 void emitDeclaration(raw_ostream &OS) const {
575 unsigned Indentation = 4;
576 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
577 LineBreak.emit(OS, true, *this);
578 OS << std::string(Indentation, ' ');
580 for (auto I = Contents.begin(), E = Contents.end(); I != E;
581 ++I) {
582 bool LineBreakIsNext = false;
583 const auto &NextI = std::next(I);
585 if (NextI != E) {
586 if (NextI->EmitStr == "" &&
587 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
588 LineBreakIsNext = true;
591 if (I->Flags & MatchTableRecord::MTRF_Indent)
592 Indentation += 2;
594 I->emit(OS, LineBreakIsNext, *this);
595 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
596 OS << std::string(Indentation, ' ');
598 if (I->Flags & MatchTableRecord::MTRF_Outdent)
599 Indentation -= 2;
601 OS << "};\n";
605 MatchTableRecord MatchTable::LineBreak = {
606 None, "" /* Emit String */, 0 /* Elements */,
607 MatchTableRecord::MTRF_LineBreakFollows};
609 void 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;
616 if (Flags & MTRF_Comment)
617 OS << (UseLineComment ? "// " : "/*");
619 OS << EmitStr;
620 if (Flags & MTRF_Label)
621 OS << ": @" << Table.getLabelIndex(LabelID);
623 if (Flags & MTRF_Comment && !UseLineComment)
624 OS << "*/";
626 if (Flags & MTRF_JumpTarget) {
627 if (Flags & MTRF_Comment)
628 OS << " ";
629 OS << Table.getLabelIndex(LabelID);
632 if (Flags & MTRF_CommaFollows) {
633 OS << ",";
634 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
635 OS << " ";
638 if (Flags & MTRF_LineBreakFollows)
639 OS << "\n";
642 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
643 Table.push_back(Value);
644 return Table;
647 //===- Matchers -----------------------------------------------------------===//
649 class OperandMatcher;
650 class MatchAction;
651 class PredicateMatcher;
652 class RuleMatcher;
654 class Matcher {
655 public:
656 virtual ~Matcher() = default;
657 virtual void optimize() {}
658 virtual void emit(MatchTable &Table) = 0;
660 virtual bool hasFirstCondition() const = 0;
661 virtual const PredicateMatcher &getFirstCondition() const = 0;
662 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
665 MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
666 bool WithCoverage) {
667 MatchTable Table(WithCoverage);
668 for (Matcher *Rule : Rules)
669 Rule->emit(Table);
671 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
674 class GroupMatcher final : public Matcher {
675 /// Conditions that form a common prefix of all the matchers contained.
676 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
678 /// All the nested matchers, sharing a common prefix.
679 std::vector<Matcher *> Matchers;
681 /// An owning collection for any auxiliary matchers created while optimizing
682 /// nested matchers contained.
683 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
685 public:
686 /// 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.
689 /// Expected to preserve its argument, so it could be moved out later on.
690 bool addMatcher(Matcher &Candidate);
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:
696 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
697 /// addMatcher(...)*; finalize(); emit(...);
699 /// or generally
701 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
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.
708 /// addMatcher() calls after the finalize() call are not supported.
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();
713 void optimize() override;
714 void emit(MatchTable &Table) override;
716 /// 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());
722 size_t size() const { return Matchers.size(); }
723 bool empty() const { return Matchers.empty(); }
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;
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();
737 bool hasFirstCondition() const override { return !Conditions.empty(); }
739 private:
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;
745 class 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;
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;
757 /// Temporary set used to check that the case values don't repeat within the
758 /// same switch.
759 std::set<MatchTableRecord> Values;
761 /// An owning collection for any auxiliary matchers created while optimizing
762 /// nested matchers contained.
763 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
765 public:
766 bool addMatcher(Matcher &Candidate);
768 void finalize();
769 void emit(MatchTable &Table) override;
771 iterator_range<std::vector<Matcher *>::iterator> matchers() {
772 return make_range(Matchers.begin(), Matchers.end());
774 size_t size() const { return Matchers.size(); }
775 bool empty() const { return Matchers.empty(); }
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");
783 const PredicateMatcher &getFirstCondition() const override {
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
786 bool hasFirstCondition() const override { return false; }
788 private:
789 /// See if the predicate type has a Switch-implementation for it.
790 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
792 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
794 /// emit()-helper
795 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
796 MatchTable &Table);
799 /// Generates code to check that a match rule matches.
800 class RuleMatcher : public Matcher {
801 public:
802 using ActionList = std::list<std::unique_ptr<MatchAction>>;
803 using action_iterator = ActionList::iterator;
805 protected:
806 /// 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.
810 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
811 MatchersTy Matchers;
813 /// A list of actions that need to be taken when all predicates in this rule
814 /// have succeeded.
815 ActionList Actions;
817 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
819 /// A map of instruction matchers to the local variables
820 DefinedInsnVariablesMap InsnVariableIDs;
822 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
824 // The set of instruction matchers that have not yet been claimed for mutation
825 // by a BuildMI.
826 MutatableInsnSet MutatableInsns;
828 /// A map of named operands defined by the matchers that may be referenced by
829 /// the renderers.
830 StringMap<OperandMatcher *> DefinedOperands;
832 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
833 unsigned NextInsnVarID;
835 /// ID for the next output instruction allocated with allocateOutputInsnID()
836 unsigned NextOutputInsnID;
838 /// ID for the next temporary register ID allocated with allocateTempRegID()
839 unsigned NextTempRegID;
841 std::vector<Record *> RequiredFeatures;
842 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
844 ArrayRef<SMLoc> SrcLoc;
846 typedef std::tuple<Record *, unsigned, unsigned>
847 DefinedComplexPatternSubOperand;
848 typedef StringMap<DefinedComplexPatternSubOperand>
849 DefinedComplexPatternSubOperandMap;
850 /// A map of Symbolic Names to ComplexPattern sub-operands.
851 DefinedComplexPatternSubOperandMap ComplexSubOperands;
853 uint64_t RuleID;
854 static uint64_t NextRuleID;
856 public:
857 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
858 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
859 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
860 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
861 RuleID(NextRuleID++) {}
862 RuleMatcher(RuleMatcher &&Other) = default;
863 RuleMatcher &operator=(RuleMatcher &&Other) = default;
865 uint64_t getRuleID() const { return RuleID; }
867 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
868 void addRequiredFeature(Record *Feature);
869 const std::vector<Record *> &getRequiredFeatures() const;
871 template <class Kind, class... Args> Kind &addAction(Args &&... args);
872 template <class Kind, class... Args>
873 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
875 /// Define an instruction without emitting any code to do so.
876 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
878 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
879 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
880 return InsnVariableIDs.begin();
882 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
883 return InsnVariableIDs.end();
885 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
886 defined_insn_vars() const {
887 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
890 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
891 return MutatableInsns.begin();
893 MutatableInsnSet::const_iterator mutatable_insns_end() const {
894 return MutatableInsns.end();
896 iterator_range<typename MutatableInsnSet::const_iterator>
897 mutatable_insns() const {
898 return make_range(mutatable_insns_begin(), mutatable_insns_end());
900 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
901 bool R = MutatableInsns.erase(InsnMatcher);
902 assert(R && "Reserving a mutatable insn that isn't available");
903 (void)R;
906 action_iterator actions_begin() { return Actions.begin(); }
907 action_iterator actions_end() { return Actions.end(); }
908 iterator_range<action_iterator> actions() {
909 return make_range(actions_begin(), actions_end());
912 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
914 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
915 unsigned RendererID, unsigned SubOperandID) {
916 if (ComplexSubOperands.count(SymbolicName))
917 return failedImport(
918 "Complex suboperand referenced more than once (Operand: " +
919 SymbolicName + ")");
921 ComplexSubOperands[SymbolicName] =
922 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
924 return Error::success();
927 Optional<DefinedComplexPatternSubOperand>
928 getComplexSubOperand(StringRef SymbolicName) const {
929 const auto &I = ComplexSubOperands.find(SymbolicName);
930 if (I == ComplexSubOperands.end())
931 return None;
932 return I->second;
935 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
936 const OperandMatcher &getOperandMatcher(StringRef Name) const;
938 void optimize() override;
939 void emit(MatchTable &Table) override;
941 /// Compare the priority of this object and B.
943 /// Returns true if this object is more important than B.
944 bool isHigherPriorityThan(const RuleMatcher &B) const;
946 /// Report the maximum number of temporary operands needed by the rule
947 /// matcher.
948 unsigned countRendererFns() const;
950 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
951 const PredicateMatcher &getFirstCondition() const override;
952 LLTCodeGen getFirstConditionAsRootType();
953 bool hasFirstCondition() const override;
954 unsigned getNumOperands() const;
955 StringRef getOpcode() const;
957 // FIXME: Remove this as soon as possible
958 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
960 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
961 unsigned allocateTempRegID() { return NextTempRegID++; }
963 iterator_range<MatchersTy::iterator> insnmatchers() {
964 return make_range(Matchers.begin(), Matchers.end());
966 bool insnmatchers_empty() const { return Matchers.empty(); }
967 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
970 uint64_t RuleMatcher::NextRuleID = 0;
972 using action_iterator = RuleMatcher::action_iterator;
974 template <class PredicateTy> class PredicateListMatcher {
975 private:
976 /// Template instantiations should specialize this to return a string to use
977 /// for the comment emitted when there are no predicates.
978 std::string getNoPredicateComment() const;
980 protected:
981 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
982 PredicatesTy Predicates;
984 /// Track if the list of predicates was manipulated by one of the optimization
985 /// methods.
986 bool Optimized = false;
988 public:
989 /// Construct a new predicate and add it to the matcher.
990 template <class Kind, class... Args>
991 Optional<Kind *> addPredicate(Args &&... args);
993 typename PredicatesTy::iterator predicates_begin() {
994 return Predicates.begin();
996 typename PredicatesTy::iterator predicates_end() {
997 return Predicates.end();
999 iterator_range<typename PredicatesTy::iterator> predicates() {
1000 return make_range(predicates_begin(), predicates_end());
1002 typename PredicatesTy::size_type predicates_size() const {
1003 return Predicates.size();
1005 bool predicates_empty() const { return Predicates.empty(); }
1007 std::unique_ptr<PredicateTy> predicates_pop_front() {
1008 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
1009 Predicates.pop_front();
1010 Optimized = true;
1011 return Front;
1014 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1015 Predicates.push_front(std::move(Predicate));
1018 void eraseNullPredicates() {
1019 const auto NewEnd =
1020 std::stable_partition(Predicates.begin(), Predicates.end(),
1021 std::logical_not<std::unique_ptr<PredicateTy>>());
1022 if (NewEnd != Predicates.begin()) {
1023 Predicates.erase(Predicates.begin(), NewEnd);
1024 Optimized = true;
1028 /// Emit MatchTable opcodes that tests whether all the predicates are met.
1029 template <class... Args>
1030 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1031 if (Predicates.empty() && !Optimized) {
1032 Table << MatchTable::Comment(getNoPredicateComment())
1033 << MatchTable::LineBreak;
1034 return;
1037 for (const auto &Predicate : predicates())
1038 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1042 class PredicateMatcher {
1043 public:
1044 /// This enum is used for RTTI and also defines the priority that is given to
1045 /// the predicate when generating the matcher code. Kinds with higher priority
1046 /// must be tested first.
1048 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1049 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1050 /// are represented by a virtual register defined by a G_CONSTANT instruction.
1052 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1053 /// are currently not compared between each other.
1054 enum PredicateKind {
1055 IPM_Opcode,
1056 IPM_NumOperands,
1057 IPM_ImmPredicate,
1058 IPM_AtomicOrderingMMO,
1059 IPM_MemoryLLTSize,
1060 IPM_MemoryVsLLTSize,
1061 IPM_MemoryAddressSpace,
1062 IPM_MemoryAlignment,
1063 IPM_GenericPredicate,
1064 OPM_SameOperand,
1065 OPM_ComplexPattern,
1066 OPM_IntrinsicID,
1067 OPM_Instruction,
1068 OPM_Int,
1069 OPM_LiteralInt,
1070 OPM_LLT,
1071 OPM_PointerToAny,
1072 OPM_RegBank,
1073 OPM_MBB,
1076 protected:
1077 PredicateKind Kind;
1078 unsigned InsnVarID;
1079 unsigned OpIdx;
1081 public:
1082 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1083 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
1085 unsigned getInsnVarID() const { return InsnVarID; }
1086 unsigned getOpIdx() const { return OpIdx; }
1088 virtual ~PredicateMatcher() = default;
1089 /// Emit MatchTable opcodes that check the predicate for the given operand.
1090 virtual void emitPredicateOpcodes(MatchTable &Table,
1091 RuleMatcher &Rule) const = 0;
1093 PredicateKind getKind() const { return Kind; }
1095 virtual bool isIdentical(const PredicateMatcher &B) const {
1096 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1097 OpIdx == B.OpIdx;
1100 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1101 return hasValue() && PredicateMatcher::isIdentical(B);
1104 virtual MatchTableRecord getValue() const {
1105 assert(hasValue() && "Can not get a value of a value-less predicate!");
1106 llvm_unreachable("Not implemented yet");
1108 virtual bool hasValue() const { return false; }
1110 /// Report the maximum number of temporary operands needed by the predicate
1111 /// matcher.
1112 virtual unsigned countRendererFns() const { return 0; }
1115 /// Generates code to check a predicate of an operand.
1117 /// Typical predicates include:
1118 /// * Operand is a particular register.
1119 /// * Operand is assigned a particular register bank.
1120 /// * Operand is an MBB.
1121 class OperandPredicateMatcher : public PredicateMatcher {
1122 public:
1123 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1124 unsigned OpIdx)
1125 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
1126 virtual ~OperandPredicateMatcher() {}
1128 /// Compare the priority of this object and B.
1130 /// Returns true if this object is more important than B.
1131 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
1134 template <>
1135 std::string
1136 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1137 return "No operand predicates";
1140 /// Generates code to check that a register operand is defined by the same exact
1141 /// one as another.
1142 class SameOperandMatcher : public OperandPredicateMatcher {
1143 std::string MatchingName;
1145 public:
1146 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
1147 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1148 MatchingName(MatchingName) {}
1150 static bool classof(const PredicateMatcher *P) {
1151 return P->getKind() == OPM_SameOperand;
1154 void emitPredicateOpcodes(MatchTable &Table,
1155 RuleMatcher &Rule) const override;
1157 bool isIdentical(const PredicateMatcher &B) const override {
1158 return OperandPredicateMatcher::isIdentical(B) &&
1159 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1163 /// Generates code to check that an operand is a particular LLT.
1164 class LLTOperandMatcher : public OperandPredicateMatcher {
1165 protected:
1166 LLTCodeGen Ty;
1168 public:
1169 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1171 static void initTypeIDValuesMap() {
1172 TypeIDValues.clear();
1174 unsigned ID = 0;
1175 for (const LLTCodeGen LLTy : KnownTypes)
1176 TypeIDValues[LLTy] = ID++;
1179 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
1180 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
1181 KnownTypes.insert(Ty);
1184 static bool classof(const PredicateMatcher *P) {
1185 return P->getKind() == OPM_LLT;
1187 bool isIdentical(const PredicateMatcher &B) const override {
1188 return OperandPredicateMatcher::isIdentical(B) &&
1189 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1191 MatchTableRecord getValue() const override {
1192 const auto VI = TypeIDValues.find(Ty);
1193 if (VI == TypeIDValues.end())
1194 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1195 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1197 bool hasValue() const override {
1198 if (TypeIDValues.size() != KnownTypes.size())
1199 initTypeIDValuesMap();
1200 return TypeIDValues.count(Ty);
1203 LLTCodeGen getTy() const { return Ty; }
1205 void emitPredicateOpcodes(MatchTable &Table,
1206 RuleMatcher &Rule) const override {
1207 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1208 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1209 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
1210 << getValue() << MatchTable::LineBreak;
1214 std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1216 /// Generates code to check that an operand is a pointer to any address space.
1218 /// In SelectionDAG, the types did not describe pointers or address spaces. As a
1219 /// result, iN is used to describe a pointer of N bits to any address space and
1220 /// PatFrag predicates are typically used to constrain the address space. There's
1221 /// no reliable means to derive the missing type information from the pattern so
1222 /// imported rules must test the components of a pointer separately.
1224 /// If SizeInBits is zero, then the pointer size will be obtained from the
1225 /// subtarget.
1226 class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1227 protected:
1228 unsigned SizeInBits;
1230 public:
1231 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1232 unsigned SizeInBits)
1233 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1234 SizeInBits(SizeInBits) {}
1236 static bool classof(const OperandPredicateMatcher *P) {
1237 return P->getKind() == OPM_PointerToAny;
1240 void emitPredicateOpcodes(MatchTable &Table,
1241 RuleMatcher &Rule) const override {
1242 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1243 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1244 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1245 << MatchTable::Comment("SizeInBits")
1246 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1250 /// Generates code to check that an operand is a particular target constant.
1251 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1252 protected:
1253 const OperandMatcher &Operand;
1254 const Record &TheDef;
1256 unsigned getAllocatedTemporariesBaseID() const;
1258 public:
1259 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1261 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1262 const OperandMatcher &Operand,
1263 const Record &TheDef)
1264 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1265 Operand(Operand), TheDef(TheDef) {}
1267 static bool classof(const PredicateMatcher *P) {
1268 return P->getKind() == OPM_ComplexPattern;
1271 void emitPredicateOpcodes(MatchTable &Table,
1272 RuleMatcher &Rule) const override {
1273 unsigned ID = getAllocatedTemporariesBaseID();
1274 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1275 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1276 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1277 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1278 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1279 << MatchTable::LineBreak;
1282 unsigned countRendererFns() const override {
1283 return 1;
1287 /// Generates code to check that an operand is in a particular register bank.
1288 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1289 protected:
1290 const CodeGenRegisterClass &RC;
1292 public:
1293 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1294 const CodeGenRegisterClass &RC)
1295 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
1297 bool isIdentical(const PredicateMatcher &B) const override {
1298 return OperandPredicateMatcher::isIdentical(B) &&
1299 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1302 static bool classof(const PredicateMatcher *P) {
1303 return P->getKind() == OPM_RegBank;
1306 void emitPredicateOpcodes(MatchTable &Table,
1307 RuleMatcher &Rule) const override {
1308 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1309 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1310 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1311 << MatchTable::Comment("RC")
1312 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1313 << MatchTable::LineBreak;
1317 /// Generates code to check that an operand is a basic block.
1318 class MBBOperandMatcher : public OperandPredicateMatcher {
1319 public:
1320 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1321 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
1323 static bool classof(const PredicateMatcher *P) {
1324 return P->getKind() == OPM_MBB;
1327 void emitPredicateOpcodes(MatchTable &Table,
1328 RuleMatcher &Rule) const override {
1329 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1330 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1331 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1335 /// Generates code to check that an operand is a G_CONSTANT with a particular
1336 /// int.
1337 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
1338 protected:
1339 int64_t Value;
1341 public:
1342 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1343 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
1345 bool isIdentical(const PredicateMatcher &B) const override {
1346 return OperandPredicateMatcher::isIdentical(B) &&
1347 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1350 static bool classof(const PredicateMatcher *P) {
1351 return P->getKind() == OPM_Int;
1354 void emitPredicateOpcodes(MatchTable &Table,
1355 RuleMatcher &Rule) const override {
1356 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1357 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1358 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1359 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1363 /// Generates code to check that an operand is a raw int (where MO.isImm() or
1364 /// MO.isCImm() is true).
1365 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1366 protected:
1367 int64_t Value;
1369 public:
1370 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1371 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1372 Value(Value) {}
1374 bool isIdentical(const PredicateMatcher &B) const override {
1375 return OperandPredicateMatcher::isIdentical(B) &&
1376 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1379 static bool classof(const PredicateMatcher *P) {
1380 return P->getKind() == OPM_LiteralInt;
1383 void emitPredicateOpcodes(MatchTable &Table,
1384 RuleMatcher &Rule) const override {
1385 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1386 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1387 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1388 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1392 /// Generates code to check that an operand is an intrinsic ID.
1393 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1394 protected:
1395 const CodeGenIntrinsic *II;
1397 public:
1398 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1399 const CodeGenIntrinsic *II)
1400 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
1402 bool isIdentical(const PredicateMatcher &B) const override {
1403 return OperandPredicateMatcher::isIdentical(B) &&
1404 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1407 static bool classof(const PredicateMatcher *P) {
1408 return P->getKind() == OPM_IntrinsicID;
1411 void emitPredicateOpcodes(MatchTable &Table,
1412 RuleMatcher &Rule) const override {
1413 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1414 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1415 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1416 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1417 << MatchTable::LineBreak;
1421 /// Generates code to check that a set of predicates match for a particular
1422 /// operand.
1423 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1424 protected:
1425 InstructionMatcher &Insn;
1426 unsigned OpIdx;
1427 std::string SymbolicName;
1429 /// The index of the first temporary variable allocated to this operand. The
1430 /// number of allocated temporaries can be found with
1431 /// countRendererFns().
1432 unsigned AllocatedTemporariesBaseID;
1434 public:
1435 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
1436 const std::string &SymbolicName,
1437 unsigned AllocatedTemporariesBaseID)
1438 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1439 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
1441 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1442 const StringRef getSymbolicName() const { return SymbolicName; }
1443 void setSymbolicName(StringRef Name) {
1444 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1445 SymbolicName = Name;
1448 /// Construct a new operand predicate and add it to the matcher.
1449 template <class Kind, class... Args>
1450 Optional<Kind *> addPredicate(Args &&... args) {
1451 if (isSameAsAnotherOperand())
1452 return None;
1453 Predicates.emplace_back(std::make_unique<Kind>(
1454 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1455 return static_cast<Kind *>(Predicates.back().get());
1458 unsigned getOpIdx() const { return OpIdx; }
1459 unsigned getInsnVarID() const;
1461 std::string getOperandExpr(unsigned InsnVarID) const {
1462 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1463 llvm::to_string(OpIdx) + ")";
1466 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1468 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1469 bool OperandIsAPointer);
1471 /// Emit MatchTable opcodes that test whether the instruction named in
1472 /// InsnVarID matches all the predicates and all the operands.
1473 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1474 if (!Optimized) {
1475 std::string Comment;
1476 raw_string_ostream CommentOS(Comment);
1477 CommentOS << "MIs[" << getInsnVarID() << "] ";
1478 if (SymbolicName.empty())
1479 CommentOS << "Operand " << OpIdx;
1480 else
1481 CommentOS << SymbolicName;
1482 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1485 emitPredicateListOpcodes(Table, Rule);
1488 /// Compare the priority of this object and B.
1490 /// Returns true if this object is more important than B.
1491 bool isHigherPriorityThan(OperandMatcher &B) {
1492 // Operand matchers involving more predicates have higher priority.
1493 if (predicates_size() > B.predicates_size())
1494 return true;
1495 if (predicates_size() < B.predicates_size())
1496 return false;
1498 // This assumes that predicates are added in a consistent order.
1499 for (auto &&Predicate : zip(predicates(), B.predicates())) {
1500 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1501 return true;
1502 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1503 return false;
1506 return false;
1509 /// Report the maximum number of temporary operands needed by the operand
1510 /// matcher.
1511 unsigned countRendererFns() {
1512 return std::accumulate(
1513 predicates().begin(), predicates().end(), 0,
1514 [](unsigned A,
1515 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
1516 return A + Predicate->countRendererFns();
1520 unsigned getAllocatedTemporariesBaseID() const {
1521 return AllocatedTemporariesBaseID;
1524 bool isSameAsAnotherOperand() {
1525 for (const auto &Predicate : predicates())
1526 if (isa<SameOperandMatcher>(Predicate))
1527 return true;
1528 return false;
1532 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1533 bool OperandIsAPointer) {
1534 if (!VTy.isMachineValueType())
1535 return failedImport("unsupported typeset");
1537 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1538 addPredicate<PointerToAnyOperandMatcher>(0);
1539 return Error::success();
1542 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1543 if (!OpTyOrNone)
1544 return failedImport("unsupported type");
1546 if (OperandIsAPointer)
1547 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1548 else if (VTy.isPointer())
1549 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1550 OpTyOrNone->get().getSizeInBits()));
1551 else
1552 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1553 return Error::success();
1556 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1557 return Operand.getAllocatedTemporariesBaseID();
1560 /// Generates code to check a predicate on an instruction.
1562 /// Typical predicates include:
1563 /// * The opcode of the instruction is a particular value.
1564 /// * The nsw/nuw flag is/isn't set.
1565 class InstructionPredicateMatcher : public PredicateMatcher {
1566 public:
1567 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1568 : PredicateMatcher(Kind, InsnVarID) {}
1569 virtual ~InstructionPredicateMatcher() {}
1571 /// Compare the priority of this object and B.
1573 /// Returns true if this object is more important than B.
1574 virtual bool
1575 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
1576 return Kind < B.Kind;
1580 template <>
1581 std::string
1582 PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
1583 return "No instruction predicates";
1586 /// Generates code to check the opcode of an instruction.
1587 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1588 protected:
1589 const CodeGenInstruction *I;
1591 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1593 public:
1594 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1595 OpcodeValues.clear();
1597 unsigned OpcodeValue = 0;
1598 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1599 OpcodeValues[I] = OpcodeValue++;
1602 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1603 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
1605 static bool classof(const PredicateMatcher *P) {
1606 return P->getKind() == IPM_Opcode;
1609 bool isIdentical(const PredicateMatcher &B) const override {
1610 return InstructionPredicateMatcher::isIdentical(B) &&
1611 I == cast<InstructionOpcodeMatcher>(&B)->I;
1613 MatchTableRecord getValue() const override {
1614 const auto VI = OpcodeValues.find(I);
1615 if (VI != OpcodeValues.end())
1616 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1617 VI->second);
1618 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1620 bool hasValue() const override { return OpcodeValues.count(I); }
1622 void emitPredicateOpcodes(MatchTable &Table,
1623 RuleMatcher &Rule) const override {
1624 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1625 << MatchTable::IntValue(InsnVarID) << getValue()
1626 << MatchTable::LineBreak;
1629 /// Compare the priority of this object and B.
1631 /// Returns true if this object is more important than B.
1632 bool
1633 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1634 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1635 return true;
1636 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1637 return false;
1639 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1640 // this is cosmetic at the moment, we may want to drive a similar ordering
1641 // using instruction frequency information to improve compile time.
1642 if (const InstructionOpcodeMatcher *BO =
1643 dyn_cast<InstructionOpcodeMatcher>(&B))
1644 return I->TheDef->getName() < BO->I->TheDef->getName();
1646 return false;
1649 bool isConstantInstruction() const {
1650 return I->TheDef->getName() == "G_CONSTANT";
1653 StringRef getOpcode() const { return I->TheDef->getName(); }
1654 unsigned getNumOperands() const { return I->Operands.size(); }
1656 StringRef getOperandType(unsigned OpIdx) const {
1657 return I->Operands[OpIdx].OperandType;
1661 DenseMap<const CodeGenInstruction *, unsigned>
1662 InstructionOpcodeMatcher::OpcodeValues;
1664 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1665 unsigned NumOperands = 0;
1667 public:
1668 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1669 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1670 NumOperands(NumOperands) {}
1672 static bool classof(const PredicateMatcher *P) {
1673 return P->getKind() == IPM_NumOperands;
1676 bool isIdentical(const PredicateMatcher &B) const override {
1677 return InstructionPredicateMatcher::isIdentical(B) &&
1678 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1681 void emitPredicateOpcodes(MatchTable &Table,
1682 RuleMatcher &Rule) const override {
1683 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1684 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1685 << MatchTable::Comment("Expected")
1686 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1690 /// Generates code to check that this instruction is a constant whose value
1691 /// meets an immediate predicate.
1693 /// Immediates are slightly odd since they are typically used like an operand
1694 /// but are represented as an operator internally. We typically write simm8:$src
1695 /// in a tablegen pattern, but this is just syntactic sugar for
1696 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1697 /// that will be matched and the predicate (which is attached to the imm
1698 /// operator) that will be tested. In SelectionDAG this describes a
1699 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1701 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1702 /// this representation, the immediate could be tested with an
1703 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1704 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1705 /// there are two implementation issues with producing that matcher
1706 /// configuration from the SelectionDAG pattern:
1707 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1708 /// were we to sink the immediate predicate to the operand we would have to
1709 /// have two partial implementations of PatFrag support, one for immediates
1710 /// and one for non-immediates.
1711 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1712 /// created yet. If we were to sink the predicate to the OperandMatcher we
1713 /// would also have to complicate (or duplicate) the code that descends and
1714 /// creates matchers for the subtree.
1715 /// Overall, it's simpler to handle it in the place it was found.
1716 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1717 protected:
1718 TreePredicateFn Predicate;
1720 public:
1721 InstructionImmPredicateMatcher(unsigned InsnVarID,
1722 const TreePredicateFn &Predicate)
1723 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1724 Predicate(Predicate) {}
1726 bool isIdentical(const PredicateMatcher &B) const override {
1727 return InstructionPredicateMatcher::isIdentical(B) &&
1728 Predicate.getOrigPatFragRecord() ==
1729 cast<InstructionImmPredicateMatcher>(&B)
1730 ->Predicate.getOrigPatFragRecord();
1733 static bool classof(const PredicateMatcher *P) {
1734 return P->getKind() == IPM_ImmPredicate;
1737 void emitPredicateOpcodes(MatchTable &Table,
1738 RuleMatcher &Rule) const override {
1739 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
1740 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1741 << MatchTable::Comment("Predicate")
1742 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1743 << MatchTable::LineBreak;
1747 /// Generates code to check that a memory instruction has a atomic ordering
1748 /// MachineMemoryOperand.
1749 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1750 public:
1751 enum AOComparator {
1752 AO_Exactly,
1753 AO_OrStronger,
1754 AO_WeakerThan,
1757 protected:
1758 StringRef Order;
1759 AOComparator Comparator;
1761 public:
1762 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
1763 AOComparator Comparator = AO_Exactly)
1764 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1765 Order(Order), Comparator(Comparator) {}
1767 static bool classof(const PredicateMatcher *P) {
1768 return P->getKind() == IPM_AtomicOrderingMMO;
1771 bool isIdentical(const PredicateMatcher &B) const override {
1772 if (!InstructionPredicateMatcher::isIdentical(B))
1773 return false;
1774 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1775 return Order == R.Order && Comparator == R.Comparator;
1778 void emitPredicateOpcodes(MatchTable &Table,
1779 RuleMatcher &Rule) const override {
1780 StringRef Opcode = "GIM_CheckAtomicOrdering";
1782 if (Comparator == AO_OrStronger)
1783 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1784 if (Comparator == AO_WeakerThan)
1785 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1787 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1788 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
1789 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
1790 << MatchTable::LineBreak;
1794 /// Generates code to check that the size of an MMO is exactly N bytes.
1795 class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1796 protected:
1797 unsigned MMOIdx;
1798 uint64_t Size;
1800 public:
1801 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1802 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1803 MMOIdx(MMOIdx), Size(Size) {}
1805 static bool classof(const PredicateMatcher *P) {
1806 return P->getKind() == IPM_MemoryLLTSize;
1808 bool isIdentical(const PredicateMatcher &B) const override {
1809 return InstructionPredicateMatcher::isIdentical(B) &&
1810 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1811 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1814 void emitPredicateOpcodes(MatchTable &Table,
1815 RuleMatcher &Rule) const override {
1816 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1817 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1818 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1819 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1820 << MatchTable::LineBreak;
1824 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1825 protected:
1826 unsigned MMOIdx;
1827 SmallVector<unsigned, 4> AddrSpaces;
1829 public:
1830 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1831 ArrayRef<unsigned> AddrSpaces)
1832 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1833 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1835 static bool classof(const PredicateMatcher *P) {
1836 return P->getKind() == IPM_MemoryAddressSpace;
1838 bool isIdentical(const PredicateMatcher &B) const override {
1839 if (!InstructionPredicateMatcher::isIdentical(B))
1840 return false;
1841 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1842 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1845 void emitPredicateOpcodes(MatchTable &Table,
1846 RuleMatcher &Rule) const override {
1847 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1848 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1849 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1850 // Encode number of address spaces to expect.
1851 << MatchTable::Comment("NumAddrSpace")
1852 << MatchTable::IntValue(AddrSpaces.size());
1853 for (unsigned AS : AddrSpaces)
1854 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1856 Table << MatchTable::LineBreak;
1860 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1861 protected:
1862 unsigned MMOIdx;
1863 int MinAlign;
1865 public:
1866 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1867 int MinAlign)
1868 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1869 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1870 assert(MinAlign > 0);
1873 static bool classof(const PredicateMatcher *P) {
1874 return P->getKind() == IPM_MemoryAlignment;
1877 bool isIdentical(const PredicateMatcher &B) const override {
1878 if (!InstructionPredicateMatcher::isIdentical(B))
1879 return false;
1880 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1881 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1884 void emitPredicateOpcodes(MatchTable &Table,
1885 RuleMatcher &Rule) const override {
1886 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1887 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1888 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1889 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1890 << MatchTable::LineBreak;
1894 /// Generates code to check that the size of an MMO is less-than, equal-to, or
1895 /// greater than a given LLT.
1896 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1897 public:
1898 enum RelationKind {
1899 GreaterThan,
1900 EqualTo,
1901 LessThan,
1904 protected:
1905 unsigned MMOIdx;
1906 RelationKind Relation;
1907 unsigned OpIdx;
1909 public:
1910 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1911 enum RelationKind Relation,
1912 unsigned OpIdx)
1913 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1914 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1916 static bool classof(const PredicateMatcher *P) {
1917 return P->getKind() == IPM_MemoryVsLLTSize;
1919 bool isIdentical(const PredicateMatcher &B) const override {
1920 return InstructionPredicateMatcher::isIdentical(B) &&
1921 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1922 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1923 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1926 void emitPredicateOpcodes(MatchTable &Table,
1927 RuleMatcher &Rule) const override {
1928 Table << MatchTable::Opcode(Relation == EqualTo
1929 ? "GIM_CheckMemorySizeEqualToLLT"
1930 : Relation == GreaterThan
1931 ? "GIM_CheckMemorySizeGreaterThanLLT"
1932 : "GIM_CheckMemorySizeLessThanLLT")
1933 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1934 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1935 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1936 << MatchTable::LineBreak;
1940 /// Generates code to check an arbitrary C++ instruction predicate.
1941 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1942 protected:
1943 TreePredicateFn Predicate;
1945 public:
1946 GenericInstructionPredicateMatcher(unsigned InsnVarID,
1947 TreePredicateFn Predicate)
1948 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
1949 Predicate(Predicate) {}
1951 static bool classof(const InstructionPredicateMatcher *P) {
1952 return P->getKind() == IPM_GenericPredicate;
1954 bool isIdentical(const PredicateMatcher &B) const override {
1955 return InstructionPredicateMatcher::isIdentical(B) &&
1956 Predicate ==
1957 static_cast<const GenericInstructionPredicateMatcher &>(B)
1958 .Predicate;
1960 void emitPredicateOpcodes(MatchTable &Table,
1961 RuleMatcher &Rule) const override {
1962 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
1963 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1964 << MatchTable::Comment("FnId")
1965 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1966 << MatchTable::LineBreak;
1970 /// Generates code to check that a set of predicates and operands match for a
1971 /// particular instruction.
1973 /// Typical predicates include:
1974 /// * Has a specific opcode.
1975 /// * Has an nsw/nuw flag or doesn't.
1976 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
1977 protected:
1978 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
1980 RuleMatcher &Rule;
1982 /// The operands to match. All rendered operands must be present even if the
1983 /// condition is always true.
1984 OperandVec Operands;
1985 bool NumOperandsCheck = true;
1987 std::string SymbolicName;
1988 unsigned InsnVarID;
1990 public:
1991 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1992 : Rule(Rule), SymbolicName(SymbolicName) {
1993 // We create a new instruction matcher.
1994 // Get a new ID for that instruction.
1995 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1998 /// Construct a new instruction predicate and add it to the matcher.
1999 template <class Kind, class... Args>
2000 Optional<Kind *> addPredicate(Args &&... args) {
2001 Predicates.emplace_back(
2002 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
2003 return static_cast<Kind *>(Predicates.back().get());
2006 RuleMatcher &getRuleMatcher() const { return Rule; }
2008 unsigned getInsnVarID() const { return InsnVarID; }
2010 /// Add an operand to the matcher.
2011 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2012 unsigned AllocatedTemporariesBaseID) {
2013 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2014 AllocatedTemporariesBaseID));
2015 if (!SymbolicName.empty())
2016 Rule.defineOperand(SymbolicName, *Operands.back());
2018 return *Operands.back();
2021 OperandMatcher &getOperand(unsigned OpIdx) {
2022 auto I = std::find_if(Operands.begin(), Operands.end(),
2023 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
2024 return X->getOpIdx() == OpIdx;
2026 if (I != Operands.end())
2027 return **I;
2028 llvm_unreachable("Failed to lookup operand");
2031 StringRef getSymbolicName() const { return SymbolicName; }
2032 unsigned getNumOperands() const { return Operands.size(); }
2033 OperandVec::iterator operands_begin() { return Operands.begin(); }
2034 OperandVec::iterator operands_end() { return Operands.end(); }
2035 iterator_range<OperandVec::iterator> operands() {
2036 return make_range(operands_begin(), operands_end());
2038 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2039 OperandVec::const_iterator operands_end() const { return Operands.end(); }
2040 iterator_range<OperandVec::const_iterator> operands() const {
2041 return make_range(operands_begin(), operands_end());
2043 bool operands_empty() const { return Operands.empty(); }
2045 void pop_front() { Operands.erase(Operands.begin()); }
2047 void optimize();
2049 /// Emit MatchTable opcodes that test whether the instruction named in
2050 /// InsnVarName matches all the predicates and all the operands.
2051 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
2052 if (NumOperandsCheck)
2053 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2054 .emitPredicateOpcodes(Table, Rule);
2056 emitPredicateListOpcodes(Table, Rule);
2058 for (const auto &Operand : Operands)
2059 Operand->emitPredicateOpcodes(Table, Rule);
2062 /// Compare the priority of this object and B.
2064 /// Returns true if this object is more important than B.
2065 bool isHigherPriorityThan(InstructionMatcher &B) {
2066 // Instruction matchers involving more operands have higher priority.
2067 if (Operands.size() > B.Operands.size())
2068 return true;
2069 if (Operands.size() < B.Operands.size())
2070 return false;
2072 for (auto &&P : zip(predicates(), B.predicates())) {
2073 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2074 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2075 if (L->isHigherPriorityThan(*R))
2076 return true;
2077 if (R->isHigherPriorityThan(*L))
2078 return false;
2081 for (const auto &Operand : zip(Operands, B.Operands)) {
2082 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
2083 return true;
2084 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
2085 return false;
2088 return false;
2091 /// Report the maximum number of temporary operands needed by the instruction
2092 /// matcher.
2093 unsigned countRendererFns() {
2094 return std::accumulate(
2095 predicates().begin(), predicates().end(), 0,
2096 [](unsigned A,
2097 const std::unique_ptr<PredicateMatcher> &Predicate) {
2098 return A + Predicate->countRendererFns();
2099 }) +
2100 std::accumulate(
2101 Operands.begin(), Operands.end(), 0,
2102 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
2103 return A + Operand->countRendererFns();
2107 InstructionOpcodeMatcher &getOpcodeMatcher() {
2108 for (auto &P : predicates())
2109 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2110 return *OpMatcher;
2111 llvm_unreachable("Didn't find an opcode matcher");
2114 bool isConstantInstruction() {
2115 return getOpcodeMatcher().isConstantInstruction();
2118 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
2121 StringRef RuleMatcher::getOpcode() const {
2122 return Matchers.front()->getOpcode();
2125 unsigned RuleMatcher::getNumOperands() const {
2126 return Matchers.front()->getNumOperands();
2129 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2130 InstructionMatcher &InsnMatcher = *Matchers.front();
2131 if (!InsnMatcher.predicates_empty())
2132 if (const auto *TM =
2133 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2134 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2135 return TM->getTy();
2136 return {};
2139 /// Generates code to check that the operand is a register defined by an
2140 /// instruction that matches the given instruction matcher.
2142 /// For example, the pattern:
2143 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2144 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2145 /// the:
2146 /// (G_ADD $src1, $src2)
2147 /// subpattern.
2148 class InstructionOperandMatcher : public OperandPredicateMatcher {
2149 protected:
2150 std::unique_ptr<InstructionMatcher> InsnMatcher;
2152 public:
2153 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2154 RuleMatcher &Rule, StringRef SymbolicName)
2155 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
2156 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
2158 static bool classof(const PredicateMatcher *P) {
2159 return P->getKind() == OPM_Instruction;
2162 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2164 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2165 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2166 Table << MatchTable::Opcode("GIM_RecordInsn")
2167 << MatchTable::Comment("DefineMI")
2168 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2169 << MatchTable::IntValue(getInsnVarID())
2170 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2171 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2172 << MatchTable::LineBreak;
2175 void emitPredicateOpcodes(MatchTable &Table,
2176 RuleMatcher &Rule) const override {
2177 emitCaptureOpcodes(Table, Rule);
2178 InsnMatcher->emitPredicateOpcodes(Table, Rule);
2181 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2182 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2183 return true;
2184 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2185 return false;
2187 if (const InstructionOperandMatcher *BP =
2188 dyn_cast<InstructionOperandMatcher>(&B))
2189 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2190 return true;
2191 return false;
2195 void InstructionMatcher::optimize() {
2196 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2197 const auto &OpcMatcher = getOpcodeMatcher();
2199 Stash.push_back(predicates_pop_front());
2200 if (Stash.back().get() == &OpcMatcher) {
2201 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2202 Stash.emplace_back(
2203 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2204 NumOperandsCheck = false;
2206 for (auto &OM : Operands)
2207 for (auto &OP : OM->predicates())
2208 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2209 Stash.push_back(std::move(OP));
2210 OM->eraseNullPredicates();
2211 break;
2215 if (InsnVarID > 0) {
2216 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2217 for (auto &OP : Operands[0]->predicates())
2218 OP.reset();
2219 Operands[0]->eraseNullPredicates();
2221 for (auto &OM : Operands) {
2222 for (auto &OP : OM->predicates())
2223 if (isa<LLTOperandMatcher>(OP))
2224 Stash.push_back(std::move(OP));
2225 OM->eraseNullPredicates();
2227 while (!Stash.empty())
2228 prependPredicate(Stash.pop_back_val());
2231 //===- Actions ------------------------------------------------------------===//
2232 class OperandRenderer {
2233 public:
2234 enum RendererKind {
2235 OR_Copy,
2236 OR_CopyOrAddZeroReg,
2237 OR_CopySubReg,
2238 OR_CopyConstantAsImm,
2239 OR_CopyFConstantAsFPImm,
2240 OR_Imm,
2241 OR_Register,
2242 OR_TempRegister,
2243 OR_ComplexPattern,
2244 OR_Custom
2247 protected:
2248 RendererKind Kind;
2250 public:
2251 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2252 virtual ~OperandRenderer() {}
2254 RendererKind getKind() const { return Kind; }
2256 virtual void emitRenderOpcodes(MatchTable &Table,
2257 RuleMatcher &Rule) const = 0;
2260 /// A CopyRenderer emits code to copy a single operand from an existing
2261 /// instruction to the one being built.
2262 class CopyRenderer : public OperandRenderer {
2263 protected:
2264 unsigned NewInsnID;
2265 /// The name of the operand.
2266 const StringRef SymbolicName;
2268 public:
2269 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2270 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
2271 SymbolicName(SymbolicName) {
2272 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2275 static bool classof(const OperandRenderer *R) {
2276 return R->getKind() == OR_Copy;
2279 const StringRef getSymbolicName() const { return SymbolicName; }
2281 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2282 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2283 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2284 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2285 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2286 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2287 << MatchTable::IntValue(Operand.getOpIdx())
2288 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2292 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2293 /// existing instruction to the one being built. If the operand turns out to be
2294 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2295 class CopyOrAddZeroRegRenderer : public OperandRenderer {
2296 protected:
2297 unsigned NewInsnID;
2298 /// The name of the operand.
2299 const StringRef SymbolicName;
2300 const Record *ZeroRegisterDef;
2302 public:
2303 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
2304 StringRef SymbolicName, Record *ZeroRegisterDef)
2305 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2306 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2307 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2310 static bool classof(const OperandRenderer *R) {
2311 return R->getKind() == OR_CopyOrAddZeroReg;
2314 const StringRef getSymbolicName() const { return SymbolicName; }
2316 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2317 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2318 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2319 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2320 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2321 << MatchTable::Comment("OldInsnID")
2322 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2323 << MatchTable::IntValue(Operand.getOpIdx())
2324 << MatchTable::NamedValue(
2325 (ZeroRegisterDef->getValue("Namespace")
2326 ? ZeroRegisterDef->getValueAsString("Namespace")
2327 : ""),
2328 ZeroRegisterDef->getName())
2329 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2333 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2334 /// an extended immediate operand.
2335 class CopyConstantAsImmRenderer : public OperandRenderer {
2336 protected:
2337 unsigned NewInsnID;
2338 /// The name of the operand.
2339 const std::string SymbolicName;
2340 bool Signed;
2342 public:
2343 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2344 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2345 SymbolicName(SymbolicName), Signed(true) {}
2347 static bool classof(const OperandRenderer *R) {
2348 return R->getKind() == OR_CopyConstantAsImm;
2351 const StringRef getSymbolicName() const { return SymbolicName; }
2353 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2354 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2355 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2356 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2357 : "GIR_CopyConstantAsUImm")
2358 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2359 << MatchTable::Comment("OldInsnID")
2360 << MatchTable::IntValue(OldInsnVarID)
2361 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2365 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2366 /// instruction to an extended immediate operand.
2367 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2368 protected:
2369 unsigned NewInsnID;
2370 /// The name of the operand.
2371 const std::string SymbolicName;
2373 public:
2374 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2375 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2376 SymbolicName(SymbolicName) {}
2378 static bool classof(const OperandRenderer *R) {
2379 return R->getKind() == OR_CopyFConstantAsFPImm;
2382 const StringRef getSymbolicName() const { return SymbolicName; }
2384 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2385 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2386 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2387 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2388 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2389 << MatchTable::Comment("OldInsnID")
2390 << MatchTable::IntValue(OldInsnVarID)
2391 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2395 /// A CopySubRegRenderer emits code to copy a single register operand from an
2396 /// existing instruction to the one being built and indicate that only a
2397 /// subregister should be copied.
2398 class CopySubRegRenderer : public OperandRenderer {
2399 protected:
2400 unsigned NewInsnID;
2401 /// The name of the operand.
2402 const StringRef SymbolicName;
2403 /// The subregister to extract.
2404 const CodeGenSubRegIndex *SubReg;
2406 public:
2407 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2408 const CodeGenSubRegIndex *SubReg)
2409 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
2410 SymbolicName(SymbolicName), SubReg(SubReg) {}
2412 static bool classof(const OperandRenderer *R) {
2413 return R->getKind() == OR_CopySubReg;
2416 const StringRef getSymbolicName() const { return SymbolicName; }
2418 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2419 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2420 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2421 Table << MatchTable::Opcode("GIR_CopySubReg")
2422 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2423 << MatchTable::Comment("OldInsnID")
2424 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2425 << MatchTable::IntValue(Operand.getOpIdx())
2426 << MatchTable::Comment("SubRegIdx")
2427 << MatchTable::IntValue(SubReg->EnumValue)
2428 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2432 /// Adds a specific physical register to the instruction being built.
2433 /// This is typically useful for WZR/XZR on AArch64.
2434 class AddRegisterRenderer : public OperandRenderer {
2435 protected:
2436 unsigned InsnID;
2437 const Record *RegisterDef;
2439 public:
2440 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2441 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2444 static bool classof(const OperandRenderer *R) {
2445 return R->getKind() == OR_Register;
2448 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2449 Table << MatchTable::Opcode("GIR_AddRegister")
2450 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2451 << MatchTable::NamedValue(
2452 (RegisterDef->getValue("Namespace")
2453 ? RegisterDef->getValueAsString("Namespace")
2454 : ""),
2455 RegisterDef->getName())
2456 << MatchTable::LineBreak;
2460 /// Adds a specific temporary virtual register to the instruction being built.
2461 /// This is used to chain instructions together when emitting multiple
2462 /// instructions.
2463 class TempRegRenderer : public OperandRenderer {
2464 protected:
2465 unsigned InsnID;
2466 unsigned TempRegID;
2467 bool IsDef;
2469 public:
2470 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2471 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2472 IsDef(IsDef) {}
2474 static bool classof(const OperandRenderer *R) {
2475 return R->getKind() == OR_TempRegister;
2478 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2479 Table << MatchTable::Opcode("GIR_AddTempRegister")
2480 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2481 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2482 << MatchTable::Comment("TempRegFlags");
2483 if (IsDef)
2484 Table << MatchTable::NamedValue("RegState::Define");
2485 else
2486 Table << MatchTable::IntValue(0);
2487 Table << MatchTable::LineBreak;
2491 /// Adds a specific immediate to the instruction being built.
2492 class ImmRenderer : public OperandRenderer {
2493 protected:
2494 unsigned InsnID;
2495 int64_t Imm;
2497 public:
2498 ImmRenderer(unsigned InsnID, int64_t Imm)
2499 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
2501 static bool classof(const OperandRenderer *R) {
2502 return R->getKind() == OR_Imm;
2505 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2506 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2507 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2508 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
2512 /// Adds operands by calling a renderer function supplied by the ComplexPattern
2513 /// matcher function.
2514 class RenderComplexPatternOperand : public OperandRenderer {
2515 private:
2516 unsigned InsnID;
2517 const Record &TheDef;
2518 /// The name of the operand.
2519 const StringRef SymbolicName;
2520 /// The renderer number. This must be unique within a rule since it's used to
2521 /// identify a temporary variable to hold the renderer function.
2522 unsigned RendererID;
2523 /// When provided, this is the suboperand of the ComplexPattern operand to
2524 /// render. Otherwise all the suboperands will be rendered.
2525 Optional<unsigned> SubOperand;
2527 unsigned getNumOperands() const {
2528 return TheDef.getValueAsDag("Operands")->getNumArgs();
2531 public:
2532 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
2533 StringRef SymbolicName, unsigned RendererID,
2534 Optional<unsigned> SubOperand = None)
2535 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
2536 SymbolicName(SymbolicName), RendererID(RendererID),
2537 SubOperand(SubOperand) {}
2539 static bool classof(const OperandRenderer *R) {
2540 return R->getKind() == OR_ComplexPattern;
2543 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2544 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2545 : "GIR_ComplexRenderer")
2546 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2547 << MatchTable::Comment("RendererID")
2548 << MatchTable::IntValue(RendererID);
2549 if (SubOperand.hasValue())
2550 Table << MatchTable::Comment("SubOperand")
2551 << MatchTable::IntValue(SubOperand.getValue());
2552 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2556 class CustomRenderer : public OperandRenderer {
2557 protected:
2558 unsigned InsnID;
2559 const Record &Renderer;
2560 /// The name of the operand.
2561 const std::string SymbolicName;
2563 public:
2564 CustomRenderer(unsigned InsnID, const Record &Renderer,
2565 StringRef SymbolicName)
2566 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2567 SymbolicName(SymbolicName) {}
2569 static bool classof(const OperandRenderer *R) {
2570 return R->getKind() == OR_Custom;
2573 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2574 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2575 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2576 Table << MatchTable::Opcode("GIR_CustomRenderer")
2577 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2578 << MatchTable::Comment("OldInsnID")
2579 << MatchTable::IntValue(OldInsnVarID)
2580 << MatchTable::Comment("Renderer")
2581 << MatchTable::NamedValue(
2582 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2583 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2587 /// An action taken when all Matcher predicates succeeded for a parent rule.
2589 /// Typical actions include:
2590 /// * Changing the opcode of an instruction.
2591 /// * Adding an operand to an instruction.
2592 class MatchAction {
2593 public:
2594 virtual ~MatchAction() {}
2596 /// Emit the MatchTable opcodes to implement the action.
2597 virtual void emitActionOpcodes(MatchTable &Table,
2598 RuleMatcher &Rule) const = 0;
2601 /// Generates a comment describing the matched rule being acted upon.
2602 class DebugCommentAction : public MatchAction {
2603 private:
2604 std::string S;
2606 public:
2607 DebugCommentAction(StringRef S) : S(S) {}
2609 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2610 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
2614 /// Generates code to build an instruction or mutate an existing instruction
2615 /// into the desired instruction when this is possible.
2616 class BuildMIAction : public MatchAction {
2617 private:
2618 unsigned InsnID;
2619 const CodeGenInstruction *I;
2620 InstructionMatcher *Matched;
2621 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2623 /// True if the instruction can be built solely by mutating the opcode.
2624 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2625 if (!Insn)
2626 return false;
2628 if (OperandRenderers.size() != Insn->getNumOperands())
2629 return false;
2631 for (const auto &Renderer : enumerate(OperandRenderers)) {
2632 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
2633 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
2634 if (Insn != &OM.getInstructionMatcher() ||
2635 OM.getOpIdx() != Renderer.index())
2636 return false;
2637 } else
2638 return false;
2641 return true;
2644 public:
2645 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2646 : InsnID(InsnID), I(I), Matched(nullptr) {}
2648 unsigned getInsnID() const { return InsnID; }
2649 const CodeGenInstruction *getCGI() const { return I; }
2651 void chooseInsnToMutate(RuleMatcher &Rule) {
2652 for (auto *MutateCandidate : Rule.mutatable_insns()) {
2653 if (canMutate(Rule, MutateCandidate)) {
2654 // Take the first one we're offered that we're able to mutate.
2655 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2656 Matched = MutateCandidate;
2657 return;
2662 template <class Kind, class... Args>
2663 Kind &addRenderer(Args&&... args) {
2664 OperandRenderers.emplace_back(
2665 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
2666 return *static_cast<Kind *>(OperandRenderers.back().get());
2669 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2670 if (Matched) {
2671 assert(canMutate(Rule, Matched) &&
2672 "Arranged to mutate an insn that isn't mutatable");
2674 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
2675 Table << MatchTable::Opcode("GIR_MutateOpcode")
2676 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2677 << MatchTable::Comment("RecycleInsnID")
2678 << MatchTable::IntValue(RecycleInsnID)
2679 << MatchTable::Comment("Opcode")
2680 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2681 << MatchTable::LineBreak;
2683 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
2684 for (auto Def : I->ImplicitDefs) {
2685 auto Namespace = Def->getValue("Namespace")
2686 ? Def->getValueAsString("Namespace")
2687 : "";
2688 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2689 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2690 << MatchTable::NamedValue(Namespace, Def->getName())
2691 << MatchTable::LineBreak;
2693 for (auto Use : I->ImplicitUses) {
2694 auto Namespace = Use->getValue("Namespace")
2695 ? Use->getValueAsString("Namespace")
2696 : "";
2697 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2698 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2699 << MatchTable::NamedValue(Namespace, Use->getName())
2700 << MatchTable::LineBreak;
2703 return;
2706 // TODO: Simple permutation looks like it could be almost as common as
2707 // mutation due to commutative operations.
2709 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2710 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2711 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2712 << MatchTable::LineBreak;
2713 for (const auto &Renderer : OperandRenderers)
2714 Renderer->emitRenderOpcodes(Table, Rule);
2716 if (I->mayLoad || I->mayStore) {
2717 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2718 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2719 << MatchTable::Comment("MergeInsnID's");
2720 // Emit the ID's for all the instructions that are matched by this rule.
2721 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2722 // some other means of having a memoperand. Also limit this to
2723 // emitted instructions that expect to have a memoperand too. For
2724 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2725 // sign-extend instructions shouldn't put the memoperand on the
2726 // sign-extend since it has no effect there.
2727 std::vector<unsigned> MergeInsnIDs;
2728 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2729 MergeInsnIDs.push_back(IDMatcherPair.second);
2730 llvm::sort(MergeInsnIDs);
2731 for (const auto &MergeInsnID : MergeInsnIDs)
2732 Table << MatchTable::IntValue(MergeInsnID);
2733 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2734 << MatchTable::LineBreak;
2737 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2738 // better for combines. Particularly when there are multiple match
2739 // roots.
2740 if (InsnID == 0)
2741 Table << MatchTable::Opcode("GIR_EraseFromParent")
2742 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2743 << MatchTable::LineBreak;
2747 /// Generates code to constrain the operands of an output instruction to the
2748 /// register classes specified by the definition of that instruction.
2749 class ConstrainOperandsToDefinitionAction : public MatchAction {
2750 unsigned InsnID;
2752 public:
2753 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
2755 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2756 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2757 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2758 << MatchTable::LineBreak;
2762 /// Generates code to constrain the specified operand of an output instruction
2763 /// to the specified register class.
2764 class ConstrainOperandToRegClassAction : public MatchAction {
2765 unsigned InsnID;
2766 unsigned OpIdx;
2767 const CodeGenRegisterClass &RC;
2769 public:
2770 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
2771 const CodeGenRegisterClass &RC)
2772 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
2774 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2775 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2776 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2777 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2778 << MatchTable::Comment("RC " + RC.getName())
2779 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
2783 /// Generates code to create a temporary register which can be used to chain
2784 /// instructions together.
2785 class MakeTempRegisterAction : public MatchAction {
2786 private:
2787 LLTCodeGen Ty;
2788 unsigned TempRegID;
2790 public:
2791 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2792 : Ty(Ty), TempRegID(TempRegID) {}
2794 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2795 Table << MatchTable::Opcode("GIR_MakeTempReg")
2796 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2797 << MatchTable::Comment("TypeID")
2798 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2799 << MatchTable::LineBreak;
2803 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
2804 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
2805 MutatableInsns.insert(Matchers.back().get());
2806 return *Matchers.back();
2809 void RuleMatcher::addRequiredFeature(Record *Feature) {
2810 RequiredFeatures.push_back(Feature);
2813 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2814 return RequiredFeatures;
2817 // Emplaces an action of the specified Kind at the end of the action list.
2819 // Returns a reference to the newly created action.
2821 // Like std::vector::emplace_back(), may invalidate all iterators if the new
2822 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
2823 // iterator.
2824 template <class Kind, class... Args>
2825 Kind &RuleMatcher::addAction(Args &&... args) {
2826 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
2827 return *static_cast<Kind *>(Actions.back().get());
2830 // Emplaces an action of the specified Kind before the given insertion point.
2832 // Returns an iterator pointing at the newly created instruction.
2834 // Like std::vector::insert(), may invalidate all iterators if the new size
2835 // exceeds the capacity. Otherwise, only invalidates the iterators from the
2836 // insertion point onwards.
2837 template <class Kind, class... Args>
2838 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2839 Args &&... args) {
2840 return Actions.emplace(InsertPt,
2841 std::make_unique<Kind>(std::forward<Args>(args)...));
2844 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
2845 unsigned NewInsnVarID = NextInsnVarID++;
2846 InsnVariableIDs[&Matcher] = NewInsnVarID;
2847 return NewInsnVarID;
2850 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
2851 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2852 if (I != InsnVariableIDs.end())
2853 return I->second;
2854 llvm_unreachable("Matched Insn was not captured in a local variable");
2857 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2858 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2859 DefinedOperands[SymbolicName] = &OM;
2860 return;
2863 // If the operand is already defined, then we must ensure both references in
2864 // the matcher have the exact same node.
2865 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2868 InstructionMatcher &
2869 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2870 for (const auto &I : InsnVariableIDs)
2871 if (I.first->getSymbolicName() == SymbolicName)
2872 return *I.first;
2873 llvm_unreachable(
2874 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2877 const OperandMatcher &
2878 RuleMatcher::getOperandMatcher(StringRef Name) const {
2879 const auto &I = DefinedOperands.find(Name);
2881 if (I == DefinedOperands.end())
2882 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2884 return *I->second;
2887 void RuleMatcher::emit(MatchTable &Table) {
2888 if (Matchers.empty())
2889 llvm_unreachable("Unexpected empty matcher!");
2891 // The representation supports rules that require multiple roots such as:
2892 // %ptr(p0) = ...
2893 // %elt0(s32) = G_LOAD %ptr
2894 // %1(p0) = G_ADD %ptr, 4
2895 // %elt1(s32) = G_LOAD p0 %1
2896 // which could be usefully folded into:
2897 // %ptr(p0) = ...
2898 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2899 // on some targets but we don't need to make use of that yet.
2900 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
2902 unsigned LabelID = Table.allocateLabelID();
2903 Table << MatchTable::Opcode("GIM_Try", +1)
2904 << MatchTable::Comment("On fail goto")
2905 << MatchTable::JumpTarget(LabelID)
2906 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
2907 << MatchTable::LineBreak;
2909 if (!RequiredFeatures.empty()) {
2910 Table << MatchTable::Opcode("GIM_CheckFeatures")
2911 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2912 << MatchTable::LineBreak;
2915 Matchers.front()->emitPredicateOpcodes(Table, *this);
2917 // We must also check if it's safe to fold the matched instructions.
2918 if (InsnVariableIDs.size() >= 2) {
2919 // Invert the map to create stable ordering (by var names)
2920 SmallVector<unsigned, 2> InsnIDs;
2921 for (const auto &Pair : InsnVariableIDs) {
2922 // Skip the root node since it isn't moving anywhere. Everything else is
2923 // sinking to meet it.
2924 if (Pair.first == Matchers.front().get())
2925 continue;
2927 InsnIDs.push_back(Pair.second);
2929 llvm::sort(InsnIDs);
2931 for (const auto &InsnID : InsnIDs) {
2932 // Reject the difficult cases until we have a more accurate check.
2933 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2934 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2935 << MatchTable::LineBreak;
2937 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2938 // account for unsafe cases.
2940 // Example:
2941 // MI1--> %0 = ...
2942 // %1 = ... %0
2943 // MI0--> %2 = ... %0
2944 // It's not safe to erase MI1. We currently handle this by not
2945 // erasing %0 (even when it's dead).
2947 // Example:
2948 // MI1--> %0 = load volatile @a
2949 // %1 = load volatile @a
2950 // MI0--> %2 = ... %0
2951 // It's not safe to sink %0's def past %1. We currently handle
2952 // this by rejecting all loads.
2954 // Example:
2955 // MI1--> %0 = load @a
2956 // %1 = store @a
2957 // MI0--> %2 = ... %0
2958 // It's not safe to sink %0's def past %1. We currently handle
2959 // this by rejecting all loads.
2961 // Example:
2962 // G_CONDBR %cond, @BB1
2963 // BB0:
2964 // MI1--> %0 = load @a
2965 // G_BR @BB1
2966 // BB1:
2967 // MI0--> %2 = ... %0
2968 // It's not always safe to sink %0 across control flow. In this
2969 // case it may introduce a memory fault. We currentl handle this
2970 // by rejecting all loads.
2974 for (const auto &PM : EpilogueMatchers)
2975 PM->emitPredicateOpcodes(Table, *this);
2977 for (const auto &MA : Actions)
2978 MA->emitActionOpcodes(Table, *this);
2980 if (Table.isWithCoverage())
2981 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2982 << MatchTable::LineBreak;
2983 else
2984 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
2985 << MatchTable::LineBreak;
2987 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
2988 << MatchTable::Label(LabelID);
2989 ++NumPatternEmitted;
2992 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2993 // Rules involving more match roots have higher priority.
2994 if (Matchers.size() > B.Matchers.size())
2995 return true;
2996 if (Matchers.size() < B.Matchers.size())
2997 return false;
2999 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
3000 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3001 return true;
3002 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3003 return false;
3006 return false;
3009 unsigned RuleMatcher::countRendererFns() const {
3010 return std::accumulate(
3011 Matchers.begin(), Matchers.end(), 0,
3012 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
3013 return A + Matcher->countRendererFns();
3017 bool OperandPredicateMatcher::isHigherPriorityThan(
3018 const OperandPredicateMatcher &B) const {
3019 // Generally speaking, an instruction is more important than an Int or a
3020 // LiteralInt because it can cover more nodes but theres an exception to
3021 // this. G_CONSTANT's are less important than either of those two because they
3022 // are more permissive.
3024 const InstructionOperandMatcher *AOM =
3025 dyn_cast<InstructionOperandMatcher>(this);
3026 const InstructionOperandMatcher *BOM =
3027 dyn_cast<InstructionOperandMatcher>(&B);
3028 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3029 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3031 if (AOM && BOM) {
3032 // The relative priorities between a G_CONSTANT and any other instruction
3033 // don't actually matter but this code is needed to ensure a strict weak
3034 // ordering. This is particularly important on Windows where the rules will
3035 // be incorrectly sorted without it.
3036 if (AIsConstantInsn != BIsConstantInsn)
3037 return AIsConstantInsn < BIsConstantInsn;
3038 return false;
3041 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3042 return false;
3043 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3044 return true;
3046 return Kind < B.Kind;
3049 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
3050 RuleMatcher &Rule) const {
3051 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
3052 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
3053 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
3055 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3056 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3057 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3058 << MatchTable::Comment("OtherMI")
3059 << MatchTable::IntValue(OtherInsnVarID)
3060 << MatchTable::Comment("OtherOpIdx")
3061 << MatchTable::IntValue(OtherOM.getOpIdx())
3062 << MatchTable::LineBreak;
3065 //===- GlobalISelEmitter class --------------------------------------------===//
3067 class GlobalISelEmitter {
3068 public:
3069 explicit GlobalISelEmitter(RecordKeeper &RK);
3070 void run(raw_ostream &OS);
3072 private:
3073 const RecordKeeper &RK;
3074 const CodeGenDAGPatterns CGP;
3075 const CodeGenTarget &Target;
3076 CodeGenRegBank CGRegs;
3078 /// Keep track of the equivalence between SDNodes and Instruction by mapping
3079 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3080 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
3081 /// This is defined using 'GINodeEquiv' in the target description.
3082 DenseMap<Record *, Record *> NodeEquivs;
3084 /// Keep track of the equivalence between ComplexPattern's and
3085 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3086 /// GIComplexPatternEquiv.
3087 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3089 /// Keep track of the equivalence between SDNodeXForm's and
3090 /// GICustomOperandRenderer. Map entries are specified by subclassing
3091 /// GISDNodeXFormEquiv.
3092 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3094 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3095 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3096 DenseMap<uint64_t, int> RuleMatcherScores;
3098 // Map of predicates to their subtarget features.
3099 SubtargetFeatureInfoMap SubtargetFeatures;
3101 // Rule coverage information.
3102 Optional<CodeGenCoverage> RuleCoverage;
3104 void gatherOpcodeValues();
3105 void gatherTypeIDValues();
3106 void gatherNodeEquivs();
3108 Record *findNodeEquiv(Record *N) const;
3109 const CodeGenInstruction *getEquivNode(Record &Equiv,
3110 const TreePatternNode *N) const;
3112 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
3113 Expected<InstructionMatcher &>
3114 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3115 InstructionMatcher &InsnMatcher,
3116 const TreePatternNode *Src, unsigned &TempOpIdx);
3117 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3118 unsigned &TempOpIdx) const;
3119 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3120 const TreePatternNode *SrcChild,
3121 bool OperandIsAPointer, unsigned OpIdx,
3122 unsigned &TempOpIdx);
3124 Expected<BuildMIAction &>
3125 createAndImportInstructionRenderer(RuleMatcher &M,
3126 const TreePatternNode *Dst);
3127 Expected<action_iterator> createAndImportSubInstructionRenderer(
3128 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3129 unsigned TempReg);
3130 Expected<action_iterator>
3131 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
3132 const TreePatternNode *Dst);
3133 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
3134 Expected<action_iterator>
3135 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3136 BuildMIAction &DstMIBuilder,
3137 const llvm::TreePatternNode *Dst);
3138 Expected<action_iterator>
3139 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3140 BuildMIAction &DstMIBuilder,
3141 TreePatternNode *DstChild);
3142 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3143 BuildMIAction &DstMIBuilder,
3144 DagInit *DefaultOps) const;
3145 Error
3146 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3147 const std::vector<Record *> &ImplicitDefs) const;
3149 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3150 StringRef TypeIdentifier, StringRef ArgType,
3151 StringRef ArgName, StringRef AdditionalDeclarations,
3152 std::function<bool(const Record *R)> Filter);
3153 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3154 StringRef ArgType,
3155 std::function<bool(const Record *R)> Filter);
3156 void emitMIPredicateFns(raw_ostream &OS);
3158 /// Analyze pattern \p P, returning a matcher for it if possible.
3159 /// Otherwise, return an Error explaining why we don't support it.
3160 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
3162 void declareSubtargetFeature(Record *Predicate);
3164 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3165 bool WithCoverage);
3167 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3168 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3169 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3170 /// If no register class is found, return None.
3171 Optional<const CodeGenRegisterClass *>
3172 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3173 TreePatternNode *SuperRegNode,
3174 TreePatternNode *SubRegIdxNode);
3176 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3177 Optional<const CodeGenRegisterClass *>
3178 getRegClassFromLeaf(TreePatternNode *Leaf);
3180 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3181 /// otherwise.
3182 Optional<const CodeGenRegisterClass *>
3183 inferRegClassFromPattern(TreePatternNode *N);
3185 public:
3186 /// Takes a sequence of \p Rules and group them based on the predicates
3187 /// they share. \p MatcherStorage is used as a memory container
3188 /// for the group that are created as part of this process.
3190 /// What this optimization does looks like if GroupT = GroupMatcher:
3191 /// Output without optimization:
3192 /// \verbatim
3193 /// # R1
3194 /// # predicate A
3195 /// # predicate B
3196 /// ...
3197 /// # R2
3198 /// # predicate A // <-- effectively this is going to be checked twice.
3199 /// // Once in R1 and once in R2.
3200 /// # predicate C
3201 /// \endverbatim
3202 /// Output with optimization:
3203 /// \verbatim
3204 /// # Group1_2
3205 /// # predicate A // <-- Check is now shared.
3206 /// # R1
3207 /// # predicate B
3208 /// # R2
3209 /// # predicate C
3210 /// \endverbatim
3211 template <class GroupT>
3212 static std::vector<Matcher *> optimizeRules(
3213 ArrayRef<Matcher *> Rules,
3214 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
3217 void GlobalISelEmitter::gatherOpcodeValues() {
3218 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3221 void GlobalISelEmitter::gatherTypeIDValues() {
3222 LLTOperandMatcher::initTypeIDValuesMap();
3225 void GlobalISelEmitter::gatherNodeEquivs() {
3226 assert(NodeEquivs.empty());
3227 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
3228 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
3230 assert(ComplexPatternEquivs.empty());
3231 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3232 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3233 if (!SelDAGEquiv)
3234 continue;
3235 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3238 assert(SDNodeXFormEquivs.empty());
3239 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3240 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3241 if (!SelDAGEquiv)
3242 continue;
3243 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3247 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
3248 return NodeEquivs.lookup(N);
3251 const CodeGenInstruction *
3252 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3253 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3254 const TreePredicateFn &Predicate = Call.Fn;
3255 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3256 Predicate.isSignExtLoad())
3257 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3258 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3259 Predicate.isZeroExtLoad())
3260 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3262 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3265 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
3266 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3267 CGRegs(RK, Target.getHwModes()) {}
3269 //===- Emitter ------------------------------------------------------------===//
3271 Error
3272 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
3273 ArrayRef<Predicate> Predicates) {
3274 for (const Predicate &P : Predicates) {
3275 if (!P.Def || P.getCondString().empty())
3276 continue;
3277 declareSubtargetFeature(P.Def);
3278 M.addRequiredFeature(P.Def);
3281 return Error::success();
3284 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3285 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3286 const TreePatternNode *Src, unsigned &TempOpIdx) {
3287 Record *SrcGIEquivOrNull = nullptr;
3288 const CodeGenInstruction *SrcGIOrNull = nullptr;
3290 // Start with the defined operands (i.e., the results of the root operator).
3291 if (Src->getExtTypes().size() > 1)
3292 return failedImport("Src pattern has multiple results");
3294 if (Src->isLeaf()) {
3295 Init *SrcInit = Src->getLeafValue();
3296 if (isa<IntInit>(SrcInit)) {
3297 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3298 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3299 } else
3300 return failedImport(
3301 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3302 } else {
3303 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
3304 if (!SrcGIEquivOrNull)
3305 return failedImport("Pattern operator lacks an equivalent Instruction" +
3306 explainOperator(Src->getOperator()));
3307 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
3309 // The operators look good: match the opcode
3310 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3313 unsigned OpIdx = 0;
3314 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3315 // Results don't have a name unless they are the root node. The caller will
3316 // set the name if appropriate.
3317 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3318 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3319 return failedImport(toString(std::move(Error)) +
3320 " for result of Src pattern operator");
3323 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3324 const TreePredicateFn &Predicate = Call.Fn;
3325 if (Predicate.isAlwaysTrue())
3326 continue;
3328 if (Predicate.isImmediatePattern()) {
3329 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3330 continue;
3333 // An address space check is needed in all contexts if there is one.
3334 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3335 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3336 SmallVector<unsigned, 4> ParsedAddrSpaces;
3338 for (Init *Val : AddrSpaces->getValues()) {
3339 IntInit *IntVal = dyn_cast<IntInit>(Val);
3340 if (!IntVal)
3341 return failedImport("Address space is not an integer");
3342 ParsedAddrSpaces.push_back(IntVal->getValue());
3345 if (!ParsedAddrSpaces.empty()) {
3346 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3347 0, ParsedAddrSpaces);
3351 int64_t MinAlign = Predicate.getMinAlignment();
3352 if (MinAlign > 0)
3353 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3356 // G_LOAD is used for both non-extending and any-extending loads.
3357 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3358 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3359 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3360 continue;
3362 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3363 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3364 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3365 continue;
3368 if (Predicate.isStore()) {
3369 if (Predicate.isTruncStore()) {
3370 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3371 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3372 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3373 continue;
3375 if (Predicate.isNonTruncStore()) {
3376 // We need to check the sizes match here otherwise we could incorrectly
3377 // match truncating stores with non-truncating ones.
3378 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3379 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3383 // No check required. We already did it by swapping the opcode.
3384 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3385 Predicate.isSignExtLoad())
3386 continue;
3388 // No check required. We already did it by swapping the opcode.
3389 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3390 Predicate.isZeroExtLoad())
3391 continue;
3393 // No check required. G_STORE by itself is a non-extending store.
3394 if (Predicate.isNonTruncStore())
3395 continue;
3397 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3398 if (Predicate.getMemoryVT() != nullptr) {
3399 Optional<LLTCodeGen> MemTyOrNone =
3400 MVTToLLT(getValueType(Predicate.getMemoryVT()));
3402 if (!MemTyOrNone)
3403 return failedImport("MemVT could not be converted to LLT");
3405 // MMO's work in bytes so we must take care of unusual types like i1
3406 // don't round down.
3407 unsigned MemSizeInBits =
3408 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3410 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3411 0, MemSizeInBits / 8);
3412 continue;
3416 if (Predicate.isLoad() || Predicate.isStore()) {
3417 // No check required. A G_LOAD/G_STORE is an unindexed load.
3418 if (Predicate.isUnindexed())
3419 continue;
3422 if (Predicate.isAtomic()) {
3423 if (Predicate.isAtomicOrderingMonotonic()) {
3424 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3425 "Monotonic");
3426 continue;
3428 if (Predicate.isAtomicOrderingAcquire()) {
3429 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3430 continue;
3432 if (Predicate.isAtomicOrderingRelease()) {
3433 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3434 continue;
3436 if (Predicate.isAtomicOrderingAcquireRelease()) {
3437 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3438 "AcquireRelease");
3439 continue;
3441 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3442 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3443 "SequentiallyConsistent");
3444 continue;
3447 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3448 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3449 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3450 continue;
3452 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3453 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3454 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3455 continue;
3458 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3459 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3460 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3461 continue;
3463 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3464 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3465 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3466 continue;
3470 if (Predicate.hasGISelPredicateCode()) {
3471 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3472 continue;
3475 return failedImport("Src pattern child has predicate (" +
3476 explainPredicates(Src) + ")");
3478 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3479 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
3481 if (Src->isLeaf()) {
3482 Init *SrcInit = Src->getLeafValue();
3483 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
3484 OperandMatcher &OM =
3485 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
3486 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3487 } else
3488 return failedImport(
3489 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3490 } else {
3491 assert(SrcGIOrNull &&
3492 "Expected to have already found an equivalent Instruction");
3493 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3494 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3495 // imm/fpimm still have operands but we don't need to do anything with it
3496 // here since we don't support ImmLeaf predicates yet. However, we still
3497 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3498 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3499 return InsnMatcher;
3502 // Match the used operands (i.e. the children of the operator).
3503 bool IsIntrinsic =
3504 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3505 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3506 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3507 if (IsIntrinsic && !II)
3508 return failedImport("Expected IntInit containing intrinsic ID)");
3510 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
3511 TreePatternNode *SrcChild = Src->getChild(i);
3513 // SelectionDAG allows pointers to be represented with iN since it doesn't
3514 // distinguish between pointers and integers but they are different types in GlobalISel.
3515 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
3516 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
3518 if (IsIntrinsic) {
3519 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3520 // following the defs is an intrinsic ID.
3521 if (i == 0) {
3522 OperandMatcher &OM =
3523 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3524 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
3525 continue;
3528 // We have to check intrinsics for llvm_anyptr_ty parameters.
3530 // Note that we have to look at the i-1th parameter, because we don't
3531 // have the intrinsic ID in the intrinsic's parameter list.
3532 OperandIsAPointer |= II->isParamAPointer(i - 1);
3535 if (auto Error =
3536 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3537 OpIdx++, TempOpIdx))
3538 return std::move(Error);
3542 return InsnMatcher;
3545 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3546 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3547 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3548 if (ComplexPattern == ComplexPatternEquivs.end())
3549 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3550 ") not mapped to GlobalISel");
3552 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3553 TempOpIdx++;
3554 return Error::success();
3557 Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3558 InstructionMatcher &InsnMatcher,
3559 const TreePatternNode *SrcChild,
3560 bool OperandIsAPointer,
3561 unsigned OpIdx,
3562 unsigned &TempOpIdx) {
3563 OperandMatcher &OM =
3564 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
3565 if (OM.isSameAsAnotherOperand())
3566 return Error::success();
3568 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
3569 if (ChildTypes.size() != 1)
3570 return failedImport("Src pattern child has multiple results");
3572 // Check MBB's before the type check since they are not a known type.
3573 if (!SrcChild->isLeaf()) {
3574 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3575 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
3576 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3577 OM.addPredicate<MBBOperandMatcher>();
3578 return Error::success();
3583 if (auto Error =
3584 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3585 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3586 to_string(*SrcChild) + ")");
3588 // Check for nested instructions.
3589 if (!SrcChild->isLeaf()) {
3590 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
3591 // When a ComplexPattern is used as an operator, it should do the same
3592 // thing as when used as a leaf. However, the children of the operator
3593 // name the sub-operands that make up the complex operand and we must
3594 // prepare to reference them in the renderer too.
3595 unsigned RendererID = TempOpIdx;
3596 if (auto Error = importComplexPatternOperandMatcher(
3597 OM, SrcChild->getOperator(), TempOpIdx))
3598 return Error;
3600 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3601 auto *SubOperand = SrcChild->getChild(i);
3602 if (!SubOperand->getName().empty()) {
3603 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3604 SrcChild->getOperator(),
3605 RendererID, i))
3606 return Error;
3610 return Error::success();
3613 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
3614 InsnMatcher.getRuleMatcher(), SrcChild->getName());
3615 if (!MaybeInsnOperand.hasValue()) {
3616 // This isn't strictly true. If the user were to provide exactly the same
3617 // matchers as the original operand then we could allow it. However, it's
3618 // simpler to not permit the redundant specification.
3619 return failedImport("Nested instruction cannot be the same as another operand");
3622 // Map the node to a gMIR instruction.
3623 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
3624 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
3625 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
3626 if (auto Error = InsnMatcherOrError.takeError())
3627 return Error;
3629 return Error::success();
3632 if (SrcChild->hasAnyPredicate())
3633 return failedImport("Src pattern child has unsupported predicate");
3635 // Check for constant immediates.
3636 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
3637 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
3638 return Error::success();
3641 // Check for def's like register classes or ComplexPattern's.
3642 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3643 auto *ChildRec = ChildDefInit->getDef();
3645 // Check for register classes.
3646 if (ChildRec->isSubClassOf("RegisterClass") ||
3647 ChildRec->isSubClassOf("RegisterOperand")) {
3648 OM.addPredicate<RegisterBankOperandMatcher>(
3649 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
3650 return Error::success();
3653 // Check for ValueType.
3654 if (ChildRec->isSubClassOf("ValueType")) {
3655 // We already added a type check as standard practice so this doesn't need
3656 // to do anything.
3657 return Error::success();
3660 // Check for ComplexPattern's.
3661 if (ChildRec->isSubClassOf("ComplexPattern"))
3662 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
3664 if (ChildRec->isSubClassOf("ImmLeaf")) {
3665 return failedImport(
3666 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3669 return failedImport(
3670 "Src pattern child def is an unsupported tablegen class");
3673 return failedImport("Src pattern child is an unsupported kind");
3676 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3677 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
3678 TreePatternNode *DstChild) {
3680 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
3681 if (SubOperand.hasValue()) {
3682 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
3683 *std::get<0>(*SubOperand), DstChild->getName(),
3684 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
3685 return InsertPt;
3688 if (!DstChild->isLeaf()) {
3690 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3691 auto Child = DstChild->getChild(0);
3692 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
3693 if (I != SDNodeXFormEquivs.end()) {
3694 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
3695 return InsertPt;
3697 return failedImport("SDNodeXForm " + Child->getName() +
3698 " has no custom renderer");
3701 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3702 // inline, but in MI it's just another operand.
3703 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3704 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
3705 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3706 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
3707 return InsertPt;
3711 // Similarly, imm is an operator in TreePatternNode's view but must be
3712 // rendered as operands.
3713 // FIXME: The target should be able to choose sign-extended when appropriate
3714 // (e.g. on Mips).
3715 if (DstChild->getOperator()->getName() == "imm") {
3716 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
3717 return InsertPt;
3718 } else if (DstChild->getOperator()->getName() == "fpimm") {
3719 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
3720 DstChild->getName());
3721 return InsertPt;
3724 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3725 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3726 if (ChildTypes.size() != 1)
3727 return failedImport("Dst pattern child has multiple results");
3729 Optional<LLTCodeGen> OpTyOrNone = None;
3730 if (ChildTypes.front().isMachineValueType())
3731 OpTyOrNone =
3732 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3733 if (!OpTyOrNone)
3734 return failedImport("Dst operand has an unsupported type");
3736 unsigned TempRegID = Rule.allocateTempRegID();
3737 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3738 InsertPt, OpTyOrNone.getValue(), TempRegID);
3739 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3741 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3742 ++InsertPt, Rule, DstChild, TempRegID);
3743 if (auto Error = InsertPtOrError.takeError())
3744 return std::move(Error);
3745 return InsertPtOrError.get();
3748 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
3751 // It could be a specific immediate in which case we should just check for
3752 // that immediate.
3753 if (const IntInit *ChildIntInit =
3754 dyn_cast<IntInit>(DstChild->getLeafValue())) {
3755 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3756 return InsertPt;
3759 // Otherwise, we're looking for a bog-standard RegisterClass operand.
3760 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
3761 auto *ChildRec = ChildDefInit->getDef();
3763 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3764 if (ChildTypes.size() != 1)
3765 return failedImport("Dst pattern child has multiple results");
3767 Optional<LLTCodeGen> OpTyOrNone = None;
3768 if (ChildTypes.front().isMachineValueType())
3769 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3770 if (!OpTyOrNone)
3771 return failedImport("Dst operand has an unsupported type");
3773 if (ChildRec->isSubClassOf("Register")) {
3774 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
3775 return InsertPt;
3778 if (ChildRec->isSubClassOf("RegisterClass") ||
3779 ChildRec->isSubClassOf("RegisterOperand") ||
3780 ChildRec->isSubClassOf("ValueType")) {
3781 if (ChildRec->isSubClassOf("RegisterOperand") &&
3782 !ChildRec->isValueUnset("GIZeroRegister")) {
3783 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
3784 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
3785 return InsertPt;
3788 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
3789 return InsertPt;
3792 if (ChildRec->isSubClassOf("SubRegIndex")) {
3793 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
3794 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
3795 return InsertPt;
3798 if (ChildRec->isSubClassOf("ComplexPattern")) {
3799 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3800 if (ComplexPattern == ComplexPatternEquivs.end())
3801 return failedImport(
3802 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3804 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
3805 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
3806 *ComplexPattern->second, DstChild->getName(),
3807 OM.getAllocatedTemporariesBaseID());
3808 return InsertPt;
3811 return failedImport(
3812 "Dst pattern child def is an unsupported tablegen class");
3815 return failedImport("Dst pattern child is an unsupported kind");
3818 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
3819 RuleMatcher &M, const TreePatternNode *Dst) {
3820 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3821 if (auto Error = InsertPtOrError.takeError())
3822 return std::move(Error);
3824 action_iterator InsertPt = InsertPtOrError.get();
3825 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
3827 importExplicitDefRenderers(DstMIBuilder);
3829 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3830 .takeError())
3831 return std::move(Error);
3833 return DstMIBuilder;
3836 Expected<action_iterator>
3837 GlobalISelEmitter::createAndImportSubInstructionRenderer(
3838 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3839 unsigned TempRegID) {
3840 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3842 // TODO: Assert there's exactly one result.
3844 if (auto Error = InsertPtOrError.takeError())
3845 return std::move(Error);
3847 BuildMIAction &DstMIBuilder =
3848 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3850 // Assign the result to TempReg.
3851 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3853 InsertPtOrError =
3854 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
3855 if (auto Error = InsertPtOrError.takeError())
3856 return std::move(Error);
3858 // We need to make sure that when we import an INSERT_SUBREG as a
3859 // subinstruction that it ends up being constrained to the correct super
3860 // register and subregister classes.
3861 if (Target.getInstruction(Dst->getOperator()).TheDef->getName() ==
3862 "INSERT_SUBREG") {
3863 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
3864 if (!SubClass)
3865 return failedImport(
3866 "Cannot infer register class from INSERT_SUBREG operand #1");
3867 Optional<const CodeGenRegisterClass *> SuperClass = inferSuperRegisterClass(
3868 Dst->getExtType(0), Dst->getChild(0), Dst->getChild(2));
3869 if (!SuperClass)
3870 return failedImport(
3871 "Cannot infer register class for INSERT_SUBREG operand #0");
3872 // The destination and the super register source of an INSERT_SUBREG must
3873 // be the same register class.
3874 M.insertAction<ConstrainOperandToRegClassAction>(
3875 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
3876 M.insertAction<ConstrainOperandToRegClassAction>(
3877 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
3878 M.insertAction<ConstrainOperandToRegClassAction>(
3879 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
3880 return InsertPtOrError.get();
3883 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3884 DstMIBuilder.getInsnID());
3885 return InsertPtOrError.get();
3888 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
3889 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
3890 Record *DstOp = Dst->getOperator();
3891 if (!DstOp->isSubClassOf("Instruction")) {
3892 if (DstOp->isSubClassOf("ValueType"))
3893 return failedImport(
3894 "Pattern operator isn't an instruction (it's a ValueType)");
3895 return failedImport("Pattern operator isn't an instruction");
3897 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
3899 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
3900 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
3901 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
3902 DstI = &Target.getInstruction(RK.getDef("COPY"));
3903 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
3904 DstI = &Target.getInstruction(RK.getDef("COPY"));
3905 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3906 return failedImport("Unable to emit REG_SEQUENCE");
3908 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3909 DstI);
3912 void GlobalISelEmitter::importExplicitDefRenderers(
3913 BuildMIAction &DstMIBuilder) {
3914 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3915 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3916 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
3917 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3921 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3922 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
3923 const llvm::TreePatternNode *Dst) {
3924 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3925 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
3927 // EXTRACT_SUBREG needs to use a subregister COPY.
3928 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
3929 if (!Dst->getChild(0)->isLeaf())
3930 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3932 if (DefInit *SubRegInit =
3933 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
3934 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3935 if (!RCDef)
3936 return failedImport("EXTRACT_SUBREG child #0 could not "
3937 "be coerced to a register class");
3939 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
3940 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3942 const auto &SrcRCDstRCPair =
3943 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3944 if (SrcRCDstRCPair.hasValue()) {
3945 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3946 if (SrcRCDstRCPair->first != RC)
3947 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3950 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
3951 SubIdx);
3952 return InsertPt;
3955 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3958 // Render the explicit uses.
3959 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
3960 unsigned ExpectedDstINumUses = Dst->getNumChildren();
3961 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3962 DstINumUses--; // Ignore the class constraint.
3963 ExpectedDstINumUses--;
3966 unsigned Child = 0;
3967 unsigned NumDefaultOps = 0;
3968 for (unsigned I = 0; I != DstINumUses; ++I) {
3969 const CGIOperandList::OperandInfo &DstIOperand =
3970 DstI->Operands[DstI->Operands.NumDefs + I];
3972 // If the operand has default values, introduce them now.
3973 // FIXME: Until we have a decent test case that dictates we should do
3974 // otherwise, we're going to assume that operands with default values cannot
3975 // be specified in the patterns. Therefore, adding them will not cause us to
3976 // end up with too many rendered operands.
3977 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
3978 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
3979 if (auto Error = importDefaultOperandRenderers(
3980 InsertPt, M, DstMIBuilder, DefaultOps))
3981 return std::move(Error);
3982 ++NumDefaultOps;
3983 continue;
3986 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
3987 Dst->getChild(Child));
3988 if (auto Error = InsertPtOrError.takeError())
3989 return std::move(Error);
3990 InsertPt = InsertPtOrError.get();
3991 ++Child;
3994 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
3995 return failedImport("Expected " + llvm::to_string(DstINumUses) +
3996 " used operands but found " +
3997 llvm::to_string(ExpectedDstINumUses) +
3998 " explicit ones and " + llvm::to_string(NumDefaultOps) +
3999 " default ones");
4001 return InsertPt;
4004 Error GlobalISelEmitter::importDefaultOperandRenderers(
4005 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4006 DagInit *DefaultOps) const {
4007 for (const auto *DefaultOp : DefaultOps->getArgs()) {
4008 Optional<LLTCodeGen> OpTyOrNone = None;
4010 // Look through ValueType operators.
4011 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4012 if (const DefInit *DefaultDagOperator =
4013 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
4014 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
4015 OpTyOrNone = MVTToLLT(getValueType(
4016 DefaultDagOperator->getDef()));
4017 DefaultOp = DefaultDagOp->getArg(0);
4022 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
4023 auto Def = DefaultDefOp->getDef();
4024 if (Def->getName() == "undef_tied_input") {
4025 unsigned TempRegID = M.allocateTempRegID();
4026 M.insertAction<MakeTempRegisterAction>(
4027 InsertPt, OpTyOrNone.getValue(), TempRegID);
4028 InsertPt = M.insertAction<BuildMIAction>(
4029 InsertPt, M.allocateOutputInsnID(),
4030 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4031 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4032 InsertPt->get());
4033 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4034 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4035 } else {
4036 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4038 continue;
4041 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
4042 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
4043 continue;
4046 return failedImport("Could not add default op");
4049 return Error::success();
4052 Error GlobalISelEmitter::importImplicitDefRenderers(
4053 BuildMIAction &DstMIBuilder,
4054 const std::vector<Record *> &ImplicitDefs) const {
4055 if (!ImplicitDefs.empty())
4056 return failedImport("Pattern defines a physical register");
4057 return Error::success();
4060 Optional<const CodeGenRegisterClass *>
4061 GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4062 assert(Leaf && "Expected node?");
4063 assert(Leaf->isLeaf() && "Expected leaf?");
4064 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4065 if (!RCRec)
4066 return None;
4067 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4068 if (!RC)
4069 return None;
4070 return RC;
4073 Optional<const CodeGenRegisterClass *>
4074 GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4075 if (!N)
4076 return None;
4078 if (N->isLeaf())
4079 return getRegClassFromLeaf(N);
4081 // We don't have a leaf node, so we have to try and infer something. Check
4082 // that we have an instruction that we an infer something from.
4084 // Only handle things that produce a single type.
4085 if (N->getNumTypes() != 1)
4086 return None;
4087 Record *OpRec = N->getOperator();
4089 // We only want instructions.
4090 if (!OpRec->isSubClassOf("Instruction"))
4091 return None;
4093 // Don't want to try and infer things when there could potentially be more
4094 // than one candidate register class.
4095 auto &Inst = Target.getInstruction(OpRec);
4096 if (Inst.Operands.NumDefs > 1)
4097 return None;
4099 // Handle any special-case instructions which we can safely infer register
4100 // classes from.
4101 StringRef InstName = Inst.TheDef->getName();
4102 if (InstName == "COPY_TO_REGCLASS") {
4103 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4104 // has the desired register class as the first child.
4105 TreePatternNode *RCChild = N->getChild(1);
4106 if (!RCChild->isLeaf())
4107 return None;
4108 return getRegClassFromLeaf(RCChild);
4111 // Handle destination record types that we can safely infer a register class
4112 // from.
4113 const auto &DstIOperand = Inst.Operands[0];
4114 Record *DstIOpRec = DstIOperand.Rec;
4115 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4116 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4117 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4118 return &RC;
4121 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4122 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4123 return &RC;
4126 return None;
4129 Optional<const CodeGenRegisterClass *>
4130 GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
4131 TreePatternNode *SuperRegNode,
4132 TreePatternNode *SubRegIdxNode) {
4133 // Check if we already have a defined register class for the super register
4134 // node. If we do, then we should preserve that rather than inferring anything
4135 // from the subregister index node. We can assume that whoever wrote the
4136 // pattern in the first place made sure that the super register and
4137 // subregister are compatible.
4138 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4139 inferRegClassFromPattern(SuperRegNode))
4140 return SuperRegisterClass;
4142 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4143 if (!Ty.isValueTypeByHwMode(false))
4144 return None;
4146 // We don't know anything about the super register. Try to use the subregister
4147 // index to infer an appropriate register class.
4148 if (!SubRegIdxNode->isLeaf())
4149 return None;
4150 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4151 if (!SubRegInit)
4152 return None;
4153 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4155 // Use the information we found above to find a minimal register class which
4156 // supports the subregister and type we want.
4157 auto RC =
4158 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4159 if (!RC)
4160 return None;
4161 return *RC;
4164 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
4165 // Keep track of the matchers and actions to emit.
4166 int Score = P.getPatternComplexity(CGP);
4167 RuleMatcher M(P.getSrcRecord()->getLoc());
4168 RuleMatcherScores[M.getRuleID()] = Score;
4169 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4170 " => " +
4171 llvm::to_string(*P.getDstPattern()));
4173 if (auto Error = importRulePredicates(M, P.getPredicates()))
4174 return std::move(Error);
4176 // Next, analyze the pattern operators.
4177 TreePatternNode *Src = P.getSrcPattern();
4178 TreePatternNode *Dst = P.getDstPattern();
4180 // If the root of either pattern isn't a simple operator, ignore it.
4181 if (auto Err = isTrivialOperatorNode(Dst))
4182 return failedImport("Dst pattern root isn't a trivial operator (" +
4183 toString(std::move(Err)) + ")");
4184 if (auto Err = isTrivialOperatorNode(Src))
4185 return failedImport("Src pattern root isn't a trivial operator (" +
4186 toString(std::move(Err)) + ")");
4188 // The different predicates and matchers created during
4189 // addInstructionMatcher use the RuleMatcher M to set up their
4190 // instruction ID (InsnVarID) that are going to be used when
4191 // M is going to be emitted.
4192 // However, the code doing the emission still relies on the IDs
4193 // returned during that process by the RuleMatcher when issuing
4194 // the recordInsn opcodes.
4195 // Because of that:
4196 // 1. The order in which we created the predicates
4197 // and such must be the same as the order in which we emit them,
4198 // and
4199 // 2. We need to reset the generation of the IDs in M somewhere between
4200 // addInstructionMatcher and emit
4202 // FIXME: Long term, we don't want to have to rely on this implicit
4203 // naming being the same. One possible solution would be to have
4204 // explicit operator for operation capture and reference those.
4205 // The plus side is that it would expose opportunities to share
4206 // the capture accross rules. The downside is that it would
4207 // introduce a dependency between predicates (captures must happen
4208 // before their first use.)
4209 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
4210 unsigned TempOpIdx = 0;
4211 auto InsnMatcherOrError =
4212 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
4213 if (auto Error = InsnMatcherOrError.takeError())
4214 return std::move(Error);
4215 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4217 if (Dst->isLeaf()) {
4218 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
4220 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4221 if (RCDef) {
4222 // We need to replace the def and all its uses with the specified
4223 // operand. However, we must also insert COPY's wherever needed.
4224 // For now, emit a copy and let the register allocator clean up.
4225 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4226 const auto &DstIOperand = DstI.Operands[0];
4228 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4229 OM0.setSymbolicName(DstIOperand.Name);
4230 M.defineOperand(OM0.getSymbolicName(), OM0);
4231 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4233 auto &DstMIBuilder =
4234 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4235 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
4236 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
4237 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4239 // We're done with this pattern! It's eligible for GISel emission; return
4240 // it.
4241 ++NumPatternImported;
4242 return std::move(M);
4245 return failedImport("Dst pattern root isn't a known leaf");
4248 // Start with the defined operands (i.e., the results of the root operator).
4249 Record *DstOp = Dst->getOperator();
4250 if (!DstOp->isSubClassOf("Instruction"))
4251 return failedImport("Pattern operator isn't an instruction");
4253 auto &DstI = Target.getInstruction(DstOp);
4254 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
4255 return failedImport("Src pattern results and dst MI defs are different (" +
4256 to_string(Src->getExtTypes().size()) + " def(s) vs " +
4257 to_string(DstI.Operands.NumDefs) + " def(s))");
4259 // The root of the match also has constraints on the register bank so that it
4260 // matches the result instruction.
4261 unsigned OpIdx = 0;
4262 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
4263 (void)VTy;
4265 const auto &DstIOperand = DstI.Operands[OpIdx];
4266 Record *DstIOpRec = DstIOperand.Rec;
4267 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
4268 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
4270 if (DstIOpRec == nullptr)
4271 return failedImport(
4272 "COPY_TO_REGCLASS operand #1 isn't a register class");
4273 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
4274 if (!Dst->getChild(0)->isLeaf())
4275 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
4277 // We can assume that a subregister is in the same bank as it's super
4278 // register.
4279 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4281 if (DstIOpRec == nullptr)
4282 return failedImport("EXTRACT_SUBREG operand #0 isn't a register class");
4283 } else if (DstI.TheDef->getName() == "INSERT_SUBREG") {
4284 auto MaybeSuperClass =
4285 inferSuperRegisterClass(VTy, Dst->getChild(0), Dst->getChild(2));
4286 if (!MaybeSuperClass)
4287 return failedImport(
4288 "Cannot infer register class for INSERT_SUBREG operand #0");
4289 // Move to the next pattern here, because the register class we found
4290 // doesn't necessarily have a record associated with it. So, we can't
4291 // set DstIOpRec using this.
4292 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4293 OM.setSymbolicName(DstIOperand.Name);
4294 M.defineOperand(OM.getSymbolicName(), OM);
4295 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4296 ++OpIdx;
4297 continue;
4298 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
4299 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4300 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
4301 return failedImport("Dst MI def isn't a register class" +
4302 to_string(*Dst));
4304 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4305 OM.setSymbolicName(DstIOperand.Name);
4306 M.defineOperand(OM.getSymbolicName(), OM);
4307 OM.addPredicate<RegisterBankOperandMatcher>(
4308 Target.getRegisterClass(DstIOpRec));
4309 ++OpIdx;
4312 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
4313 if (auto Error = DstMIBuilderOrError.takeError())
4314 return std::move(Error);
4315 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
4317 // Render the implicit defs.
4318 // These are only added to the root of the result.
4319 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
4320 return std::move(Error);
4322 DstMIBuilder.chooseInsnToMutate(M);
4324 // Constrain the registers to classes. This is normally derived from the
4325 // emitted instruction but a few instructions require special handling.
4326 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
4327 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4328 // result is constrained to the class given by the second child.
4329 Record *DstIOpRec =
4330 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
4332 if (DstIOpRec == nullptr)
4333 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4335 M.addAction<ConstrainOperandToRegClassAction>(
4336 0, 0, Target.getRegisterClass(DstIOpRec));
4338 // We're done with this pattern! It's eligible for GISel emission; return
4339 // it.
4340 ++NumPatternImported;
4341 return std::move(M);
4344 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
4345 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4346 // instructions, the result register class is controlled by the
4347 // subregisters of the operand. As a result, we must constrain the result
4348 // class rather than check that it's already the right one.
4349 if (!Dst->getChild(0)->isLeaf())
4350 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4352 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4353 if (!SubRegInit)
4354 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4356 // Constrain the result to the same register bank as the operand.
4357 Record *DstIOpRec =
4358 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4360 if (DstIOpRec == nullptr)
4361 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
4363 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4364 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
4366 // It would be nice to leave this constraint implicit but we're required
4367 // to pick a register class so constrain the result to a register class
4368 // that can hold the correct MVT.
4370 // FIXME: This may introduce an extra copy if the chosen class doesn't
4371 // actually contain the subregisters.
4372 assert(Src->getExtTypes().size() == 1 &&
4373 "Expected Src of EXTRACT_SUBREG to have one result type");
4375 const auto &SrcRCDstRCPair =
4376 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4377 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4378 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4379 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4381 // We're done with this pattern! It's eligible for GISel emission; return
4382 // it.
4383 ++NumPatternImported;
4384 return std::move(M);
4387 if (DstI.TheDef->getName() == "INSERT_SUBREG") {
4388 assert(Src->getExtTypes().size() == 1 &&
4389 "Expected Src of INSERT_SUBREG to have one result type");
4390 // We need to constrain the destination, a super regsister source, and a
4391 // subregister source.
4392 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4393 if (!SubClass)
4394 return failedImport(
4395 "Cannot infer register class from INSERT_SUBREG operand #1");
4396 auto SuperClass = inferSuperRegisterClass(
4397 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4398 if (!SuperClass)
4399 return failedImport(
4400 "Cannot infer register class for INSERT_SUBREG operand #0");
4401 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4402 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4403 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4404 ++NumPatternImported;
4405 return std::move(M);
4408 M.addAction<ConstrainOperandsToDefinitionAction>(0);
4410 // We're done with this pattern! It's eligible for GISel emission; return it.
4411 ++NumPatternImported;
4412 return std::move(M);
4415 // Emit imm predicate table and an enum to reference them with.
4416 // The 'Predicate_' part of the name is redundant but eliminating it is more
4417 // trouble than it's worth.
4418 void GlobalISelEmitter::emitCxxPredicateFns(
4419 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4420 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
4421 std::function<bool(const Record *R)> Filter) {
4422 std::vector<const Record *> MatchedRecords;
4423 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4424 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4425 [&](Record *Record) {
4426 return !Record->getValueAsString(CodeFieldName).empty() &&
4427 Filter(Record);
4430 if (!MatchedRecords.empty()) {
4431 OS << "// PatFrag predicates.\n"
4432 << "enum {\n";
4433 std::string EnumeratorSeparator =
4434 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4435 for (const auto *Record : MatchedRecords) {
4436 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4437 << EnumeratorSeparator;
4438 EnumeratorSeparator = ",\n";
4440 OS << "};\n";
4443 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4444 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4445 << ArgName << ") const {\n"
4446 << AdditionalDeclarations;
4447 if (!AdditionalDeclarations.empty())
4448 OS << "\n";
4449 if (!MatchedRecords.empty())
4450 OS << " switch (PredicateID) {\n";
4451 for (const auto *Record : MatchedRecords) {
4452 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4453 << Record->getName() << ": {\n"
4454 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4455 << " llvm_unreachable(\"" << CodeFieldName
4456 << " should have returned\");\n"
4457 << " return false;\n"
4458 << " }\n";
4460 if (!MatchedRecords.empty())
4461 OS << " }\n";
4462 OS << " llvm_unreachable(\"Unknown predicate\");\n"
4463 << " return false;\n"
4464 << "}\n";
4467 void GlobalISelEmitter::emitImmPredicateFns(
4468 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4469 std::function<bool(const Record *R)> Filter) {
4470 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4471 "Imm", "", Filter);
4474 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4475 return emitCxxPredicateFns(
4476 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4477 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
4478 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4479 " (void)MRI;",
4480 [](const Record *R) { return true; });
4483 template <class GroupT>
4484 std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
4485 ArrayRef<Matcher *> Rules,
4486 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4488 std::vector<Matcher *> OptRules;
4489 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
4490 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4491 unsigned NumGroups = 0;
4493 auto ProcessCurrentGroup = [&]() {
4494 if (CurrentGroup->empty())
4495 // An empty group is good to be reused:
4496 return;
4498 // If the group isn't large enough to provide any benefit, move all the
4499 // added rules out of it and make sure to re-create the group to properly
4500 // re-initialize it:
4501 if (CurrentGroup->size() < 2)
4502 for (Matcher *M : CurrentGroup->matchers())
4503 OptRules.push_back(M);
4504 else {
4505 CurrentGroup->finalize();
4506 OptRules.push_back(CurrentGroup.get());
4507 MatcherStorage.emplace_back(std::move(CurrentGroup));
4508 ++NumGroups;
4510 CurrentGroup = std::make_unique<GroupT>();
4512 for (Matcher *Rule : Rules) {
4513 // Greedily add as many matchers as possible to the current group:
4514 if (CurrentGroup->addMatcher(*Rule))
4515 continue;
4517 ProcessCurrentGroup();
4518 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4520 // Try to add the pending matcher to a newly created empty group:
4521 if (!CurrentGroup->addMatcher(*Rule))
4522 // If we couldn't add the matcher to an empty group, that group type
4523 // doesn't support that kind of matchers at all, so just skip it:
4524 OptRules.push_back(Rule);
4526 ProcessCurrentGroup();
4528 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
4529 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
4530 return OptRules;
4533 MatchTable
4534 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
4535 bool Optimize, bool WithCoverage) {
4536 std::vector<Matcher *> InputRules;
4537 for (Matcher &Rule : Rules)
4538 InputRules.push_back(&Rule);
4540 if (!Optimize)
4541 return MatchTable::buildTable(InputRules, WithCoverage);
4543 unsigned CurrentOrdering = 0;
4544 StringMap<unsigned> OpcodeOrder;
4545 for (RuleMatcher &Rule : Rules) {
4546 const StringRef Opcode = Rule.getOpcode();
4547 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4548 if (OpcodeOrder.count(Opcode) == 0)
4549 OpcodeOrder[Opcode] = CurrentOrdering++;
4552 std::stable_sort(InputRules.begin(), InputRules.end(),
4553 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4554 auto *L = static_cast<const RuleMatcher *>(A);
4555 auto *R = static_cast<const RuleMatcher *>(B);
4556 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4557 L->getNumOperands()) <
4558 std::make_tuple(OpcodeOrder[R->getOpcode()],
4559 R->getNumOperands());
4562 for (Matcher *Rule : InputRules)
4563 Rule->optimize();
4565 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
4566 std::vector<Matcher *> OptRules =
4567 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4569 for (Matcher *Rule : OptRules)
4570 Rule->optimize();
4572 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4574 return MatchTable::buildTable(OptRules, WithCoverage);
4577 void GroupMatcher::optimize() {
4578 // Make sure we only sort by a specific predicate within a range of rules that
4579 // all have that predicate checked against a specific value (not a wildcard):
4580 auto F = Matchers.begin();
4581 auto T = F;
4582 auto E = Matchers.end();
4583 while (T != E) {
4584 while (T != E) {
4585 auto *R = static_cast<RuleMatcher *>(*T);
4586 if (!R->getFirstConditionAsRootType().get().isValid())
4587 break;
4588 ++T;
4590 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4591 auto *L = static_cast<RuleMatcher *>(A);
4592 auto *R = static_cast<RuleMatcher *>(B);
4593 return L->getFirstConditionAsRootType() <
4594 R->getFirstConditionAsRootType();
4596 if (T != E)
4597 F = ++T;
4599 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4600 .swap(Matchers);
4601 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4602 .swap(Matchers);
4605 void GlobalISelEmitter::run(raw_ostream &OS) {
4606 if (!UseCoverageFile.empty()) {
4607 RuleCoverage = CodeGenCoverage();
4608 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4609 if (!RuleCoverageBufOrErr) {
4610 PrintWarning(SMLoc(), "Missing rule coverage data");
4611 RuleCoverage = None;
4612 } else {
4613 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4614 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4615 RuleCoverage = None;
4620 // Track the run-time opcode values
4621 gatherOpcodeValues();
4622 // Track the run-time LLT ID values
4623 gatherTypeIDValues();
4625 // Track the GINodeEquiv definitions.
4626 gatherNodeEquivs();
4628 emitSourceFileHeader(("Global Instruction Selector for the " +
4629 Target.getName() + " target").str(), OS);
4630 std::vector<RuleMatcher> Rules;
4631 // Look through the SelectionDAG patterns we found, possibly emitting some.
4632 for (const PatternToMatch &Pat : CGP.ptms()) {
4633 ++NumPatternTotal;
4635 auto MatcherOrErr = runOnPattern(Pat);
4637 // The pattern analysis can fail, indicating an unsupported pattern.
4638 // Report that if we've been asked to do so.
4639 if (auto Err = MatcherOrErr.takeError()) {
4640 if (WarnOnSkippedPatterns) {
4641 PrintWarning(Pat.getSrcRecord()->getLoc(),
4642 "Skipped pattern: " + toString(std::move(Err)));
4643 } else {
4644 consumeError(std::move(Err));
4646 ++NumPatternImportsSkipped;
4647 continue;
4650 if (RuleCoverage) {
4651 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4652 ++NumPatternsTested;
4653 else
4654 PrintWarning(Pat.getSrcRecord()->getLoc(),
4655 "Pattern is not covered by a test");
4657 Rules.push_back(std::move(MatcherOrErr.get()));
4660 // Comparison function to order records by name.
4661 auto orderByName = [](const Record *A, const Record *B) {
4662 return A->getName() < B->getName();
4665 std::vector<Record *> ComplexPredicates =
4666 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
4667 llvm::sort(ComplexPredicates, orderByName);
4669 std::vector<Record *> CustomRendererFns =
4670 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
4671 llvm::sort(CustomRendererFns, orderByName);
4673 unsigned MaxTemporaries = 0;
4674 for (const auto &Rule : Rules)
4675 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
4677 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4678 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4679 << ";\n"
4680 << "using PredicateBitset = "
4681 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4682 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4684 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4685 << " mutable MatcherState State;\n"
4686 << " typedef "
4687 "ComplexRendererFns("
4688 << Target.getName()
4689 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
4691 << " typedef void(" << Target.getName()
4692 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
4693 "MachineInstr&) "
4694 "const;\n"
4695 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
4696 "CustomRendererFn> "
4697 "ISelInfo;\n";
4698 OS << " static " << Target.getName()
4699 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
4700 << " static " << Target.getName()
4701 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
4702 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
4703 "override;\n"
4704 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
4705 "const override;\n"
4706 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
4707 "&Imm) const override;\n"
4708 << " const int64_t *getMatchTable() const override;\n"
4709 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
4710 "const override;\n"
4711 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
4713 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
4714 << ", State(" << MaxTemporaries << "),\n"
4715 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
4716 << ", ComplexPredicateFns, CustomRenderers)\n"
4717 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
4719 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
4720 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
4721 OS);
4723 // Separate subtarget features by how often they must be recomputed.
4724 SubtargetFeatureInfoMap ModuleFeatures;
4725 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4726 std::inserter(ModuleFeatures, ModuleFeatures.end()),
4727 [](const SubtargetFeatureInfoMap::value_type &X) {
4728 return !X.second.mustRecomputePerFunction();
4730 SubtargetFeatureInfoMap FunctionFeatures;
4731 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4732 std::inserter(FunctionFeatures, FunctionFeatures.end()),
4733 [](const SubtargetFeatureInfoMap::value_type &X) {
4734 return X.second.mustRecomputePerFunction();
4737 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4738 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
4739 ModuleFeatures, OS);
4740 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4741 Target.getName(), "InstructionSelector",
4742 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
4743 "const MachineFunction *MF");
4745 // Emit a table containing the LLT objects needed by the matcher and an enum
4746 // for the matcher to reference them with.
4747 std::vector<LLTCodeGen> TypeObjects;
4748 for (const auto &Ty : KnownTypes)
4749 TypeObjects.push_back(Ty);
4750 llvm::sort(TypeObjects);
4751 OS << "// LLT Objects.\n"
4752 << "enum {\n";
4753 for (const auto &TypeObject : TypeObjects) {
4754 OS << " ";
4755 TypeObject.emitCxxEnumValue(OS);
4756 OS << ",\n";
4758 OS << "};\n";
4759 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
4760 << "const static LLT TypeObjects[] = {\n";
4761 for (const auto &TypeObject : TypeObjects) {
4762 OS << " ";
4763 TypeObject.emitCxxConstructorCall(OS);
4764 OS << ",\n";
4766 OS << "};\n\n";
4768 // Emit a table containing the PredicateBitsets objects needed by the matcher
4769 // and an enum for the matcher to reference them with.
4770 std::vector<std::vector<Record *>> FeatureBitsets;
4771 for (auto &Rule : Rules)
4772 FeatureBitsets.push_back(Rule.getRequiredFeatures());
4773 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
4774 const std::vector<Record *> &B) {
4775 if (A.size() < B.size())
4776 return true;
4777 if (A.size() > B.size())
4778 return false;
4779 for (const auto &Pair : zip(A, B)) {
4780 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
4781 return true;
4782 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
4783 return false;
4785 return false;
4787 FeatureBitsets.erase(
4788 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4789 FeatureBitsets.end());
4790 OS << "// Feature bitsets.\n"
4791 << "enum {\n"
4792 << " GIFBS_Invalid,\n";
4793 for (const auto &FeatureBitset : FeatureBitsets) {
4794 if (FeatureBitset.empty())
4795 continue;
4796 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4798 OS << "};\n"
4799 << "const static PredicateBitset FeatureBitsets[] {\n"
4800 << " {}, // GIFBS_Invalid\n";
4801 for (const auto &FeatureBitset : FeatureBitsets) {
4802 if (FeatureBitset.empty())
4803 continue;
4804 OS << " {";
4805 for (const auto &Feature : FeatureBitset) {
4806 const auto &I = SubtargetFeatures.find(Feature);
4807 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4808 OS << I->second.getEnumBitName() << ", ";
4810 OS << "},\n";
4812 OS << "};\n\n";
4814 // Emit complex predicate table and an enum to reference them with.
4815 OS << "// ComplexPattern predicates.\n"
4816 << "enum {\n"
4817 << " GICP_Invalid,\n";
4818 for (const auto &Record : ComplexPredicates)
4819 OS << " GICP_" << Record->getName() << ",\n";
4820 OS << "};\n"
4821 << "// See constructor for table contents\n\n";
4823 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
4824 bool Unset;
4825 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4826 !R->getValueAsBit("IsAPInt");
4828 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
4829 bool Unset;
4830 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4832 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
4833 return R->getValueAsBit("IsAPInt");
4835 emitMIPredicateFns(OS);
4836 OS << "\n";
4838 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4839 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4840 << " nullptr, // GICP_Invalid\n";
4841 for (const auto &Record : ComplexPredicates)
4842 OS << " &" << Target.getName()
4843 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4844 << ", // " << Record->getName() << "\n";
4845 OS << "};\n\n";
4847 OS << "// Custom renderers.\n"
4848 << "enum {\n"
4849 << " GICR_Invalid,\n";
4850 for (const auto &Record : CustomRendererFns)
4851 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4852 OS << "};\n";
4854 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4855 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4856 << " nullptr, // GICP_Invalid\n";
4857 for (const auto &Record : CustomRendererFns)
4858 OS << " &" << Target.getName()
4859 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4860 << ", // " << Record->getName() << "\n";
4861 OS << "};\n\n";
4863 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
4864 int ScoreA = RuleMatcherScores[A.getRuleID()];
4865 int ScoreB = RuleMatcherScores[B.getRuleID()];
4866 if (ScoreA > ScoreB)
4867 return true;
4868 if (ScoreB > ScoreA)
4869 return false;
4870 if (A.isHigherPriorityThan(B)) {
4871 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4872 "and less important at "
4873 "the same time");
4874 return true;
4876 return false;
4879 OS << "bool " << Target.getName()
4880 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4881 "&CoverageInfo) const {\n"
4882 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4883 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4884 << " // FIXME: This should be computed on a per-function basis rather "
4885 "than per-insn.\n"
4886 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4887 "&MF);\n"
4888 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4889 << " NewMIVector OutMIs;\n"
4890 << " State.MIs.clear();\n"
4891 << " State.MIs.push_back(&I);\n\n"
4892 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4893 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4894 << ", CoverageInfo)) {\n"
4895 << " return true;\n"
4896 << " }\n\n"
4897 << " return false;\n"
4898 << "}\n\n";
4900 const MatchTable Table =
4901 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
4902 OS << "const int64_t *" << Target.getName()
4903 << "InstructionSelector::getMatchTable() const {\n";
4904 Table.emitDeclaration(OS);
4905 OS << " return ";
4906 Table.emitUse(OS);
4907 OS << ";\n}\n";
4908 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
4910 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4911 << "PredicateBitset AvailableModuleFeatures;\n"
4912 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4913 << "PredicateBitset getAvailableFeatures() const {\n"
4914 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4915 << "}\n"
4916 << "PredicateBitset\n"
4917 << "computeAvailableModuleFeatures(const " << Target.getName()
4918 << "Subtarget *Subtarget) const;\n"
4919 << "PredicateBitset\n"
4920 << "computeAvailableFunctionFeatures(const " << Target.getName()
4921 << "Subtarget *Subtarget,\n"
4922 << " const MachineFunction *MF) const;\n"
4923 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4925 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4926 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4927 << "AvailableFunctionFeatures()\n"
4928 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
4931 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4932 if (SubtargetFeatures.count(Predicate) == 0)
4933 SubtargetFeatures.emplace(
4934 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4937 void RuleMatcher::optimize() {
4938 for (auto &Item : InsnVariableIDs) {
4939 InstructionMatcher &InsnMatcher = *Item.first;
4940 for (auto &OM : InsnMatcher.operands()) {
4941 // Complex Patterns are usually expensive and they relatively rarely fail
4942 // on their own: more often we end up throwing away all the work done by a
4943 // matching part of a complex pattern because some other part of the
4944 // enclosing pattern didn't match. All of this makes it beneficial to
4945 // delay complex patterns until the very end of the rule matching,
4946 // especially for targets having lots of complex patterns.
4947 for (auto &OP : OM->predicates())
4948 if (isa<ComplexPatternOperandMatcher>(OP))
4949 EpilogueMatchers.emplace_back(std::move(OP));
4950 OM->eraseNullPredicates();
4952 InsnMatcher.optimize();
4954 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
4955 const std::unique_ptr<PredicateMatcher> &R) {
4956 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
4957 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
4961 bool RuleMatcher::hasFirstCondition() const {
4962 if (insnmatchers_empty())
4963 return false;
4964 InstructionMatcher &Matcher = insnmatchers_front();
4965 if (!Matcher.predicates_empty())
4966 return true;
4967 for (auto &OM : Matcher.operands())
4968 for (auto &OP : OM->predicates())
4969 if (!isa<InstructionOperandMatcher>(OP))
4970 return true;
4971 return false;
4974 const PredicateMatcher &RuleMatcher::getFirstCondition() const {
4975 assert(!insnmatchers_empty() &&
4976 "Trying to get a condition from an empty RuleMatcher");
4978 InstructionMatcher &Matcher = insnmatchers_front();
4979 if (!Matcher.predicates_empty())
4980 return **Matcher.predicates_begin();
4981 // If there is no more predicate on the instruction itself, look at its
4982 // operands.
4983 for (auto &OM : Matcher.operands())
4984 for (auto &OP : OM->predicates())
4985 if (!isa<InstructionOperandMatcher>(OP))
4986 return *OP;
4988 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
4989 "no conditions");
4992 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
4993 assert(!insnmatchers_empty() &&
4994 "Trying to pop a condition from an empty RuleMatcher");
4996 InstructionMatcher &Matcher = insnmatchers_front();
4997 if (!Matcher.predicates_empty())
4998 return Matcher.predicates_pop_front();
4999 // If there is no more predicate on the instruction itself, look at its
5000 // operands.
5001 for (auto &OM : Matcher.operands())
5002 for (auto &OP : OM->predicates())
5003 if (!isa<InstructionOperandMatcher>(OP)) {
5004 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5005 OM->eraseNullPredicates();
5006 return Result;
5009 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5010 "no conditions");
5013 bool GroupMatcher::candidateConditionMatches(
5014 const PredicateMatcher &Predicate) const {
5016 if (empty()) {
5017 // Sharing predicates for nested instructions is not supported yet as we
5018 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5019 // only work on the original root instruction (InsnVarID == 0):
5020 if (Predicate.getInsnVarID() != 0)
5021 return false;
5022 // ... otherwise an empty group can handle any predicate with no specific
5023 // requirements:
5024 return true;
5027 const Matcher &Representative = **Matchers.begin();
5028 const auto &RepresentativeCondition = Representative.getFirstCondition();
5029 // ... if not empty, the group can only accomodate matchers with the exact
5030 // same first condition:
5031 return Predicate.isIdentical(RepresentativeCondition);
5034 bool GroupMatcher::addMatcher(Matcher &Candidate) {
5035 if (!Candidate.hasFirstCondition())
5036 return false;
5038 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5039 if (!candidateConditionMatches(Predicate))
5040 return false;
5042 Matchers.push_back(&Candidate);
5043 return true;
5046 void GroupMatcher::finalize() {
5047 assert(Conditions.empty() && "Already finalized?");
5048 if (empty())
5049 return;
5051 Matcher &FirstRule = **Matchers.begin();
5052 for (;;) {
5053 // All the checks are expected to succeed during the first iteration:
5054 for (const auto &Rule : Matchers)
5055 if (!Rule->hasFirstCondition())
5056 return;
5057 const auto &FirstCondition = FirstRule.getFirstCondition();
5058 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5059 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5060 return;
5062 Conditions.push_back(FirstRule.popFirstCondition());
5063 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5064 Matchers[I]->popFirstCondition();
5068 void GroupMatcher::emit(MatchTable &Table) {
5069 unsigned LabelID = ~0U;
5070 if (!Conditions.empty()) {
5071 LabelID = Table.allocateLabelID();
5072 Table << MatchTable::Opcode("GIM_Try", +1)
5073 << MatchTable::Comment("On fail goto")
5074 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
5076 for (auto &Condition : Conditions)
5077 Condition->emitPredicateOpcodes(
5078 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5080 for (const auto &M : Matchers)
5081 M->emit(Table);
5083 // Exit the group
5084 if (!Conditions.empty())
5085 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
5086 << MatchTable::Label(LabelID);
5089 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
5090 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
5093 bool SwitchMatcher::candidateConditionMatches(
5094 const PredicateMatcher &Predicate) const {
5096 if (empty()) {
5097 // Sharing predicates for nested instructions is not supported yet as we
5098 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5099 // only work on the original root instruction (InsnVarID == 0):
5100 if (Predicate.getInsnVarID() != 0)
5101 return false;
5102 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5103 // could fail as not all the types of conditions are supported:
5104 if (!isSupportedPredicateType(Predicate))
5105 return false;
5106 // ... or the condition might not have a proper implementation of
5107 // getValue() / isIdenticalDownToValue() yet:
5108 if (!Predicate.hasValue())
5109 return false;
5110 // ... otherwise an empty Switch can accomodate the condition with no
5111 // further requirements:
5112 return true;
5115 const Matcher &CaseRepresentative = **Matchers.begin();
5116 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5117 // Switch-cases must share the same kind of condition and path to the value it
5118 // checks:
5119 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5120 return false;
5122 const auto Value = Predicate.getValue();
5123 // ... but be unique with respect to the actual value they check:
5124 return Values.count(Value) == 0;
5127 bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5128 if (!Candidate.hasFirstCondition())
5129 return false;
5131 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5132 if (!candidateConditionMatches(Predicate))
5133 return false;
5134 const auto Value = Predicate.getValue();
5135 Values.insert(Value);
5137 Matchers.push_back(&Candidate);
5138 return true;
5141 void SwitchMatcher::finalize() {
5142 assert(Condition == nullptr && "Already finalized");
5143 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5144 if (empty())
5145 return;
5147 std::stable_sort(Matchers.begin(), Matchers.end(),
5148 [](const Matcher *L, const Matcher *R) {
5149 return L->getFirstCondition().getValue() <
5150 R->getFirstCondition().getValue();
5152 Condition = Matchers[0]->popFirstCondition();
5153 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5154 Matchers[I]->popFirstCondition();
5157 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5158 MatchTable &Table) {
5159 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5161 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5162 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5163 << MatchTable::IntValue(Condition->getInsnVarID());
5164 return;
5166 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5167 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5168 << MatchTable::IntValue(Condition->getInsnVarID())
5169 << MatchTable::Comment("Op")
5170 << MatchTable::IntValue(Condition->getOpIdx());
5171 return;
5174 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5175 "predicate type that is claimed to be supported");
5178 void SwitchMatcher::emit(MatchTable &Table) {
5179 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5180 if (empty())
5181 return;
5182 assert(Condition != nullptr &&
5183 "Broken SwitchMatcher, hasn't been finalized?");
5185 std::vector<unsigned> LabelIDs(Values.size());
5186 std::generate(LabelIDs.begin(), LabelIDs.end(),
5187 [&Table]() { return Table.allocateLabelID(); });
5188 const unsigned Default = Table.allocateLabelID();
5190 const int64_t LowerBound = Values.begin()->getRawValue();
5191 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5193 emitPredicateSpecificOpcodes(*Condition, Table);
5195 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5196 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5197 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5199 int64_t J = LowerBound;
5200 auto VI = Values.begin();
5201 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5202 auto V = *VI++;
5203 while (J++ < V.getRawValue())
5204 Table << MatchTable::IntValue(0);
5205 V.turnIntoComment();
5206 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5208 Table << MatchTable::LineBreak;
5210 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5211 Table << MatchTable::Label(LabelIDs[I]);
5212 Matchers[I]->emit(Table);
5213 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5215 Table << MatchTable::Label(Default);
5218 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
5220 } // end anonymous namespace
5222 //===----------------------------------------------------------------------===//
5224 namespace llvm {
5225 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5226 GlobalISelEmitter(RK).run(OS);
5228 } // End llvm namespace