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