1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT; SDNode to generic Instruction).
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
23 /// The generated file defines a single method:
24 /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
31 //===----------------------------------------------------------------------===//
33 #include "CodeGenDAGPatterns.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/CodeGen/MachineValueType.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/LowLevelTypeImpl.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"
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(NumPatternEmitted, "Number of patterns emitted");
57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59 static cl::opt<bool> WarnOnSkippedPatterns(
60 "warn-on-skipped-patterns",
61 cl::desc("Explain why a pattern was skipped for inclusion "
62 "in the GlobalISel selector"),
63 cl::init(false), cl::cat(GlobalISelEmitterCat));
66 //===- Helper functions ---------------------------------------------------===//
68 /// This class stands in for LLT wherever we want to tablegen-erate an
69 /// equivalent at compiler run-time.
75 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
77 void emitCxxConstructorCall(raw_ostream &OS) const {
79 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
83 OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getScalarSizeInBits()
87 llvm_unreachable("Unhandled LLT");
90 const LLT &get() const { return Ty; }
93 class InstructionMatcher;
94 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
95 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
96 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
98 if (VT.isVector() && VT.getVectorNumElements() != 1)
99 return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
100 if (VT.isInteger() || VT.isFloatingPoint())
101 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
105 static std::string explainPredicates(const TreePatternNode *N) {
106 std::string Explanation = "";
107 StringRef Separator = "";
108 for (const auto &P : N->getPredicateFns()) {
110 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
111 if (P.isAlwaysTrue())
112 Explanation += " always-true";
113 if (P.isImmediatePattern())
114 Explanation += " immediate";
119 std::string explainOperator(Record *Operator) {
120 if (Operator->isSubClassOf("SDNode"))
121 return " (" + Operator->getValueAsString("Opcode") + ")";
123 if (Operator->isSubClassOf("Intrinsic"))
124 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
126 return " (Operator not understood)";
129 /// Helper function to let the emitter report skip reason error messages.
130 static Error failedImport(const Twine &Reason) {
131 return make_error<StringError>(Reason, inconvertibleErrorCode());
134 static Error isTrivialOperatorNode(const TreePatternNode *N) {
135 std::string Explanation = "";
136 std::string Separator = "";
138 Explanation = "Is a leaf";
142 if (N->hasAnyPredicate()) {
143 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
147 if (N->getTransformFn()) {
148 Explanation += Separator + "Has a transform function";
152 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
153 return Error::success();
155 return failedImport(Explanation);
158 //===- Matchers -----------------------------------------------------------===//
160 class OperandMatcher;
163 /// Generates code to check that a match rule matches.
165 /// A list of matchers that all need to succeed for the current rule to match.
166 /// FIXME: This currently supports a single match position but could be
167 /// extended to support multiple positions to support div/rem fusion or
168 /// load-multiple instructions.
169 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
171 /// A list of actions that need to be taken when all predicates in this rule
173 std::vector<std::unique_ptr<MatchAction>> Actions;
175 /// A map of instruction matchers to the local variables created by
176 /// emitCxxCaptureStmts().
177 std::map<const InstructionMatcher *, std::string> InsnVariableNames;
179 /// ID for the next instruction variable defined with defineInsnVar()
180 unsigned NextInsnVarID;
182 std::vector<Record *> RequiredFeatures;
186 : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {}
187 RuleMatcher(RuleMatcher &&Other) = default;
188 RuleMatcher &operator=(RuleMatcher &&Other) = default;
190 InstructionMatcher &addInstructionMatcher();
191 void addRequiredFeature(Record *Feature);
193 template <class Kind, class... Args> Kind &addAction(Args &&... args);
195 std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
197 StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const;
199 void emitCxxCapturedInsnList(raw_ostream &OS);
200 void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr);
202 void emit(raw_ostream &OS, SubtargetFeatureInfoMap SubtargetFeatures);
204 /// Compare the priority of this object and B.
206 /// Returns true if this object is more important than B.
207 bool isHigherPriorityThan(const RuleMatcher &B) const;
209 /// Report the maximum number of temporary operands needed by the rule
211 unsigned countRendererFns() const;
213 // FIXME: Remove this as soon as possible
214 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
217 template <class PredicateTy> class PredicateListMatcher {
219 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
220 PredicateVec Predicates;
223 /// Construct a new operand predicate and add it to the matcher.
224 template <class Kind, class... Args>
225 Kind &addPredicate(Args&&... args) {
226 Predicates.emplace_back(
227 llvm::make_unique<Kind>(std::forward<Args>(args)...));
228 return *static_cast<Kind *>(Predicates.back().get());
231 typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
232 typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
233 iterator_range<typename PredicateVec::const_iterator> predicates() const {
234 return make_range(predicates_begin(), predicates_end());
236 typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
238 /// Emit a C++ expression that tests whether all the predicates are met.
239 template <class... Args>
240 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
241 if (Predicates.empty()) {
246 StringRef Separator = "";
247 for (const auto &Predicate : predicates()) {
248 OS << Separator << "(";
249 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
256 /// Generates code to check a predicate of an operand.
258 /// Typical predicates include:
259 /// * Operand is a particular register.
260 /// * Operand is assigned a particular register bank.
261 /// * Operand is an MBB.
262 class OperandPredicateMatcher {
264 /// This enum is used for RTTI and also defines the priority that is given to
265 /// the predicate when generating the matcher code. Kinds with higher priority
266 /// must be tested first.
268 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
269 /// but OPM_Int must have priority over OPM_RegBank since constant integers
270 /// are represented by a virtual register defined by a G_CONSTANT instruction.
284 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
285 virtual ~OperandPredicateMatcher() {}
287 PredicateKind getKind() const { return Kind; }
289 /// Return the OperandMatcher for the specified operand or nullptr if there
290 /// isn't one by that name in this operand predicate matcher.
292 /// InstructionOperandMatcher is the only subclass that can return non-null
294 virtual Optional<const OperandMatcher *>
295 getOptionalOperand(StringRef SymbolicName) const {
296 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
300 /// Emit C++ statements to capture instructions into local variables.
302 /// Only InstructionOperandMatcher needs to do anything for this method.
303 virtual void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
304 StringRef Expr) const {}
306 /// Emit a C++ expression that checks the predicate for the given operand.
307 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
308 StringRef OperandExpr) const = 0;
310 /// Compare the priority of this object and B.
312 /// Returns true if this object is more important than B.
313 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
314 return Kind < B.Kind;
317 /// Report the maximum number of temporary operands needed by the predicate
319 virtual unsigned countRendererFns() const { return 0; }
322 /// Generates code to check that an operand is a particular LLT.
323 class LLTOperandMatcher : public OperandPredicateMatcher {
328 LLTOperandMatcher(const LLTCodeGen &Ty)
329 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
331 static bool classof(const OperandPredicateMatcher *P) {
332 return P->getKind() == OPM_LLT;
335 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
336 StringRef OperandExpr) const override {
337 OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
338 Ty.emitCxxConstructorCall(OS);
343 /// Generates code to check that an operand is a particular target constant.
344 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
346 const OperandMatcher &Operand;
347 const Record &TheDef;
349 unsigned getAllocatedTemporariesBaseID() const;
352 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
353 const Record &TheDef)
354 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
357 static bool classof(const OperandPredicateMatcher *P) {
358 return P->getKind() == OPM_ComplexPattern;
361 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
362 StringRef OperandExpr) const override {
363 unsigned ID = getAllocatedTemporariesBaseID();
364 OS << "(Renderer" << ID << " = " << TheDef.getValueAsString("MatcherFn")
365 << "(" << OperandExpr << "))";
368 unsigned countRendererFns() const override {
373 /// Generates code to check that an operand is in a particular register bank.
374 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
376 const CodeGenRegisterClass &RC;
379 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
380 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
382 static bool classof(const OperandPredicateMatcher *P) {
383 return P->getKind() == OPM_RegBank;
386 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
387 StringRef OperandExpr) const override {
388 OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
389 << "RegClass) == RBI.getRegBank(" << OperandExpr
390 << ".getReg(), MRI, TRI))";
394 /// Generates code to check that an operand is a basic block.
395 class MBBOperandMatcher : public OperandPredicateMatcher {
397 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
399 static bool classof(const OperandPredicateMatcher *P) {
400 return P->getKind() == OPM_MBB;
403 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
404 StringRef OperandExpr) const override {
405 OS << OperandExpr << ".isMBB()";
409 /// Generates code to check that an operand is a particular int.
410 class IntOperandMatcher : public OperandPredicateMatcher {
415 IntOperandMatcher(int64_t Value)
416 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
418 static bool classof(const OperandPredicateMatcher *P) {
419 return P->getKind() == OPM_Int;
422 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
423 StringRef OperandExpr) const override {
424 OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
428 /// Generates code to check that a set of predicates match for a particular
430 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
432 InstructionMatcher &Insn;
434 std::string SymbolicName;
436 /// The index of the first temporary variable allocated to this operand. The
437 /// number of allocated temporaries can be found with
438 /// countRendererFns().
439 unsigned AllocatedTemporariesBaseID;
442 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
443 const std::string &SymbolicName,
444 unsigned AllocatedTemporariesBaseID)
445 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
446 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
448 bool hasSymbolicName() const { return !SymbolicName.empty(); }
449 const StringRef getSymbolicName() const { return SymbolicName; }
450 void setSymbolicName(StringRef Name) {
451 assert(SymbolicName.empty() && "Operand already has a symbolic name");
454 unsigned getOperandIndex() const { return OpIdx; }
456 std::string getOperandExpr(StringRef InsnVarName) const {
457 return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
460 Optional<const OperandMatcher *>
461 getOptionalOperand(StringRef DesiredSymbolicName) const {
462 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
463 if (DesiredSymbolicName == SymbolicName)
465 for (const auto &OP : predicates()) {
466 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
467 if (MaybeOperand.hasValue())
468 return MaybeOperand.getValue();
473 InstructionMatcher &getInstructionMatcher() const { return Insn; }
475 /// Emit C++ statements to capture instructions into local variables.
476 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
477 StringRef OperandExpr) const {
478 for (const auto &Predicate : predicates())
479 Predicate->emitCxxCaptureStmts(OS, Rule, OperandExpr);
482 /// Emit a C++ expression that tests whether the instruction named in
483 /// InsnVarName matches all the predicate and all the operands.
484 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
485 StringRef InsnVarName) const {
487 if (SymbolicName.empty())
488 OS << "Operand " << OpIdx;
492 emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName));
496 /// Compare the priority of this object and B.
498 /// Returns true if this object is more important than B.
499 bool isHigherPriorityThan(const OperandMatcher &B) const {
500 // Operand matchers involving more predicates have higher priority.
501 if (predicates_size() > B.predicates_size())
503 if (predicates_size() < B.predicates_size())
506 // This assumes that predicates are added in a consistent order.
507 for (const auto &Predicate : zip(predicates(), B.predicates())) {
508 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
510 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
517 /// Report the maximum number of temporary operands needed by the operand
519 unsigned countRendererFns() const {
520 return std::accumulate(
521 predicates().begin(), predicates().end(), 0,
523 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
524 return A + Predicate->countRendererFns();
528 unsigned getAllocatedTemporariesBaseID() const {
529 return AllocatedTemporariesBaseID;
533 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
534 return Operand.getAllocatedTemporariesBaseID();
537 /// Generates code to check a predicate on an instruction.
539 /// Typical predicates include:
540 /// * The opcode of the instruction is a particular value.
541 /// * The nsw/nuw flag is/isn't set.
542 class InstructionPredicateMatcher {
544 /// This enum is used for RTTI and also defines the priority that is given to
545 /// the predicate when generating the matcher code. Kinds with higher priority
546 /// must be tested first.
554 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
555 virtual ~InstructionPredicateMatcher() {}
557 PredicateKind getKind() const { return Kind; }
559 /// Emit a C++ expression that tests whether the instruction named in
560 /// InsnVarName matches the predicate.
561 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
562 StringRef InsnVarName) const = 0;
564 /// Compare the priority of this object and B.
566 /// Returns true if this object is more important than B.
567 virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
568 return Kind < B.Kind;
571 /// Report the maximum number of temporary operands needed by the predicate
573 virtual unsigned countRendererFns() const { return 0; }
576 /// Generates code to check the opcode of an instruction.
577 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
579 const CodeGenInstruction *I;
582 InstructionOpcodeMatcher(const CodeGenInstruction *I)
583 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
585 static bool classof(const InstructionPredicateMatcher *P) {
586 return P->getKind() == IPM_Opcode;
589 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
590 StringRef InsnVarName) const override {
591 OS << InsnVarName << ".getOpcode() == " << I->Namespace
592 << "::" << I->TheDef->getName();
595 /// Compare the priority of this object and B.
597 /// Returns true if this object is more important than B.
598 bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
599 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
601 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
604 // Prioritize opcodes for cosmetic reasons in the generated source. Although
605 // this is cosmetic at the moment, we may want to drive a similar ordering
606 // using instruction frequency information to improve compile time.
607 if (const InstructionOpcodeMatcher *BO =
608 dyn_cast<InstructionOpcodeMatcher>(&B))
609 return I->TheDef->getName() < BO->I->TheDef->getName();
615 /// Generates code to check that a set of predicates and operands match for a
616 /// particular instruction.
618 /// Typical predicates include:
619 /// * Has a specific opcode.
620 /// * Has an nsw/nuw flag or doesn't.
621 class InstructionMatcher
622 : public PredicateListMatcher<InstructionPredicateMatcher> {
624 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
626 /// The operands to match. All rendered operands must be present even if the
627 /// condition is always true.
631 /// Add an operand to the matcher.
632 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
633 unsigned AllocatedTemporariesBaseID) {
634 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
635 AllocatedTemporariesBaseID));
636 return *Operands.back();
639 OperandMatcher &getOperand(unsigned OpIdx) {
640 auto I = std::find_if(Operands.begin(), Operands.end(),
641 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
642 return X->getOperandIndex() == OpIdx;
644 if (I != Operands.end())
646 llvm_unreachable("Failed to lookup operand");
649 Optional<const OperandMatcher *>
650 getOptionalOperand(StringRef SymbolicName) const {
651 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
652 for (const auto &Operand : Operands) {
653 const auto &OM = Operand->getOptionalOperand(SymbolicName);
655 return OM.getValue();
660 const OperandMatcher &getOperand(StringRef SymbolicName) const {
661 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
663 return *OM.getValue();
664 llvm_unreachable("Failed to lookup operand");
667 unsigned getNumOperands() const { return Operands.size(); }
668 OperandVec::iterator operands_begin() { return Operands.begin(); }
669 OperandVec::iterator operands_end() { return Operands.end(); }
670 iterator_range<OperandVec::iterator> operands() {
671 return make_range(operands_begin(), operands_end());
673 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
674 OperandVec::const_iterator operands_end() const { return Operands.end(); }
675 iterator_range<OperandVec::const_iterator> operands() const {
676 return make_range(operands_begin(), operands_end());
679 /// Emit C++ statements to check the shape of the match and capture
680 /// instructions into local variables.
681 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) {
682 OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n"
683 << " return false;\n";
684 for (const auto &Operand : Operands) {
685 Operand->emitCxxCaptureStmts(OS, Rule, Operand->getOperandExpr(Expr));
689 /// Emit a C++ expression that tests whether the instruction named in
690 /// InsnVarName matches all the predicates and all the operands.
691 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
692 StringRef InsnVarName) const {
693 emitCxxPredicateListExpr(OS, Rule, InsnVarName);
694 for (const auto &Operand : Operands) {
696 Operand->emitCxxPredicateExpr(OS, Rule, InsnVarName);
701 /// Compare the priority of this object and B.
703 /// Returns true if this object is more important than B.
704 bool isHigherPriorityThan(const InstructionMatcher &B) const {
705 // Instruction matchers involving more operands have higher priority.
706 if (Operands.size() > B.Operands.size())
708 if (Operands.size() < B.Operands.size())
711 for (const auto &Predicate : zip(predicates(), B.predicates())) {
712 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
714 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
718 for (const auto &Operand : zip(Operands, B.Operands)) {
719 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
721 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
728 /// Report the maximum number of temporary operands needed by the instruction
730 unsigned countRendererFns() const {
731 return std::accumulate(predicates().begin(), predicates().end(), 0,
733 const std::unique_ptr<InstructionPredicateMatcher>
735 return A + Predicate->countRendererFns();
738 Operands.begin(), Operands.end(), 0,
739 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
740 return A + Operand->countRendererFns();
745 /// Generates code to check that the operand is a register defined by an
746 /// instruction that matches the given instruction matcher.
748 /// For example, the pattern:
749 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
750 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
752 /// (G_ADD $src1, $src2)
754 class InstructionOperandMatcher : public OperandPredicateMatcher {
756 std::unique_ptr<InstructionMatcher> InsnMatcher;
759 InstructionOperandMatcher()
760 : OperandPredicateMatcher(OPM_Instruction),
761 InsnMatcher(new InstructionMatcher()) {}
763 static bool classof(const OperandPredicateMatcher *P) {
764 return P->getKind() == OPM_Instruction;
767 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
769 Optional<const OperandMatcher *>
770 getOptionalOperand(StringRef SymbolicName) const override {
771 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
772 return InsnMatcher->getOptionalOperand(SymbolicName);
775 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
776 StringRef OperandExpr) const override {
777 OS << "if (!" << OperandExpr + ".isReg())\n"
778 << " return false;\n";
779 std::string InsnVarName = Rule.defineInsnVar(
781 ("*MRI.getVRegDef(" + OperandExpr + ".getReg())").str());
782 InsnMatcher->emitCxxCaptureStmts(OS, Rule, InsnVarName);
785 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
786 StringRef OperandExpr) const override {
787 OperandExpr = Rule.getInsnVarName(*InsnMatcher);
789 InsnMatcher->emitCxxPredicateExpr(OS, Rule, OperandExpr);
794 //===- Actions ------------------------------------------------------------===//
795 class OperandRenderer {
797 enum RendererKind { OR_Copy, OR_Imm, OR_Register, OR_ComplexPattern };
803 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
804 virtual ~OperandRenderer() {}
806 RendererKind getKind() const { return Kind; }
808 virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
811 /// A CopyRenderer emits code to copy a single operand from an existing
812 /// instruction to the one being built.
813 class CopyRenderer : public OperandRenderer {
815 /// The matcher for the instruction that this operand is copied from.
816 /// This provides the facility for looking up an a operand by it's name so
817 /// that it can be used as a source for the instruction being built.
818 const InstructionMatcher &Matched;
819 /// The name of the operand.
820 const StringRef SymbolicName;
823 CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
824 : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
827 static bool classof(const OperandRenderer *R) {
828 return R->getKind() == OR_Copy;
831 const StringRef getSymbolicName() const { return SymbolicName; }
833 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
834 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
835 StringRef InsnVarName =
836 Rule.getInsnVarName(Operand.getInstructionMatcher());
837 std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
838 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
842 /// Adds a specific physical register to the instruction being built.
843 /// This is typically useful for WZR/XZR on AArch64.
844 class AddRegisterRenderer : public OperandRenderer {
846 const Record *RegisterDef;
849 AddRegisterRenderer(const Record *RegisterDef)
850 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
852 static bool classof(const OperandRenderer *R) {
853 return R->getKind() == OR_Register;
856 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
857 OS << " MIB.addReg(" << (RegisterDef->getValue("Namespace")
858 ? RegisterDef->getValueAsString("Namespace")
860 << "::" << RegisterDef->getName() << ");\n";
864 /// Adds a specific immediate to the instruction being built.
865 class ImmRenderer : public OperandRenderer {
870 ImmRenderer(int64_t Imm)
871 : OperandRenderer(OR_Imm), Imm(Imm) {}
873 static bool classof(const OperandRenderer *R) {
874 return R->getKind() == OR_Imm;
877 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
878 OS << " MIB.addImm(" << Imm << ");\n";
882 /// Adds operands by calling a renderer function supplied by the ComplexPattern
883 /// matcher function.
884 class RenderComplexPatternOperand : public OperandRenderer {
886 const Record &TheDef;
887 /// The name of the operand.
888 const StringRef SymbolicName;
889 /// The renderer number. This must be unique within a rule since it's used to
890 /// identify a temporary variable to hold the renderer function.
893 unsigned getNumOperands() const {
894 return TheDef.getValueAsDag("Operands")->getNumArgs();
898 RenderComplexPatternOperand(const Record &TheDef, StringRef SymbolicName,
900 : OperandRenderer(OR_ComplexPattern), TheDef(TheDef),
901 SymbolicName(SymbolicName), RendererID(RendererID) {}
903 static bool classof(const OperandRenderer *R) {
904 return R->getKind() == OR_ComplexPattern;
907 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
908 OS << "Renderer" << RendererID << "(MIB);\n";
912 /// An action taken when all Matcher predicates succeeded for a parent rule.
914 /// Typical actions include:
915 /// * Changing the opcode of an instruction.
916 /// * Adding an operand to an instruction.
919 virtual ~MatchAction() {}
921 /// Emit the C++ statements to implement the action.
923 /// \param RecycleVarName If given, it's an instruction to recycle. The
924 /// requirements on the instruction vary from action to
926 virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
927 StringRef RecycleVarName) const = 0;
930 /// Generates a comment describing the matched rule being acted upon.
931 class DebugCommentAction : public MatchAction {
933 const PatternToMatch &P;
936 DebugCommentAction(const PatternToMatch &P) : P(P) {}
938 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
939 StringRef RecycleVarName) const override {
940 OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern() << "\n";
944 /// Generates code to build an instruction or mutate an existing instruction
945 /// into the desired instruction when this is possible.
946 class BuildMIAction : public MatchAction {
948 const CodeGenInstruction *I;
949 const InstructionMatcher &Matched;
950 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
952 /// True if the instruction can be built solely by mutating the opcode.
953 bool canMutate() const {
954 if (OperandRenderers.size() != Matched.getNumOperands())
957 for (const auto &Renderer : enumerate(OperandRenderers)) {
958 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
959 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
960 if (&Matched != &OM.getInstructionMatcher() ||
961 OM.getOperandIndex() != Renderer.index())
971 BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched)
972 : I(I), Matched(Matched) {}
974 template <class Kind, class... Args>
975 Kind &addRenderer(Args&&... args) {
976 OperandRenderers.emplace_back(
977 llvm::make_unique<Kind>(std::forward<Args>(args)...));
978 return *static_cast<Kind *>(OperandRenderers.back().get());
981 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
982 StringRef RecycleVarName) const override {
984 OS << " " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
985 << "::" << I->TheDef->getName() << "));\n";
987 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
988 OS << " auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
991 for (auto Def : I->ImplicitDefs) {
992 auto Namespace = Def->getValue("Namespace")
993 ? Def->getValueAsString("Namespace")
995 OS << " MIB.addDef(" << Namespace << "::" << Def->getName()
996 << ", RegState::Implicit);\n";
998 for (auto Use : I->ImplicitUses) {
999 auto Namespace = Use->getValue("Namespace")
1000 ? Use->getValueAsString("Namespace")
1002 OS << " MIB.addUse(" << Namespace << "::" << Use->getName()
1003 << ", RegState::Implicit);\n";
1007 OS << " MachineInstr &NewI = " << RecycleVarName << ";\n";
1011 // TODO: Simple permutation looks like it could be almost as common as
1012 // mutation due to commutative operations.
1014 OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
1015 "I.getDebugLoc(), TII.get("
1016 << I->Namespace << "::" << I->TheDef->getName() << "));\n";
1017 for (const auto &Renderer : OperandRenderers)
1018 Renderer->emitCxxRenderStmts(OS, Rule);
1019 OS << " for (const auto *FromMI : ";
1020 Rule.emitCxxCapturedInsnList(OS);
1022 OS << " for (const auto &MMO : FromMI->memoperands())\n";
1023 OS << " MIB.addMemOperand(MMO);\n";
1024 OS << " " << RecycleVarName << ".eraseFromParent();\n";
1025 OS << " MachineInstr &NewI = *MIB;\n";
1029 InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1030 Matchers.emplace_back(new InstructionMatcher());
1031 return *Matchers.back();
1034 void RuleMatcher::addRequiredFeature(Record *Feature) {
1035 RequiredFeatures.push_back(Feature);
1038 template <class Kind, class... Args>
1039 Kind &RuleMatcher::addAction(Args &&... args) {
1040 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1041 return *static_cast<Kind *>(Actions.back().get());
1044 std::string RuleMatcher::defineInsnVar(raw_ostream &OS,
1045 const InstructionMatcher &Matcher,
1047 std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++);
1048 OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n";
1049 InsnVariableNames[&Matcher] = InsnVarName;
1053 StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const {
1054 const auto &I = InsnVariableNames.find(&InsnMatcher);
1055 if (I != InsnVariableNames.end())
1057 llvm_unreachable("Matched Insn was not captured in a local variable");
1060 /// Emit a C++ initializer_list containing references to every matched instruction.
1061 void RuleMatcher::emitCxxCapturedInsnList(raw_ostream &OS) {
1062 SmallVector<StringRef, 2> Names;
1063 for (const auto &Pair : InsnVariableNames)
1064 Names.push_back(Pair.second);
1065 std::sort(Names.begin(), Names.end());
1068 for (const auto &Name : Names)
1069 OS << "&" << Name << ", ";
1073 /// Emit C++ statements to check the shape of the match and capture
1074 /// instructions into local variables.
1075 void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) {
1076 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1077 std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr);
1078 Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName);
1081 void RuleMatcher::emit(raw_ostream &OS,
1082 SubtargetFeatureInfoMap SubtargetFeatures) {
1083 if (Matchers.empty())
1084 llvm_unreachable("Unexpected empty matcher!");
1086 // The representation supports rules that require multiple roots such as:
1088 // %elt0(s32) = G_LOAD %ptr
1089 // %1(p0) = G_ADD %ptr, 4
1090 // %elt1(s32) = G_LOAD p0 %1
1091 // which could be usefully folded into:
1093 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1094 // on some targets but we don't need to make use of that yet.
1095 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1099 if (!RequiredFeatures.empty()) {
1100 OS << " PredicateBitset ExpectedFeatures = {";
1101 StringRef Separator = "";
1102 for (const auto &Predicate : RequiredFeatures) {
1103 const auto &I = SubtargetFeatures.find(Predicate);
1104 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
1105 OS << Separator << I->second.getEnumBitName();
1109 OS << "if ((AvailableFeatures & ExpectedFeatures) != ExpectedFeatures)\n"
1110 << " return false;\n";
1113 emitCxxCaptureStmts(OS, "I");
1116 Matchers.front()->emitCxxPredicateExpr(OS, *this,
1117 getInsnVarName(*Matchers.front()));
1120 // We must also check if it's safe to fold the matched instructions.
1121 if (InsnVariableNames.size() >= 2) {
1122 for (const auto &Pair : InsnVariableNames) {
1123 // Skip the root node since it isn't moving anywhere. Everything else is
1124 // sinking to meet it.
1125 if (Pair.first == Matchers.front().get())
1128 // Reject the difficult cases until we have a more accurate check.
1129 OS << " if (!isObviouslySafeToFold(" << Pair.second
1130 << ")) return false;\n";
1132 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1133 // account for unsafe cases.
1138 // MI0--> %2 = ... %0
1139 // It's not safe to erase MI1. We currently handle this by not
1140 // erasing %0 (even when it's dead).
1143 // MI1--> %0 = load volatile @a
1144 // %1 = load volatile @a
1145 // MI0--> %2 = ... %0
1146 // It's not safe to sink %0's def past %1. We currently handle
1147 // this by rejecting all loads.
1150 // MI1--> %0 = load @a
1152 // MI0--> %2 = ... %0
1153 // It's not safe to sink %0's def past %1. We currently handle
1154 // this by rejecting all loads.
1157 // G_CONDBR %cond, @BB1
1159 // MI1--> %0 = load @a
1162 // MI0--> %2 = ... %0
1163 // It's not always safe to sink %0 across control flow. In this
1164 // case it may introduce a memory fault. We currentl handle this
1165 // by rejecting all loads.
1169 for (const auto &MA : Actions) {
1170 MA->emitCxxActionStmts(OS, *this, "I");
1173 OS << " constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n";
1174 OS << " return true;\n";
1176 OS << " return false;\n";
1177 OS << " }()) { return true; }\n\n";
1180 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1181 // Rules involving more match roots have higher priority.
1182 if (Matchers.size() > B.Matchers.size())
1184 if (Matchers.size() < B.Matchers.size())
1187 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1188 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1190 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1197 unsigned RuleMatcher::countRendererFns() const {
1198 return std::accumulate(
1199 Matchers.begin(), Matchers.end(), 0,
1200 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1201 return A + Matcher->countRendererFns();
1205 //===- GlobalISelEmitter class --------------------------------------------===//
1207 class GlobalISelEmitter {
1209 explicit GlobalISelEmitter(RecordKeeper &RK);
1210 void run(raw_ostream &OS);
1213 const RecordKeeper &RK;
1214 const CodeGenDAGPatterns CGP;
1215 const CodeGenTarget &Target;
1217 /// Keep track of the equivalence between SDNodes and Instruction.
1218 /// This is defined using 'GINodeEquiv' in the target description.
1219 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1221 /// Keep track of the equivalence between ComplexPattern's and
1222 /// GIComplexOperandMatcher. Map entries are specified by subclassing
1223 /// GIComplexPatternEquiv.
1224 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1226 // Map of predicates to their subtarget features.
1227 SubtargetFeatureInfoMap SubtargetFeatures;
1229 void gatherNodeEquivs();
1230 const CodeGenInstruction *findNodeEquiv(Record *N) const;
1232 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
1233 Expected<InstructionMatcher &>
1234 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1235 const TreePatternNode *Src) const;
1236 Error importChildMatcher(InstructionMatcher &InsnMatcher,
1237 TreePatternNode *SrcChild, unsigned OpIdx,
1238 unsigned &TempOpIdx) const;
1239 Expected<BuildMIAction &> createAndImportInstructionRenderer(
1240 RuleMatcher &M, const TreePatternNode *Dst,
1241 const InstructionMatcher &InsnMatcher) const;
1242 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1243 TreePatternNode *DstChild,
1244 const InstructionMatcher &InsnMatcher) const;
1246 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1247 const std::vector<Record *> &ImplicitDefs) const;
1249 /// Analyze pattern \p P, returning a matcher for it if possible.
1250 /// Otherwise, return an Error explaining why we don't support it.
1251 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1253 void declareSubtargetFeature(Record *Predicate);
1256 void GlobalISelEmitter::gatherNodeEquivs() {
1257 assert(NodeEquivs.empty());
1258 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1259 NodeEquivs[Equiv->getValueAsDef("Node")] =
1260 &Target.getInstruction(Equiv->getValueAsDef("I"));
1262 assert(ComplexPatternEquivs.empty());
1263 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1264 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1267 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1271 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1272 return NodeEquivs.lookup(N);
1275 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1276 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
1278 //===- Emitter ------------------------------------------------------------===//
1281 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1282 ArrayRef<Init *> Predicates) {
1283 for (const Init *Predicate : Predicates) {
1284 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1285 declareSubtargetFeature(PredicateDef->getDef());
1286 M.addRequiredFeature(PredicateDef->getDef());
1289 return Error::success();
1292 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
1293 InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const {
1294 // Start with the defined operands (i.e., the results of the root operator).
1295 if (Src->getExtTypes().size() > 1)
1296 return failedImport("Src pattern has multiple results");
1298 auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1300 return failedImport("Pattern operator lacks an equivalent Instruction" +
1301 explainOperator(Src->getOperator()));
1302 auto &SrcGI = *SrcGIOrNull;
1304 // The operators look good: match the opcode and mutate it to the new one.
1305 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1308 unsigned TempOpIdx = 0;
1309 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1310 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1313 return failedImport(
1314 "Result of Src pattern operator has an unsupported type");
1316 // Results don't have a name unless they are the root node. The caller will
1317 // set the name if appropriate.
1318 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1319 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1322 // Match the used operands (i.e. the children of the operator).
1323 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1324 if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i), OpIdx++,
1326 return std::move(Error);
1332 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
1333 TreePatternNode *SrcChild,
1335 unsigned &TempOpIdx) const {
1336 OperandMatcher &OM =
1337 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
1339 if (SrcChild->hasAnyPredicate())
1340 return failedImport("Src pattern child has predicate (" +
1341 explainPredicates(SrcChild) + ")");
1343 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1344 if (ChildTypes.size() != 1)
1345 return failedImport("Src pattern child has multiple results");
1347 // Check MBB's before the type check since they are not a known type.
1348 if (!SrcChild->isLeaf()) {
1349 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1350 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1351 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1352 OM.addPredicate<MBBOperandMatcher>();
1353 return Error::success();
1358 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1360 return failedImport("Src operand has an unsupported type");
1361 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1363 // Check for nested instructions.
1364 if (!SrcChild->isLeaf()) {
1365 // Map the node to a gMIR instruction.
1366 InstructionOperandMatcher &InsnOperand =
1367 OM.addPredicate<InstructionOperandMatcher>();
1368 auto InsnMatcherOrError =
1369 createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild);
1370 if (auto Error = InsnMatcherOrError.takeError())
1373 return Error::success();
1376 // Check for constant immediates.
1377 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1378 OM.addPredicate<IntOperandMatcher>(ChildInt->getValue());
1379 return Error::success();
1382 // Check for def's like register classes or ComplexPattern's.
1383 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1384 auto *ChildRec = ChildDefInit->getDef();
1386 // Check for register classes.
1387 if (ChildRec->isSubClassOf("RegisterClass")) {
1388 OM.addPredicate<RegisterBankOperandMatcher>(
1389 Target.getRegisterClass(ChildRec));
1390 return Error::success();
1393 if (ChildRec->isSubClassOf("RegisterOperand")) {
1394 OM.addPredicate<RegisterBankOperandMatcher>(
1395 Target.getRegisterClass(ChildRec->getValueAsDef("RegClass")));
1396 return Error::success();
1399 // Check for ComplexPattern's.
1400 if (ChildRec->isSubClassOf("ComplexPattern")) {
1401 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1402 if (ComplexPattern == ComplexPatternEquivs.end())
1403 return failedImport("SelectionDAG ComplexPattern (" +
1404 ChildRec->getName() + ") not mapped to GlobalISel");
1406 OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1407 *ComplexPattern->second);
1409 return Error::success();
1412 if (ChildRec->isSubClassOf("ImmLeaf")) {
1413 return failedImport(
1414 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1417 return failedImport(
1418 "Src pattern child def is an unsupported tablegen class");
1421 return failedImport("Src pattern child is an unsupported kind");
1424 Error GlobalISelEmitter::importExplicitUseRenderer(
1425 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
1426 const InstructionMatcher &InsnMatcher) const {
1427 // The only non-leaf child we accept is 'bb': it's an operator because
1428 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1429 if (!DstChild->isLeaf()) {
1430 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1431 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1432 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1433 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
1434 DstChild->getName());
1435 return Error::success();
1438 return failedImport("Dst pattern child isn't a leaf node or an MBB");
1441 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1442 if (DstChild->hasAnyPredicate())
1443 return failedImport("Dst pattern child has predicate (" +
1444 explainPredicates(DstChild) + ")");
1446 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1447 auto *ChildRec = ChildDefInit->getDef();
1449 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1450 if (ChildTypes.size() != 1)
1451 return failedImport("Dst pattern child has multiple results");
1453 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1455 return failedImport("Dst operand has an unsupported type");
1457 if (ChildRec->isSubClassOf("Register")) {
1458 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
1459 return Error::success();
1462 if (ChildRec->isSubClassOf("RegisterClass") ||
1463 ChildRec->isSubClassOf("RegisterOperand")) {
1464 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName());
1465 return Error::success();
1468 if (ChildRec->isSubClassOf("ComplexPattern")) {
1469 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1470 if (ComplexPattern == ComplexPatternEquivs.end())
1471 return failedImport(
1472 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1474 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
1475 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1476 *ComplexPattern->second, DstChild->getName(),
1477 OM.getAllocatedTemporariesBaseID());
1478 return Error::success();
1481 if (ChildRec->isSubClassOf("SDNodeXForm"))
1482 return failedImport("Dst pattern child def is an unsupported tablegen "
1483 "class (SDNodeXForm)");
1485 return failedImport(
1486 "Dst pattern child def is an unsupported tablegen class");
1489 return failedImport("Dst pattern child is an unsupported kind");
1492 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
1493 RuleMatcher &M, const TreePatternNode *Dst,
1494 const InstructionMatcher &InsnMatcher) const {
1495 Record *DstOp = Dst->getOperator();
1496 if (!DstOp->isSubClassOf("Instruction")) {
1497 if (DstOp->isSubClassOf("ValueType"))
1498 return failedImport(
1499 "Pattern operator isn't an instruction (it's a ValueType)");
1500 return failedImport("Pattern operator isn't an instruction");
1502 auto &DstI = Target.getInstruction(DstOp);
1504 auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher);
1506 // Render the explicit defs.
1507 for (unsigned I = 0; I < DstI.Operands.NumDefs; ++I) {
1508 const auto &DstIOperand = DstI.Operands[I];
1509 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
1512 // Figure out which operands need defaults inserted. Operands that subclass
1513 // OperandWithDefaultOps are considered from left to right until we have
1514 // enough operands to render the instruction.
1515 SmallSet<unsigned, 2> DefaultOperands;
1516 unsigned DstINumUses = DstI.Operands.size() - DstI.Operands.NumDefs;
1517 unsigned NumDefaultOperands = 0;
1518 for (unsigned I = 0; I < DstINumUses &&
1519 DstINumUses > Dst->getNumChildren() + NumDefaultOperands;
1521 const auto &DstIOperand = DstI.Operands[DstI.Operands.NumDefs + I];
1522 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
1523 DefaultOperands.insert(I);
1524 NumDefaultOperands +=
1525 DstIOperand.Rec->getValueAsDag("DefaultOps")->getNumArgs();
1528 if (DstINumUses > Dst->getNumChildren() + DefaultOperands.size())
1529 return failedImport("Insufficient operands supplied and default ops "
1530 "couldn't make up the shortfall");
1531 if (DstINumUses < Dst->getNumChildren() + DefaultOperands.size())
1532 return failedImport("Too many operands supplied");
1534 // Render the explicit uses.
1536 for (unsigned I = 0; I != DstINumUses; ++I) {
1537 // If we need to insert default ops here, then do so.
1538 if (DefaultOperands.count(I)) {
1539 const auto &DstIOperand = DstI.Operands[DstI.Operands.NumDefs + I];
1541 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
1542 for (const auto *DefaultOp : DefaultOps->args()) {
1543 // Look through ValueType operators.
1544 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
1545 if (const DefInit *DefaultDagOperator =
1546 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
1547 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
1548 DefaultOp = DefaultDagOp->getArg(0);
1552 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
1553 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
1557 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
1558 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
1562 return failedImport("Could not add default op");
1568 if (auto Error = importExplicitUseRenderer(
1569 DstMIBuilder, Dst->getChild(Child), InsnMatcher))
1570 return std::move(Error);
1574 return DstMIBuilder;
1577 Error GlobalISelEmitter::importImplicitDefRenderers(
1578 BuildMIAction &DstMIBuilder,
1579 const std::vector<Record *> &ImplicitDefs) const {
1580 if (!ImplicitDefs.empty())
1581 return failedImport("Pattern defines a physical register");
1582 return Error::success();
1585 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
1586 // Keep track of the matchers and actions to emit.
1588 M.addAction<DebugCommentAction>(P);
1590 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
1591 return std::move(Error);
1593 // Next, analyze the pattern operators.
1594 TreePatternNode *Src = P.getSrcPattern();
1595 TreePatternNode *Dst = P.getDstPattern();
1597 // If the root of either pattern isn't a simple operator, ignore it.
1598 if (auto Err = isTrivialOperatorNode(Dst))
1599 return failedImport("Dst pattern root isn't a trivial operator (" +
1600 toString(std::move(Err)) + ")");
1601 if (auto Err = isTrivialOperatorNode(Src))
1602 return failedImport("Src pattern root isn't a trivial operator (" +
1603 toString(std::move(Err)) + ")");
1605 // Start with the defined operands (i.e., the results of the root operator).
1606 Record *DstOp = Dst->getOperator();
1607 if (!DstOp->isSubClassOf("Instruction"))
1608 return failedImport("Pattern operator isn't an instruction");
1610 auto &DstI = Target.getInstruction(DstOp);
1611 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
1612 return failedImport("Src pattern results and dst MI defs are different (" +
1613 to_string(Src->getExtTypes().size()) + " def(s) vs " +
1614 to_string(DstI.Operands.NumDefs) + " def(s))");
1616 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
1617 auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src);
1618 if (auto Error = InsnMatcherOrError.takeError())
1619 return std::move(Error);
1620 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
1622 // The root of the match also has constraints on the register bank so that it
1623 // matches the result instruction.
1625 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1628 const auto &DstIOperand = DstI.Operands[OpIdx];
1629 Record *DstIOpRec = DstIOperand.Rec;
1630 if (DstIOpRec->isSubClassOf("RegisterOperand"))
1631 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
1632 if (!DstIOpRec->isSubClassOf("RegisterClass"))
1633 return failedImport("Dst MI def isn't a register class");
1635 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
1636 OM.setSymbolicName(DstIOperand.Name);
1637 OM.addPredicate<RegisterBankOperandMatcher>(
1638 Target.getRegisterClass(DstIOpRec));
1642 auto DstMIBuilderOrError =
1643 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
1644 if (auto Error = DstMIBuilderOrError.takeError())
1645 return std::move(Error);
1646 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
1648 // Render the implicit defs.
1649 // These are only added to the root of the result.
1650 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
1651 return std::move(Error);
1653 // We're done with this pattern! It's eligible for GISel emission; return it.
1654 ++NumPatternImported;
1655 return std::move(M);
1658 void GlobalISelEmitter::run(raw_ostream &OS) {
1659 // Track the GINodeEquiv definitions.
1662 emitSourceFileHeader(("Global Instruction Selector for the " +
1663 Target.getName() + " target").str(), OS);
1664 std::vector<RuleMatcher> Rules;
1665 // Look through the SelectionDAG patterns we found, possibly emitting some.
1666 for (const PatternToMatch &Pat : CGP.ptms()) {
1668 auto MatcherOrErr = runOnPattern(Pat);
1670 // The pattern analysis can fail, indicating an unsupported pattern.
1671 // Report that if we've been asked to do so.
1672 if (auto Err = MatcherOrErr.takeError()) {
1673 if (WarnOnSkippedPatterns) {
1674 PrintWarning(Pat.getSrcRecord()->getLoc(),
1675 "Skipped pattern: " + toString(std::move(Err)));
1677 consumeError(std::move(Err));
1679 ++NumPatternImportsSkipped;
1683 Rules.push_back(std::move(MatcherOrErr.get()));
1686 std::stable_sort(Rules.begin(), Rules.end(),
1687 [&](const RuleMatcher &A, const RuleMatcher &B) {
1688 if (A.isHigherPriorityThan(B)) {
1689 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
1690 "and less important at "
1697 unsigned MaxTemporaries = 0;
1698 for (const auto &Rule : Rules)
1699 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
1701 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
1702 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
1704 << "using PredicateBitset = "
1705 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
1706 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
1708 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n";
1709 for (unsigned I = 0; I < MaxTemporaries; ++I)
1710 OS << " mutable ComplexRendererFn Renderer" << I << ";\n";
1711 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
1713 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n";
1714 for (unsigned I = 0; I < MaxTemporaries; ++I)
1715 OS << ", Renderer" << I << "(nullptr)\n";
1716 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
1718 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
1719 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
1722 // Separate subtarget features by how often they must be recomputed.
1723 SubtargetFeatureInfoMap ModuleFeatures;
1724 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1725 std::inserter(ModuleFeatures, ModuleFeatures.end()),
1726 [](const SubtargetFeatureInfoMap::value_type &X) {
1727 return !X.second.mustRecomputePerFunction();
1729 SubtargetFeatureInfoMap FunctionFeatures;
1730 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1731 std::inserter(FunctionFeatures, FunctionFeatures.end()),
1732 [](const SubtargetFeatureInfoMap::value_type &X) {
1733 return X.second.mustRecomputePerFunction();
1736 SubtargetFeatureInfo::emitComputeAvailableFeatures(
1737 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
1738 ModuleFeatures, OS);
1739 SubtargetFeatureInfo::emitComputeAvailableFeatures(
1740 Target.getName(), "InstructionSelector",
1741 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
1742 "const MachineFunction *MF");
1744 OS << "bool " << Target.getName()
1745 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
1746 << " MachineFunction &MF = *I.getParent()->getParent();\n"
1747 << " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
1748 << " // FIXME: This should be computed on a per-function basis rather than per-insn.\n"
1749 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, &MF);\n"
1750 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n";
1752 for (auto &Rule : Rules) {
1753 Rule.emit(OS, SubtargetFeatures);
1754 ++NumPatternEmitted;
1757 OS << " return false;\n"
1759 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
1761 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
1762 << "PredicateBitset AvailableModuleFeatures;\n"
1763 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
1764 << "PredicateBitset getAvailableFeatures() const {\n"
1765 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
1767 << "PredicateBitset\n"
1768 << "computeAvailableModuleFeatures(const " << Target.getName()
1769 << "Subtarget *Subtarget) const;\n"
1770 << "PredicateBitset\n"
1771 << "computeAvailableFunctionFeatures(const " << Target.getName()
1772 << "Subtarget *Subtarget,\n"
1773 << " const MachineFunction *MF) const;\n"
1774 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
1776 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
1777 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
1778 << "AvailableFunctionFeatures()\n"
1779 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
1782 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
1783 if (SubtargetFeatures.count(Predicate) == 0)
1784 SubtargetFeatures.emplace(
1785 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
1788 } // end anonymous namespace
1790 //===----------------------------------------------------------------------===//
1793 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
1794 GlobalISelEmitter(RK).run(OS);
1796 } // End llvm namespace