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   std::string getCxxEnumValue() const {
78     std::string Str;
79     raw_string_ostream OS(Str);
80 
81     emitCxxEnumValue(OS);
82     return OS.str();
83   }
84 
85   void emitCxxEnumValue(raw_ostream &OS) const {
86     if (Ty.isScalar()) {
87       OS << "GILLT_s" << Ty.getSizeInBits();
88       return;
89     }
90     if (Ty.isVector()) {
91       OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
92       return;
93     }
94     llvm_unreachable("Unhandled LLT");
95   }
96 
97   void emitCxxConstructorCall(raw_ostream &OS) const {
98     if (Ty.isScalar()) {
99       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
100       return;
101     }
102     if (Ty.isVector()) {
103       OS << "LLT::vector(" << Ty.getNumElements() << ", "
104          << Ty.getScalarSizeInBits() << ")";
105       return;
106     }
107     llvm_unreachable("Unhandled LLT");
108   }
109 
110   const LLT &get() const { return Ty; }
111 
112   /// This ordering is used for std::unique() and std::sort(). There's no
113   /// particular logic behind the order but either A < B or B < A must be
114   /// true if A != B.
115   bool operator<(const LLTCodeGen &Other) const {
116     if (Ty.isValid() != Other.Ty.isValid())
117       return Ty.isValid() < Other.Ty.isValid();
118     if (!Ty.isValid())
119       return false;
120 
121     if (Ty.isVector() != Other.Ty.isVector())
122       return Ty.isVector() < Other.Ty.isVector();
123     if (Ty.isScalar() != Other.Ty.isScalar())
124       return Ty.isScalar() < Other.Ty.isScalar();
125     if (Ty.isPointer() != Other.Ty.isPointer())
126       return Ty.isPointer() < Other.Ty.isPointer();
127 
128     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
129       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
130 
131     if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
132       return Ty.getNumElements() < Other.Ty.getNumElements();
133 
134     return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
135   }
136 };
137 
138 class InstructionMatcher;
139 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
140 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
141 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
142   MVT VT(SVT);
143   if (VT.isVector() && VT.getVectorNumElements() != 1)
144     return LLTCodeGen(
145         LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
146   if (VT.isInteger() || VT.isFloatingPoint())
147     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
148   return None;
149 }
150 
151 static std::string explainPredicates(const TreePatternNode *N) {
152   std::string Explanation = "";
153   StringRef Separator = "";
154   for (const auto &P : N->getPredicateFns()) {
155     Explanation +=
156         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
157     if (P.isAlwaysTrue())
158       Explanation += " always-true";
159     if (P.isImmediatePattern())
160       Explanation += " immediate";
161   }
162   return Explanation;
163 }
164 
165 std::string explainOperator(Record *Operator) {
166   if (Operator->isSubClassOf("SDNode"))
167     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
168 
169   if (Operator->isSubClassOf("Intrinsic"))
170     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
171 
172   return " (Operator not understood)";
173 }
174 
175 /// Helper function to let the emitter report skip reason error messages.
176 static Error failedImport(const Twine &Reason) {
177   return make_error<StringError>(Reason, inconvertibleErrorCode());
178 }
179 
180 static Error isTrivialOperatorNode(const TreePatternNode *N) {
181   std::string Explanation = "";
182   std::string Separator = "";
183 
184   bool HasUnsupportedPredicate = false;
185   for (const auto &Predicate : N->getPredicateFns()) {
186     if (Predicate.isAlwaysTrue())
187       continue;
188 
189     if (Predicate.isImmediatePattern())
190       continue;
191 
192     HasUnsupportedPredicate = true;
193     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
194     Separator = ", ";
195     break;
196   }
197 
198   if (N->getTransformFn()) {
199     Explanation += Separator + "Has a transform function";
200     Separator = ", ";
201   }
202 
203   if (!HasUnsupportedPredicate && !N->getTransformFn())
204     return Error::success();
205 
206   return failedImport(Explanation);
207 }
208 
209 static Record *getInitValueAsRegClass(Init *V) {
210   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
211     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
212       return VDefInit->getDef()->getValueAsDef("RegClass");
213     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
214       return VDefInit->getDef();
215   }
216   return nullptr;
217 }
218 
219 std::string
220 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
221   std::string Name = "GIFBS";
222   for (const auto &Feature : FeatureBitset)
223     Name += ("_" + Feature->getName()).str();
224   return Name;
225 }
226 
227 //===- MatchTable Helpers -------------------------------------------------===//
228 
229 class MatchTable;
230 
231 /// A record to be stored in a MatchTable.
232 ///
233 /// This class represents any and all output that may be required to emit the
234 /// MatchTable. Instances  are most often configured to represent an opcode or
235 /// value that will be emitted to the table with some formatting but it can also
236 /// represent commas, comments, and other formatting instructions.
237 struct MatchTableRecord {
238   enum RecordFlagsBits {
239     MTRF_None = 0x0,
240     /// Causes EmitStr to be formatted as comment when emitted.
241     MTRF_Comment = 0x1,
242     /// Causes the record value to be followed by a comma when emitted.
243     MTRF_CommaFollows = 0x2,
244     /// Causes the record value to be followed by a line break when emitted.
245     MTRF_LineBreakFollows = 0x4,
246     /// Indicates that the record defines a label and causes an additional
247     /// comment to be emitted containing the index of the label.
248     MTRF_Label = 0x8,
249     /// Causes the record to be emitted as the index of the label specified by
250     /// LabelID along with a comment indicating where that label is.
251     MTRF_JumpTarget = 0x10,
252     /// Causes the formatter to add a level of indentation before emitting the
253     /// record.
254     MTRF_Indent = 0x20,
255     /// Causes the formatter to remove a level of indentation after emitting the
256     /// record.
257     MTRF_Outdent = 0x40,
258   };
259 
260   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
261   /// reference or define.
262   unsigned LabelID;
263   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
264   /// value, a label name.
265   std::string EmitStr;
266 
267 private:
268   /// The number of MatchTable elements described by this record. Comments are 0
269   /// while values are typically 1. Values >1 may occur when we need to emit
270   /// values that exceed the size of a MatchTable element.
271   unsigned NumElements;
272 
273 public:
274   /// A bitfield of RecordFlagsBits flags.
275   unsigned Flags;
276 
277   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
278                    unsigned NumElements, unsigned Flags)
279       : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
280         EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
281     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
282            "This value is reserved for non-labels");
283   }
284 
285   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
286             const MatchTable &Table) const;
287   unsigned size() const { return NumElements; }
288 };
289 
290 /// Holds the contents of a generated MatchTable to enable formatting and the
291 /// necessary index tracking needed to support GIM_Try.
292 class MatchTable {
293   /// An unique identifier for the table. The generated table will be named
294   /// MatchTable${ID}.
295   unsigned ID;
296   /// The records that make up the table. Also includes comments describing the
297   /// values being emitted and line breaks to format it.
298   std::vector<MatchTableRecord> Contents;
299   /// The currently defined labels.
300   DenseMap<unsigned, unsigned> LabelMap;
301   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
302   unsigned CurrentSize;
303 
304   /// A unique identifier for a MatchTable label.
305   static unsigned CurrentLabelID;
306 
307 public:
308   static MatchTableRecord LineBreak;
309   static MatchTableRecord Comment(StringRef Comment) {
310     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
311   }
312   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
313     unsigned ExtraFlags = 0;
314     if (IndentAdjust > 0)
315       ExtraFlags |= MatchTableRecord::MTRF_Indent;
316     if (IndentAdjust < 0)
317       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
318 
319     return MatchTableRecord(None, Opcode, 1,
320                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
321   }
322   static MatchTableRecord NamedValue(StringRef NamedValue) {
323     return MatchTableRecord(None, NamedValue, 1,
324                             MatchTableRecord::MTRF_CommaFollows);
325   }
326   static MatchTableRecord NamedValue(StringRef Namespace,
327                                      StringRef NamedValue) {
328     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
329                             MatchTableRecord::MTRF_CommaFollows);
330   }
331   static MatchTableRecord IntValue(int64_t IntValue) {
332     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
333                             MatchTableRecord::MTRF_CommaFollows);
334   }
335   static MatchTableRecord Label(unsigned LabelID) {
336     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
337                             MatchTableRecord::MTRF_Label |
338                                 MatchTableRecord::MTRF_Comment |
339                                 MatchTableRecord::MTRF_LineBreakFollows);
340   }
341   static MatchTableRecord JumpTarget(unsigned LabelID) {
342     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
343                             MatchTableRecord::MTRF_JumpTarget |
344                                 MatchTableRecord::MTRF_Comment |
345                                 MatchTableRecord::MTRF_CommaFollows);
346   }
347 
348   MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
349 
350   void push_back(const MatchTableRecord &Value) {
351     if (Value.Flags & MatchTableRecord::MTRF_Label)
352       defineLabel(Value.LabelID);
353     Contents.push_back(Value);
354     CurrentSize += Value.size();
355   }
356 
357   unsigned allocateLabelID() const { return CurrentLabelID++; }
358 
359   void defineLabel(unsigned LabelID) {
360     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
361   }
362 
363   unsigned getLabelIndex(unsigned LabelID) const {
364     const auto I = LabelMap.find(LabelID);
365     assert(I != LabelMap.end() && "Use of undeclared label");
366     return I->second;
367   }
368 
369   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
370 
371   void emitDeclaration(raw_ostream &OS) const {
372     unsigned Indentation = 4;
373     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
374     LineBreak.emit(OS, true, *this);
375     OS << std::string(Indentation, ' ');
376 
377     for (auto I = Contents.begin(), E = Contents.end(); I != E;
378          ++I) {
379       bool LineBreakIsNext = false;
380       const auto &NextI = std::next(I);
381 
382       if (NextI != E) {
383         if (NextI->EmitStr == "" &&
384             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
385           LineBreakIsNext = true;
386       }
387 
388       if (I->Flags & MatchTableRecord::MTRF_Indent)
389         Indentation += 2;
390 
391       I->emit(OS, LineBreakIsNext, *this);
392       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
393         OS << std::string(Indentation, ' ');
394 
395       if (I->Flags & MatchTableRecord::MTRF_Outdent)
396         Indentation -= 2;
397     }
398     OS << "};\n";
399   }
400 };
401 
402 unsigned MatchTable::CurrentLabelID = 0;
403 
404 MatchTableRecord MatchTable::LineBreak = {
405     None, "" /* Emit String */, 0 /* Elements */,
406     MatchTableRecord::MTRF_LineBreakFollows};
407 
408 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
409                             const MatchTable &Table) const {
410   bool UseLineComment =
411       LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
412   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
413     UseLineComment = false;
414 
415   if (Flags & MTRF_Comment)
416     OS << (UseLineComment ? "// " : "/*");
417 
418   OS << EmitStr;
419   if (Flags & MTRF_Label)
420     OS << ": @" << Table.getLabelIndex(LabelID);
421 
422   if (Flags & MTRF_Comment && !UseLineComment)
423     OS << "*/";
424 
425   if (Flags & MTRF_JumpTarget) {
426     if (Flags & MTRF_Comment)
427       OS << " ";
428     OS << Table.getLabelIndex(LabelID);
429   }
430 
431   if (Flags & MTRF_CommaFollows) {
432     OS << ",";
433     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
434       OS << " ";
435   }
436 
437   if (Flags & MTRF_LineBreakFollows)
438     OS << "\n";
439 }
440 
441 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
442   Table.push_back(Value);
443   return Table;
444 }
445 
446 //===- Matchers -----------------------------------------------------------===//
447 
448 class OperandMatcher;
449 class MatchAction;
450 
451 /// Generates code to check that a match rule matches.
452 class RuleMatcher {
453   /// A list of matchers that all need to succeed for the current rule to match.
454   /// FIXME: This currently supports a single match position but could be
455   /// extended to support multiple positions to support div/rem fusion or
456   /// load-multiple instructions.
457   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
458 
459   /// A list of actions that need to be taken when all predicates in this rule
460   /// have succeeded.
461   std::vector<std::unique_ptr<MatchAction>> Actions;
462 
463   typedef std::map<const InstructionMatcher *, unsigned>
464       DefinedInsnVariablesMap;
465   /// A map of instruction matchers to the local variables created by
466   /// emitCaptureOpcodes().
467   DefinedInsnVariablesMap InsnVariableIDs;
468 
469   /// ID for the next instruction variable defined with defineInsnVar()
470   unsigned NextInsnVarID;
471 
472   std::vector<Record *> RequiredFeatures;
473 
474 public:
475   RuleMatcher()
476       : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
477   RuleMatcher(RuleMatcher &&Other) = default;
478   RuleMatcher &operator=(RuleMatcher &&Other) = default;
479 
480   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
481   void addRequiredFeature(Record *Feature);
482   const std::vector<Record *> &getRequiredFeatures() const;
483 
484   template <class Kind, class... Args> Kind &addAction(Args &&... args);
485 
486   /// Define an instruction without emitting any code to do so.
487   /// This is used for the root of the match.
488   unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
489   /// Define an instruction and emit corresponding state-machine opcodes.
490   unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
491                          unsigned InsnVarID, unsigned OpIdx);
492   unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
493   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
494     return InsnVariableIDs.begin();
495   }
496   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
497     return InsnVariableIDs.end();
498   }
499   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
500   defined_insn_vars() const {
501     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
502   }
503 
504   const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
505 
506   void emitCaptureOpcodes(MatchTable &Table);
507 
508   void emit(MatchTable &Table);
509 
510   /// Compare the priority of this object and B.
511   ///
512   /// Returns true if this object is more important than B.
513   bool isHigherPriorityThan(const RuleMatcher &B) const;
514 
515   /// Report the maximum number of temporary operands needed by the rule
516   /// matcher.
517   unsigned countRendererFns() const;
518 
519   // FIXME: Remove this as soon as possible
520   InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
521 };
522 
523 template <class PredicateTy> class PredicateListMatcher {
524 private:
525   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
526   PredicateVec Predicates;
527 
528   /// Template instantiations should specialize this to return a string to use
529   /// for the comment emitted when there are no predicates.
530   std::string getNoPredicateComment() const;
531 
532 public:
533   /// Construct a new operand predicate and add it to the matcher.
534   template <class Kind, class... Args>
535   Kind &addPredicate(Args&&... args) {
536     Predicates.emplace_back(
537         llvm::make_unique<Kind>(std::forward<Args>(args)...));
538     return *static_cast<Kind *>(Predicates.back().get());
539   }
540 
541   typename PredicateVec::const_iterator predicates_begin() const {
542     return Predicates.begin();
543   }
544   typename PredicateVec::const_iterator predicates_end() const {
545     return Predicates.end();
546   }
547   iterator_range<typename PredicateVec::const_iterator> predicates() const {
548     return make_range(predicates_begin(), predicates_end());
549   }
550   typename PredicateVec::size_type predicates_size() const {
551     return Predicates.size();
552   }
553 
554   /// Emit MatchTable opcodes that tests whether all the predicates are met.
555   template <class... Args>
556   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
557     if (Predicates.empty()) {
558       Table << MatchTable::Comment(getNoPredicateComment())
559             << MatchTable::LineBreak;
560       return;
561     }
562 
563     for (const auto &Predicate : predicates())
564       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
565   }
566 };
567 
568 /// Generates code to check a predicate of an operand.
569 ///
570 /// Typical predicates include:
571 /// * Operand is a particular register.
572 /// * Operand is assigned a particular register bank.
573 /// * Operand is an MBB.
574 class OperandPredicateMatcher {
575 public:
576   /// This enum is used for RTTI and also defines the priority that is given to
577   /// the predicate when generating the matcher code. Kinds with higher priority
578   /// must be tested first.
579   ///
580   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
581   /// but OPM_Int must have priority over OPM_RegBank since constant integers
582   /// are represented by a virtual register defined by a G_CONSTANT instruction.
583   enum PredicateKind {
584     OPM_ComplexPattern,
585     OPM_IntrinsicID,
586     OPM_Instruction,
587     OPM_Int,
588     OPM_LiteralInt,
589     OPM_LLT,
590     OPM_RegBank,
591     OPM_MBB,
592   };
593 
594 protected:
595   PredicateKind Kind;
596 
597 public:
598   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
599   virtual ~OperandPredicateMatcher() {}
600 
601   PredicateKind getKind() const { return Kind; }
602 
603   /// Return the OperandMatcher for the specified operand or nullptr if there
604   /// isn't one by that name in this operand predicate matcher.
605   ///
606   /// InstructionOperandMatcher is the only subclass that can return non-null
607   /// for this.
608   virtual Optional<const OperandMatcher *>
609   getOptionalOperand(StringRef SymbolicName) const {
610     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
611     return None;
612   }
613 
614   /// Emit MatchTable opcodes to capture instructions into the MIs table.
615   ///
616   /// Only InstructionOperandMatcher needs to do anything for this method the
617   /// rest just walk the tree.
618   virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
619                                   unsigned InsnVarID, unsigned OpIdx) const {}
620 
621   /// Emit MatchTable opcodes that check the predicate for the given operand.
622   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
623                                     unsigned InsnVarID,
624                                     unsigned OpIdx) const = 0;
625 
626   /// Compare the priority of this object and B.
627   ///
628   /// Returns true if this object is more important than B.
629   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
630 
631   /// Report the maximum number of temporary operands needed by the predicate
632   /// matcher.
633   virtual unsigned countRendererFns() const { return 0; }
634 };
635 
636 template <>
637 std::string
638 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
639   return "No operand predicates";
640 }
641 
642 /// Generates code to check that an operand is a particular LLT.
643 class LLTOperandMatcher : public OperandPredicateMatcher {
644 protected:
645   LLTCodeGen Ty;
646 
647 public:
648   static std::set<LLTCodeGen> KnownTypes;
649 
650   LLTOperandMatcher(const LLTCodeGen &Ty)
651       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {
652     KnownTypes.insert(Ty);
653   }
654 
655   static bool classof(const OperandPredicateMatcher *P) {
656     return P->getKind() == OPM_LLT;
657   }
658 
659   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
660                             unsigned InsnVarID, unsigned OpIdx) const override {
661     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
662           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
663           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
664           << MatchTable::NamedValue(Ty.getCxxEnumValue())
665           << MatchTable::LineBreak;
666   }
667 };
668 
669 std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
670 
671 /// Generates code to check that an operand is a particular target constant.
672 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
673 protected:
674   const OperandMatcher &Operand;
675   const Record &TheDef;
676 
677   unsigned getAllocatedTemporariesBaseID() const;
678 
679 public:
680   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
681                                const Record &TheDef)
682       : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
683         TheDef(TheDef) {}
684 
685   static bool classof(const OperandPredicateMatcher *P) {
686     return P->getKind() == OPM_ComplexPattern;
687   }
688 
689   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
690                             unsigned InsnVarID, unsigned OpIdx) const override {
691     unsigned ID = getAllocatedTemporariesBaseID();
692     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
693           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
694           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
695           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
696           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
697           << MatchTable::LineBreak;
698   }
699 
700   unsigned countRendererFns() const override {
701     return 1;
702   }
703 };
704 
705 /// Generates code to check that an operand is in a particular register bank.
706 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
707 protected:
708   const CodeGenRegisterClass &RC;
709 
710 public:
711   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
712       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
713 
714   static bool classof(const OperandPredicateMatcher *P) {
715     return P->getKind() == OPM_RegBank;
716   }
717 
718   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
719                             unsigned InsnVarID, unsigned OpIdx) const override {
720     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
721           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
722           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
723           << MatchTable::Comment("RC")
724           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
725           << MatchTable::LineBreak;
726   }
727 };
728 
729 /// Generates code to check that an operand is a basic block.
730 class MBBOperandMatcher : public OperandPredicateMatcher {
731 public:
732   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
733 
734   static bool classof(const OperandPredicateMatcher *P) {
735     return P->getKind() == OPM_MBB;
736   }
737 
738   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
739                             unsigned InsnVarID, unsigned OpIdx) const override {
740     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
741           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
742           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
743   }
744 };
745 
746 /// Generates code to check that an operand is a G_CONSTANT with a particular
747 /// int.
748 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
749 protected:
750   int64_t Value;
751 
752 public:
753   ConstantIntOperandMatcher(int64_t Value)
754       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
755 
756   static bool classof(const OperandPredicateMatcher *P) {
757     return P->getKind() == OPM_Int;
758   }
759 
760   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
761                             unsigned InsnVarID, unsigned OpIdx) const override {
762     Table << MatchTable::Opcode("GIM_CheckConstantInt")
763           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
764           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
765           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
766   }
767 };
768 
769 /// Generates code to check that an operand is a raw int (where MO.isImm() or
770 /// MO.isCImm() is true).
771 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
772 protected:
773   int64_t Value;
774 
775 public:
776   LiteralIntOperandMatcher(int64_t Value)
777       : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
778 
779   static bool classof(const OperandPredicateMatcher *P) {
780     return P->getKind() == OPM_LiteralInt;
781   }
782 
783   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
784                             unsigned InsnVarID, unsigned OpIdx) const override {
785     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
786           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
787           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
788           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
789   }
790 };
791 
792 /// Generates code to check that an operand is an intrinsic ID.
793 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
794 protected:
795   const CodeGenIntrinsic *II;
796 
797 public:
798   IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
799       : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
800 
801   static bool classof(const OperandPredicateMatcher *P) {
802     return P->getKind() == OPM_IntrinsicID;
803   }
804 
805   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
806                             unsigned InsnVarID, unsigned OpIdx) const override {
807     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
808           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
809           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
810           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
811           << MatchTable::LineBreak;
812   }
813 };
814 
815 /// Generates code to check that a set of predicates match for a particular
816 /// operand.
817 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
818 protected:
819   InstructionMatcher &Insn;
820   unsigned OpIdx;
821   std::string SymbolicName;
822 
823   /// The index of the first temporary variable allocated to this operand. The
824   /// number of allocated temporaries can be found with
825   /// countRendererFns().
826   unsigned AllocatedTemporariesBaseID;
827 
828 public:
829   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
830                  const std::string &SymbolicName,
831                  unsigned AllocatedTemporariesBaseID)
832       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
833         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
834 
835   bool hasSymbolicName() const { return !SymbolicName.empty(); }
836   const StringRef getSymbolicName() const { return SymbolicName; }
837   void setSymbolicName(StringRef Name) {
838     assert(SymbolicName.empty() && "Operand already has a symbolic name");
839     SymbolicName = Name;
840   }
841   unsigned getOperandIndex() const { return OpIdx; }
842 
843   std::string getOperandExpr(unsigned InsnVarID) const {
844     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
845            llvm::to_string(OpIdx) + ")";
846   }
847 
848   Optional<const OperandMatcher *>
849   getOptionalOperand(StringRef DesiredSymbolicName) const {
850     assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
851     if (DesiredSymbolicName == SymbolicName)
852       return this;
853     for (const auto &OP : predicates()) {
854       const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
855       if (MaybeOperand.hasValue())
856         return MaybeOperand.getValue();
857     }
858     return None;
859   }
860 
861   InstructionMatcher &getInstructionMatcher() const { return Insn; }
862 
863   /// Emit MatchTable opcodes to capture instructions into the MIs table.
864   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
865                           unsigned InsnVarID) const {
866     for (const auto &Predicate : predicates())
867       Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
868   }
869 
870   /// Emit MatchTable opcodes that test whether the instruction named in
871   /// InsnVarID matches all the predicates and all the operands.
872   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
873                             unsigned InsnVarID) const {
874     std::string Comment;
875     raw_string_ostream CommentOS(Comment);
876     CommentOS << "MIs[" << InsnVarID << "] ";
877     if (SymbolicName.empty())
878       CommentOS << "Operand " << OpIdx;
879     else
880       CommentOS << SymbolicName;
881     Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
882 
883     emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
884   }
885 
886   /// Compare the priority of this object and B.
887   ///
888   /// Returns true if this object is more important than B.
889   bool isHigherPriorityThan(const OperandMatcher &B) const {
890     // Operand matchers involving more predicates have higher priority.
891     if (predicates_size() > B.predicates_size())
892       return true;
893     if (predicates_size() < B.predicates_size())
894       return false;
895 
896     // This assumes that predicates are added in a consistent order.
897     for (const auto &Predicate : zip(predicates(), B.predicates())) {
898       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
899         return true;
900       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
901         return false;
902     }
903 
904     return false;
905   };
906 
907   /// Report the maximum number of temporary operands needed by the operand
908   /// matcher.
909   unsigned countRendererFns() const {
910     return std::accumulate(
911         predicates().begin(), predicates().end(), 0,
912         [](unsigned A,
913            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
914           return A + Predicate->countRendererFns();
915         });
916   }
917 
918   unsigned getAllocatedTemporariesBaseID() const {
919     return AllocatedTemporariesBaseID;
920   }
921 };
922 
923 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
924   return Operand.getAllocatedTemporariesBaseID();
925 }
926 
927 /// Generates code to check a predicate on an instruction.
928 ///
929 /// Typical predicates include:
930 /// * The opcode of the instruction is a particular value.
931 /// * The nsw/nuw flag is/isn't set.
932 class InstructionPredicateMatcher {
933 protected:
934   /// This enum is used for RTTI and also defines the priority that is given to
935   /// the predicate when generating the matcher code. Kinds with higher priority
936   /// must be tested first.
937   enum PredicateKind {
938     IPM_Opcode,
939     IPM_ImmPredicate,
940   };
941 
942   PredicateKind Kind;
943 
944 public:
945   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
946   virtual ~InstructionPredicateMatcher() {}
947 
948   PredicateKind getKind() const { return Kind; }
949 
950   /// Emit MatchTable opcodes that test whether the instruction named in
951   /// InsnVarID matches the predicate.
952   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
953                                     unsigned InsnVarID) const = 0;
954 
955   /// Compare the priority of this object and B.
956   ///
957   /// Returns true if this object is more important than B.
958   virtual bool
959   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
960     return Kind < B.Kind;
961   };
962 
963   /// Report the maximum number of temporary operands needed by the predicate
964   /// matcher.
965   virtual unsigned countRendererFns() const { return 0; }
966 };
967 
968 template <>
969 std::string
970 PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
971   return "No instruction predicates";
972 }
973 
974 /// Generates code to check the opcode of an instruction.
975 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
976 protected:
977   const CodeGenInstruction *I;
978 
979 public:
980   InstructionOpcodeMatcher(const CodeGenInstruction *I)
981       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
982 
983   static bool classof(const InstructionPredicateMatcher *P) {
984     return P->getKind() == IPM_Opcode;
985   }
986 
987   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
988                             unsigned InsnVarID) const override {
989     Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
990           << MatchTable::IntValue(InsnVarID)
991           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
992           << MatchTable::LineBreak;
993   }
994 
995   /// Compare the priority of this object and B.
996   ///
997   /// Returns true if this object is more important than B.
998   bool
999   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1000     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1001       return true;
1002     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1003       return false;
1004 
1005     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1006     // this is cosmetic at the moment, we may want to drive a similar ordering
1007     // using instruction frequency information to improve compile time.
1008     if (const InstructionOpcodeMatcher *BO =
1009             dyn_cast<InstructionOpcodeMatcher>(&B))
1010       return I->TheDef->getName() < BO->I->TheDef->getName();
1011 
1012     return false;
1013   };
1014 
1015   bool isConstantInstruction() const {
1016     return I->TheDef->getName() == "G_CONSTANT";
1017   }
1018 };
1019 
1020 /// Generates code to check that this instruction is a constant whose value
1021 /// meets an immediate predicate.
1022 ///
1023 /// Immediates are slightly odd since they are typically used like an operand
1024 /// but are represented as an operator internally. We typically write simm8:$src
1025 /// in a tablegen pattern, but this is just syntactic sugar for
1026 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1027 /// that will be matched and the predicate (which is attached to the imm
1028 /// operator) that will be tested. In SelectionDAG this describes a
1029 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1030 ///
1031 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1032 /// this representation, the immediate could be tested with an
1033 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1034 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1035 /// there are two implementation issues with producing that matcher
1036 /// configuration from the SelectionDAG pattern:
1037 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1038 ///   were we to sink the immediate predicate to the operand we would have to
1039 ///   have two partial implementations of PatFrag support, one for immediates
1040 ///   and one for non-immediates.
1041 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1042 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1043 ///   would also have to complicate (or duplicate) the code that descends and
1044 ///   creates matchers for the subtree.
1045 /// Overall, it's simpler to handle it in the place it was found.
1046 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1047 protected:
1048   TreePredicateFn Predicate;
1049 
1050 public:
1051   InstructionImmPredicateMatcher(const TreePredicateFn &Predicate)
1052       : InstructionPredicateMatcher(IPM_ImmPredicate), Predicate(Predicate) {}
1053 
1054   static bool classof(const InstructionPredicateMatcher *P) {
1055     return P->getKind() == IPM_ImmPredicate;
1056   }
1057 
1058   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1059                             unsigned InsnVarID) const override {
1060     Table << MatchTable::Opcode("GIM_CheckImmPredicate")
1061           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1062           << MatchTable::Comment("Predicate")
1063           << MatchTable::NamedValue("GIPFP_" + Predicate.getFnName())
1064           << MatchTable::LineBreak;
1065   }
1066 };
1067 
1068 /// Generates code to check that a set of predicates and operands match for a
1069 /// particular instruction.
1070 ///
1071 /// Typical predicates include:
1072 /// * Has a specific opcode.
1073 /// * Has an nsw/nuw flag or doesn't.
1074 class InstructionMatcher
1075     : public PredicateListMatcher<InstructionPredicateMatcher> {
1076 protected:
1077   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
1078 
1079   /// The operands to match. All rendered operands must be present even if the
1080   /// condition is always true.
1081   OperandVec Operands;
1082 
1083   std::string SymbolicName;
1084 
1085 public:
1086   InstructionMatcher(StringRef SymbolicName) : SymbolicName(SymbolicName) {}
1087 
1088   /// Add an operand to the matcher.
1089   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1090                              unsigned AllocatedTemporariesBaseID) {
1091     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1092                                              AllocatedTemporariesBaseID));
1093     return *Operands.back();
1094   }
1095 
1096   OperandMatcher &getOperand(unsigned OpIdx) {
1097     auto I = std::find_if(Operands.begin(), Operands.end(),
1098                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1099                             return X->getOperandIndex() == OpIdx;
1100                           });
1101     if (I != Operands.end())
1102       return **I;
1103     llvm_unreachable("Failed to lookup operand");
1104   }
1105 
1106   Optional<const OperandMatcher *>
1107   getOptionalOperand(StringRef SymbolicName) const {
1108     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1109     for (const auto &Operand : Operands) {
1110       const auto &OM = Operand->getOptionalOperand(SymbolicName);
1111       if (OM.hasValue())
1112         return OM.getValue();
1113     }
1114     return None;
1115   }
1116 
1117   const OperandMatcher &getOperand(StringRef SymbolicName) const {
1118     Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
1119     if (OM.hasValue())
1120       return *OM.getValue();
1121     llvm_unreachable("Failed to lookup operand");
1122   }
1123 
1124   StringRef getSymbolicName() const { return SymbolicName; }
1125   unsigned getNumOperands() const { return Operands.size(); }
1126   OperandVec::iterator operands_begin() { return Operands.begin(); }
1127   OperandVec::iterator operands_end() { return Operands.end(); }
1128   iterator_range<OperandVec::iterator> operands() {
1129     return make_range(operands_begin(), operands_end());
1130   }
1131   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1132   OperandVec::const_iterator operands_end() const { return Operands.end(); }
1133   iterator_range<OperandVec::const_iterator> operands() const {
1134     return make_range(operands_begin(), operands_end());
1135   }
1136 
1137   /// Emit MatchTable opcodes to check the shape of the match and capture
1138   /// instructions into the MIs table.
1139   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1140                           unsigned InsnID) {
1141     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1142           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1143           << MatchTable::Comment("Expected")
1144           << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
1145     for (const auto &Operand : Operands)
1146       Operand->emitCaptureOpcodes(Table, Rule, InsnID);
1147   }
1148 
1149   /// Emit MatchTable opcodes that test whether the instruction named in
1150   /// InsnVarName matches all the predicates and all the operands.
1151   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1152                             unsigned InsnVarID) const {
1153     emitPredicateListOpcodes(Table, Rule, InsnVarID);
1154     for (const auto &Operand : Operands)
1155       Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
1156   }
1157 
1158   /// Compare the priority of this object and B.
1159   ///
1160   /// Returns true if this object is more important than B.
1161   bool isHigherPriorityThan(const InstructionMatcher &B) const {
1162     // Instruction matchers involving more operands have higher priority.
1163     if (Operands.size() > B.Operands.size())
1164       return true;
1165     if (Operands.size() < B.Operands.size())
1166       return false;
1167 
1168     for (const auto &Predicate : zip(predicates(), B.predicates())) {
1169       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1170         return true;
1171       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1172         return false;
1173     }
1174 
1175     for (const auto &Operand : zip(Operands, B.Operands)) {
1176       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
1177         return true;
1178       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
1179         return false;
1180     }
1181 
1182     return false;
1183   };
1184 
1185   /// Report the maximum number of temporary operands needed by the instruction
1186   /// matcher.
1187   unsigned countRendererFns() const {
1188     return std::accumulate(predicates().begin(), predicates().end(), 0,
1189                            [](unsigned A,
1190                               const std::unique_ptr<InstructionPredicateMatcher>
1191                                   &Predicate) {
1192                              return A + Predicate->countRendererFns();
1193                            }) +
1194            std::accumulate(
1195                Operands.begin(), Operands.end(), 0,
1196                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
1197                  return A + Operand->countRendererFns();
1198                });
1199   }
1200 
1201   bool isConstantInstruction() const {
1202     for (const auto &P : predicates())
1203       if (const InstructionOpcodeMatcher *Opcode =
1204               dyn_cast<InstructionOpcodeMatcher>(P.get()))
1205         return Opcode->isConstantInstruction();
1206     return false;
1207   }
1208 };
1209 
1210 /// Generates code to check that the operand is a register defined by an
1211 /// instruction that matches the given instruction matcher.
1212 ///
1213 /// For example, the pattern:
1214 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1215 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1216 /// the:
1217 ///   (G_ADD $src1, $src2)
1218 /// subpattern.
1219 class InstructionOperandMatcher : public OperandPredicateMatcher {
1220 protected:
1221   std::unique_ptr<InstructionMatcher> InsnMatcher;
1222 
1223 public:
1224   InstructionOperandMatcher(StringRef SymbolicName)
1225       : OperandPredicateMatcher(OPM_Instruction),
1226         InsnMatcher(new InstructionMatcher(SymbolicName)) {}
1227 
1228   static bool classof(const OperandPredicateMatcher *P) {
1229     return P->getKind() == OPM_Instruction;
1230   }
1231 
1232   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1233 
1234   Optional<const OperandMatcher *>
1235   getOptionalOperand(StringRef SymbolicName) const override {
1236     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1237     return InsnMatcher->getOptionalOperand(SymbolicName);
1238   }
1239 
1240   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1241                           unsigned InsnID, unsigned OpIdx) const override {
1242     unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1243     InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
1244   }
1245 
1246   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1247                             unsigned InsnVarID_,
1248                             unsigned OpIdx_) const override {
1249     unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
1250     InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
1251   }
1252 };
1253 
1254 //===- Actions ------------------------------------------------------------===//
1255 class OperandRenderer {
1256 public:
1257   enum RendererKind {
1258     OR_Copy,
1259     OR_CopySubReg,
1260     OR_CopyConstantAsImm,
1261     OR_Imm,
1262     OR_Register,
1263     OR_ComplexPattern
1264   };
1265 
1266 protected:
1267   RendererKind Kind;
1268 
1269 public:
1270   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1271   virtual ~OperandRenderer() {}
1272 
1273   RendererKind getKind() const { return Kind; }
1274 
1275   virtual void emitRenderOpcodes(MatchTable &Table,
1276                                  RuleMatcher &Rule) const = 0;
1277 };
1278 
1279 /// A CopyRenderer emits code to copy a single operand from an existing
1280 /// instruction to the one being built.
1281 class CopyRenderer : public OperandRenderer {
1282 protected:
1283   unsigned NewInsnID;
1284   /// The matcher for the instruction that this operand is copied from.
1285   /// This provides the facility for looking up an a operand by it's name so
1286   /// that it can be used as a source for the instruction being built.
1287   const InstructionMatcher &Matched;
1288   /// The name of the operand.
1289   const StringRef SymbolicName;
1290 
1291 public:
1292   CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1293                StringRef SymbolicName)
1294       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
1295         SymbolicName(SymbolicName) {
1296     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1297   }
1298 
1299   static bool classof(const OperandRenderer *R) {
1300     return R->getKind() == OR_Copy;
1301   }
1302 
1303   const StringRef getSymbolicName() const { return SymbolicName; }
1304 
1305   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1306     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
1307     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1308     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1309           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1310           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1311           << MatchTable::IntValue(Operand.getOperandIndex())
1312           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1313   }
1314 };
1315 
1316 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1317 /// an extended immediate operand.
1318 class CopyConstantAsImmRenderer : public OperandRenderer {
1319 protected:
1320   unsigned NewInsnID;
1321   /// The name of the operand.
1322   const std::string SymbolicName;
1323   bool Signed;
1324 
1325 public:
1326   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1327       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1328         SymbolicName(SymbolicName), Signed(true) {}
1329 
1330   static bool classof(const OperandRenderer *R) {
1331     return R->getKind() == OR_CopyConstantAsImm;
1332   }
1333 
1334   const StringRef getSymbolicName() const { return SymbolicName; }
1335 
1336   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1337     const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1338     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1339     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1340                                        : "GIR_CopyConstantAsUImm")
1341           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1342           << MatchTable::Comment("OldInsnID")
1343           << MatchTable::IntValue(OldInsnVarID)
1344           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1345   }
1346 };
1347 
1348 /// A CopySubRegRenderer emits code to copy a single register operand from an
1349 /// existing instruction to the one being built and indicate that only a
1350 /// subregister should be copied.
1351 class CopySubRegRenderer : public OperandRenderer {
1352 protected:
1353   unsigned NewInsnID;
1354   /// The matcher for the instruction that this operand is copied from.
1355   /// This provides the facility for looking up an a operand by it's name so
1356   /// that it can be used as a source for the instruction being built.
1357   const InstructionMatcher &Matched;
1358   /// The name of the operand.
1359   const StringRef SymbolicName;
1360   /// The subregister to extract.
1361   const CodeGenSubRegIndex *SubReg;
1362 
1363 public:
1364   CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1365                      StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1366       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
1367         SymbolicName(SymbolicName), SubReg(SubReg) {}
1368 
1369   static bool classof(const OperandRenderer *R) {
1370     return R->getKind() == OR_CopySubReg;
1371   }
1372 
1373   const StringRef getSymbolicName() const { return SymbolicName; }
1374 
1375   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1376     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
1377     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1378     Table << MatchTable::Opcode("GIR_CopySubReg")
1379           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1380           << MatchTable::Comment("OldInsnID")
1381           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1382           << MatchTable::IntValue(Operand.getOperandIndex())
1383           << MatchTable::Comment("SubRegIdx")
1384           << MatchTable::IntValue(SubReg->EnumValue)
1385           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1386   }
1387 };
1388 
1389 /// Adds a specific physical register to the instruction being built.
1390 /// This is typically useful for WZR/XZR on AArch64.
1391 class AddRegisterRenderer : public OperandRenderer {
1392 protected:
1393   unsigned InsnID;
1394   const Record *RegisterDef;
1395 
1396 public:
1397   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1398       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1399   }
1400 
1401   static bool classof(const OperandRenderer *R) {
1402     return R->getKind() == OR_Register;
1403   }
1404 
1405   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1406     Table << MatchTable::Opcode("GIR_AddRegister")
1407           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1408           << MatchTable::NamedValue(
1409                  (RegisterDef->getValue("Namespace")
1410                       ? RegisterDef->getValueAsString("Namespace")
1411                       : ""),
1412                  RegisterDef->getName())
1413           << MatchTable::LineBreak;
1414   }
1415 };
1416 
1417 /// Adds a specific immediate to the instruction being built.
1418 class ImmRenderer : public OperandRenderer {
1419 protected:
1420   unsigned InsnID;
1421   int64_t Imm;
1422 
1423 public:
1424   ImmRenderer(unsigned InsnID, int64_t Imm)
1425       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
1426 
1427   static bool classof(const OperandRenderer *R) {
1428     return R->getKind() == OR_Imm;
1429   }
1430 
1431   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1432     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1433           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1434           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
1435   }
1436 };
1437 
1438 /// Adds operands by calling a renderer function supplied by the ComplexPattern
1439 /// matcher function.
1440 class RenderComplexPatternOperand : public OperandRenderer {
1441 private:
1442   unsigned InsnID;
1443   const Record &TheDef;
1444   /// The name of the operand.
1445   const StringRef SymbolicName;
1446   /// The renderer number. This must be unique within a rule since it's used to
1447   /// identify a temporary variable to hold the renderer function.
1448   unsigned RendererID;
1449 
1450   unsigned getNumOperands() const {
1451     return TheDef.getValueAsDag("Operands")->getNumArgs();
1452   }
1453 
1454 public:
1455   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1456                               StringRef SymbolicName, unsigned RendererID)
1457       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
1458         SymbolicName(SymbolicName), RendererID(RendererID) {}
1459 
1460   static bool classof(const OperandRenderer *R) {
1461     return R->getKind() == OR_ComplexPattern;
1462   }
1463 
1464   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1465     Table << MatchTable::Opcode("GIR_ComplexRenderer")
1466           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1467           << MatchTable::Comment("RendererID")
1468           << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
1469   }
1470 };
1471 
1472 /// An action taken when all Matcher predicates succeeded for a parent rule.
1473 ///
1474 /// Typical actions include:
1475 /// * Changing the opcode of an instruction.
1476 /// * Adding an operand to an instruction.
1477 class MatchAction {
1478 public:
1479   virtual ~MatchAction() {}
1480 
1481   /// Emit the MatchTable opcodes to implement the action.
1482   ///
1483   /// \param RecycleInsnID If given, it's an instruction to recycle. The
1484   ///                      requirements on the instruction vary from action to
1485   ///                      action.
1486   virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1487                                  unsigned RecycleInsnID) const = 0;
1488 };
1489 
1490 /// Generates a comment describing the matched rule being acted upon.
1491 class DebugCommentAction : public MatchAction {
1492 private:
1493   const PatternToMatch &P;
1494 
1495 public:
1496   DebugCommentAction(const PatternToMatch &P) : P(P) {}
1497 
1498   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1499                          unsigned RecycleInsnID) const override {
1500     Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + "  =>  " +
1501                                llvm::to_string(*P.getDstPattern()))
1502           << MatchTable::LineBreak;
1503   }
1504 };
1505 
1506 /// Generates code to build an instruction or mutate an existing instruction
1507 /// into the desired instruction when this is possible.
1508 class BuildMIAction : public MatchAction {
1509 private:
1510   unsigned InsnID;
1511   const CodeGenInstruction *I;
1512   const InstructionMatcher &Matched;
1513   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1514 
1515   /// True if the instruction can be built solely by mutating the opcode.
1516   bool canMutate() const {
1517     if (OperandRenderers.size() != Matched.getNumOperands())
1518       return false;
1519 
1520     for (const auto &Renderer : enumerate(OperandRenderers)) {
1521       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
1522         const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1523         if (&Matched != &OM.getInstructionMatcher() ||
1524             OM.getOperandIndex() != Renderer.index())
1525           return false;
1526       } else
1527         return false;
1528     }
1529 
1530     return true;
1531   }
1532 
1533 public:
1534   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
1535                 const InstructionMatcher &Matched)
1536       : InsnID(InsnID), I(I), Matched(Matched) {}
1537 
1538   template <class Kind, class... Args>
1539   Kind &addRenderer(Args&&... args) {
1540     OperandRenderers.emplace_back(
1541         llvm::make_unique<Kind>(std::forward<Args>(args)...));
1542     return *static_cast<Kind *>(OperandRenderers.back().get());
1543   }
1544 
1545   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1546                          unsigned RecycleInsnID) const override {
1547     if (canMutate()) {
1548       Table << MatchTable::Opcode("GIR_MutateOpcode")
1549             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1550             << MatchTable::Comment("RecycleInsnID")
1551             << MatchTable::IntValue(RecycleInsnID)
1552             << MatchTable::Comment("Opcode")
1553             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1554             << MatchTable::LineBreak;
1555 
1556       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1557         for (auto Def : I->ImplicitDefs) {
1558           auto Namespace = Def->getValue("Namespace")
1559                                ? Def->getValueAsString("Namespace")
1560                                : "";
1561           Table << MatchTable::Opcode("GIR_AddImplicitDef")
1562                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1563                 << MatchTable::NamedValue(Namespace, Def->getName())
1564                 << MatchTable::LineBreak;
1565         }
1566         for (auto Use : I->ImplicitUses) {
1567           auto Namespace = Use->getValue("Namespace")
1568                                ? Use->getValueAsString("Namespace")
1569                                : "";
1570           Table << MatchTable::Opcode("GIR_AddImplicitUse")
1571                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1572                 << MatchTable::NamedValue(Namespace, Use->getName())
1573                 << MatchTable::LineBreak;
1574         }
1575       }
1576       return;
1577     }
1578 
1579     // TODO: Simple permutation looks like it could be almost as common as
1580     //       mutation due to commutative operations.
1581 
1582     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1583           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1584           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1585           << MatchTable::LineBreak;
1586     for (const auto &Renderer : OperandRenderers)
1587       Renderer->emitRenderOpcodes(Table, Rule);
1588 
1589     if (I->mayLoad || I->mayStore) {
1590       Table << MatchTable::Opcode("GIR_MergeMemOperands")
1591             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1592             << MatchTable::Comment("MergeInsnID's");
1593       // Emit the ID's for all the instructions that are matched by this rule.
1594       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1595       //       some other means of having a memoperand. Also limit this to
1596       //       emitted instructions that expect to have a memoperand too. For
1597       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
1598       //       sign-extend instructions shouldn't put the memoperand on the
1599       //       sign-extend since it has no effect there.
1600       std::vector<unsigned> MergeInsnIDs;
1601       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1602         MergeInsnIDs.push_back(IDMatcherPair.second);
1603       std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1604       for (const auto &MergeInsnID : MergeInsnIDs)
1605         Table << MatchTable::IntValue(MergeInsnID);
1606       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1607             << MatchTable::LineBreak;
1608     }
1609 
1610     Table << MatchTable::Opcode("GIR_EraseFromParent")
1611           << MatchTable::Comment("InsnID")
1612           << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
1613   }
1614 };
1615 
1616 /// Generates code to constrain the operands of an output instruction to the
1617 /// register classes specified by the definition of that instruction.
1618 class ConstrainOperandsToDefinitionAction : public MatchAction {
1619   unsigned InsnID;
1620 
1621 public:
1622   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
1623 
1624   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1625                          unsigned RecycleInsnID) const override {
1626     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1627           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1628           << MatchTable::LineBreak;
1629   }
1630 };
1631 
1632 /// Generates code to constrain the specified operand of an output instruction
1633 /// to the specified register class.
1634 class ConstrainOperandToRegClassAction : public MatchAction {
1635   unsigned InsnID;
1636   unsigned OpIdx;
1637   const CodeGenRegisterClass &RC;
1638 
1639 public:
1640   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
1641                                    const CodeGenRegisterClass &RC)
1642       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
1643 
1644   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1645                          unsigned RecycleInsnID) const override {
1646     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1647           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1648           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1649           << MatchTable::Comment("RC " + RC.getName())
1650           << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
1651   }
1652 };
1653 
1654 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
1655   Matchers.emplace_back(new InstructionMatcher(SymbolicName));
1656   return *Matchers.back();
1657 }
1658 
1659 void RuleMatcher::addRequiredFeature(Record *Feature) {
1660   RequiredFeatures.push_back(Feature);
1661 }
1662 
1663 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1664   return RequiredFeatures;
1665 }
1666 
1667 template <class Kind, class... Args>
1668 Kind &RuleMatcher::addAction(Args &&... args) {
1669   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1670   return *static_cast<Kind *>(Actions.back().get());
1671 }
1672 
1673 unsigned
1674 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1675   unsigned NewInsnVarID = NextInsnVarID++;
1676   InsnVariableIDs[&Matcher] = NewInsnVarID;
1677   return NewInsnVarID;
1678 }
1679 
1680 unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
1681                                     const InstructionMatcher &Matcher,
1682                                     unsigned InsnID, unsigned OpIdx) {
1683   unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
1684   Table << MatchTable::Opcode("GIM_RecordInsn")
1685         << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1686         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1687         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1688         << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1689         << MatchTable::LineBreak;
1690   return NewInsnVarID;
1691 }
1692 
1693 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1694   const auto &I = InsnVariableIDs.find(&InsnMatcher);
1695   if (I != InsnVariableIDs.end())
1696     return I->second;
1697   llvm_unreachable("Matched Insn was not captured in a local variable");
1698 }
1699 
1700 const InstructionMatcher &
1701 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1702   for (const auto &I : InsnVariableIDs)
1703     if (I.first->getSymbolicName() == SymbolicName)
1704       return *I.first;
1705   llvm_unreachable(
1706       ("Failed to lookup instruction " + SymbolicName).str().c_str());
1707 }
1708 
1709 /// Emit MatchTable opcodes to check the shape of the match and capture
1710 /// instructions into local variables.
1711 void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
1712   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1713   unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
1714   Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
1715 }
1716 
1717 void RuleMatcher::emit(MatchTable &Table) {
1718   if (Matchers.empty())
1719     llvm_unreachable("Unexpected empty matcher!");
1720 
1721   // The representation supports rules that require multiple roots such as:
1722   //    %ptr(p0) = ...
1723   //    %elt0(s32) = G_LOAD %ptr
1724   //    %1(p0) = G_ADD %ptr, 4
1725   //    %elt1(s32) = G_LOAD p0 %1
1726   // which could be usefully folded into:
1727   //    %ptr(p0) = ...
1728   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1729   // on some targets but we don't need to make use of that yet.
1730   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1731 
1732   unsigned LabelID = Table.allocateLabelID();
1733   Table << MatchTable::Opcode("GIM_Try", +1)
1734         << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
1735         << MatchTable::LineBreak;
1736 
1737   if (!RequiredFeatures.empty()) {
1738     Table << MatchTable::Opcode("GIM_CheckFeatures")
1739           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1740           << MatchTable::LineBreak;
1741   }
1742 
1743   emitCaptureOpcodes(Table);
1744 
1745   Matchers.front()->emitPredicateOpcodes(Table, *this,
1746                                          getInsnVarID(*Matchers.front()));
1747 
1748   // We must also check if it's safe to fold the matched instructions.
1749   if (InsnVariableIDs.size() >= 2) {
1750     // Invert the map to create stable ordering (by var names)
1751     SmallVector<unsigned, 2> InsnIDs;
1752     for (const auto &Pair : InsnVariableIDs) {
1753       // Skip the root node since it isn't moving anywhere. Everything else is
1754       // sinking to meet it.
1755       if (Pair.first == Matchers.front().get())
1756         continue;
1757 
1758       InsnIDs.push_back(Pair.second);
1759     }
1760     std::sort(InsnIDs.begin(), InsnIDs.end());
1761 
1762     for (const auto &InsnID : InsnIDs) {
1763       // Reject the difficult cases until we have a more accurate check.
1764       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1765             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1766             << MatchTable::LineBreak;
1767 
1768       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1769       //        account for unsafe cases.
1770       //
1771       //        Example:
1772       //          MI1--> %0 = ...
1773       //                 %1 = ... %0
1774       //          MI0--> %2 = ... %0
1775       //          It's not safe to erase MI1. We currently handle this by not
1776       //          erasing %0 (even when it's dead).
1777       //
1778       //        Example:
1779       //          MI1--> %0 = load volatile @a
1780       //                 %1 = load volatile @a
1781       //          MI0--> %2 = ... %0
1782       //          It's not safe to sink %0's def past %1. We currently handle
1783       //          this by rejecting all loads.
1784       //
1785       //        Example:
1786       //          MI1--> %0 = load @a
1787       //                 %1 = store @a
1788       //          MI0--> %2 = ... %0
1789       //          It's not safe to sink %0's def past %1. We currently handle
1790       //          this by rejecting all loads.
1791       //
1792       //        Example:
1793       //                   G_CONDBR %cond, @BB1
1794       //                 BB0:
1795       //          MI1-->   %0 = load @a
1796       //                   G_BR @BB1
1797       //                 BB1:
1798       //          MI0-->   %2 = ... %0
1799       //          It's not always safe to sink %0 across control flow. In this
1800       //          case it may introduce a memory fault. We currentl handle this
1801       //          by rejecting all loads.
1802     }
1803   }
1804 
1805   for (const auto &MA : Actions)
1806     MA->emitActionOpcodes(Table, *this, 0);
1807   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
1808         << MatchTable::Label(LabelID);
1809 }
1810 
1811 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1812   // Rules involving more match roots have higher priority.
1813   if (Matchers.size() > B.Matchers.size())
1814     return true;
1815   if (Matchers.size() < B.Matchers.size())
1816     return false;
1817 
1818   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1819     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1820       return true;
1821     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1822       return false;
1823   }
1824 
1825   return false;
1826 }
1827 
1828 unsigned RuleMatcher::countRendererFns() const {
1829   return std::accumulate(
1830       Matchers.begin(), Matchers.end(), 0,
1831       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1832         return A + Matcher->countRendererFns();
1833       });
1834 }
1835 
1836 bool OperandPredicateMatcher::isHigherPriorityThan(
1837     const OperandPredicateMatcher &B) const {
1838   // Generally speaking, an instruction is more important than an Int or a
1839   // LiteralInt because it can cover more nodes but theres an exception to
1840   // this. G_CONSTANT's are less important than either of those two because they
1841   // are more permissive.
1842 
1843   const InstructionOperandMatcher *AOM =
1844       dyn_cast<InstructionOperandMatcher>(this);
1845   const InstructionOperandMatcher *BOM =
1846       dyn_cast<InstructionOperandMatcher>(&B);
1847   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
1848   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
1849 
1850   if (AOM && BOM) {
1851     // The relative priorities between a G_CONSTANT and any other instruction
1852     // don't actually matter but this code is needed to ensure a strict weak
1853     // ordering. This is particularly important on Windows where the rules will
1854     // be incorrectly sorted without it.
1855     if (AIsConstantInsn != BIsConstantInsn)
1856       return AIsConstantInsn < BIsConstantInsn;
1857     return false;
1858   }
1859 
1860   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
1861     return false;
1862   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
1863     return true;
1864 
1865   return Kind < B.Kind;
1866 }
1867 
1868 //===- GlobalISelEmitter class --------------------------------------------===//
1869 
1870 class GlobalISelEmitter {
1871 public:
1872   explicit GlobalISelEmitter(RecordKeeper &RK);
1873   void run(raw_ostream &OS);
1874 
1875 private:
1876   const RecordKeeper &RK;
1877   const CodeGenDAGPatterns CGP;
1878   const CodeGenTarget &Target;
1879   CodeGenRegBank CGRegs;
1880 
1881   /// Keep track of the equivalence between SDNodes and Instruction.
1882   /// This is defined using 'GINodeEquiv' in the target description.
1883   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1884 
1885   /// Keep track of the equivalence between ComplexPattern's and
1886   /// GIComplexOperandMatcher. Map entries are specified by subclassing
1887   /// GIComplexPatternEquiv.
1888   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1889 
1890   // Map of predicates to their subtarget features.
1891   SubtargetFeatureInfoMap SubtargetFeatures;
1892 
1893   void gatherNodeEquivs();
1894   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1895 
1896   Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
1897   Expected<InstructionMatcher &>
1898   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1899                                const TreePatternNode *Src,
1900                                unsigned &TempOpIdx) const;
1901   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1902                            const TreePatternNode *SrcChild, unsigned OpIdx,
1903                            unsigned &TempOpIdx) const;
1904   Expected<BuildMIAction &>
1905   createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1906                                      const InstructionMatcher &InsnMatcher);
1907   Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1908                                   TreePatternNode *DstChild,
1909                                   const InstructionMatcher &InsnMatcher) const;
1910   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1911                                       DagInit *DefaultOps) const;
1912   Error
1913   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1914                              const std::vector<Record *> &ImplicitDefs) const;
1915 
1916   /// Analyze pattern \p P, returning a matcher for it if possible.
1917   /// Otherwise, return an Error explaining why we don't support it.
1918   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1919 
1920   void declareSubtargetFeature(Record *Predicate);
1921 };
1922 
1923 void GlobalISelEmitter::gatherNodeEquivs() {
1924   assert(NodeEquivs.empty());
1925   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1926     NodeEquivs[Equiv->getValueAsDef("Node")] =
1927         &Target.getInstruction(Equiv->getValueAsDef("I"));
1928 
1929   assert(ComplexPatternEquivs.empty());
1930   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1931     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1932     if (!SelDAGEquiv)
1933       continue;
1934     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1935  }
1936 }
1937 
1938 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1939   return NodeEquivs.lookup(N);
1940 }
1941 
1942 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1943     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
1944       CGRegs(RK, Target.getHwModes()) {}
1945 
1946 //===- Emitter ------------------------------------------------------------===//
1947 
1948 Error
1949 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1950                                         ArrayRef<Predicate> Predicates) {
1951   for (const Predicate &P : Predicates) {
1952     if (!P.Def)
1953       continue;
1954     declareSubtargetFeature(P.Def);
1955     M.addRequiredFeature(P.Def);
1956   }
1957 
1958   return Error::success();
1959 }
1960 
1961 Expected<InstructionMatcher &>
1962 GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1963                                                 const TreePatternNode *Src,
1964                                                 unsigned &TempOpIdx) const {
1965   const CodeGenInstruction *SrcGIOrNull = nullptr;
1966 
1967   // Start with the defined operands (i.e., the results of the root operator).
1968   if (Src->getExtTypes().size() > 1)
1969     return failedImport("Src pattern has multiple results");
1970 
1971   if (Src->isLeaf()) {
1972     Init *SrcInit = Src->getLeafValue();
1973     if (isa<IntInit>(SrcInit)) {
1974       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1975           &Target.getInstruction(RK.getDef("G_CONSTANT")));
1976     } else
1977       return failedImport(
1978           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1979   } else {
1980     SrcGIOrNull = findNodeEquiv(Src->getOperator());
1981     if (!SrcGIOrNull)
1982       return failedImport("Pattern operator lacks an equivalent Instruction" +
1983                           explainOperator(Src->getOperator()));
1984     auto &SrcGI = *SrcGIOrNull;
1985 
1986     // The operators look good: match the opcode
1987     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1988   }
1989 
1990   unsigned OpIdx = 0;
1991   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
1992     auto OpTyOrNone = VTy.isMachineValueType()
1993                           ? MVTToLLT(VTy.getMachineValueType().SimpleTy)
1994                           : None;
1995     if (!OpTyOrNone)
1996       return failedImport(
1997           "Result of Src pattern operator has an unsupported type");
1998 
1999     // Results don't have a name unless they are the root node. The caller will
2000     // set the name if appropriate.
2001     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2002     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
2003   }
2004 
2005   for (const auto &Predicate : Src->getPredicateFns()) {
2006     if (Predicate.isAlwaysTrue())
2007       continue;
2008 
2009     if (Predicate.isImmediatePattern()) {
2010       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2011       continue;
2012     }
2013 
2014     return failedImport("Src pattern child has predicate (" +
2015                         explainPredicates(Src) + ")");
2016   }
2017 
2018   if (Src->isLeaf()) {
2019     Init *SrcInit = Src->getLeafValue();
2020     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
2021       OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2022       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2023     } else
2024       return failedImport(
2025           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2026   } else {
2027     assert(SrcGIOrNull &&
2028            "Expected to have already found an equivalent Instruction");
2029     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT") {
2030       // imm still has an operand but we don't need to do anything with it
2031       // here since we don't support ImmLeaf predicates yet. However, we still
2032       // need to note the hidden operand to get GIM_CheckNumOperands correct.
2033       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2034       return InsnMatcher;
2035     }
2036 
2037     // Match the used operands (i.e. the children of the operator).
2038     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
2039       TreePatternNode *SrcChild = Src->getChild(i);
2040 
2041       // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2042       // following the defs is an intrinsic ID.
2043       if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2044            SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2045           i == 0) {
2046         if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
2047           OperandMatcher &OM =
2048               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
2049           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
2050           continue;
2051         }
2052 
2053         return failedImport("Expected IntInit containing instrinsic ID)");
2054       }
2055 
2056       if (auto Error =
2057               importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
2058         return std::move(Error);
2059     }
2060   }
2061 
2062   return InsnMatcher;
2063 }
2064 
2065 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
2066                                             const TreePatternNode *SrcChild,
2067                                             unsigned OpIdx,
2068                                             unsigned &TempOpIdx) const {
2069   OperandMatcher &OM =
2070       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
2071 
2072   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
2073   if (ChildTypes.size() != 1)
2074     return failedImport("Src pattern child has multiple results");
2075 
2076   // Check MBB's before the type check since they are not a known type.
2077   if (!SrcChild->isLeaf()) {
2078     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2079       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2080       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2081         OM.addPredicate<MBBOperandMatcher>();
2082         return Error::success();
2083       }
2084     }
2085   }
2086 
2087   Optional<LLTCodeGen> OpTyOrNone = None;
2088   if (ChildTypes.front().isMachineValueType())
2089     OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
2090   if (!OpTyOrNone)
2091     return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
2092   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
2093 
2094   // Check for nested instructions.
2095   if (!SrcChild->isLeaf()) {
2096     // Map the node to a gMIR instruction.
2097     InstructionOperandMatcher &InsnOperand =
2098         OM.addPredicate<InstructionOperandMatcher>(SrcChild->getName());
2099     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
2100         InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
2101     if (auto Error = InsnMatcherOrError.takeError())
2102       return Error;
2103 
2104     return Error::success();
2105   }
2106 
2107   // Check for constant immediates.
2108   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
2109     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
2110     return Error::success();
2111   }
2112 
2113   // Check for def's like register classes or ComplexPattern's.
2114   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2115     auto *ChildRec = ChildDefInit->getDef();
2116 
2117     // Check for register classes.
2118     if (ChildRec->isSubClassOf("RegisterClass") ||
2119         ChildRec->isSubClassOf("RegisterOperand")) {
2120       OM.addPredicate<RegisterBankOperandMatcher>(
2121           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
2122       return Error::success();
2123     }
2124 
2125     // Check for ComplexPattern's.
2126     if (ChildRec->isSubClassOf("ComplexPattern")) {
2127       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2128       if (ComplexPattern == ComplexPatternEquivs.end())
2129         return failedImport("SelectionDAG ComplexPattern (" +
2130                             ChildRec->getName() + ") not mapped to GlobalISel");
2131 
2132       OM.addPredicate<ComplexPatternOperandMatcher>(OM,
2133                                                     *ComplexPattern->second);
2134       TempOpIdx++;
2135       return Error::success();
2136     }
2137 
2138     if (ChildRec->isSubClassOf("ImmLeaf")) {
2139       return failedImport(
2140           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2141     }
2142 
2143     return failedImport(
2144         "Src pattern child def is an unsupported tablegen class");
2145   }
2146 
2147   return failedImport("Src pattern child is an unsupported kind");
2148 }
2149 
2150 Error GlobalISelEmitter::importExplicitUseRenderer(
2151     BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
2152     const InstructionMatcher &InsnMatcher) const {
2153   if (DstChild->getTransformFn() != nullptr) {
2154     return failedImport("Dst pattern child has transform fn " +
2155                         DstChild->getTransformFn()->getName());
2156   }
2157 
2158   if (!DstChild->isLeaf()) {
2159     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2160     // inline, but in MI it's just another operand.
2161     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2162       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2163       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2164         DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2165                                                DstChild->getName());
2166         return Error::success();
2167       }
2168     }
2169 
2170     // Similarly, imm is an operator in TreePatternNode's view but must be
2171     // rendered as operands.
2172     // FIXME: The target should be able to choose sign-extended when appropriate
2173     //        (e.g. on Mips).
2174     if (DstChild->getOperator()->getName() == "imm") {
2175       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2176                                                           DstChild->getName());
2177       return Error::success();
2178     }
2179 
2180     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
2181   }
2182 
2183   // Otherwise, we're looking for a bog-standard RegisterClass operand.
2184   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2185     auto *ChildRec = ChildDefInit->getDef();
2186 
2187     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
2188     if (ChildTypes.size() != 1)
2189       return failedImport("Dst pattern child has multiple results");
2190 
2191     Optional<LLTCodeGen> OpTyOrNone = None;
2192     if (ChildTypes.front().isMachineValueType())
2193       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
2194     if (!OpTyOrNone)
2195       return failedImport("Dst operand has an unsupported type");
2196 
2197     if (ChildRec->isSubClassOf("Register")) {
2198       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
2199       return Error::success();
2200     }
2201 
2202     if (ChildRec->isSubClassOf("RegisterClass") ||
2203         ChildRec->isSubClassOf("RegisterOperand")) {
2204       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2205                                              DstChild->getName());
2206       return Error::success();
2207     }
2208 
2209     if (ChildRec->isSubClassOf("ComplexPattern")) {
2210       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2211       if (ComplexPattern == ComplexPatternEquivs.end())
2212         return failedImport(
2213             "SelectionDAG ComplexPattern not mapped to GlobalISel");
2214 
2215       const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
2216       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2217           0, *ComplexPattern->second, DstChild->getName(),
2218           OM.getAllocatedTemporariesBaseID());
2219       return Error::success();
2220     }
2221 
2222     if (ChildRec->isSubClassOf("SDNodeXForm"))
2223       return failedImport("Dst pattern child def is an unsupported tablegen "
2224                           "class (SDNodeXForm)");
2225 
2226     return failedImport(
2227         "Dst pattern child def is an unsupported tablegen class");
2228   }
2229 
2230   return failedImport("Dst pattern child is an unsupported kind");
2231 }
2232 
2233 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
2234     RuleMatcher &M, const TreePatternNode *Dst,
2235     const InstructionMatcher &InsnMatcher) {
2236   Record *DstOp = Dst->getOperator();
2237   if (!DstOp->isSubClassOf("Instruction")) {
2238     if (DstOp->isSubClassOf("ValueType"))
2239       return failedImport(
2240           "Pattern operator isn't an instruction (it's a ValueType)");
2241     return failedImport("Pattern operator isn't an instruction");
2242   }
2243   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
2244 
2245   unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2246   unsigned ExpectedDstINumUses = Dst->getNumChildren();
2247   bool IsExtractSubReg = false;
2248 
2249   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
2250   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
2251   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2252     DstI = &Target.getInstruction(RK.getDef("COPY"));
2253     DstINumUses--; // Ignore the class constraint.
2254     ExpectedDstINumUses--;
2255   } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2256     DstI = &Target.getInstruction(RK.getDef("COPY"));
2257     IsExtractSubReg = true;
2258   }
2259 
2260   auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
2261 
2262   // Render the explicit defs.
2263   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2264     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
2265     DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2266   }
2267 
2268   // EXTRACT_SUBREG needs to use a subregister COPY.
2269   if (IsExtractSubReg) {
2270     if (!Dst->getChild(0)->isLeaf())
2271       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2272 
2273     if (DefInit *SubRegInit =
2274             dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
2275       CodeGenRegisterClass *RC = CGRegs.getRegClass(
2276           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2277       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2278 
2279       const auto &SrcRCDstRCPair =
2280           RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2281       if (SrcRCDstRCPair.hasValue()) {
2282         assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2283         if (SrcRCDstRCPair->first != RC)
2284           return failedImport("EXTRACT_SUBREG requires an additional COPY");
2285       }
2286 
2287       DstMIBuilder.addRenderer<CopySubRegRenderer>(
2288           0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
2289       return DstMIBuilder;
2290     }
2291 
2292     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2293   }
2294 
2295   // Render the explicit uses.
2296   unsigned Child = 0;
2297   unsigned NumDefaultOps = 0;
2298   for (unsigned I = 0; I != DstINumUses; ++I) {
2299     const CGIOperandList::OperandInfo &DstIOperand =
2300         DstI->Operands[DstI->Operands.NumDefs + I];
2301 
2302     // If the operand has default values, introduce them now.
2303     // FIXME: Until we have a decent test case that dictates we should do
2304     // otherwise, we're going to assume that operands with default values cannot
2305     // be specified in the patterns. Therefore, adding them will not cause us to
2306     // end up with too many rendered operands.
2307     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
2308       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
2309       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2310         return std::move(Error);
2311       ++NumDefaultOps;
2312       continue;
2313     }
2314 
2315     if (auto Error = importExplicitUseRenderer(
2316             DstMIBuilder, Dst->getChild(Child), InsnMatcher))
2317       return std::move(Error);
2318     ++Child;
2319   }
2320 
2321   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
2322     return failedImport("Expected " + llvm::to_string(DstINumUses) +
2323                         " used operands but found " +
2324                         llvm::to_string(ExpectedDstINumUses) +
2325                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
2326                         " default ones");
2327 
2328   return DstMIBuilder;
2329 }
2330 
2331 Error GlobalISelEmitter::importDefaultOperandRenderers(
2332     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
2333   for (const auto *DefaultOp : DefaultOps->getArgs()) {
2334     // Look through ValueType operators.
2335     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2336       if (const DefInit *DefaultDagOperator =
2337               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2338         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2339           DefaultOp = DefaultDagOp->getArg(0);
2340       }
2341     }
2342 
2343     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
2344       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
2345       continue;
2346     }
2347 
2348     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
2349       DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
2350       continue;
2351     }
2352 
2353     return failedImport("Could not add default op");
2354   }
2355 
2356   return Error::success();
2357 }
2358 
2359 Error GlobalISelEmitter::importImplicitDefRenderers(
2360     BuildMIAction &DstMIBuilder,
2361     const std::vector<Record *> &ImplicitDefs) const {
2362   if (!ImplicitDefs.empty())
2363     return failedImport("Pattern defines a physical register");
2364   return Error::success();
2365 }
2366 
2367 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
2368   // Keep track of the matchers and actions to emit.
2369   RuleMatcher M;
2370   M.addAction<DebugCommentAction>(P);
2371 
2372   if (auto Error = importRulePredicates(M, P.getPredicates()))
2373     return std::move(Error);
2374 
2375   // Next, analyze the pattern operators.
2376   TreePatternNode *Src = P.getSrcPattern();
2377   TreePatternNode *Dst = P.getDstPattern();
2378 
2379   // If the root of either pattern isn't a simple operator, ignore it.
2380   if (auto Err = isTrivialOperatorNode(Dst))
2381     return failedImport("Dst pattern root isn't a trivial operator (" +
2382                         toString(std::move(Err)) + ")");
2383   if (auto Err = isTrivialOperatorNode(Src))
2384     return failedImport("Src pattern root isn't a trivial operator (" +
2385                         toString(std::move(Err)) + ")");
2386 
2387   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2388   unsigned TempOpIdx = 0;
2389   auto InsnMatcherOrError =
2390       createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
2391   if (auto Error = InsnMatcherOrError.takeError())
2392     return std::move(Error);
2393   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2394 
2395   if (Dst->isLeaf()) {
2396     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2397 
2398     const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2399     if (RCDef) {
2400       // We need to replace the def and all its uses with the specified
2401       // operand. However, we must also insert COPY's wherever needed.
2402       // For now, emit a copy and let the register allocator clean up.
2403       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2404       const auto &DstIOperand = DstI.Operands[0];
2405 
2406       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2407       OM0.setSymbolicName(DstIOperand.Name);
2408       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2409 
2410       auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, InsnMatcher);
2411       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2412       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, Dst->getName());
2413       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2414 
2415       // We're done with this pattern!  It's eligible for GISel emission; return
2416       // it.
2417       ++NumPatternImported;
2418       return std::move(M);
2419     }
2420 
2421     return failedImport("Dst pattern root isn't a known leaf");
2422   }
2423 
2424   // Start with the defined operands (i.e., the results of the root operator).
2425   Record *DstOp = Dst->getOperator();
2426   if (!DstOp->isSubClassOf("Instruction"))
2427     return failedImport("Pattern operator isn't an instruction");
2428 
2429   auto &DstI = Target.getInstruction(DstOp);
2430   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
2431     return failedImport("Src pattern results and dst MI defs are different (" +
2432                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
2433                         to_string(DstI.Operands.NumDefs) + " def(s))");
2434 
2435   // The root of the match also has constraints on the register bank so that it
2436   // matches the result instruction.
2437   unsigned OpIdx = 0;
2438   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2439     (void)VTy;
2440 
2441     const auto &DstIOperand = DstI.Operands[OpIdx];
2442     Record *DstIOpRec = DstIOperand.Rec;
2443     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2444       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2445 
2446       if (DstIOpRec == nullptr)
2447         return failedImport(
2448             "COPY_TO_REGCLASS operand #1 isn't a register class");
2449     } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2450       if (!Dst->getChild(0)->isLeaf())
2451         return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2452 
2453       // We can assume that a subregister is in the same bank as it's super
2454       // register.
2455       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2456 
2457       if (DstIOpRec == nullptr)
2458         return failedImport(
2459             "EXTRACT_SUBREG operand #0 isn't a register class");
2460     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
2461       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
2462     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
2463       return failedImport("Dst MI def isn't a register class" +
2464                           to_string(*Dst));
2465 
2466     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2467     OM.setSymbolicName(DstIOperand.Name);
2468     OM.addPredicate<RegisterBankOperandMatcher>(
2469         Target.getRegisterClass(DstIOpRec));
2470     ++OpIdx;
2471   }
2472 
2473   auto DstMIBuilderOrError =
2474       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
2475   if (auto Error = DstMIBuilderOrError.takeError())
2476     return std::move(Error);
2477   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
2478 
2479   // Render the implicit defs.
2480   // These are only added to the root of the result.
2481   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
2482     return std::move(Error);
2483 
2484   // Constrain the registers to classes. This is normally derived from the
2485   // emitted instruction but a few instructions require special handling.
2486   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2487     // COPY_TO_REGCLASS does not provide operand constraints itself but the
2488     // result is constrained to the class given by the second child.
2489     Record *DstIOpRec =
2490         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2491 
2492     if (DstIOpRec == nullptr)
2493       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2494 
2495     M.addAction<ConstrainOperandToRegClassAction>(
2496         0, 0, Target.getRegisterClass(DstIOpRec));
2497 
2498     // We're done with this pattern!  It's eligible for GISel emission; return
2499     // it.
2500     ++NumPatternImported;
2501     return std::move(M);
2502   }
2503 
2504   if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2505     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2506     // instructions, the result register class is controlled by the
2507     // subregisters of the operand. As a result, we must constrain the result
2508     // class rather than check that it's already the right one.
2509     if (!Dst->getChild(0)->isLeaf())
2510       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2511 
2512     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2513     if (!SubRegInit)
2514       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2515 
2516     // Constrain the result to the same register bank as the operand.
2517     Record *DstIOpRec =
2518         getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2519 
2520     if (DstIOpRec == nullptr)
2521       return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
2522 
2523     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2524     CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
2525 
2526     // It would be nice to leave this constraint implicit but we're required
2527     // to pick a register class so constrain the result to a register class
2528     // that can hold the correct MVT.
2529     //
2530     // FIXME: This may introduce an extra copy if the chosen class doesn't
2531     //        actually contain the subregisters.
2532     assert(Src->getExtTypes().size() == 1 &&
2533              "Expected Src of EXTRACT_SUBREG to have one result type");
2534 
2535     const auto &SrcRCDstRCPair =
2536         SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2537     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2538     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2539     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2540 
2541     // We're done with this pattern!  It's eligible for GISel emission; return
2542     // it.
2543     ++NumPatternImported;
2544     return std::move(M);
2545   }
2546 
2547   M.addAction<ConstrainOperandsToDefinitionAction>(0);
2548 
2549   // We're done with this pattern!  It's eligible for GISel emission; return it.
2550   ++NumPatternImported;
2551   return std::move(M);
2552 }
2553 
2554 void GlobalISelEmitter::run(raw_ostream &OS) {
2555   // Track the GINodeEquiv definitions.
2556   gatherNodeEquivs();
2557 
2558   emitSourceFileHeader(("Global Instruction Selector for the " +
2559                        Target.getName() + " target").str(), OS);
2560   std::vector<RuleMatcher> Rules;
2561   // Look through the SelectionDAG patterns we found, possibly emitting some.
2562   for (const PatternToMatch &Pat : CGP.ptms()) {
2563     ++NumPatternTotal;
2564     auto MatcherOrErr = runOnPattern(Pat);
2565 
2566     // The pattern analysis can fail, indicating an unsupported pattern.
2567     // Report that if we've been asked to do so.
2568     if (auto Err = MatcherOrErr.takeError()) {
2569       if (WarnOnSkippedPatterns) {
2570         PrintWarning(Pat.getSrcRecord()->getLoc(),
2571                      "Skipped pattern: " + toString(std::move(Err)));
2572       } else {
2573         consumeError(std::move(Err));
2574       }
2575       ++NumPatternImportsSkipped;
2576       continue;
2577     }
2578 
2579     Rules.push_back(std::move(MatcherOrErr.get()));
2580   }
2581 
2582   std::stable_sort(Rules.begin(), Rules.end(),
2583             [&](const RuleMatcher &A, const RuleMatcher &B) {
2584               if (A.isHigherPriorityThan(B)) {
2585                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2586                                                      "and less important at "
2587                                                      "the same time");
2588                 return true;
2589               }
2590               return false;
2591             });
2592 
2593   std::vector<Record *> ComplexPredicates =
2594       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2595   std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2596             [](const Record *A, const Record *B) {
2597               if (A->getName() < B->getName())
2598                 return true;
2599               return false;
2600             });
2601   unsigned MaxTemporaries = 0;
2602   for (const auto &Rule : Rules)
2603     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
2604 
2605   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2606      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2607      << ";\n"
2608      << "using PredicateBitset = "
2609         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2610      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2611 
2612   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2613      << "  mutable MatcherState State;\n"
2614      << "  typedef "
2615         "ComplexRendererFn("
2616      << Target.getName()
2617      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2618      << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2619         "MatcherInfo;\n"
2620      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
2621 
2622   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2623      << ", State(" << MaxTemporaries << "),\n"
2624      << "MatcherInfo({TypeObjects, FeatureBitsets, ImmPredicateFns, {\n"
2625      << "  nullptr, // GICP_Invalid\n";
2626   for (const auto &Record : ComplexPredicates)
2627     OS << "  &" << Target.getName()
2628        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2629        << ", // " << Record->getName() << "\n";
2630   OS << "}})\n"
2631      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
2632 
2633   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2634   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2635                                                            OS);
2636 
2637   // Separate subtarget features by how often they must be recomputed.
2638   SubtargetFeatureInfoMap ModuleFeatures;
2639   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2640                std::inserter(ModuleFeatures, ModuleFeatures.end()),
2641                [](const SubtargetFeatureInfoMap::value_type &X) {
2642                  return !X.second.mustRecomputePerFunction();
2643                });
2644   SubtargetFeatureInfoMap FunctionFeatures;
2645   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2646                std::inserter(FunctionFeatures, FunctionFeatures.end()),
2647                [](const SubtargetFeatureInfoMap::value_type &X) {
2648                  return X.second.mustRecomputePerFunction();
2649                });
2650 
2651   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2652       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2653       ModuleFeatures, OS);
2654   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2655       Target.getName(), "InstructionSelector",
2656       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2657       "const MachineFunction *MF");
2658 
2659   // Emit a table containing the LLT objects needed by the matcher and an enum
2660   // for the matcher to reference them with.
2661   std::vector<LLTCodeGen> TypeObjects;
2662   for (const auto &Ty : LLTOperandMatcher::KnownTypes)
2663     TypeObjects.push_back(Ty);
2664   std::sort(TypeObjects.begin(), TypeObjects.end());
2665   OS << "// LLT Objects.\n"
2666      << "enum {\n";
2667   for (const auto &TypeObject : TypeObjects) {
2668     OS << "  ";
2669     TypeObject.emitCxxEnumValue(OS);
2670     OS << ",\n";
2671   }
2672   OS << "};\n"
2673      << "const static LLT TypeObjects[] = {\n";
2674   for (const auto &TypeObject : TypeObjects) {
2675     OS << "  ";
2676     TypeObject.emitCxxConstructorCall(OS);
2677     OS << ",\n";
2678   }
2679   OS << "};\n\n";
2680 
2681   // Emit a table containing the PredicateBitsets objects needed by the matcher
2682   // and an enum for the matcher to reference them with.
2683   std::vector<std::vector<Record *>> FeatureBitsets;
2684   for (auto &Rule : Rules)
2685     FeatureBitsets.push_back(Rule.getRequiredFeatures());
2686   std::sort(
2687       FeatureBitsets.begin(), FeatureBitsets.end(),
2688       [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2689         if (A.size() < B.size())
2690           return true;
2691         if (A.size() > B.size())
2692           return false;
2693         for (const auto &Pair : zip(A, B)) {
2694           if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2695             return true;
2696           if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2697             return false;
2698         }
2699         return false;
2700       });
2701   FeatureBitsets.erase(
2702       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2703       FeatureBitsets.end());
2704   OS << "// Feature bitsets.\n"
2705      << "enum {\n"
2706      << "  GIFBS_Invalid,\n";
2707   for (const auto &FeatureBitset : FeatureBitsets) {
2708     if (FeatureBitset.empty())
2709       continue;
2710     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2711   }
2712   OS << "};\n"
2713      << "const static PredicateBitset FeatureBitsets[] {\n"
2714      << "  {}, // GIFBS_Invalid\n";
2715   for (const auto &FeatureBitset : FeatureBitsets) {
2716     if (FeatureBitset.empty())
2717       continue;
2718     OS << "  {";
2719     for (const auto &Feature : FeatureBitset) {
2720       const auto &I = SubtargetFeatures.find(Feature);
2721       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2722       OS << I->second.getEnumBitName() << ", ";
2723     }
2724     OS << "},\n";
2725   }
2726   OS << "};\n\n";
2727 
2728   // Emit complex predicate table and an enum to reference them with.
2729   OS << "// ComplexPattern predicates.\n"
2730      << "enum {\n"
2731      << "  GICP_Invalid,\n";
2732   for (const auto &Record : ComplexPredicates)
2733     OS << "  GICP_" << Record->getName() << ",\n";
2734   OS << "};\n"
2735      << "// See constructor for table contents\n\n";
2736 
2737   // Emit imm predicate table and an enum to reference them with.
2738   // The 'Predicate_' part of the name is redundant but eliminating it is more
2739   // trouble than it's worth.
2740   {
2741     OS << "// PatFrag predicates.\n"
2742        << "enum {\n";
2743     StringRef EnumeratorSeparator = " = GIPFP_Invalid + 1,\n";
2744     for (const auto *Record : RK.getAllDerivedDefinitions("PatFrag")) {
2745       if (!Record->getValueAsString("ImmediateCode").empty()) {
2746         OS << "  GIPFP_Predicate_" << Record->getName() << EnumeratorSeparator;
2747         EnumeratorSeparator = ",\n";
2748       }
2749     }
2750     OS << "};\n";
2751   }
2752   for (const auto *Record : RK.getAllDerivedDefinitions("PatFrag"))
2753     if (!Record->getValueAsString("ImmediateCode").empty())
2754       OS << "  static bool Predicate_" << Record->getName() << "(int64_t Imm) {"
2755          << Record->getValueAsString("ImmediateCode") << "  }\n";
2756   OS << "static InstructionSelector::ImmediatePredicateFn ImmPredicateFns[] = "
2757         "{\n"
2758      << "  nullptr,\n";
2759   for (const auto *Record : RK.getAllDerivedDefinitions("PatFrag"))
2760     if (!Record->getValueAsString("ImmediateCode").empty())
2761       OS << "  Predicate_" << Record->getName() << ",\n";
2762   OS << "};\n";
2763 
2764   OS << "bool " << Target.getName()
2765      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2766      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
2767      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2768      << "  // FIXME: This should be computed on a per-function basis rather "
2769         "than per-insn.\n"
2770      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2771         "&MF);\n"
2772      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2773      << "  NewMIVector OutMIs;\n"
2774      << "  State.MIs.clear();\n"
2775      << "  State.MIs.push_back(&I);\n\n";
2776 
2777   MatchTable Table(0);
2778   for (auto &Rule : Rules) {
2779     Rule.emit(Table);
2780     ++NumPatternEmitted;
2781   }
2782   Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
2783   Table.emitDeclaration(OS);
2784   OS << "  if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
2785   Table.emitUse(OS);
2786   OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
2787      << "    return true;\n"
2788      << "  }\n\n";
2789 
2790   OS << "  return false;\n"
2791      << "}\n"
2792      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
2793 
2794   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2795      << "PredicateBitset AvailableModuleFeatures;\n"
2796      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2797      << "PredicateBitset getAvailableFeatures() const {\n"
2798      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2799      << "}\n"
2800      << "PredicateBitset\n"
2801      << "computeAvailableModuleFeatures(const " << Target.getName()
2802      << "Subtarget *Subtarget) const;\n"
2803      << "PredicateBitset\n"
2804      << "computeAvailableFunctionFeatures(const " << Target.getName()
2805      << "Subtarget *Subtarget,\n"
2806      << "                                 const MachineFunction *MF) const;\n"
2807      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2808 
2809   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2810      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2811      << "AvailableFunctionFeatures()\n"
2812      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
2813 }
2814 
2815 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2816   if (SubtargetFeatures.count(Predicate) == 0)
2817     SubtargetFeatures.emplace(
2818         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2819 }
2820 
2821 } // end anonymous namespace
2822 
2823 //===----------------------------------------------------------------------===//
2824 
2825 namespace llvm {
2826 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2827   GlobalISelEmitter(RK).run(OS);
2828 }
2829 } // End llvm namespace
2830