1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
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).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
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++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
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"
46 #include <string>
47 #include <numeric>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
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");
56 
57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58 
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));
64 
65 namespace {
66 //===- Helper functions ---------------------------------------------------===//
67 
68 /// This class stands in for LLT wherever we want to tablegen-erate an
69 /// equivalent at compiler run-time.
70 class LLTCodeGen {
71 private:
72   LLT Ty;
73 
74 public:
75   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
76 
77   void emitCxxConstructorCall(raw_ostream &OS) const {
78     if (Ty.isScalar()) {
79       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
80       return;
81     }
82     if (Ty.isVector()) {
83       OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getScalarSizeInBits()
84          << ")";
85       return;
86     }
87     llvm_unreachable("Unhandled LLT");
88   }
89 
90   const LLT &get() const { return Ty; }
91 };
92 
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) {
97   MVT VT(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()));
102   return None;
103 }
104 
105 static std::string explainPredicates(const TreePatternNode *N) {
106   std::string Explanation = "";
107   StringRef Separator = "";
108   for (const auto &P : N->getPredicateFns()) {
109     Explanation +=
110         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
111     if (P.isAlwaysTrue())
112       Explanation += " always-true";
113     if (P.isImmediatePattern())
114       Explanation += " immediate";
115   }
116   return Explanation;
117 }
118 
119 std::string explainOperator(Record *Operator) {
120   if (Operator->isSubClassOf("SDNode"))
121     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
122 
123   if (Operator->isSubClassOf("Intrinsic"))
124     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
125 
126   return " (Operator not understood)";
127 }
128 
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());
132 }
133 
134 static Error isTrivialOperatorNode(const TreePatternNode *N) {
135   std::string Explanation = "";
136   std::string Separator = "";
137   if (N->isLeaf()) {
138     if (isa<IntInit>(N->getLeafValue()))
139       return Error::success();
140 
141     Explanation = "Is a leaf";
142     Separator = ", ";
143   }
144 
145   if (N->hasAnyPredicate()) {
146     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
147     Separator = ", ";
148   }
149 
150   if (N->getTransformFn()) {
151     Explanation += Separator + "Has a transform function";
152     Separator = ", ";
153   }
154 
155   if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
156     return Error::success();
157 
158   return failedImport(Explanation);
159 }
160 
161 static Record *getInitValueAsRegClass(Init *V) {
162   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
163     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
164       return VDefInit->getDef()->getValueAsDef("RegClass");
165     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
166       return VDefInit->getDef();
167   }
168   return nullptr;
169 }
170 
171 //===- Matchers -----------------------------------------------------------===//
172 
173 class OperandMatcher;
174 class MatchAction;
175 
176 /// Generates code to check that a match rule matches.
177 class RuleMatcher {
178   /// A list of matchers that all need to succeed for the current rule to match.
179   /// FIXME: This currently supports a single match position but could be
180   /// extended to support multiple positions to support div/rem fusion or
181   /// load-multiple instructions.
182   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
183 
184   /// A list of actions that need to be taken when all predicates in this rule
185   /// have succeeded.
186   std::vector<std::unique_ptr<MatchAction>> Actions;
187 
188   /// A map of instruction matchers to the local variables created by
189   /// emitCxxCaptureStmts().
190   std::map<const InstructionMatcher *, std::string> InsnVariableNames;
191 
192   /// ID for the next instruction variable defined with defineInsnVar()
193   unsigned NextInsnVarID;
194 
195   std::vector<Record *> RequiredFeatures;
196 
197 public:
198   RuleMatcher()
199       : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {}
200   RuleMatcher(RuleMatcher &&Other) = default;
201   RuleMatcher &operator=(RuleMatcher &&Other) = default;
202 
203   InstructionMatcher &addInstructionMatcher();
204   void addRequiredFeature(Record *Feature);
205 
206   template <class Kind, class... Args> Kind &addAction(Args &&... args);
207 
208   std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
209                             StringRef Value);
210   StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const;
211 
212   void emitCxxCapturedInsnList(raw_ostream &OS);
213   void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr);
214 
215 void emit(raw_ostream &OS, SubtargetFeatureInfoMap SubtargetFeatures);
216 
217 /// Compare the priority of this object and B.
218 ///
219 /// Returns true if this object is more important than B.
220 bool isHigherPriorityThan(const RuleMatcher &B) const;
221 
222 /// Report the maximum number of temporary operands needed by the rule
223 /// matcher.
224 unsigned countRendererFns() const;
225 
226 // FIXME: Remove this as soon as possible
227 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
228 };
229 
230 template <class PredicateTy> class PredicateListMatcher {
231 private:
232   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
233   PredicateVec Predicates;
234 
235 public:
236   /// Construct a new operand predicate and add it to the matcher.
237   template <class Kind, class... Args>
238   Kind &addPredicate(Args&&... args) {
239     Predicates.emplace_back(
240         llvm::make_unique<Kind>(std::forward<Args>(args)...));
241     return *static_cast<Kind *>(Predicates.back().get());
242   }
243 
244   typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
245   typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
246   iterator_range<typename PredicateVec::const_iterator> predicates() const {
247     return make_range(predicates_begin(), predicates_end());
248   }
249   typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
250 
251   /// Emit a C++ expression that tests whether all the predicates are met.
252   template <class... Args>
253   void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
254     if (Predicates.empty()) {
255       OS << "true";
256       return;
257     }
258 
259     StringRef Separator = "";
260     for (const auto &Predicate : predicates()) {
261       OS << Separator << "(";
262       Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
263       OS << ")";
264       Separator = " &&\n";
265     }
266   }
267 };
268 
269 /// Generates code to check a predicate of an operand.
270 ///
271 /// Typical predicates include:
272 /// * Operand is a particular register.
273 /// * Operand is assigned a particular register bank.
274 /// * Operand is an MBB.
275 class OperandPredicateMatcher {
276 public:
277   /// This enum is used for RTTI and also defines the priority that is given to
278   /// the predicate when generating the matcher code. Kinds with higher priority
279   /// must be tested first.
280   ///
281   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
282   /// but OPM_Int must have priority over OPM_RegBank since constant integers
283   /// are represented by a virtual register defined by a G_CONSTANT instruction.
284   enum PredicateKind {
285     OPM_ComplexPattern,
286     OPM_Instruction,
287     OPM_Int,
288     OPM_LiteralInt,
289     OPM_LLT,
290     OPM_RegBank,
291     OPM_MBB,
292   };
293 
294 protected:
295   PredicateKind Kind;
296 
297 public:
298   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
299   virtual ~OperandPredicateMatcher() {}
300 
301   PredicateKind getKind() const { return Kind; }
302 
303   /// Return the OperandMatcher for the specified operand or nullptr if there
304   /// isn't one by that name in this operand predicate matcher.
305   ///
306   /// InstructionOperandMatcher is the only subclass that can return non-null
307   /// for this.
308   virtual Optional<const OperandMatcher *>
309   getOptionalOperand(StringRef SymbolicName) const {
310     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
311     return None;
312   }
313 
314   /// Emit C++ statements to capture instructions into local variables.
315   ///
316   /// Only InstructionOperandMatcher needs to do anything for this method.
317   virtual void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
318                                    StringRef Expr) const {}
319 
320   /// Emit a C++ expression that checks the predicate for the given operand.
321   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
322                                     StringRef OperandExpr) const = 0;
323 
324   /// Compare the priority of this object and B.
325   ///
326   /// Returns true if this object is more important than B.
327   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
328     return Kind < B.Kind;
329   };
330 
331   /// Report the maximum number of temporary operands needed by the predicate
332   /// matcher.
333   virtual unsigned countRendererFns() const { return 0; }
334 };
335 
336 /// Generates code to check that an operand is a particular LLT.
337 class LLTOperandMatcher : public OperandPredicateMatcher {
338 protected:
339   LLTCodeGen Ty;
340 
341 public:
342   LLTOperandMatcher(const LLTCodeGen &Ty)
343       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
344 
345   static bool classof(const OperandPredicateMatcher *P) {
346     return P->getKind() == OPM_LLT;
347   }
348 
349   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
350                             StringRef OperandExpr) const override {
351     OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
352     Ty.emitCxxConstructorCall(OS);
353     OS << ")";
354   }
355 };
356 
357 /// Generates code to check that an operand is a particular target constant.
358 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
359 protected:
360   const OperandMatcher &Operand;
361   const Record &TheDef;
362 
363   unsigned getAllocatedTemporariesBaseID() const;
364 
365 public:
366   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
367                                const Record &TheDef)
368       : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
369         TheDef(TheDef) {}
370 
371   static bool classof(const OperandPredicateMatcher *P) {
372     return P->getKind() == OPM_ComplexPattern;
373   }
374 
375   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
376                             StringRef OperandExpr) const override {
377     unsigned ID = getAllocatedTemporariesBaseID();
378     OS << "(Renderer" << ID << " = " << TheDef.getValueAsString("MatcherFn")
379        << "(" << OperandExpr << "))";
380   }
381 
382   unsigned countRendererFns() const override {
383     return 1;
384   }
385 };
386 
387 /// Generates code to check that an operand is in a particular register bank.
388 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
389 protected:
390   const CodeGenRegisterClass &RC;
391 
392 public:
393   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
394       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
395 
396   static bool classof(const OperandPredicateMatcher *P) {
397     return P->getKind() == OPM_RegBank;
398   }
399 
400   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
401                             StringRef OperandExpr) const override {
402     OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
403        << "RegClass) == RBI.getRegBank(" << OperandExpr
404        << ".getReg(), MRI, TRI))";
405   }
406 };
407 
408 /// Generates code to check that an operand is a basic block.
409 class MBBOperandMatcher : public OperandPredicateMatcher {
410 public:
411   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
412 
413   static bool classof(const OperandPredicateMatcher *P) {
414     return P->getKind() == OPM_MBB;
415   }
416 
417   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
418                             StringRef OperandExpr) const override {
419     OS << OperandExpr << ".isMBB()";
420   }
421 };
422 
423 /// Generates code to check that an operand is a G_CONSTANT with a particular
424 /// int.
425 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
426 protected:
427   int64_t Value;
428 
429 public:
430   ConstantIntOperandMatcher(int64_t Value)
431       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
432 
433   static bool classof(const OperandPredicateMatcher *P) {
434     return P->getKind() == OPM_Int;
435   }
436 
437   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
438                             StringRef OperandExpr) const override {
439     OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
440   }
441 };
442 
443 /// Generates code to check that an operand is a raw int (where MO.isImm() or
444 /// MO.isCImm() is true).
445 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
446 protected:
447   int64_t Value;
448 
449 public:
450   LiteralIntOperandMatcher(int64_t Value)
451       : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
452 
453   static bool classof(const OperandPredicateMatcher *P) {
454     return P->getKind() == OPM_LiteralInt;
455   }
456 
457   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
458                             StringRef OperandExpr) const override {
459     OS << OperandExpr << ".isCImm() && " << OperandExpr
460        << ".getCImm()->equalsInt(" << Value << ")";
461   }
462 };
463 
464 /// Generates code to check that a set of predicates match for a particular
465 /// operand.
466 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
467 protected:
468   InstructionMatcher &Insn;
469   unsigned OpIdx;
470   std::string SymbolicName;
471 
472   /// The index of the first temporary variable allocated to this operand. The
473   /// number of allocated temporaries can be found with
474   /// countRendererFns().
475   unsigned AllocatedTemporariesBaseID;
476 
477 public:
478   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
479                  const std::string &SymbolicName,
480                  unsigned AllocatedTemporariesBaseID)
481       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
482         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
483 
484   bool hasSymbolicName() const { return !SymbolicName.empty(); }
485   const StringRef getSymbolicName() const { return SymbolicName; }
486   void setSymbolicName(StringRef Name) {
487     assert(SymbolicName.empty() && "Operand already has a symbolic name");
488     SymbolicName = Name;
489   }
490   unsigned getOperandIndex() const { return OpIdx; }
491 
492   std::string getOperandExpr(StringRef InsnVarName) const {
493     return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
494   }
495 
496   Optional<const OperandMatcher *>
497   getOptionalOperand(StringRef DesiredSymbolicName) const {
498     assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
499     if (DesiredSymbolicName == SymbolicName)
500       return this;
501     for (const auto &OP : predicates()) {
502       const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
503       if (MaybeOperand.hasValue())
504         return MaybeOperand.getValue();
505     }
506     return None;
507   }
508 
509   InstructionMatcher &getInstructionMatcher() const { return Insn; }
510 
511   /// Emit C++ statements to capture instructions into local variables.
512   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
513                            StringRef OperandExpr) const {
514     for (const auto &Predicate : predicates())
515       Predicate->emitCxxCaptureStmts(OS, Rule, OperandExpr);
516   }
517 
518   /// Emit a C++ expression that tests whether the instruction named in
519   /// InsnVarName matches all the predicate and all the operands.
520   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
521                             StringRef InsnVarName) const {
522     OS << "(/* ";
523     if (SymbolicName.empty())
524       OS << "Operand " << OpIdx;
525     else
526       OS << SymbolicName;
527     OS << " */ ";
528     emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName));
529     OS << ")";
530   }
531 
532   /// Compare the priority of this object and B.
533   ///
534   /// Returns true if this object is more important than B.
535   bool isHigherPriorityThan(const OperandMatcher &B) const {
536     // Operand matchers involving more predicates have higher priority.
537     if (predicates_size() > B.predicates_size())
538       return true;
539     if (predicates_size() < B.predicates_size())
540       return false;
541 
542     // This assumes that predicates are added in a consistent order.
543     for (const auto &Predicate : zip(predicates(), B.predicates())) {
544       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
545         return true;
546       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
547         return false;
548     }
549 
550     return false;
551   };
552 
553   /// Report the maximum number of temporary operands needed by the operand
554   /// matcher.
555   unsigned countRendererFns() const {
556     return std::accumulate(
557         predicates().begin(), predicates().end(), 0,
558         [](unsigned A,
559            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
560           return A + Predicate->countRendererFns();
561         });
562   }
563 
564   unsigned getAllocatedTemporariesBaseID() const {
565     return AllocatedTemporariesBaseID;
566   }
567 };
568 
569 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
570   return Operand.getAllocatedTemporariesBaseID();
571 }
572 
573 /// Generates code to check a predicate on an instruction.
574 ///
575 /// Typical predicates include:
576 /// * The opcode of the instruction is a particular value.
577 /// * The nsw/nuw flag is/isn't set.
578 class InstructionPredicateMatcher {
579 protected:
580   /// This enum is used for RTTI and also defines the priority that is given to
581   /// the predicate when generating the matcher code. Kinds with higher priority
582   /// must be tested first.
583   enum PredicateKind {
584     IPM_Opcode,
585   };
586 
587   PredicateKind Kind;
588 
589 public:
590   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
591   virtual ~InstructionPredicateMatcher() {}
592 
593   PredicateKind getKind() const { return Kind; }
594 
595   /// Emit a C++ expression that tests whether the instruction named in
596   /// InsnVarName matches the predicate.
597   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
598                                     StringRef InsnVarName) const = 0;
599 
600   /// Compare the priority of this object and B.
601   ///
602   /// Returns true if this object is more important than B.
603   virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
604     return Kind < B.Kind;
605   };
606 
607   /// Report the maximum number of temporary operands needed by the predicate
608   /// matcher.
609   virtual unsigned countRendererFns() const { return 0; }
610 };
611 
612 /// Generates code to check the opcode of an instruction.
613 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
614 protected:
615   const CodeGenInstruction *I;
616 
617 public:
618   InstructionOpcodeMatcher(const CodeGenInstruction *I)
619       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
620 
621   static bool classof(const InstructionPredicateMatcher *P) {
622     return P->getKind() == IPM_Opcode;
623   }
624 
625   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
626                             StringRef InsnVarName) const override {
627     OS << InsnVarName << ".getOpcode() == " << I->Namespace
628        << "::" << I->TheDef->getName();
629   }
630 
631   /// Compare the priority of this object and B.
632   ///
633   /// Returns true if this object is more important than B.
634   bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
635     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
636       return true;
637     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
638       return false;
639 
640     // Prioritize opcodes for cosmetic reasons in the generated source. Although
641     // this is cosmetic at the moment, we may want to drive a similar ordering
642     // using instruction frequency information to improve compile time.
643     if (const InstructionOpcodeMatcher *BO =
644             dyn_cast<InstructionOpcodeMatcher>(&B))
645       return I->TheDef->getName() < BO->I->TheDef->getName();
646 
647     return false;
648   };
649 };
650 
651 /// Generates code to check that a set of predicates and operands match for a
652 /// particular instruction.
653 ///
654 /// Typical predicates include:
655 /// * Has a specific opcode.
656 /// * Has an nsw/nuw flag or doesn't.
657 class InstructionMatcher
658     : public PredicateListMatcher<InstructionPredicateMatcher> {
659 protected:
660   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
661 
662   /// The operands to match. All rendered operands must be present even if the
663   /// condition is always true.
664   OperandVec Operands;
665 
666 public:
667   /// Add an operand to the matcher.
668   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
669                              unsigned AllocatedTemporariesBaseID) {
670     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
671                                              AllocatedTemporariesBaseID));
672     return *Operands.back();
673   }
674 
675   OperandMatcher &getOperand(unsigned OpIdx) {
676     auto I = std::find_if(Operands.begin(), Operands.end(),
677                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
678                             return X->getOperandIndex() == OpIdx;
679                           });
680     if (I != Operands.end())
681       return **I;
682     llvm_unreachable("Failed to lookup operand");
683   }
684 
685   Optional<const OperandMatcher *>
686   getOptionalOperand(StringRef SymbolicName) const {
687     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
688     for (const auto &Operand : Operands) {
689       const auto &OM = Operand->getOptionalOperand(SymbolicName);
690       if (OM.hasValue())
691         return OM.getValue();
692     }
693     return None;
694   }
695 
696   const OperandMatcher &getOperand(StringRef SymbolicName) const {
697     Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
698     if (OM.hasValue())
699       return *OM.getValue();
700     llvm_unreachable("Failed to lookup operand");
701   }
702 
703   unsigned getNumOperands() const { return Operands.size(); }
704   OperandVec::iterator operands_begin() { return Operands.begin(); }
705   OperandVec::iterator operands_end() { return Operands.end(); }
706   iterator_range<OperandVec::iterator> operands() {
707     return make_range(operands_begin(), operands_end());
708   }
709   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
710   OperandVec::const_iterator operands_end() const { return Operands.end(); }
711   iterator_range<OperandVec::const_iterator> operands() const {
712     return make_range(operands_begin(), operands_end());
713   }
714 
715   /// Emit C++ statements to check the shape of the match and capture
716   /// instructions into local variables.
717   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) {
718     OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n"
719        << "  return false;\n";
720     for (const auto &Operand : Operands) {
721       Operand->emitCxxCaptureStmts(OS, Rule, Operand->getOperandExpr(Expr));
722     }
723   }
724 
725   /// Emit a C++ expression that tests whether the instruction named in
726   /// InsnVarName matches all the predicates and all the operands.
727   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
728                             StringRef InsnVarName) const {
729     emitCxxPredicateListExpr(OS, Rule, InsnVarName);
730     for (const auto &Operand : Operands) {
731       OS << " &&\n(";
732       Operand->emitCxxPredicateExpr(OS, Rule, InsnVarName);
733       OS << ")";
734     }
735   }
736 
737   /// Compare the priority of this object and B.
738   ///
739   /// Returns true if this object is more important than B.
740   bool isHigherPriorityThan(const InstructionMatcher &B) const {
741     // Instruction matchers involving more operands have higher priority.
742     if (Operands.size() > B.Operands.size())
743       return true;
744     if (Operands.size() < B.Operands.size())
745       return false;
746 
747     for (const auto &Predicate : zip(predicates(), B.predicates())) {
748       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
749         return true;
750       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
751         return false;
752     }
753 
754     for (const auto &Operand : zip(Operands, B.Operands)) {
755       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
756         return true;
757       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
758         return false;
759     }
760 
761     return false;
762   };
763 
764   /// Report the maximum number of temporary operands needed by the instruction
765   /// matcher.
766   unsigned countRendererFns() const {
767     return std::accumulate(predicates().begin(), predicates().end(), 0,
768                            [](unsigned A,
769                               const std::unique_ptr<InstructionPredicateMatcher>
770                                   &Predicate) {
771                              return A + Predicate->countRendererFns();
772                            }) +
773            std::accumulate(
774                Operands.begin(), Operands.end(), 0,
775                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
776                  return A + Operand->countRendererFns();
777                });
778   }
779 };
780 
781 /// Generates code to check that the operand is a register defined by an
782 /// instruction that matches the given instruction matcher.
783 ///
784 /// For example, the pattern:
785 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
786 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
787 /// the:
788 ///   (G_ADD $src1, $src2)
789 /// subpattern.
790 class InstructionOperandMatcher : public OperandPredicateMatcher {
791 protected:
792   std::unique_ptr<InstructionMatcher> InsnMatcher;
793 
794 public:
795   InstructionOperandMatcher()
796       : OperandPredicateMatcher(OPM_Instruction),
797         InsnMatcher(new InstructionMatcher()) {}
798 
799   static bool classof(const OperandPredicateMatcher *P) {
800     return P->getKind() == OPM_Instruction;
801   }
802 
803   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
804 
805   Optional<const OperandMatcher *>
806   getOptionalOperand(StringRef SymbolicName) const override {
807     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
808     return InsnMatcher->getOptionalOperand(SymbolicName);
809   }
810 
811   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
812                            StringRef OperandExpr) const override {
813     OS << "if (!" << OperandExpr + ".isReg())\n"
814        << "  return false;\n"
815        << "if (TRI.isPhysicalRegister(" << OperandExpr + ".getReg()))\n"
816        << "  return false;\n";
817     std::string InsnVarName = Rule.defineInsnVar(
818         OS, *InsnMatcher,
819         ("*MRI.getVRegDef(" + OperandExpr + ".getReg())").str());
820     InsnMatcher->emitCxxCaptureStmts(OS, Rule, InsnVarName);
821   }
822 
823   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
824                             StringRef OperandExpr) const override {
825     OperandExpr = Rule.getInsnVarName(*InsnMatcher);
826     OS << "(";
827     InsnMatcher->emitCxxPredicateExpr(OS, Rule, OperandExpr);
828     OS << ")\n";
829   }
830 };
831 
832 //===- Actions ------------------------------------------------------------===//
833 class OperandRenderer {
834 public:
835   enum RendererKind { OR_Copy, OR_Imm, OR_Register, OR_ComplexPattern };
836 
837 protected:
838   RendererKind Kind;
839 
840 public:
841   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
842   virtual ~OperandRenderer() {}
843 
844   RendererKind getKind() const { return Kind; }
845 
846   virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
847 };
848 
849 /// A CopyRenderer emits code to copy a single operand from an existing
850 /// instruction to the one being built.
851 class CopyRenderer : public OperandRenderer {
852 protected:
853   /// The matcher for the instruction that this operand is copied from.
854   /// This provides the facility for looking up an a operand by it's name so
855   /// that it can be used as a source for the instruction being built.
856   const InstructionMatcher &Matched;
857   /// The name of the operand.
858   const StringRef SymbolicName;
859 
860 public:
861   CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
862       : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
863   }
864 
865   static bool classof(const OperandRenderer *R) {
866     return R->getKind() == OR_Copy;
867   }
868 
869   const StringRef getSymbolicName() const { return SymbolicName; }
870 
871   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
872     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
873     StringRef InsnVarName =
874         Rule.getInsnVarName(Operand.getInstructionMatcher());
875     std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
876     OS << "    MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
877   }
878 };
879 
880 /// Adds a specific physical register to the instruction being built.
881 /// This is typically useful for WZR/XZR on AArch64.
882 class AddRegisterRenderer : public OperandRenderer {
883 protected:
884   const Record *RegisterDef;
885 
886 public:
887   AddRegisterRenderer(const Record *RegisterDef)
888       : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
889 
890   static bool classof(const OperandRenderer *R) {
891     return R->getKind() == OR_Register;
892   }
893 
894   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
895     OS << "    MIB.addReg(" << (RegisterDef->getValue("Namespace")
896                                     ? RegisterDef->getValueAsString("Namespace")
897                                     : "")
898        << "::" << RegisterDef->getName() << ");\n";
899   }
900 };
901 
902 /// Adds a specific immediate to the instruction being built.
903 class ImmRenderer : public OperandRenderer {
904 protected:
905   int64_t Imm;
906 
907 public:
908   ImmRenderer(int64_t Imm)
909       : OperandRenderer(OR_Imm), Imm(Imm) {}
910 
911   static bool classof(const OperandRenderer *R) {
912     return R->getKind() == OR_Imm;
913   }
914 
915   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
916     OS << "    MIB.addImm(" << Imm << ");\n";
917   }
918 };
919 
920 /// Adds operands by calling a renderer function supplied by the ComplexPattern
921 /// matcher function.
922 class RenderComplexPatternOperand : public OperandRenderer {
923 private:
924   const Record &TheDef;
925   /// The name of the operand.
926   const StringRef SymbolicName;
927   /// The renderer number. This must be unique within a rule since it's used to
928   /// identify a temporary variable to hold the renderer function.
929   unsigned RendererID;
930 
931   unsigned getNumOperands() const {
932     return TheDef.getValueAsDag("Operands")->getNumArgs();
933   }
934 
935 public:
936   RenderComplexPatternOperand(const Record &TheDef, StringRef SymbolicName,
937                               unsigned RendererID)
938       : OperandRenderer(OR_ComplexPattern), TheDef(TheDef),
939         SymbolicName(SymbolicName), RendererID(RendererID) {}
940 
941   static bool classof(const OperandRenderer *R) {
942     return R->getKind() == OR_ComplexPattern;
943   }
944 
945   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
946     OS << "Renderer" << RendererID << "(MIB);\n";
947   }
948 };
949 
950 /// An action taken when all Matcher predicates succeeded for a parent rule.
951 ///
952 /// Typical actions include:
953 /// * Changing the opcode of an instruction.
954 /// * Adding an operand to an instruction.
955 class MatchAction {
956 public:
957   virtual ~MatchAction() {}
958 
959   /// Emit the C++ statements to implement the action.
960   ///
961   /// \param RecycleVarName If given, it's an instruction to recycle. The
962   ///                       requirements on the instruction vary from action to
963   ///                       action.
964   virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
965                                   StringRef RecycleVarName) const = 0;
966 };
967 
968 /// Generates a comment describing the matched rule being acted upon.
969 class DebugCommentAction : public MatchAction {
970 private:
971   const PatternToMatch &P;
972 
973 public:
974   DebugCommentAction(const PatternToMatch &P) : P(P) {}
975 
976   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
977                           StringRef RecycleVarName) const override {
978     OS << "// " << *P.getSrcPattern() << "  =>  " << *P.getDstPattern() << "\n";
979   }
980 };
981 
982 /// Generates code to build an instruction or mutate an existing instruction
983 /// into the desired instruction when this is possible.
984 class BuildMIAction : public MatchAction {
985 private:
986   std::string Name;
987   const CodeGenInstruction *I;
988   const InstructionMatcher &Matched;
989   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
990 
991   /// True if the instruction can be built solely by mutating the opcode.
992   bool canMutate() const {
993     if (OperandRenderers.size() != Matched.getNumOperands())
994       return false;
995 
996     for (const auto &Renderer : enumerate(OperandRenderers)) {
997       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
998         const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
999         if (&Matched != &OM.getInstructionMatcher() ||
1000             OM.getOperandIndex() != Renderer.index())
1001           return false;
1002       } else
1003         return false;
1004     }
1005 
1006     return true;
1007   }
1008 
1009 public:
1010   BuildMIAction(const StringRef Name, const CodeGenInstruction *I,
1011                 const InstructionMatcher &Matched)
1012       : Name(Name), I(I), Matched(Matched) {}
1013 
1014   template <class Kind, class... Args>
1015   Kind &addRenderer(Args&&... args) {
1016     OperandRenderers.emplace_back(
1017         llvm::make_unique<Kind>(std::forward<Args>(args)...));
1018     return *static_cast<Kind *>(OperandRenderers.back().get());
1019   }
1020 
1021   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1022                           StringRef RecycleVarName) const override {
1023     if (canMutate()) {
1024       OS << "    " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
1025          << "::" << I->TheDef->getName() << "));\n";
1026 
1027       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1028         OS << "    auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
1029            << ");\n";
1030 
1031         for (auto Def : I->ImplicitDefs) {
1032           auto Namespace = Def->getValue("Namespace")
1033                                ? Def->getValueAsString("Namespace")
1034                                : "";
1035           OS << "    MIB.addDef(" << Namespace << "::" << Def->getName()
1036              << ", RegState::Implicit);\n";
1037         }
1038         for (auto Use : I->ImplicitUses) {
1039           auto Namespace = Use->getValue("Namespace")
1040                                ? Use->getValueAsString("Namespace")
1041                                : "";
1042           OS << "    MIB.addUse(" << Namespace << "::" << Use->getName()
1043              << ", RegState::Implicit);\n";
1044         }
1045       }
1046 
1047       OS << "    MachineInstr &" << Name << " = " << RecycleVarName << ";\n";
1048       return;
1049     }
1050 
1051     // TODO: Simple permutation looks like it could be almost as common as
1052     //       mutation due to commutative operations.
1053 
1054     OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
1055           "I.getDebugLoc(), TII.get("
1056        << I->Namespace << "::" << I->TheDef->getName() << "));\n";
1057     for (const auto &Renderer : OperandRenderers)
1058       Renderer->emitCxxRenderStmts(OS, Rule);
1059     OS << "    for (const auto *FromMI : ";
1060     Rule.emitCxxCapturedInsnList(OS);
1061     OS << ")\n";
1062     OS << "      for (const auto &MMO : FromMI->memoperands())\n";
1063     OS << "        MIB.addMemOperand(MMO);\n";
1064     OS << "    " << RecycleVarName << ".eraseFromParent();\n";
1065     OS << "    MachineInstr &" << Name << " = *MIB;\n";
1066   }
1067 };
1068 
1069 /// Generates code to constrain the operands of an output instruction to the
1070 /// register classes specified by the definition of that instruction.
1071 class ConstrainOperandsToDefinitionAction : public MatchAction {
1072   std::string Name;
1073 
1074 public:
1075   ConstrainOperandsToDefinitionAction(const StringRef Name) : Name(Name) {}
1076 
1077   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1078                           StringRef RecycleVarName) const override {
1079     OS << "      constrainSelectedInstRegOperands(" << Name << ", TII, TRI, RBI);\n";
1080   }
1081 };
1082 
1083 /// Generates code to constrain the specified operand of an output instruction
1084 /// to the specified register class.
1085 class ConstrainOperandToRegClassAction : public MatchAction {
1086   std::string Name;
1087   unsigned OpIdx;
1088   const CodeGenRegisterClass &RC;
1089 
1090 public:
1091   ConstrainOperandToRegClassAction(const StringRef Name, unsigned OpIdx,
1092                                    const CodeGenRegisterClass &RC)
1093       : Name(Name), OpIdx(OpIdx), RC(RC) {}
1094 
1095   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1096                           StringRef RecycleVarName) const override {
1097     OS << "      constrainOperandRegToRegClass(" << Name << ", " << OpIdx
1098        << ", " << RC.getQualifiedName() << "RegClass, TII, TRI, RBI);\n";
1099   }
1100 };
1101 
1102 InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1103   Matchers.emplace_back(new InstructionMatcher());
1104   return *Matchers.back();
1105 }
1106 
1107 void RuleMatcher::addRequiredFeature(Record *Feature) {
1108   RequiredFeatures.push_back(Feature);
1109 }
1110 
1111 template <class Kind, class... Args>
1112 Kind &RuleMatcher::addAction(Args &&... args) {
1113   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1114   return *static_cast<Kind *>(Actions.back().get());
1115 }
1116 
1117 std::string RuleMatcher::defineInsnVar(raw_ostream &OS,
1118                                        const InstructionMatcher &Matcher,
1119                                        StringRef Value) {
1120   std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++);
1121   OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n";
1122   InsnVariableNames[&Matcher] = InsnVarName;
1123   return InsnVarName;
1124 }
1125 
1126 StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const {
1127   const auto &I = InsnVariableNames.find(&InsnMatcher);
1128   if (I != InsnVariableNames.end())
1129     return I->second;
1130   llvm_unreachable("Matched Insn was not captured in a local variable");
1131 }
1132 
1133 /// Emit a C++ initializer_list containing references to every matched instruction.
1134 void RuleMatcher::emitCxxCapturedInsnList(raw_ostream &OS) {
1135   SmallVector<StringRef, 2> Names;
1136   for (const auto &Pair : InsnVariableNames)
1137     Names.push_back(Pair.second);
1138   std::sort(Names.begin(), Names.end());
1139 
1140   OS << "{";
1141   for (const auto &Name : Names)
1142     OS << "&" << Name << ", ";
1143   OS << "}";
1144 }
1145 
1146 /// Emit C++ statements to check the shape of the match and capture
1147 /// instructions into local variables.
1148 void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) {
1149   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1150   std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr);
1151   Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName);
1152 }
1153 
1154 void RuleMatcher::emit(raw_ostream &OS,
1155                        SubtargetFeatureInfoMap SubtargetFeatures) {
1156   if (Matchers.empty())
1157     llvm_unreachable("Unexpected empty matcher!");
1158 
1159   // The representation supports rules that require multiple roots such as:
1160   //    %ptr(p0) = ...
1161   //    %elt0(s32) = G_LOAD %ptr
1162   //    %1(p0) = G_ADD %ptr, 4
1163   //    %elt1(s32) = G_LOAD p0 %1
1164   // which could be usefully folded into:
1165   //    %ptr(p0) = ...
1166   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1167   // on some targets but we don't need to make use of that yet.
1168   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1169 
1170   OS << "if (";
1171   OS << "[&]() {\n";
1172   if (!RequiredFeatures.empty()) {
1173     OS << "  PredicateBitset ExpectedFeatures = {";
1174     StringRef Separator = "";
1175     for (const auto &Predicate : RequiredFeatures) {
1176       const auto &I = SubtargetFeatures.find(Predicate);
1177       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
1178       OS << Separator << I->second.getEnumBitName();
1179       Separator = ", ";
1180     }
1181     OS << "};\n";
1182     OS << "if ((AvailableFeatures & ExpectedFeatures) != ExpectedFeatures)\n"
1183        << "  return false;\n";
1184   }
1185 
1186   emitCxxCaptureStmts(OS, "I");
1187 
1188   OS << "    if (";
1189   Matchers.front()->emitCxxPredicateExpr(OS, *this,
1190                                          getInsnVarName(*Matchers.front()));
1191   OS << ") {\n";
1192 
1193   // We must also check if it's safe to fold the matched instructions.
1194   if (InsnVariableNames.size() >= 2) {
1195     // Invert the map to create stable ordering (by var names)
1196     SmallVector<StringRef, 2> Names;
1197     for (const auto &Pair : InsnVariableNames) {
1198       // Skip the root node since it isn't moving anywhere. Everything else is
1199       // sinking to meet it.
1200       if (Pair.first == Matchers.front().get())
1201         continue;
1202 
1203       Names.push_back(Pair.second);
1204     }
1205     std::sort(Names.begin(), Names.end());
1206 
1207     for (const auto &Name : Names) {
1208       // Reject the difficult cases until we have a more accurate check.
1209       OS << "      if (!isObviouslySafeToFold(" << Name
1210          << ")) return false;\n";
1211 
1212       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1213       //        account for unsafe cases.
1214       //
1215       //        Example:
1216       //          MI1--> %0 = ...
1217       //                 %1 = ... %0
1218       //          MI0--> %2 = ... %0
1219       //          It's not safe to erase MI1. We currently handle this by not
1220       //          erasing %0 (even when it's dead).
1221       //
1222       //        Example:
1223       //          MI1--> %0 = load volatile @a
1224       //                 %1 = load volatile @a
1225       //          MI0--> %2 = ... %0
1226       //          It's not safe to sink %0's def past %1. We currently handle
1227       //          this by rejecting all loads.
1228       //
1229       //        Example:
1230       //          MI1--> %0 = load @a
1231       //                 %1 = store @a
1232       //          MI0--> %2 = ... %0
1233       //          It's not safe to sink %0's def past %1. We currently handle
1234       //          this by rejecting all loads.
1235       //
1236       //        Example:
1237       //                   G_CONDBR %cond, @BB1
1238       //                 BB0:
1239       //          MI1-->   %0 = load @a
1240       //                   G_BR @BB1
1241       //                 BB1:
1242       //          MI0-->   %2 = ... %0
1243       //          It's not always safe to sink %0 across control flow. In this
1244       //          case it may introduce a memory fault. We currentl handle this
1245       //          by rejecting all loads.
1246     }
1247   }
1248 
1249   for (const auto &MA : Actions) {
1250     MA->emitCxxActionStmts(OS, *this, "I");
1251   }
1252 
1253   OS << "      return true;\n";
1254   OS << "    }\n";
1255   OS << "    return false;\n";
1256   OS << "  }()) { return true; }\n\n";
1257 }
1258 
1259 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1260   // Rules involving more match roots have higher priority.
1261   if (Matchers.size() > B.Matchers.size())
1262     return true;
1263   if (Matchers.size() < B.Matchers.size())
1264     return false;
1265 
1266   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1267     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1268       return true;
1269     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1270       return false;
1271   }
1272 
1273   return false;
1274 }
1275 
1276 unsigned RuleMatcher::countRendererFns() const {
1277   return std::accumulate(
1278       Matchers.begin(), Matchers.end(), 0,
1279       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1280         return A + Matcher->countRendererFns();
1281       });
1282 }
1283 
1284 //===- GlobalISelEmitter class --------------------------------------------===//
1285 
1286 class GlobalISelEmitter {
1287 public:
1288   explicit GlobalISelEmitter(RecordKeeper &RK);
1289   void run(raw_ostream &OS);
1290 
1291 private:
1292   const RecordKeeper &RK;
1293   const CodeGenDAGPatterns CGP;
1294   const CodeGenTarget &Target;
1295 
1296   /// Keep track of the equivalence between SDNodes and Instruction.
1297   /// This is defined using 'GINodeEquiv' in the target description.
1298   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1299 
1300   /// Keep track of the equivalence between ComplexPattern's and
1301   /// GIComplexOperandMatcher. Map entries are specified by subclassing
1302   /// GIComplexPatternEquiv.
1303   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1304 
1305   // Map of predicates to their subtarget features.
1306   SubtargetFeatureInfoMap SubtargetFeatures;
1307 
1308   void gatherNodeEquivs();
1309   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1310 
1311   Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
1312   Expected<InstructionMatcher &>
1313   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1314                                const TreePatternNode *Src) const;
1315   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1316                            const TreePatternNode *SrcChild, unsigned OpIdx,
1317                            unsigned &TempOpIdx) const;
1318   Expected<BuildMIAction &> createAndImportInstructionRenderer(
1319       RuleMatcher &M, const TreePatternNode *Dst,
1320       const InstructionMatcher &InsnMatcher) const;
1321   Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1322                                   TreePatternNode *DstChild,
1323                                   const InstructionMatcher &InsnMatcher) const;
1324   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1325                                       DagInit *DefaultOps) const;
1326   Error
1327   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1328                              const std::vector<Record *> &ImplicitDefs) const;
1329 
1330   /// Analyze pattern \p P, returning a matcher for it if possible.
1331   /// Otherwise, return an Error explaining why we don't support it.
1332   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1333 
1334   void declareSubtargetFeature(Record *Predicate);
1335 };
1336 
1337 void GlobalISelEmitter::gatherNodeEquivs() {
1338   assert(NodeEquivs.empty());
1339   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1340     NodeEquivs[Equiv->getValueAsDef("Node")] =
1341         &Target.getInstruction(Equiv->getValueAsDef("I"));
1342 
1343   assert(ComplexPatternEquivs.empty());
1344   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1345     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1346     if (!SelDAGEquiv)
1347       continue;
1348     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1349  }
1350 }
1351 
1352 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1353   return NodeEquivs.lookup(N);
1354 }
1355 
1356 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1357     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
1358 
1359 //===- Emitter ------------------------------------------------------------===//
1360 
1361 Error
1362 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1363                                         ArrayRef<Init *> Predicates) {
1364   for (const Init *Predicate : Predicates) {
1365     const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1366     declareSubtargetFeature(PredicateDef->getDef());
1367     M.addRequiredFeature(PredicateDef->getDef());
1368   }
1369 
1370   return Error::success();
1371 }
1372 
1373 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
1374     InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const {
1375   // Start with the defined operands (i.e., the results of the root operator).
1376   if (Src->getExtTypes().size() > 1)
1377     return failedImport("Src pattern has multiple results");
1378 
1379   if (Src->isLeaf()) {
1380     Init *SrcInit = Src->getLeafValue();
1381     if (isa<IntInit>(SrcInit)) {
1382       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1383           &Target.getInstruction(RK.getDef("G_CONSTANT")));
1384     } else
1385       return failedImport("Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1386   } else {
1387     auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1388     if (!SrcGIOrNull)
1389       return failedImport("Pattern operator lacks an equivalent Instruction" +
1390                           explainOperator(Src->getOperator()));
1391     auto &SrcGI = *SrcGIOrNull;
1392 
1393     // The operators look good: match the opcode
1394     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1395   }
1396 
1397   unsigned OpIdx = 0;
1398   unsigned TempOpIdx = 0;
1399   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1400     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1401 
1402     if (!OpTyOrNone)
1403       return failedImport(
1404           "Result of Src pattern operator has an unsupported type");
1405 
1406     // Results don't have a name unless they are the root node. The caller will
1407     // set the name if appropriate.
1408     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1409     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1410   }
1411 
1412   if (Src->isLeaf()) {
1413     Init *SrcInit = Src->getLeafValue();
1414     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1415       OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1416       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1417     } else
1418       return failedImport("Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1419   } else {
1420     // Match the used operands (i.e. the children of the operator).
1421     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1422       if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i),
1423                                           OpIdx++, TempOpIdx))
1424         return std::move(Error);
1425     }
1426   }
1427 
1428   return InsnMatcher;
1429 }
1430 
1431 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
1432                                             const TreePatternNode *SrcChild,
1433                                             unsigned OpIdx,
1434                                             unsigned &TempOpIdx) const {
1435   OperandMatcher &OM =
1436       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
1437 
1438   if (SrcChild->hasAnyPredicate())
1439     return failedImport("Src pattern child has predicate (" +
1440                         explainPredicates(SrcChild) + ")");
1441 
1442   ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1443   if (ChildTypes.size() != 1)
1444     return failedImport("Src pattern child has multiple results");
1445 
1446   // Check MBB's before the type check since they are not a known type.
1447   if (!SrcChild->isLeaf()) {
1448     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1449       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1450       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1451         OM.addPredicate<MBBOperandMatcher>();
1452         return Error::success();
1453       }
1454     }
1455   }
1456 
1457   auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1458   if (!OpTyOrNone)
1459     return failedImport("Src operand has an unsupported type");
1460   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1461 
1462   // Check for nested instructions.
1463   if (!SrcChild->isLeaf()) {
1464     // Map the node to a gMIR instruction.
1465     InstructionOperandMatcher &InsnOperand =
1466         OM.addPredicate<InstructionOperandMatcher>();
1467     auto InsnMatcherOrError =
1468         createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild);
1469     if (auto Error = InsnMatcherOrError.takeError())
1470       return Error;
1471 
1472     return Error::success();
1473   }
1474 
1475   // Check for constant immediates.
1476   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1477     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
1478     return Error::success();
1479   }
1480 
1481   // Check for def's like register classes or ComplexPattern's.
1482   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1483     auto *ChildRec = ChildDefInit->getDef();
1484 
1485     // Check for register classes.
1486     if (ChildRec->isSubClassOf("RegisterClass") ||
1487         ChildRec->isSubClassOf("RegisterOperand")) {
1488       OM.addPredicate<RegisterBankOperandMatcher>(
1489           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
1490       return Error::success();
1491     }
1492 
1493     // Check for ComplexPattern's.
1494     if (ChildRec->isSubClassOf("ComplexPattern")) {
1495       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1496       if (ComplexPattern == ComplexPatternEquivs.end())
1497         return failedImport("SelectionDAG ComplexPattern (" +
1498                             ChildRec->getName() + ") not mapped to GlobalISel");
1499 
1500       OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1501                                                     *ComplexPattern->second);
1502       TempOpIdx++;
1503       return Error::success();
1504     }
1505 
1506     if (ChildRec->isSubClassOf("ImmLeaf")) {
1507       return failedImport(
1508           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1509     }
1510 
1511     return failedImport(
1512         "Src pattern child def is an unsupported tablegen class");
1513   }
1514 
1515   return failedImport("Src pattern child is an unsupported kind");
1516 }
1517 
1518 Error GlobalISelEmitter::importExplicitUseRenderer(
1519     BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
1520     const InstructionMatcher &InsnMatcher) const {
1521   // The only non-leaf child we accept is 'bb': it's an operator because
1522   // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1523   if (!DstChild->isLeaf()) {
1524     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1525       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1526       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1527         DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
1528                                                DstChild->getName());
1529         return Error::success();
1530       }
1531     }
1532     return failedImport("Dst pattern child isn't a leaf node or an MBB");
1533   }
1534 
1535   // Otherwise, we're looking for a bog-standard RegisterClass operand.
1536   if (DstChild->hasAnyPredicate())
1537     return failedImport("Dst pattern child has predicate (" +
1538                         explainPredicates(DstChild) + ")");
1539 
1540   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1541     auto *ChildRec = ChildDefInit->getDef();
1542 
1543     ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1544     if (ChildTypes.size() != 1)
1545       return failedImport("Dst pattern child has multiple results");
1546 
1547     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1548     if (!OpTyOrNone)
1549       return failedImport("Dst operand has an unsupported type");
1550 
1551     if (ChildRec->isSubClassOf("Register")) {
1552       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
1553       return Error::success();
1554     }
1555 
1556     if (ChildRec->isSubClassOf("RegisterClass") ||
1557         ChildRec->isSubClassOf("RegisterOperand")) {
1558       DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName());
1559       return Error::success();
1560     }
1561 
1562     if (ChildRec->isSubClassOf("ComplexPattern")) {
1563       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1564       if (ComplexPattern == ComplexPatternEquivs.end())
1565         return failedImport(
1566             "SelectionDAG ComplexPattern not mapped to GlobalISel");
1567 
1568       const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
1569       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1570           *ComplexPattern->second, DstChild->getName(),
1571           OM.getAllocatedTemporariesBaseID());
1572       return Error::success();
1573     }
1574 
1575     if (ChildRec->isSubClassOf("SDNodeXForm"))
1576       return failedImport("Dst pattern child def is an unsupported tablegen "
1577                           "class (SDNodeXForm)");
1578 
1579     return failedImport(
1580         "Dst pattern child def is an unsupported tablegen class");
1581   }
1582 
1583   return failedImport("Dst pattern child is an unsupported kind");
1584 }
1585 
1586 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
1587     RuleMatcher &M, const TreePatternNode *Dst,
1588     const InstructionMatcher &InsnMatcher) const {
1589   Record *DstOp = Dst->getOperator();
1590   if (!DstOp->isSubClassOf("Instruction")) {
1591     if (DstOp->isSubClassOf("ValueType"))
1592       return failedImport(
1593           "Pattern operator isn't an instruction (it's a ValueType)");
1594     return failedImport("Pattern operator isn't an instruction");
1595   }
1596   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
1597 
1598   unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
1599   unsigned ExpectedDstINumUses = Dst->getNumChildren();
1600 
1601   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
1602   // attached.
1603   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
1604     DstI = &Target.getInstruction(RK.getDef("COPY"));
1605     DstINumUses--; // Ignore the class constraint.
1606     ExpectedDstINumUses--;
1607   }
1608 
1609   auto &DstMIBuilder = M.addAction<BuildMIAction>("NewI", DstI, InsnMatcher);
1610 
1611   // Render the explicit defs.
1612   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
1613     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
1614     DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
1615   }
1616 
1617   // Render the explicit uses.
1618   unsigned Child = 0;
1619   unsigned NumDefaultOps = 0;
1620   for (unsigned I = 0; I != DstINumUses; ++I) {
1621     const CGIOperandList::OperandInfo &DstIOperand =
1622         DstI->Operands[DstI->Operands.NumDefs + I];
1623 
1624     // If the operand has default values, introduce them now.
1625     // FIXME: Until we have a decent test case that dictates we should do
1626     // otherwise, we're going to assume that operands with default values cannot
1627     // be specified in the patterns. Therefore, adding them will not cause us to
1628     // end up with too many rendered operands.
1629     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
1630       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
1631       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
1632         return std::move(Error);
1633       ++NumDefaultOps;
1634       continue;
1635     }
1636 
1637     if (auto Error = importExplicitUseRenderer(
1638             DstMIBuilder, Dst->getChild(Child), InsnMatcher))
1639       return std::move(Error);
1640     ++Child;
1641   }
1642 
1643   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
1644     return failedImport("Expected " + llvm::to_string(DstINumUses) +
1645                         " used operands but found " +
1646                         llvm::to_string(ExpectedDstINumUses) +
1647                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
1648                         " default ones");
1649 
1650   return DstMIBuilder;
1651 }
1652 
1653 Error GlobalISelEmitter::importDefaultOperandRenderers(
1654     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
1655   for (const auto *DefaultOp : DefaultOps->getArgs()) {
1656     // Look through ValueType operators.
1657     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
1658       if (const DefInit *DefaultDagOperator =
1659               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
1660         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
1661           DefaultOp = DefaultDagOp->getArg(0);
1662       }
1663     }
1664 
1665     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
1666       DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
1667       continue;
1668     }
1669 
1670     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
1671       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
1672       continue;
1673     }
1674 
1675     return failedImport("Could not add default op");
1676   }
1677 
1678   return Error::success();
1679 }
1680 
1681 Error GlobalISelEmitter::importImplicitDefRenderers(
1682     BuildMIAction &DstMIBuilder,
1683     const std::vector<Record *> &ImplicitDefs) const {
1684   if (!ImplicitDefs.empty())
1685     return failedImport("Pattern defines a physical register");
1686   return Error::success();
1687 }
1688 
1689 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
1690   // Keep track of the matchers and actions to emit.
1691   RuleMatcher M;
1692   M.addAction<DebugCommentAction>(P);
1693 
1694   if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
1695     return std::move(Error);
1696 
1697   // Next, analyze the pattern operators.
1698   TreePatternNode *Src = P.getSrcPattern();
1699   TreePatternNode *Dst = P.getDstPattern();
1700 
1701   // If the root of either pattern isn't a simple operator, ignore it.
1702   if (auto Err = isTrivialOperatorNode(Dst))
1703     return failedImport("Dst pattern root isn't a trivial operator (" +
1704                         toString(std::move(Err)) + ")");
1705   if (auto Err = isTrivialOperatorNode(Src))
1706     return failedImport("Src pattern root isn't a trivial operator (" +
1707                         toString(std::move(Err)) + ")");
1708 
1709   if (Dst->isLeaf())
1710     return failedImport("Dst pattern root isn't a known leaf");
1711 
1712   // Start with the defined operands (i.e., the results of the root operator).
1713   Record *DstOp = Dst->getOperator();
1714   if (!DstOp->isSubClassOf("Instruction"))
1715     return failedImport("Pattern operator isn't an instruction");
1716 
1717   auto &DstI = Target.getInstruction(DstOp);
1718   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
1719     return failedImport("Src pattern results and dst MI defs are different (" +
1720                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
1721                         to_string(DstI.Operands.NumDefs) + " def(s))");
1722 
1723   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
1724   auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src);
1725   if (auto Error = InsnMatcherOrError.takeError())
1726     return std::move(Error);
1727   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
1728 
1729   // The root of the match also has constraints on the register bank so that it
1730   // matches the result instruction.
1731   unsigned OpIdx = 0;
1732   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1733     (void)Ty;
1734 
1735     const auto &DstIOperand = DstI.Operands[OpIdx];
1736     Record *DstIOpRec = DstIOperand.Rec;
1737     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1738       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1739 
1740       if (DstIOpRec == nullptr)
1741         return failedImport(
1742             "COPY_TO_REGCLASS operand #1 isn't a register class");
1743     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
1744       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
1745     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
1746       return failedImport("Dst MI def isn't a register class" + to_string(*Dst));
1747 
1748     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
1749     OM.setSymbolicName(DstIOperand.Name);
1750     OM.addPredicate<RegisterBankOperandMatcher>(
1751         Target.getRegisterClass(DstIOpRec));
1752     ++OpIdx;
1753   }
1754 
1755   auto DstMIBuilderOrError =
1756       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
1757   if (auto Error = DstMIBuilderOrError.takeError())
1758     return std::move(Error);
1759   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
1760 
1761   // Render the implicit defs.
1762   // These are only added to the root of the result.
1763   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
1764     return std::move(Error);
1765 
1766   // Constrain the registers to classes. This is normally derived from the
1767   // emitted instruction but a few instructions require special handling.
1768   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1769     // COPY_TO_REGCLASS does not provide operand constraints itself but the
1770     // result is constrained to the class given by the second child.
1771     Record *DstIOpRec =
1772         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1773 
1774     if (DstIOpRec == nullptr)
1775       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
1776 
1777     M.addAction<ConstrainOperandToRegClassAction>(
1778         "NewI", 0, Target.getRegisterClass(DstIOpRec));
1779   } else
1780     M.addAction<ConstrainOperandsToDefinitionAction>("NewI");
1781 
1782   // We're done with this pattern!  It's eligible for GISel emission; return it.
1783   ++NumPatternImported;
1784   return std::move(M);
1785 }
1786 
1787 void GlobalISelEmitter::run(raw_ostream &OS) {
1788   // Track the GINodeEquiv definitions.
1789   gatherNodeEquivs();
1790 
1791   emitSourceFileHeader(("Global Instruction Selector for the " +
1792                        Target.getName() + " target").str(), OS);
1793   std::vector<RuleMatcher> Rules;
1794   // Look through the SelectionDAG patterns we found, possibly emitting some.
1795   for (const PatternToMatch &Pat : CGP.ptms()) {
1796     ++NumPatternTotal;
1797     auto MatcherOrErr = runOnPattern(Pat);
1798 
1799     // The pattern analysis can fail, indicating an unsupported pattern.
1800     // Report that if we've been asked to do so.
1801     if (auto Err = MatcherOrErr.takeError()) {
1802       if (WarnOnSkippedPatterns) {
1803         PrintWarning(Pat.getSrcRecord()->getLoc(),
1804                      "Skipped pattern: " + toString(std::move(Err)));
1805       } else {
1806         consumeError(std::move(Err));
1807       }
1808       ++NumPatternImportsSkipped;
1809       continue;
1810     }
1811 
1812     Rules.push_back(std::move(MatcherOrErr.get()));
1813   }
1814 
1815   std::stable_sort(Rules.begin(), Rules.end(),
1816             [&](const RuleMatcher &A, const RuleMatcher &B) {
1817               if (A.isHigherPriorityThan(B)) {
1818                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
1819                                                      "and less important at "
1820                                                      "the same time");
1821                 return true;
1822               }
1823               return false;
1824             });
1825 
1826   unsigned MaxTemporaries = 0;
1827   for (const auto &Rule : Rules)
1828     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
1829 
1830   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
1831      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
1832      << ";\n"
1833      << "using PredicateBitset = "
1834         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
1835      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
1836 
1837   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n";
1838   for (unsigned I = 0; I < MaxTemporaries; ++I)
1839     OS << "  mutable ComplexRendererFn Renderer" << I << ";\n";
1840   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
1841 
1842   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n";
1843   for (unsigned I = 0; I < MaxTemporaries; ++I)
1844     OS << ", Renderer" << I << "(nullptr)\n";
1845   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
1846 
1847   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
1848   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
1849                                                            OS);
1850 
1851   // Separate subtarget features by how often they must be recomputed.
1852   SubtargetFeatureInfoMap ModuleFeatures;
1853   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1854                std::inserter(ModuleFeatures, ModuleFeatures.end()),
1855                [](const SubtargetFeatureInfoMap::value_type &X) {
1856                  return !X.second.mustRecomputePerFunction();
1857                });
1858   SubtargetFeatureInfoMap FunctionFeatures;
1859   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1860                std::inserter(FunctionFeatures, FunctionFeatures.end()),
1861                [](const SubtargetFeatureInfoMap::value_type &X) {
1862                  return X.second.mustRecomputePerFunction();
1863                });
1864 
1865   SubtargetFeatureInfo::emitComputeAvailableFeatures(
1866       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
1867       ModuleFeatures, OS);
1868   SubtargetFeatureInfo::emitComputeAvailableFeatures(
1869       Target.getName(), "InstructionSelector",
1870       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
1871       "const MachineFunction *MF");
1872 
1873   OS << "bool " << Target.getName()
1874      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
1875      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
1876      << "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
1877      << "  // FIXME: This should be computed on a per-function basis rather than per-insn.\n"
1878      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, &MF);\n"
1879      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n";
1880 
1881   for (auto &Rule : Rules) {
1882     Rule.emit(OS, SubtargetFeatures);
1883     ++NumPatternEmitted;
1884   }
1885 
1886   OS << "  return false;\n"
1887      << "}\n"
1888      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
1889 
1890   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
1891      << "PredicateBitset AvailableModuleFeatures;\n"
1892      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
1893      << "PredicateBitset getAvailableFeatures() const {\n"
1894      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
1895      << "}\n"
1896      << "PredicateBitset\n"
1897      << "computeAvailableModuleFeatures(const " << Target.getName()
1898      << "Subtarget *Subtarget) const;\n"
1899      << "PredicateBitset\n"
1900      << "computeAvailableFunctionFeatures(const " << Target.getName()
1901      << "Subtarget *Subtarget,\n"
1902      << "                                 const MachineFunction *MF) const;\n"
1903      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
1904 
1905   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
1906      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
1907      << "AvailableFunctionFeatures()\n"
1908      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
1909 }
1910 
1911 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
1912   if (SubtargetFeatures.count(Predicate) == 0)
1913     SubtargetFeatures.emplace(
1914         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
1915 }
1916 
1917 } // end anonymous namespace
1918 
1919 //===----------------------------------------------------------------------===//
1920 
1921 namespace llvm {
1922 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
1923   GlobalISelEmitter(RK).run(OS);
1924 }
1925 } // End llvm namespace
1926