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