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