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