1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This tablegen backend emits code for use by the GlobalISel instruction
11 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12 ///
13 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14 /// backend, filters out the ones that are unsupported, maps
15 /// SelectionDAG-specific constructs to their GlobalISel counterpart
16 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
17 ///
18 /// Not all patterns are supported: pass the tablegen invocation
19 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20 /// as well as why.
21 ///
22 /// The generated file defines a single method:
23 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24 /// intended to be used in InstructionSelector::select as the first-step
25 /// selector for the patterns that don't require complex C++.
26 ///
27 /// FIXME: We'll probably want to eventually define a base
28 /// "TargetGenInstructionSelector" class.
29 ///
30 //===----------------------------------------------------------------------===//
31 
32 #include "CodeGenDAGPatterns.h"
33 #include "SubtargetFeatureInfo.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CodeGenCoverage.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/LowLevelTypeImpl.h"
41 #include "llvm/Support/MachineValueType.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <numeric>
47 #include <string>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
56 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57 
58 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59 
60 static cl::opt<bool> WarnOnSkippedPatterns(
61     "warn-on-skipped-patterns",
62     cl::desc("Explain why a pattern was skipped for inclusion "
63              "in the GlobalISel selector"),
64     cl::init(false), cl::cat(GlobalISelEmitterCat));
65 
66 static cl::opt<bool> GenerateCoverage(
67     "instrument-gisel-coverage",
68     cl::desc("Generate coverage instrumentation for GlobalISel"),
69     cl::init(false), cl::cat(GlobalISelEmitterCat));
70 
71 static cl::opt<std::string> UseCoverageFile(
72     "gisel-coverage-file", cl::init(""),
73     cl::desc("Specify file to retrieve coverage information from"),
74     cl::cat(GlobalISelEmitterCat));
75 
76 static cl::opt<bool> OptimizeMatchTable(
77     "optimize-match-table",
78     cl::desc("Generate an optimized version of the match table"),
79     cl::init(true), cl::cat(GlobalISelEmitterCat));
80 
81 namespace {
82 //===- Helper functions ---------------------------------------------------===//
83 
84 /// Get the name of the enum value used to number the predicate function.
85 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
86   if (Predicate.hasGISelPredicateCode())
87     return "GIPFP_MI_" + Predicate.getFnName();
88   return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
89          Predicate.getFnName();
90 }
91 
92 /// Get the opcode used to check this predicate.
93 std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
94   return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
95 }
96 
97 /// This class stands in for LLT wherever we want to tablegen-erate an
98 /// equivalent at compiler run-time.
99 class LLTCodeGen {
100 private:
101   LLT Ty;
102 
103 public:
104   LLTCodeGen() = default;
105   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106 
107   std::string getCxxEnumValue() const {
108     std::string Str;
109     raw_string_ostream OS(Str);
110 
111     emitCxxEnumValue(OS);
112     return OS.str();
113   }
114 
115   void emitCxxEnumValue(raw_ostream &OS) const {
116     if (Ty.isScalar()) {
117       OS << "GILLT_s" << Ty.getSizeInBits();
118       return;
119     }
120     if (Ty.isVector()) {
121       OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122       return;
123     }
124     if (Ty.isPointer()) {
125       OS << "GILLT_p" << Ty.getAddressSpace();
126       if (Ty.getSizeInBits() > 0)
127         OS << "s" << Ty.getSizeInBits();
128       return;
129     }
130     llvm_unreachable("Unhandled LLT");
131   }
132 
133   void emitCxxConstructorCall(raw_ostream &OS) const {
134     if (Ty.isScalar()) {
135       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136       return;
137     }
138     if (Ty.isVector()) {
139       OS << "LLT::vector(" << Ty.getNumElements() << ", "
140          << Ty.getScalarSizeInBits() << ")";
141       return;
142     }
143     if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144       OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145          << Ty.getSizeInBits() << ")";
146       return;
147     }
148     llvm_unreachable("Unhandled LLT");
149   }
150 
151   const LLT &get() const { return Ty; }
152 
153   /// This ordering is used for std::unique() and llvm::sort(). There's no
154   /// particular logic behind the order but either A < B or B < A must be
155   /// true if A != B.
156   bool operator<(const LLTCodeGen &Other) const {
157     if (Ty.isValid() != Other.Ty.isValid())
158       return Ty.isValid() < Other.Ty.isValid();
159     if (!Ty.isValid())
160       return false;
161 
162     if (Ty.isVector() != Other.Ty.isVector())
163       return Ty.isVector() < Other.Ty.isVector();
164     if (Ty.isScalar() != Other.Ty.isScalar())
165       return Ty.isScalar() < Other.Ty.isScalar();
166     if (Ty.isPointer() != Other.Ty.isPointer())
167       return Ty.isPointer() < Other.Ty.isPointer();
168 
169     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171 
172     if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173       return Ty.getNumElements() < Other.Ty.getNumElements();
174 
175     return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
176   }
177 
178   bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
179 };
180 
181 // Track all types that are used so we can emit the corresponding enum.
182 std::set<LLTCodeGen> KnownTypes;
183 
184 class InstructionMatcher;
185 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
187 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
188   MVT VT(SVT);
189 
190   if (VT.isVector() && VT.getVectorNumElements() != 1)
191     return LLTCodeGen(
192         LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
193 
194   if (VT.isInteger() || VT.isFloatingPoint())
195     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196   return None;
197 }
198 
199 static std::string explainPredicates(const TreePatternNode *N) {
200   std::string Explanation = "";
201   StringRef Separator = "";
202   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203     const TreePredicateFn &P = Call.Fn;
204     Explanation +=
205         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
206     Separator = ", ";
207 
208     if (P.isAlwaysTrue())
209       Explanation += " always-true";
210     if (P.isImmediatePattern())
211       Explanation += " immediate";
212 
213     if (P.isUnindexed())
214       Explanation += " unindexed";
215 
216     if (P.isNonExtLoad())
217       Explanation += " non-extload";
218     if (P.isAnyExtLoad())
219       Explanation += " extload";
220     if (P.isSignExtLoad())
221       Explanation += " sextload";
222     if (P.isZeroExtLoad())
223       Explanation += " zextload";
224 
225     if (P.isNonTruncStore())
226       Explanation += " non-truncstore";
227     if (P.isTruncStore())
228       Explanation += " truncstore";
229 
230     if (Record *VT = P.getMemoryVT())
231       Explanation += (" MemVT=" + VT->getName()).str();
232     if (Record *VT = P.getScalarMemoryVT())
233       Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
234 
235     if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236       raw_string_ostream OS(Explanation);
237       OS << " AddressSpaces=[";
238 
239       StringRef AddrSpaceSeparator;
240       for (Init *Val : AddrSpaces->getValues()) {
241         IntInit *IntVal = dyn_cast<IntInit>(Val);
242         if (!IntVal)
243           continue;
244 
245         OS << AddrSpaceSeparator << IntVal->getValue();
246         AddrSpaceSeparator = ", ";
247       }
248 
249       OS << ']';
250     }
251 
252     int64_t MinAlign = P.getMinAlignment();
253     if (MinAlign > 0)
254       Explanation += " MinAlign=" + utostr(MinAlign);
255 
256     if (P.isAtomicOrderingMonotonic())
257       Explanation += " monotonic";
258     if (P.isAtomicOrderingAcquire())
259       Explanation += " acquire";
260     if (P.isAtomicOrderingRelease())
261       Explanation += " release";
262     if (P.isAtomicOrderingAcquireRelease())
263       Explanation += " acq_rel";
264     if (P.isAtomicOrderingSequentiallyConsistent())
265       Explanation += " seq_cst";
266     if (P.isAtomicOrderingAcquireOrStronger())
267       Explanation += " >=acquire";
268     if (P.isAtomicOrderingWeakerThanAcquire())
269       Explanation += " <acquire";
270     if (P.isAtomicOrderingReleaseOrStronger())
271       Explanation += " >=release";
272     if (P.isAtomicOrderingWeakerThanRelease())
273       Explanation += " <release";
274   }
275   return Explanation;
276 }
277 
278 std::string explainOperator(Record *Operator) {
279   if (Operator->isSubClassOf("SDNode"))
280     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
281 
282   if (Operator->isSubClassOf("Intrinsic"))
283     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284 
285   if (Operator->isSubClassOf("ComplexPattern"))
286     return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287             ")")
288         .str();
289 
290   if (Operator->isSubClassOf("SDNodeXForm"))
291     return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292             ")")
293         .str();
294 
295   return (" (Operator " + Operator->getName() + " not understood)").str();
296 }
297 
298 /// Helper function to let the emitter report skip reason error messages.
299 static Error failedImport(const Twine &Reason) {
300   return make_error<StringError>(Reason, inconvertibleErrorCode());
301 }
302 
303 static Error isTrivialOperatorNode(const TreePatternNode *N) {
304   std::string Explanation = "";
305   std::string Separator = "";
306 
307   bool HasUnsupportedPredicate = false;
308   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309     const TreePredicateFn &Predicate = Call.Fn;
310 
311     if (Predicate.isAlwaysTrue())
312       continue;
313 
314     if (Predicate.isImmediatePattern())
315       continue;
316 
317     if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318         Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
319       continue;
320 
321     if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
322       continue;
323 
324     if (Predicate.isLoad() && Predicate.getMemoryVT())
325       continue;
326 
327     if (Predicate.isLoad() || Predicate.isStore()) {
328       if (Predicate.isUnindexed())
329         continue;
330     }
331 
332     if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333       const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334       if (AddrSpaces && !AddrSpaces->empty())
335         continue;
336 
337       if (Predicate.getMinAlignment() > 0)
338         continue;
339     }
340 
341     if (Predicate.isAtomic() && Predicate.getMemoryVT())
342       continue;
343 
344     if (Predicate.isAtomic() &&
345         (Predicate.isAtomicOrderingMonotonic() ||
346          Predicate.isAtomicOrderingAcquire() ||
347          Predicate.isAtomicOrderingRelease() ||
348          Predicate.isAtomicOrderingAcquireRelease() ||
349          Predicate.isAtomicOrderingSequentiallyConsistent() ||
350          Predicate.isAtomicOrderingAcquireOrStronger() ||
351          Predicate.isAtomicOrderingWeakerThanAcquire() ||
352          Predicate.isAtomicOrderingReleaseOrStronger() ||
353          Predicate.isAtomicOrderingWeakerThanRelease()))
354       continue;
355 
356     if (Predicate.hasGISelPredicateCode())
357       continue;
358 
359     HasUnsupportedPredicate = true;
360     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361     Separator = ", ";
362     Explanation += (Separator + "first-failing:" +
363                     Predicate.getOrigPatFragRecord()->getRecord()->getName())
364                        .str();
365     break;
366   }
367 
368   if (!HasUnsupportedPredicate)
369     return Error::success();
370 
371   return failedImport(Explanation);
372 }
373 
374 static Record *getInitValueAsRegClass(Init *V) {
375   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377       return VDefInit->getDef()->getValueAsDef("RegClass");
378     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379       return VDefInit->getDef();
380   }
381   return nullptr;
382 }
383 
384 std::string
385 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386   std::string Name = "GIFBS";
387   for (const auto &Feature : FeatureBitset)
388     Name += ("_" + Feature->getName()).str();
389   return Name;
390 }
391 
392 //===- MatchTable Helpers -------------------------------------------------===//
393 
394 class MatchTable;
395 
396 /// A record to be stored in a MatchTable.
397 ///
398 /// This class represents any and all output that may be required to emit the
399 /// MatchTable. Instances  are most often configured to represent an opcode or
400 /// value that will be emitted to the table with some formatting but it can also
401 /// represent commas, comments, and other formatting instructions.
402 struct MatchTableRecord {
403   enum RecordFlagsBits {
404     MTRF_None = 0x0,
405     /// Causes EmitStr to be formatted as comment when emitted.
406     MTRF_Comment = 0x1,
407     /// Causes the record value to be followed by a comma when emitted.
408     MTRF_CommaFollows = 0x2,
409     /// Causes the record value to be followed by a line break when emitted.
410     MTRF_LineBreakFollows = 0x4,
411     /// Indicates that the record defines a label and causes an additional
412     /// comment to be emitted containing the index of the label.
413     MTRF_Label = 0x8,
414     /// Causes the record to be emitted as the index of the label specified by
415     /// LabelID along with a comment indicating where that label is.
416     MTRF_JumpTarget = 0x10,
417     /// Causes the formatter to add a level of indentation before emitting the
418     /// record.
419     MTRF_Indent = 0x20,
420     /// Causes the formatter to remove a level of indentation after emitting the
421     /// record.
422     MTRF_Outdent = 0x40,
423   };
424 
425   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426   /// reference or define.
427   unsigned LabelID;
428   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429   /// value, a label name.
430   std::string EmitStr;
431 
432 private:
433   /// The number of MatchTable elements described by this record. Comments are 0
434   /// while values are typically 1. Values >1 may occur when we need to emit
435   /// values that exceed the size of a MatchTable element.
436   unsigned NumElements;
437 
438 public:
439   /// A bitfield of RecordFlagsBits flags.
440   unsigned Flags;
441 
442   /// The actual run-time value, if known
443   int64_t RawValue;
444 
445   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
446                    unsigned NumElements, unsigned Flags,
447                    int64_t RawValue = std::numeric_limits<int64_t>::min())
448       : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
449         EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450         RawValue(RawValue) {
451     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
452            "This value is reserved for non-labels");
453   }
454   MatchTableRecord(const MatchTableRecord &Other) = default;
455   MatchTableRecord(MatchTableRecord &&Other) = default;
456 
457   /// Useful if a Match Table Record gets optimized out
458   void turnIntoComment() {
459     Flags |= MTRF_Comment;
460     Flags &= ~MTRF_CommaFollows;
461     NumElements = 0;
462   }
463 
464   /// For Jump Table generation purposes
465   bool operator<(const MatchTableRecord &Other) const {
466     return RawValue < Other.RawValue;
467   }
468   int64_t getRawValue() const { return RawValue; }
469 
470   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
471             const MatchTable &Table) const;
472   unsigned size() const { return NumElements; }
473 };
474 
475 class Matcher;
476 
477 /// Holds the contents of a generated MatchTable to enable formatting and the
478 /// necessary index tracking needed to support GIM_Try.
479 class MatchTable {
480   /// An unique identifier for the table. The generated table will be named
481   /// MatchTable${ID}.
482   unsigned ID;
483   /// The records that make up the table. Also includes comments describing the
484   /// values being emitted and line breaks to format it.
485   std::vector<MatchTableRecord> Contents;
486   /// The currently defined labels.
487   DenseMap<unsigned, unsigned> LabelMap;
488   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
489   unsigned CurrentSize = 0;
490   /// A unique identifier for a MatchTable label.
491   unsigned CurrentLabelID = 0;
492   /// Determines if the table should be instrumented for rule coverage tracking.
493   bool IsWithCoverage;
494 
495 public:
496   static MatchTableRecord LineBreak;
497   static MatchTableRecord Comment(StringRef Comment) {
498     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
499   }
500   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
501     unsigned ExtraFlags = 0;
502     if (IndentAdjust > 0)
503       ExtraFlags |= MatchTableRecord::MTRF_Indent;
504     if (IndentAdjust < 0)
505       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
506 
507     return MatchTableRecord(None, Opcode, 1,
508                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
509   }
510   static MatchTableRecord NamedValue(StringRef NamedValue) {
511     return MatchTableRecord(None, NamedValue, 1,
512                             MatchTableRecord::MTRF_CommaFollows);
513   }
514   static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
515     return MatchTableRecord(None, NamedValue, 1,
516                             MatchTableRecord::MTRF_CommaFollows, RawValue);
517   }
518   static MatchTableRecord NamedValue(StringRef Namespace,
519                                      StringRef NamedValue) {
520     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
521                             MatchTableRecord::MTRF_CommaFollows);
522   }
523   static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
524                                      int64_t RawValue) {
525     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
526                             MatchTableRecord::MTRF_CommaFollows, RawValue);
527   }
528   static MatchTableRecord IntValue(int64_t IntValue) {
529     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
530                             MatchTableRecord::MTRF_CommaFollows);
531   }
532   static MatchTableRecord Label(unsigned LabelID) {
533     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
534                             MatchTableRecord::MTRF_Label |
535                                 MatchTableRecord::MTRF_Comment |
536                                 MatchTableRecord::MTRF_LineBreakFollows);
537   }
538   static MatchTableRecord JumpTarget(unsigned LabelID) {
539     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
540                             MatchTableRecord::MTRF_JumpTarget |
541                                 MatchTableRecord::MTRF_Comment |
542                                 MatchTableRecord::MTRF_CommaFollows);
543   }
544 
545   static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
546 
547   MatchTable(bool WithCoverage, unsigned ID = 0)
548       : ID(ID), IsWithCoverage(WithCoverage) {}
549 
550   bool isWithCoverage() const { return IsWithCoverage; }
551 
552   void push_back(const MatchTableRecord &Value) {
553     if (Value.Flags & MatchTableRecord::MTRF_Label)
554       defineLabel(Value.LabelID);
555     Contents.push_back(Value);
556     CurrentSize += Value.size();
557   }
558 
559   unsigned allocateLabelID() { return CurrentLabelID++; }
560 
561   void defineLabel(unsigned LabelID) {
562     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
563   }
564 
565   unsigned getLabelIndex(unsigned LabelID) const {
566     const auto I = LabelMap.find(LabelID);
567     assert(I != LabelMap.end() && "Use of undeclared label");
568     return I->second;
569   }
570 
571   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
572 
573   void emitDeclaration(raw_ostream &OS) const {
574     unsigned Indentation = 4;
575     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
576     LineBreak.emit(OS, true, *this);
577     OS << std::string(Indentation, ' ');
578 
579     for (auto I = Contents.begin(), E = Contents.end(); I != E;
580          ++I) {
581       bool LineBreakIsNext = false;
582       const auto &NextI = std::next(I);
583 
584       if (NextI != E) {
585         if (NextI->EmitStr == "" &&
586             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
587           LineBreakIsNext = true;
588       }
589 
590       if (I->Flags & MatchTableRecord::MTRF_Indent)
591         Indentation += 2;
592 
593       I->emit(OS, LineBreakIsNext, *this);
594       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
595         OS << std::string(Indentation, ' ');
596 
597       if (I->Flags & MatchTableRecord::MTRF_Outdent)
598         Indentation -= 2;
599     }
600     OS << "};\n";
601   }
602 };
603 
604 MatchTableRecord MatchTable::LineBreak = {
605     None, "" /* Emit String */, 0 /* Elements */,
606     MatchTableRecord::MTRF_LineBreakFollows};
607 
608 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
609                             const MatchTable &Table) const {
610   bool UseLineComment =
611       LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
612   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
613     UseLineComment = false;
614 
615   if (Flags & MTRF_Comment)
616     OS << (UseLineComment ? "// " : "/*");
617 
618   OS << EmitStr;
619   if (Flags & MTRF_Label)
620     OS << ": @" << Table.getLabelIndex(LabelID);
621 
622   if ((Flags & MTRF_Comment) && !UseLineComment)
623     OS << "*/";
624 
625   if (Flags & MTRF_JumpTarget) {
626     if (Flags & MTRF_Comment)
627       OS << " ";
628     OS << Table.getLabelIndex(LabelID);
629   }
630 
631   if (Flags & MTRF_CommaFollows) {
632     OS << ",";
633     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
634       OS << " ";
635   }
636 
637   if (Flags & MTRF_LineBreakFollows)
638     OS << "\n";
639 }
640 
641 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
642   Table.push_back(Value);
643   return Table;
644 }
645 
646 //===- Matchers -----------------------------------------------------------===//
647 
648 class OperandMatcher;
649 class MatchAction;
650 class PredicateMatcher;
651 class RuleMatcher;
652 
653 class Matcher {
654 public:
655   virtual ~Matcher() = default;
656   virtual void optimize() {}
657   virtual void emit(MatchTable &Table) = 0;
658 
659   virtual bool hasFirstCondition() const = 0;
660   virtual const PredicateMatcher &getFirstCondition() const = 0;
661   virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
662 };
663 
664 MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
665                                   bool WithCoverage) {
666   MatchTable Table(WithCoverage);
667   for (Matcher *Rule : Rules)
668     Rule->emit(Table);
669 
670   return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
671 }
672 
673 class GroupMatcher final : public Matcher {
674   /// Conditions that form a common prefix of all the matchers contained.
675   SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
676 
677   /// All the nested matchers, sharing a common prefix.
678   std::vector<Matcher *> Matchers;
679 
680   /// An owning collection for any auxiliary matchers created while optimizing
681   /// nested matchers contained.
682   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
683 
684 public:
685   /// Add a matcher to the collection of nested matchers if it meets the
686   /// requirements, and return true. If it doesn't, do nothing and return false.
687   ///
688   /// Expected to preserve its argument, so it could be moved out later on.
689   bool addMatcher(Matcher &Candidate);
690 
691   /// Mark the matcher as fully-built and ensure any invariants expected by both
692   /// optimize() and emit(...) methods. Generally, both sequences of calls
693   /// are expected to lead to a sensible result:
694   ///
695   /// addMatcher(...)*; finalize(); optimize(); emit(...); and
696   /// addMatcher(...)*; finalize(); emit(...);
697   ///
698   /// or generally
699   ///
700   /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
701   ///
702   /// Multiple calls to optimize() are expected to be handled gracefully, though
703   /// optimize() is not expected to be idempotent. Multiple calls to finalize()
704   /// aren't generally supported. emit(...) is expected to be non-mutating and
705   /// producing the exact same results upon repeated calls.
706   ///
707   /// addMatcher() calls after the finalize() call are not supported.
708   ///
709   /// finalize() and optimize() are both allowed to mutate the contained
710   /// matchers, so moving them out after finalize() is not supported.
711   void finalize();
712   void optimize() override;
713   void emit(MatchTable &Table) override;
714 
715   /// Could be used to move out the matchers added previously, unless finalize()
716   /// has been already called. If any of the matchers are moved out, the group
717   /// becomes safe to destroy, but not safe to re-use for anything else.
718   iterator_range<std::vector<Matcher *>::iterator> matchers() {
719     return make_range(Matchers.begin(), Matchers.end());
720   }
721   size_t size() const { return Matchers.size(); }
722   bool empty() const { return Matchers.empty(); }
723 
724   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
725     assert(!Conditions.empty() &&
726            "Trying to pop a condition from a condition-less group");
727     std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
728     Conditions.erase(Conditions.begin());
729     return P;
730   }
731   const PredicateMatcher &getFirstCondition() const override {
732     assert(!Conditions.empty() &&
733            "Trying to get a condition from a condition-less group");
734     return *Conditions.front();
735   }
736   bool hasFirstCondition() const override { return !Conditions.empty(); }
737 
738 private:
739   /// See if a candidate matcher could be added to this group solely by
740   /// analyzing its first condition.
741   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
742 };
743 
744 class SwitchMatcher : public Matcher {
745   /// All the nested matchers, representing distinct switch-cases. The first
746   /// conditions (as Matcher::getFirstCondition() reports) of all the nested
747   /// matchers must share the same type and path to a value they check, in other
748   /// words, be isIdenticalDownToValue, but have different values they check
749   /// against.
750   std::vector<Matcher *> Matchers;
751 
752   /// The representative condition, with a type and a path (InsnVarID and OpIdx
753   /// in most cases)  shared by all the matchers contained.
754   std::unique_ptr<PredicateMatcher> Condition = nullptr;
755 
756   /// Temporary set used to check that the case values don't repeat within the
757   /// same switch.
758   std::set<MatchTableRecord> Values;
759 
760   /// An owning collection for any auxiliary matchers created while optimizing
761   /// nested matchers contained.
762   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
763 
764 public:
765   bool addMatcher(Matcher &Candidate);
766 
767   void finalize();
768   void emit(MatchTable &Table) override;
769 
770   iterator_range<std::vector<Matcher *>::iterator> matchers() {
771     return make_range(Matchers.begin(), Matchers.end());
772   }
773   size_t size() const { return Matchers.size(); }
774   bool empty() const { return Matchers.empty(); }
775 
776   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
777     // SwitchMatcher doesn't have a common first condition for its cases, as all
778     // the cases only share a kind of a value (a type and a path to it) they
779     // match, but deliberately differ in the actual value they match.
780     llvm_unreachable("Trying to pop a condition from a condition-less group");
781   }
782   const PredicateMatcher &getFirstCondition() const override {
783     llvm_unreachable("Trying to pop a condition from a condition-less group");
784   }
785   bool hasFirstCondition() const override { return false; }
786 
787 private:
788   /// See if the predicate type has a Switch-implementation for it.
789   static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
790 
791   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
792 
793   /// emit()-helper
794   static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
795                                            MatchTable &Table);
796 };
797 
798 /// Generates code to check that a match rule matches.
799 class RuleMatcher : public Matcher {
800 public:
801   using ActionList = std::list<std::unique_ptr<MatchAction>>;
802   using action_iterator = ActionList::iterator;
803 
804 protected:
805   /// A list of matchers that all need to succeed for the current rule to match.
806   /// FIXME: This currently supports a single match position but could be
807   /// extended to support multiple positions to support div/rem fusion or
808   /// load-multiple instructions.
809   using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
810   MatchersTy Matchers;
811 
812   /// A list of actions that need to be taken when all predicates in this rule
813   /// have succeeded.
814   ActionList Actions;
815 
816   using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
817 
818   /// A map of instruction matchers to the local variables
819   DefinedInsnVariablesMap InsnVariableIDs;
820 
821   using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
822 
823   // The set of instruction matchers that have not yet been claimed for mutation
824   // by a BuildMI.
825   MutatableInsnSet MutatableInsns;
826 
827   /// A map of named operands defined by the matchers that may be referenced by
828   /// the renderers.
829   StringMap<OperandMatcher *> DefinedOperands;
830 
831   /// A map of anonymous physical register operands defined by the matchers that
832   /// may be referenced by the renderers.
833   DenseMap<Record *, OperandMatcher *> PhysRegOperands;
834 
835   /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
836   unsigned NextInsnVarID;
837 
838   /// ID for the next output instruction allocated with allocateOutputInsnID()
839   unsigned NextOutputInsnID;
840 
841   /// ID for the next temporary register ID allocated with allocateTempRegID()
842   unsigned NextTempRegID;
843 
844   std::vector<Record *> RequiredFeatures;
845   std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
846 
847   ArrayRef<SMLoc> SrcLoc;
848 
849   typedef std::tuple<Record *, unsigned, unsigned>
850       DefinedComplexPatternSubOperand;
851   typedef StringMap<DefinedComplexPatternSubOperand>
852       DefinedComplexPatternSubOperandMap;
853   /// A map of Symbolic Names to ComplexPattern sub-operands.
854   DefinedComplexPatternSubOperandMap ComplexSubOperands;
855 
856   uint64_t RuleID;
857   static uint64_t NextRuleID;
858 
859 public:
860   RuleMatcher(ArrayRef<SMLoc> SrcLoc)
861       : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
862         DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
863         NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
864         RuleID(NextRuleID++) {}
865   RuleMatcher(RuleMatcher &&Other) = default;
866   RuleMatcher &operator=(RuleMatcher &&Other) = default;
867 
868   uint64_t getRuleID() const { return RuleID; }
869 
870   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
871   void addRequiredFeature(Record *Feature);
872   const std::vector<Record *> &getRequiredFeatures() const;
873 
874   template <class Kind, class... Args> Kind &addAction(Args &&... args);
875   template <class Kind, class... Args>
876   action_iterator insertAction(action_iterator InsertPt, Args &&... args);
877 
878   /// Define an instruction without emitting any code to do so.
879   unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
880 
881   unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
882   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
883     return InsnVariableIDs.begin();
884   }
885   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
886     return InsnVariableIDs.end();
887   }
888   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
889   defined_insn_vars() const {
890     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
891   }
892 
893   MutatableInsnSet::const_iterator mutatable_insns_begin() const {
894     return MutatableInsns.begin();
895   }
896   MutatableInsnSet::const_iterator mutatable_insns_end() const {
897     return MutatableInsns.end();
898   }
899   iterator_range<typename MutatableInsnSet::const_iterator>
900   mutatable_insns() const {
901     return make_range(mutatable_insns_begin(), mutatable_insns_end());
902   }
903   void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
904     bool R = MutatableInsns.erase(InsnMatcher);
905     assert(R && "Reserving a mutatable insn that isn't available");
906     (void)R;
907   }
908 
909   action_iterator actions_begin() { return Actions.begin(); }
910   action_iterator actions_end() { return Actions.end(); }
911   iterator_range<action_iterator> actions() {
912     return make_range(actions_begin(), actions_end());
913   }
914 
915   void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
916 
917   void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
918 
919   Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
920                                 unsigned RendererID, unsigned SubOperandID) {
921     if (ComplexSubOperands.count(SymbolicName))
922       return failedImport(
923           "Complex suboperand referenced more than once (Operand: " +
924           SymbolicName + ")");
925 
926     ComplexSubOperands[SymbolicName] =
927         std::make_tuple(ComplexPattern, RendererID, SubOperandID);
928 
929     return Error::success();
930   }
931 
932   Optional<DefinedComplexPatternSubOperand>
933   getComplexSubOperand(StringRef SymbolicName) const {
934     const auto &I = ComplexSubOperands.find(SymbolicName);
935     if (I == ComplexSubOperands.end())
936       return None;
937     return I->second;
938   }
939 
940   InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
941   const OperandMatcher &getOperandMatcher(StringRef Name) const;
942   const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
943 
944   void optimize() override;
945   void emit(MatchTable &Table) override;
946 
947   /// Compare the priority of this object and B.
948   ///
949   /// Returns true if this object is more important than B.
950   bool isHigherPriorityThan(const RuleMatcher &B) const;
951 
952   /// Report the maximum number of temporary operands needed by the rule
953   /// matcher.
954   unsigned countRendererFns() const;
955 
956   std::unique_ptr<PredicateMatcher> popFirstCondition() override;
957   const PredicateMatcher &getFirstCondition() const override;
958   LLTCodeGen getFirstConditionAsRootType();
959   bool hasFirstCondition() const override;
960   unsigned getNumOperands() const;
961   StringRef getOpcode() const;
962 
963   // FIXME: Remove this as soon as possible
964   InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
965 
966   unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
967   unsigned allocateTempRegID() { return NextTempRegID++; }
968 
969   iterator_range<MatchersTy::iterator> insnmatchers() {
970     return make_range(Matchers.begin(), Matchers.end());
971   }
972   bool insnmatchers_empty() const { return Matchers.empty(); }
973   void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
974 };
975 
976 uint64_t RuleMatcher::NextRuleID = 0;
977 
978 using action_iterator = RuleMatcher::action_iterator;
979 
980 template <class PredicateTy> class PredicateListMatcher {
981 private:
982   /// Template instantiations should specialize this to return a string to use
983   /// for the comment emitted when there are no predicates.
984   std::string getNoPredicateComment() const;
985 
986 protected:
987   using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
988   PredicatesTy Predicates;
989 
990   /// Track if the list of predicates was manipulated by one of the optimization
991   /// methods.
992   bool Optimized = false;
993 
994 public:
995   /// Construct a new predicate and add it to the matcher.
996   template <class Kind, class... Args>
997   Optional<Kind *> addPredicate(Args &&... args);
998 
999   typename PredicatesTy::iterator predicates_begin() {
1000     return Predicates.begin();
1001   }
1002   typename PredicatesTy::iterator predicates_end() {
1003     return Predicates.end();
1004   }
1005   iterator_range<typename PredicatesTy::iterator> predicates() {
1006     return make_range(predicates_begin(), predicates_end());
1007   }
1008   typename PredicatesTy::size_type predicates_size() const {
1009     return Predicates.size();
1010   }
1011   bool predicates_empty() const { return Predicates.empty(); }
1012 
1013   std::unique_ptr<PredicateTy> predicates_pop_front() {
1014     std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
1015     Predicates.pop_front();
1016     Optimized = true;
1017     return Front;
1018   }
1019 
1020   void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1021     Predicates.push_front(std::move(Predicate));
1022   }
1023 
1024   void eraseNullPredicates() {
1025     const auto NewEnd =
1026         std::stable_partition(Predicates.begin(), Predicates.end(),
1027                               std::logical_not<std::unique_ptr<PredicateTy>>());
1028     if (NewEnd != Predicates.begin()) {
1029       Predicates.erase(Predicates.begin(), NewEnd);
1030       Optimized = true;
1031     }
1032   }
1033 
1034   /// Emit MatchTable opcodes that tests whether all the predicates are met.
1035   template <class... Args>
1036   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1037     if (Predicates.empty() && !Optimized) {
1038       Table << MatchTable::Comment(getNoPredicateComment())
1039             << MatchTable::LineBreak;
1040       return;
1041     }
1042 
1043     for (const auto &Predicate : predicates())
1044       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1045   }
1046 
1047   /// Provide a function to avoid emitting certain predicates. This is used to
1048   /// defer some predicate checks until after others
1049   using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
1050 
1051   /// Emit MatchTable opcodes for predicates which satisfy \p
1052   /// ShouldEmitPredicate. This should be called multiple times to ensure all
1053   /// predicates are eventually added to the match table.
1054   template <class... Args>
1055   void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
1056                                         MatchTable &Table, Args &&... args) {
1057     if (Predicates.empty() && !Optimized) {
1058       Table << MatchTable::Comment(getNoPredicateComment())
1059             << MatchTable::LineBreak;
1060       return;
1061     }
1062 
1063     for (const auto &Predicate : predicates()) {
1064       if (ShouldEmitPredicate(*Predicate))
1065         Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1066     }
1067   }
1068 };
1069 
1070 class PredicateMatcher {
1071 public:
1072   /// This enum is used for RTTI and also defines the priority that is given to
1073   /// the predicate when generating the matcher code. Kinds with higher priority
1074   /// must be tested first.
1075   ///
1076   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1077   /// but OPM_Int must have priority over OPM_RegBank since constant integers
1078   /// are represented by a virtual register defined by a G_CONSTANT instruction.
1079   ///
1080   /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1081   /// are currently not compared between each other.
1082   enum PredicateKind {
1083     IPM_Opcode,
1084     IPM_NumOperands,
1085     IPM_ImmPredicate,
1086     IPM_Imm,
1087     IPM_AtomicOrderingMMO,
1088     IPM_MemoryLLTSize,
1089     IPM_MemoryVsLLTSize,
1090     IPM_MemoryAddressSpace,
1091     IPM_MemoryAlignment,
1092     IPM_VectorSplatImm,
1093     IPM_GenericPredicate,
1094     OPM_SameOperand,
1095     OPM_ComplexPattern,
1096     OPM_IntrinsicID,
1097     OPM_CmpPredicate,
1098     OPM_Instruction,
1099     OPM_Int,
1100     OPM_LiteralInt,
1101     OPM_LLT,
1102     OPM_PointerToAny,
1103     OPM_RegBank,
1104     OPM_MBB,
1105   };
1106 
1107 protected:
1108   PredicateKind Kind;
1109   unsigned InsnVarID;
1110   unsigned OpIdx;
1111 
1112 public:
1113   PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1114       : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
1115 
1116   unsigned getInsnVarID() const { return InsnVarID; }
1117   unsigned getOpIdx() const { return OpIdx; }
1118 
1119   virtual ~PredicateMatcher() = default;
1120   /// Emit MatchTable opcodes that check the predicate for the given operand.
1121   virtual void emitPredicateOpcodes(MatchTable &Table,
1122                                     RuleMatcher &Rule) const = 0;
1123 
1124   PredicateKind getKind() const { return Kind; }
1125 
1126   bool dependsOnOperands() const {
1127     // Custom predicates really depend on the context pattern of the
1128     // instruction, not just the individual instruction. This therefore
1129     // implicitly depends on all other pattern constraints.
1130     return Kind == IPM_GenericPredicate;
1131   }
1132 
1133   virtual bool isIdentical(const PredicateMatcher &B) const {
1134     return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1135            OpIdx == B.OpIdx;
1136   }
1137 
1138   virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1139     return hasValue() && PredicateMatcher::isIdentical(B);
1140   }
1141 
1142   virtual MatchTableRecord getValue() const {
1143     assert(hasValue() && "Can not get a value of a value-less predicate!");
1144     llvm_unreachable("Not implemented yet");
1145   }
1146   virtual bool hasValue() const { return false; }
1147 
1148   /// Report the maximum number of temporary operands needed by the predicate
1149   /// matcher.
1150   virtual unsigned countRendererFns() const { return 0; }
1151 };
1152 
1153 /// Generates code to check a predicate of an operand.
1154 ///
1155 /// Typical predicates include:
1156 /// * Operand is a particular register.
1157 /// * Operand is assigned a particular register bank.
1158 /// * Operand is an MBB.
1159 class OperandPredicateMatcher : public PredicateMatcher {
1160 public:
1161   OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1162                           unsigned OpIdx)
1163       : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
1164   virtual ~OperandPredicateMatcher() {}
1165 
1166   /// Compare the priority of this object and B.
1167   ///
1168   /// Returns true if this object is more important than B.
1169   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
1170 };
1171 
1172 template <>
1173 std::string
1174 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1175   return "No operand predicates";
1176 }
1177 
1178 /// Generates code to check that a register operand is defined by the same exact
1179 /// one as another.
1180 class SameOperandMatcher : public OperandPredicateMatcher {
1181   std::string MatchingName;
1182 
1183 public:
1184   SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
1185       : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1186         MatchingName(MatchingName) {}
1187 
1188   static bool classof(const PredicateMatcher *P) {
1189     return P->getKind() == OPM_SameOperand;
1190   }
1191 
1192   void emitPredicateOpcodes(MatchTable &Table,
1193                             RuleMatcher &Rule) const override;
1194 
1195   bool isIdentical(const PredicateMatcher &B) const override {
1196     return OperandPredicateMatcher::isIdentical(B) &&
1197            MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1198   }
1199 };
1200 
1201 /// Generates code to check that an operand is a particular LLT.
1202 class LLTOperandMatcher : public OperandPredicateMatcher {
1203 protected:
1204   LLTCodeGen Ty;
1205 
1206 public:
1207   static std::map<LLTCodeGen, unsigned> TypeIDValues;
1208 
1209   static void initTypeIDValuesMap() {
1210     TypeIDValues.clear();
1211 
1212     unsigned ID = 0;
1213     for (const LLTCodeGen &LLTy : KnownTypes)
1214       TypeIDValues[LLTy] = ID++;
1215   }
1216 
1217   LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
1218       : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
1219     KnownTypes.insert(Ty);
1220   }
1221 
1222   static bool classof(const PredicateMatcher *P) {
1223     return P->getKind() == OPM_LLT;
1224   }
1225   bool isIdentical(const PredicateMatcher &B) const override {
1226     return OperandPredicateMatcher::isIdentical(B) &&
1227            Ty == cast<LLTOperandMatcher>(&B)->Ty;
1228   }
1229   MatchTableRecord getValue() const override {
1230     const auto VI = TypeIDValues.find(Ty);
1231     if (VI == TypeIDValues.end())
1232       return MatchTable::NamedValue(getTy().getCxxEnumValue());
1233     return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1234   }
1235   bool hasValue() const override {
1236     if (TypeIDValues.size() != KnownTypes.size())
1237       initTypeIDValuesMap();
1238     return TypeIDValues.count(Ty);
1239   }
1240 
1241   LLTCodeGen getTy() const { return Ty; }
1242 
1243   void emitPredicateOpcodes(MatchTable &Table,
1244                             RuleMatcher &Rule) const override {
1245     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1246           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1247           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
1248           << getValue() << MatchTable::LineBreak;
1249   }
1250 };
1251 
1252 std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1253 
1254 /// Generates code to check that an operand is a pointer to any address space.
1255 ///
1256 /// In SelectionDAG, the types did not describe pointers or address spaces. As a
1257 /// result, iN is used to describe a pointer of N bits to any address space and
1258 /// PatFrag predicates are typically used to constrain the address space. There's
1259 /// no reliable means to derive the missing type information from the pattern so
1260 /// imported rules must test the components of a pointer separately.
1261 ///
1262 /// If SizeInBits is zero, then the pointer size will be obtained from the
1263 /// subtarget.
1264 class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1265 protected:
1266   unsigned SizeInBits;
1267 
1268 public:
1269   PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1270                              unsigned SizeInBits)
1271       : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1272         SizeInBits(SizeInBits) {}
1273 
1274   static bool classof(const OperandPredicateMatcher *P) {
1275     return P->getKind() == OPM_PointerToAny;
1276   }
1277 
1278   void emitPredicateOpcodes(MatchTable &Table,
1279                             RuleMatcher &Rule) const override {
1280     Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1281           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1282           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1283           << MatchTable::Comment("SizeInBits")
1284           << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1285   }
1286 };
1287 
1288 /// Generates code to check that an operand is a particular target constant.
1289 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1290 protected:
1291   const OperandMatcher &Operand;
1292   const Record &TheDef;
1293 
1294   unsigned getAllocatedTemporariesBaseID() const;
1295 
1296 public:
1297   bool isIdentical(const PredicateMatcher &B) const override { return false; }
1298 
1299   ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1300                                const OperandMatcher &Operand,
1301                                const Record &TheDef)
1302       : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1303         Operand(Operand), TheDef(TheDef) {}
1304 
1305   static bool classof(const PredicateMatcher *P) {
1306     return P->getKind() == OPM_ComplexPattern;
1307   }
1308 
1309   void emitPredicateOpcodes(MatchTable &Table,
1310                             RuleMatcher &Rule) const override {
1311     unsigned ID = getAllocatedTemporariesBaseID();
1312     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1313           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1314           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1315           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1316           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1317           << MatchTable::LineBreak;
1318   }
1319 
1320   unsigned countRendererFns() const override {
1321     return 1;
1322   }
1323 };
1324 
1325 /// Generates code to check that an operand is in a particular register bank.
1326 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1327 protected:
1328   const CodeGenRegisterClass &RC;
1329 
1330 public:
1331   RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1332                              const CodeGenRegisterClass &RC)
1333       : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
1334 
1335   bool isIdentical(const PredicateMatcher &B) const override {
1336     return OperandPredicateMatcher::isIdentical(B) &&
1337            RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1338   }
1339 
1340   static bool classof(const PredicateMatcher *P) {
1341     return P->getKind() == OPM_RegBank;
1342   }
1343 
1344   void emitPredicateOpcodes(MatchTable &Table,
1345                             RuleMatcher &Rule) const override {
1346     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1347           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1348           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1349           << MatchTable::Comment("RC")
1350           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1351           << MatchTable::LineBreak;
1352   }
1353 };
1354 
1355 /// Generates code to check that an operand is a basic block.
1356 class MBBOperandMatcher : public OperandPredicateMatcher {
1357 public:
1358   MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1359       : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
1360 
1361   static bool classof(const PredicateMatcher *P) {
1362     return P->getKind() == OPM_MBB;
1363   }
1364 
1365   void emitPredicateOpcodes(MatchTable &Table,
1366                             RuleMatcher &Rule) const override {
1367     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1368           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1369           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1370   }
1371 };
1372 
1373 class ImmOperandMatcher : public OperandPredicateMatcher {
1374 public:
1375   ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1376       : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1377 
1378   static bool classof(const PredicateMatcher *P) {
1379     return P->getKind() == IPM_Imm;
1380   }
1381 
1382   void emitPredicateOpcodes(MatchTable &Table,
1383                             RuleMatcher &Rule) const override {
1384     Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1385           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1386           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1387   }
1388 };
1389 
1390 /// Generates code to check that an operand is a G_CONSTANT with a particular
1391 /// int.
1392 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
1393 protected:
1394   int64_t Value;
1395 
1396 public:
1397   ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1398       : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
1399 
1400   bool isIdentical(const PredicateMatcher &B) const override {
1401     return OperandPredicateMatcher::isIdentical(B) &&
1402            Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1403   }
1404 
1405   static bool classof(const PredicateMatcher *P) {
1406     return P->getKind() == OPM_Int;
1407   }
1408 
1409   void emitPredicateOpcodes(MatchTable &Table,
1410                             RuleMatcher &Rule) const override {
1411     Table << MatchTable::Opcode("GIM_CheckConstantInt")
1412           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1413           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1414           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1415   }
1416 };
1417 
1418 /// Generates code to check that an operand is a raw int (where MO.isImm() or
1419 /// MO.isCImm() is true).
1420 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1421 protected:
1422   int64_t Value;
1423 
1424 public:
1425   LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1426       : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1427         Value(Value) {}
1428 
1429   bool isIdentical(const PredicateMatcher &B) const override {
1430     return OperandPredicateMatcher::isIdentical(B) &&
1431            Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1432   }
1433 
1434   static bool classof(const PredicateMatcher *P) {
1435     return P->getKind() == OPM_LiteralInt;
1436   }
1437 
1438   void emitPredicateOpcodes(MatchTable &Table,
1439                             RuleMatcher &Rule) const override {
1440     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1441           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1442           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1443           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1444   }
1445 };
1446 
1447 /// Generates code to check that an operand is an CmpInst predicate
1448 class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1449 protected:
1450   std::string PredName;
1451 
1452 public:
1453   CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1454                              std::string P)
1455     : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1456 
1457   bool isIdentical(const PredicateMatcher &B) const override {
1458     return OperandPredicateMatcher::isIdentical(B) &&
1459            PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1460   }
1461 
1462   static bool classof(const PredicateMatcher *P) {
1463     return P->getKind() == OPM_CmpPredicate;
1464   }
1465 
1466   void emitPredicateOpcodes(MatchTable &Table,
1467                             RuleMatcher &Rule) const override {
1468     Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1469           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1470           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1471           << MatchTable::Comment("Predicate")
1472           << MatchTable::NamedValue("CmpInst", PredName)
1473           << MatchTable::LineBreak;
1474   }
1475 };
1476 
1477 /// Generates code to check that an operand is an intrinsic ID.
1478 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1479 protected:
1480   const CodeGenIntrinsic *II;
1481 
1482 public:
1483   IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1484                             const CodeGenIntrinsic *II)
1485       : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
1486 
1487   bool isIdentical(const PredicateMatcher &B) const override {
1488     return OperandPredicateMatcher::isIdentical(B) &&
1489            II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1490   }
1491 
1492   static bool classof(const PredicateMatcher *P) {
1493     return P->getKind() == OPM_IntrinsicID;
1494   }
1495 
1496   void emitPredicateOpcodes(MatchTable &Table,
1497                             RuleMatcher &Rule) const override {
1498     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1499           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1500           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1501           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1502           << MatchTable::LineBreak;
1503   }
1504 };
1505 
1506 /// Generates code to check that a set of predicates match for a particular
1507 /// operand.
1508 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1509 protected:
1510   InstructionMatcher &Insn;
1511   unsigned OpIdx;
1512   std::string SymbolicName;
1513 
1514   /// The index of the first temporary variable allocated to this operand. The
1515   /// number of allocated temporaries can be found with
1516   /// countRendererFns().
1517   unsigned AllocatedTemporariesBaseID;
1518 
1519 public:
1520   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
1521                  const std::string &SymbolicName,
1522                  unsigned AllocatedTemporariesBaseID)
1523       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1524         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
1525 
1526   bool hasSymbolicName() const { return !SymbolicName.empty(); }
1527   const StringRef getSymbolicName() const { return SymbolicName; }
1528   void setSymbolicName(StringRef Name) {
1529     assert(SymbolicName.empty() && "Operand already has a symbolic name");
1530     SymbolicName = std::string(Name);
1531   }
1532 
1533   /// Construct a new operand predicate and add it to the matcher.
1534   template <class Kind, class... Args>
1535   Optional<Kind *> addPredicate(Args &&... args) {
1536     if (isSameAsAnotherOperand())
1537       return None;
1538     Predicates.emplace_back(std::make_unique<Kind>(
1539         getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1540     return static_cast<Kind *>(Predicates.back().get());
1541   }
1542 
1543   unsigned getOpIdx() const { return OpIdx; }
1544   unsigned getInsnVarID() const;
1545 
1546   std::string getOperandExpr(unsigned InsnVarID) const {
1547     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1548            llvm::to_string(OpIdx) + ")";
1549   }
1550 
1551   InstructionMatcher &getInstructionMatcher() const { return Insn; }
1552 
1553   Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1554                               bool OperandIsAPointer);
1555 
1556   /// Emit MatchTable opcodes that test whether the instruction named in
1557   /// InsnVarID matches all the predicates and all the operands.
1558   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1559     if (!Optimized) {
1560       std::string Comment;
1561       raw_string_ostream CommentOS(Comment);
1562       CommentOS << "MIs[" << getInsnVarID() << "] ";
1563       if (SymbolicName.empty())
1564         CommentOS << "Operand " << OpIdx;
1565       else
1566         CommentOS << SymbolicName;
1567       Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1568     }
1569 
1570     emitPredicateListOpcodes(Table, Rule);
1571   }
1572 
1573   /// Compare the priority of this object and B.
1574   ///
1575   /// Returns true if this object is more important than B.
1576   bool isHigherPriorityThan(OperandMatcher &B) {
1577     // Operand matchers involving more predicates have higher priority.
1578     if (predicates_size() > B.predicates_size())
1579       return true;
1580     if (predicates_size() < B.predicates_size())
1581       return false;
1582 
1583     // This assumes that predicates are added in a consistent order.
1584     for (auto &&Predicate : zip(predicates(), B.predicates())) {
1585       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1586         return true;
1587       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1588         return false;
1589     }
1590 
1591     return false;
1592   };
1593 
1594   /// Report the maximum number of temporary operands needed by the operand
1595   /// matcher.
1596   unsigned countRendererFns() {
1597     return std::accumulate(
1598         predicates().begin(), predicates().end(), 0,
1599         [](unsigned A,
1600            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
1601           return A + Predicate->countRendererFns();
1602         });
1603   }
1604 
1605   unsigned getAllocatedTemporariesBaseID() const {
1606     return AllocatedTemporariesBaseID;
1607   }
1608 
1609   bool isSameAsAnotherOperand() {
1610     for (const auto &Predicate : predicates())
1611       if (isa<SameOperandMatcher>(Predicate))
1612         return true;
1613     return false;
1614   }
1615 };
1616 
1617 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1618                                             bool OperandIsAPointer) {
1619   if (!VTy.isMachineValueType())
1620     return failedImport("unsupported typeset");
1621 
1622   if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1623     addPredicate<PointerToAnyOperandMatcher>(0);
1624     return Error::success();
1625   }
1626 
1627   auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1628   if (!OpTyOrNone)
1629     return failedImport("unsupported type");
1630 
1631   if (OperandIsAPointer)
1632     addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1633   else if (VTy.isPointer())
1634     addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1635                                                  OpTyOrNone->get().getSizeInBits()));
1636   else
1637     addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1638   return Error::success();
1639 }
1640 
1641 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1642   return Operand.getAllocatedTemporariesBaseID();
1643 }
1644 
1645 /// Generates code to check a predicate on an instruction.
1646 ///
1647 /// Typical predicates include:
1648 /// * The opcode of the instruction is a particular value.
1649 /// * The nsw/nuw flag is/isn't set.
1650 class InstructionPredicateMatcher : public PredicateMatcher {
1651 public:
1652   InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1653       : PredicateMatcher(Kind, InsnVarID) {}
1654   virtual ~InstructionPredicateMatcher() {}
1655 
1656   /// Compare the priority of this object and B.
1657   ///
1658   /// Returns true if this object is more important than B.
1659   virtual bool
1660   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
1661     return Kind < B.Kind;
1662   };
1663 };
1664 
1665 template <>
1666 std::string
1667 PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
1668   return "No instruction predicates";
1669 }
1670 
1671 /// Generates code to check the opcode of an instruction.
1672 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1673 protected:
1674   // Allow matching one to several, similar opcodes that share properties. This
1675   // is to handle patterns where one SelectionDAG operation maps to multiple
1676   // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
1677   // is treated as the canonical opcode.
1678   SmallVector<const CodeGenInstruction *, 2> Insts;
1679 
1680   static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1681 
1682 
1683   MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
1684     const auto VI = OpcodeValues.find(I);
1685     if (VI != OpcodeValues.end())
1686       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1687                                     VI->second);
1688     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1689   }
1690 
1691 public:
1692   static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1693     OpcodeValues.clear();
1694 
1695     unsigned OpcodeValue = 0;
1696     for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1697       OpcodeValues[I] = OpcodeValue++;
1698   }
1699 
1700   InstructionOpcodeMatcher(unsigned InsnVarID,
1701                            ArrayRef<const CodeGenInstruction *> I)
1702       : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
1703         Insts(I.begin(), I.end()) {
1704     assert((Insts.size() == 1 || Insts.size() == 2) &&
1705            "unexpected number of opcode alternatives");
1706   }
1707 
1708   static bool classof(const PredicateMatcher *P) {
1709     return P->getKind() == IPM_Opcode;
1710   }
1711 
1712   bool isIdentical(const PredicateMatcher &B) const override {
1713     return InstructionPredicateMatcher::isIdentical(B) &&
1714            Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
1715   }
1716 
1717   bool hasValue() const override {
1718     return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
1719   }
1720 
1721   // TODO: This is used for the SwitchMatcher optimization. We should be able to
1722   // return a list of the opcodes to match.
1723   MatchTableRecord getValue() const override {
1724     assert(Insts.size() == 1);
1725 
1726     const CodeGenInstruction *I = Insts[0];
1727     const auto VI = OpcodeValues.find(I);
1728     if (VI != OpcodeValues.end())
1729       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1730                                     VI->second);
1731     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1732   }
1733 
1734   void emitPredicateOpcodes(MatchTable &Table,
1735                             RuleMatcher &Rule) const override {
1736     StringRef CheckType = Insts.size() == 1 ?
1737                           "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
1738     Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
1739           << MatchTable::IntValue(InsnVarID);
1740 
1741     for (const CodeGenInstruction *I : Insts)
1742       Table << getInstValue(I);
1743     Table << MatchTable::LineBreak;
1744   }
1745 
1746   /// Compare the priority of this object and B.
1747   ///
1748   /// Returns true if this object is more important than B.
1749   bool
1750   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1751     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1752       return true;
1753     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1754       return false;
1755 
1756     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1757     // this is cosmetic at the moment, we may want to drive a similar ordering
1758     // using instruction frequency information to improve compile time.
1759     if (const InstructionOpcodeMatcher *BO =
1760             dyn_cast<InstructionOpcodeMatcher>(&B))
1761       return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
1762 
1763     return false;
1764   };
1765 
1766   bool isConstantInstruction() const {
1767     return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
1768   }
1769 
1770   // The first opcode is the canonical opcode, and later are alternatives.
1771   StringRef getOpcode() const {
1772     return Insts[0]->TheDef->getName();
1773   }
1774 
1775   ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
1776     return Insts;
1777   }
1778 
1779   bool isVariadicNumOperands() const {
1780     // If one is variadic, they all should be.
1781     return Insts[0]->Operands.isVariadic;
1782   }
1783 
1784   StringRef getOperandType(unsigned OpIdx) const {
1785     // Types expected to be uniform for all alternatives.
1786     return Insts[0]->Operands[OpIdx].OperandType;
1787   }
1788 };
1789 
1790 DenseMap<const CodeGenInstruction *, unsigned>
1791     InstructionOpcodeMatcher::OpcodeValues;
1792 
1793 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1794   unsigned NumOperands = 0;
1795 
1796 public:
1797   InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1798       : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1799         NumOperands(NumOperands) {}
1800 
1801   static bool classof(const PredicateMatcher *P) {
1802     return P->getKind() == IPM_NumOperands;
1803   }
1804 
1805   bool isIdentical(const PredicateMatcher &B) const override {
1806     return InstructionPredicateMatcher::isIdentical(B) &&
1807            NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1808   }
1809 
1810   void emitPredicateOpcodes(MatchTable &Table,
1811                             RuleMatcher &Rule) const override {
1812     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1813           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1814           << MatchTable::Comment("Expected")
1815           << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1816   }
1817 };
1818 
1819 /// Generates code to check that this instruction is a constant whose value
1820 /// meets an immediate predicate.
1821 ///
1822 /// Immediates are slightly odd since they are typically used like an operand
1823 /// but are represented as an operator internally. We typically write simm8:$src
1824 /// in a tablegen pattern, but this is just syntactic sugar for
1825 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1826 /// that will be matched and the predicate (which is attached to the imm
1827 /// operator) that will be tested. In SelectionDAG this describes a
1828 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1829 ///
1830 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1831 /// this representation, the immediate could be tested with an
1832 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1833 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1834 /// there are two implementation issues with producing that matcher
1835 /// configuration from the SelectionDAG pattern:
1836 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1837 ///   were we to sink the immediate predicate to the operand we would have to
1838 ///   have two partial implementations of PatFrag support, one for immediates
1839 ///   and one for non-immediates.
1840 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1841 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1842 ///   would also have to complicate (or duplicate) the code that descends and
1843 ///   creates matchers for the subtree.
1844 /// Overall, it's simpler to handle it in the place it was found.
1845 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1846 protected:
1847   TreePredicateFn Predicate;
1848 
1849 public:
1850   InstructionImmPredicateMatcher(unsigned InsnVarID,
1851                                  const TreePredicateFn &Predicate)
1852       : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1853         Predicate(Predicate) {}
1854 
1855   bool isIdentical(const PredicateMatcher &B) const override {
1856     return InstructionPredicateMatcher::isIdentical(B) &&
1857            Predicate.getOrigPatFragRecord() ==
1858                cast<InstructionImmPredicateMatcher>(&B)
1859                    ->Predicate.getOrigPatFragRecord();
1860   }
1861 
1862   static bool classof(const PredicateMatcher *P) {
1863     return P->getKind() == IPM_ImmPredicate;
1864   }
1865 
1866   void emitPredicateOpcodes(MatchTable &Table,
1867                             RuleMatcher &Rule) const override {
1868     Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
1869           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1870           << MatchTable::Comment("Predicate")
1871           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1872           << MatchTable::LineBreak;
1873   }
1874 };
1875 
1876 /// Generates code to check that a memory instruction has a atomic ordering
1877 /// MachineMemoryOperand.
1878 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1879 public:
1880   enum AOComparator {
1881     AO_Exactly,
1882     AO_OrStronger,
1883     AO_WeakerThan,
1884   };
1885 
1886 protected:
1887   StringRef Order;
1888   AOComparator Comparator;
1889 
1890 public:
1891   AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
1892                                     AOComparator Comparator = AO_Exactly)
1893       : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1894         Order(Order), Comparator(Comparator) {}
1895 
1896   static bool classof(const PredicateMatcher *P) {
1897     return P->getKind() == IPM_AtomicOrderingMMO;
1898   }
1899 
1900   bool isIdentical(const PredicateMatcher &B) const override {
1901     if (!InstructionPredicateMatcher::isIdentical(B))
1902       return false;
1903     const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1904     return Order == R.Order && Comparator == R.Comparator;
1905   }
1906 
1907   void emitPredicateOpcodes(MatchTable &Table,
1908                             RuleMatcher &Rule) const override {
1909     StringRef Opcode = "GIM_CheckAtomicOrdering";
1910 
1911     if (Comparator == AO_OrStronger)
1912       Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1913     if (Comparator == AO_WeakerThan)
1914       Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1915 
1916     Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1917           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
1918           << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
1919           << MatchTable::LineBreak;
1920   }
1921 };
1922 
1923 /// Generates code to check that the size of an MMO is exactly N bytes.
1924 class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1925 protected:
1926   unsigned MMOIdx;
1927   uint64_t Size;
1928 
1929 public:
1930   MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1931       : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1932         MMOIdx(MMOIdx), Size(Size) {}
1933 
1934   static bool classof(const PredicateMatcher *P) {
1935     return P->getKind() == IPM_MemoryLLTSize;
1936   }
1937   bool isIdentical(const PredicateMatcher &B) const override {
1938     return InstructionPredicateMatcher::isIdentical(B) &&
1939            MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1940            Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1941   }
1942 
1943   void emitPredicateOpcodes(MatchTable &Table,
1944                             RuleMatcher &Rule) const override {
1945     Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1946           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1947           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1948           << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1949           << MatchTable::LineBreak;
1950   }
1951 };
1952 
1953 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1954 protected:
1955   unsigned MMOIdx;
1956   SmallVector<unsigned, 4> AddrSpaces;
1957 
1958 public:
1959   MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1960                                      ArrayRef<unsigned> AddrSpaces)
1961       : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1962         MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1963 
1964   static bool classof(const PredicateMatcher *P) {
1965     return P->getKind() == IPM_MemoryAddressSpace;
1966   }
1967   bool isIdentical(const PredicateMatcher &B) const override {
1968     if (!InstructionPredicateMatcher::isIdentical(B))
1969       return false;
1970     auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1971     return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1972   }
1973 
1974   void emitPredicateOpcodes(MatchTable &Table,
1975                             RuleMatcher &Rule) const override {
1976     Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1977           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1978           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1979         // Encode number of address spaces to expect.
1980           << MatchTable::Comment("NumAddrSpace")
1981           << MatchTable::IntValue(AddrSpaces.size());
1982     for (unsigned AS : AddrSpaces)
1983       Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1984 
1985     Table << MatchTable::LineBreak;
1986   }
1987 };
1988 
1989 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1990 protected:
1991   unsigned MMOIdx;
1992   int MinAlign;
1993 
1994 public:
1995   MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1996                                   int MinAlign)
1997       : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1998         MMOIdx(MMOIdx), MinAlign(MinAlign) {
1999     assert(MinAlign > 0);
2000   }
2001 
2002   static bool classof(const PredicateMatcher *P) {
2003     return P->getKind() == IPM_MemoryAlignment;
2004   }
2005 
2006   bool isIdentical(const PredicateMatcher &B) const override {
2007     if (!InstructionPredicateMatcher::isIdentical(B))
2008       return false;
2009     auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
2010     return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
2011   }
2012 
2013   void emitPredicateOpcodes(MatchTable &Table,
2014                             RuleMatcher &Rule) const override {
2015     Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
2016           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2017           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2018           << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
2019           << MatchTable::LineBreak;
2020   }
2021 };
2022 
2023 /// Generates code to check that the size of an MMO is less-than, equal-to, or
2024 /// greater than a given LLT.
2025 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
2026 public:
2027   enum RelationKind {
2028     GreaterThan,
2029     EqualTo,
2030     LessThan,
2031   };
2032 
2033 protected:
2034   unsigned MMOIdx;
2035   RelationKind Relation;
2036   unsigned OpIdx;
2037 
2038 public:
2039   MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2040                                   enum RelationKind Relation,
2041                                   unsigned OpIdx)
2042       : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
2043         MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
2044 
2045   static bool classof(const PredicateMatcher *P) {
2046     return P->getKind() == IPM_MemoryVsLLTSize;
2047   }
2048   bool isIdentical(const PredicateMatcher &B) const override {
2049     return InstructionPredicateMatcher::isIdentical(B) &&
2050            MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2051            Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2052            OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2053   }
2054 
2055   void emitPredicateOpcodes(MatchTable &Table,
2056                             RuleMatcher &Rule) const override {
2057     Table << MatchTable::Opcode(Relation == EqualTo
2058                                     ? "GIM_CheckMemorySizeEqualToLLT"
2059                                     : Relation == GreaterThan
2060                                           ? "GIM_CheckMemorySizeGreaterThanLLT"
2061                                           : "GIM_CheckMemorySizeLessThanLLT")
2062           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2063           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2064           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2065           << MatchTable::LineBreak;
2066   }
2067 };
2068 
2069 // Matcher for immAllOnesV/immAllZerosV
2070 class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
2071 public:
2072   enum SplatKind {
2073     AllZeros,
2074     AllOnes
2075   };
2076 
2077 private:
2078   SplatKind Kind;
2079 
2080 public:
2081   VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
2082       : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
2083 
2084   static bool classof(const PredicateMatcher *P) {
2085     return P->getKind() == IPM_VectorSplatImm;
2086   }
2087 
2088   bool isIdentical(const PredicateMatcher &B) const override {
2089     return InstructionPredicateMatcher::isIdentical(B) &&
2090            Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
2091   }
2092 
2093   void emitPredicateOpcodes(MatchTable &Table,
2094                             RuleMatcher &Rule) const override {
2095     if (Kind == AllOnes)
2096       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
2097     else
2098       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
2099 
2100     Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
2101     Table << MatchTable::LineBreak;
2102   }
2103 };
2104 
2105 /// Generates code to check an arbitrary C++ instruction predicate.
2106 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2107 protected:
2108   TreePredicateFn Predicate;
2109 
2110 public:
2111   GenericInstructionPredicateMatcher(unsigned InsnVarID,
2112                                      TreePredicateFn Predicate)
2113       : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2114         Predicate(Predicate) {}
2115 
2116   static bool classof(const InstructionPredicateMatcher *P) {
2117     return P->getKind() == IPM_GenericPredicate;
2118   }
2119   bool isIdentical(const PredicateMatcher &B) const override {
2120     return InstructionPredicateMatcher::isIdentical(B) &&
2121            Predicate ==
2122                static_cast<const GenericInstructionPredicateMatcher &>(B)
2123                    .Predicate;
2124   }
2125   void emitPredicateOpcodes(MatchTable &Table,
2126                             RuleMatcher &Rule) const override {
2127     Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2128           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2129           << MatchTable::Comment("FnId")
2130           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2131           << MatchTable::LineBreak;
2132   }
2133 };
2134 
2135 /// Generates code to check that a set of predicates and operands match for a
2136 /// particular instruction.
2137 ///
2138 /// Typical predicates include:
2139 /// * Has a specific opcode.
2140 /// * Has an nsw/nuw flag or doesn't.
2141 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
2142 protected:
2143   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
2144 
2145   RuleMatcher &Rule;
2146 
2147   /// The operands to match. All rendered operands must be present even if the
2148   /// condition is always true.
2149   OperandVec Operands;
2150   bool NumOperandsCheck = true;
2151 
2152   std::string SymbolicName;
2153   unsigned InsnVarID;
2154 
2155   /// PhysRegInputs - List list has an entry for each explicitly specified
2156   /// physreg input to the pattern.  The first elt is the Register node, the
2157   /// second is the recorded slot number the input pattern match saved it in.
2158   SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2159 
2160 public:
2161   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
2162                      bool NumOpsCheck = true)
2163       : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
2164     // We create a new instruction matcher.
2165     // Get a new ID for that instruction.
2166     InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2167   }
2168 
2169   /// Construct a new instruction predicate and add it to the matcher.
2170   template <class Kind, class... Args>
2171   Optional<Kind *> addPredicate(Args &&... args) {
2172     Predicates.emplace_back(
2173         std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
2174     return static_cast<Kind *>(Predicates.back().get());
2175   }
2176 
2177   RuleMatcher &getRuleMatcher() const { return Rule; }
2178 
2179   unsigned getInsnVarID() const { return InsnVarID; }
2180 
2181   /// Add an operand to the matcher.
2182   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2183                              unsigned AllocatedTemporariesBaseID) {
2184     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2185                                              AllocatedTemporariesBaseID));
2186     if (!SymbolicName.empty())
2187       Rule.defineOperand(SymbolicName, *Operands.back());
2188 
2189     return *Operands.back();
2190   }
2191 
2192   OperandMatcher &getOperand(unsigned OpIdx) {
2193     auto I = std::find_if(Operands.begin(), Operands.end(),
2194                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
2195                             return X->getOpIdx() == OpIdx;
2196                           });
2197     if (I != Operands.end())
2198       return **I;
2199     llvm_unreachable("Failed to lookup operand");
2200   }
2201 
2202   OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2203                                   unsigned TempOpIdx) {
2204     assert(SymbolicName.empty());
2205     OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2206     Operands.emplace_back(OM);
2207     Rule.definePhysRegOperand(Reg, *OM);
2208     PhysRegInputs.emplace_back(Reg, OpIdx);
2209     return *OM;
2210   }
2211 
2212   ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2213     return PhysRegInputs;
2214   }
2215 
2216   StringRef getSymbolicName() const { return SymbolicName; }
2217   unsigned getNumOperands() const { return Operands.size(); }
2218   OperandVec::iterator operands_begin() { return Operands.begin(); }
2219   OperandVec::iterator operands_end() { return Operands.end(); }
2220   iterator_range<OperandVec::iterator> operands() {
2221     return make_range(operands_begin(), operands_end());
2222   }
2223   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2224   OperandVec::const_iterator operands_end() const { return Operands.end(); }
2225   iterator_range<OperandVec::const_iterator> operands() const {
2226     return make_range(operands_begin(), operands_end());
2227   }
2228   bool operands_empty() const { return Operands.empty(); }
2229 
2230   void pop_front() { Operands.erase(Operands.begin()); }
2231 
2232   void optimize();
2233 
2234   /// Emit MatchTable opcodes that test whether the instruction named in
2235   /// InsnVarName matches all the predicates and all the operands.
2236   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
2237     if (NumOperandsCheck)
2238       InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2239           .emitPredicateOpcodes(Table, Rule);
2240 
2241     // First emit all instruction level predicates need to be verified before we
2242     // can verify operands.
2243     emitFilteredPredicateListOpcodes(
2244       [](const PredicateMatcher &P) {
2245         return !P.dependsOnOperands();
2246       }, Table, Rule);
2247 
2248     // Emit all operand constraints.
2249     for (const auto &Operand : Operands)
2250       Operand->emitPredicateOpcodes(Table, Rule);
2251 
2252     // All of the tablegen defined predicates should now be matched. Now emit
2253     // any custom predicates that rely on all generated checks.
2254     emitFilteredPredicateListOpcodes(
2255       [](const PredicateMatcher &P) {
2256         return P.dependsOnOperands();
2257       }, Table, Rule);
2258   }
2259 
2260   /// Compare the priority of this object and B.
2261   ///
2262   /// Returns true if this object is more important than B.
2263   bool isHigherPriorityThan(InstructionMatcher &B) {
2264     // Instruction matchers involving more operands have higher priority.
2265     if (Operands.size() > B.Operands.size())
2266       return true;
2267     if (Operands.size() < B.Operands.size())
2268       return false;
2269 
2270     for (auto &&P : zip(predicates(), B.predicates())) {
2271       auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2272       auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2273       if (L->isHigherPriorityThan(*R))
2274         return true;
2275       if (R->isHigherPriorityThan(*L))
2276         return false;
2277     }
2278 
2279     for (auto Operand : zip(Operands, B.Operands)) {
2280       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
2281         return true;
2282       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
2283         return false;
2284     }
2285 
2286     return false;
2287   };
2288 
2289   /// Report the maximum number of temporary operands needed by the instruction
2290   /// matcher.
2291   unsigned countRendererFns() {
2292     return std::accumulate(
2293                predicates().begin(), predicates().end(), 0,
2294                [](unsigned A,
2295                   const std::unique_ptr<PredicateMatcher> &Predicate) {
2296                  return A + Predicate->countRendererFns();
2297                }) +
2298            std::accumulate(
2299                Operands.begin(), Operands.end(), 0,
2300                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
2301                  return A + Operand->countRendererFns();
2302                });
2303   }
2304 
2305   InstructionOpcodeMatcher &getOpcodeMatcher() {
2306     for (auto &P : predicates())
2307       if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2308         return *OpMatcher;
2309     llvm_unreachable("Didn't find an opcode matcher");
2310   }
2311 
2312   bool isConstantInstruction() {
2313     return getOpcodeMatcher().isConstantInstruction();
2314   }
2315 
2316   StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
2317 };
2318 
2319 StringRef RuleMatcher::getOpcode() const {
2320   return Matchers.front()->getOpcode();
2321 }
2322 
2323 unsigned RuleMatcher::getNumOperands() const {
2324   return Matchers.front()->getNumOperands();
2325 }
2326 
2327 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2328   InstructionMatcher &InsnMatcher = *Matchers.front();
2329   if (!InsnMatcher.predicates_empty())
2330     if (const auto *TM =
2331             dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2332       if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2333         return TM->getTy();
2334   return {};
2335 }
2336 
2337 /// Generates code to check that the operand is a register defined by an
2338 /// instruction that matches the given instruction matcher.
2339 ///
2340 /// For example, the pattern:
2341 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2342 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2343 /// the:
2344 ///   (G_ADD $src1, $src2)
2345 /// subpattern.
2346 class InstructionOperandMatcher : public OperandPredicateMatcher {
2347 protected:
2348   std::unique_ptr<InstructionMatcher> InsnMatcher;
2349 
2350 public:
2351   InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2352                             RuleMatcher &Rule, StringRef SymbolicName,
2353                             bool NumOpsCheck = true)
2354       : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
2355         InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
2356 
2357   static bool classof(const PredicateMatcher *P) {
2358     return P->getKind() == OPM_Instruction;
2359   }
2360 
2361   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2362 
2363   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2364     const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2365     Table << MatchTable::Opcode("GIM_RecordInsn")
2366           << MatchTable::Comment("DefineMI")
2367           << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2368           << MatchTable::IntValue(getInsnVarID())
2369           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2370           << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2371           << MatchTable::LineBreak;
2372   }
2373 
2374   void emitPredicateOpcodes(MatchTable &Table,
2375                             RuleMatcher &Rule) const override {
2376     emitCaptureOpcodes(Table, Rule);
2377     InsnMatcher->emitPredicateOpcodes(Table, Rule);
2378   }
2379 
2380   bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2381     if (OperandPredicateMatcher::isHigherPriorityThan(B))
2382       return true;
2383     if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2384       return false;
2385 
2386     if (const InstructionOperandMatcher *BP =
2387             dyn_cast<InstructionOperandMatcher>(&B))
2388       if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2389         return true;
2390     return false;
2391   }
2392 };
2393 
2394 void InstructionMatcher::optimize() {
2395   SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2396   const auto &OpcMatcher = getOpcodeMatcher();
2397 
2398   Stash.push_back(predicates_pop_front());
2399   if (Stash.back().get() == &OpcMatcher) {
2400     if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
2401       Stash.emplace_back(
2402           new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2403     NumOperandsCheck = false;
2404 
2405     for (auto &OM : Operands)
2406       for (auto &OP : OM->predicates())
2407         if (isa<IntrinsicIDOperandMatcher>(OP)) {
2408           Stash.push_back(std::move(OP));
2409           OM->eraseNullPredicates();
2410           break;
2411         }
2412   }
2413 
2414   if (InsnVarID > 0) {
2415     assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2416     for (auto &OP : Operands[0]->predicates())
2417       OP.reset();
2418     Operands[0]->eraseNullPredicates();
2419   }
2420   for (auto &OM : Operands) {
2421     for (auto &OP : OM->predicates())
2422       if (isa<LLTOperandMatcher>(OP))
2423         Stash.push_back(std::move(OP));
2424     OM->eraseNullPredicates();
2425   }
2426   while (!Stash.empty())
2427     prependPredicate(Stash.pop_back_val());
2428 }
2429 
2430 //===- Actions ------------------------------------------------------------===//
2431 class OperandRenderer {
2432 public:
2433   enum RendererKind {
2434     OR_Copy,
2435     OR_CopyOrAddZeroReg,
2436     OR_CopySubReg,
2437     OR_CopyPhysReg,
2438     OR_CopyConstantAsImm,
2439     OR_CopyFConstantAsFPImm,
2440     OR_Imm,
2441     OR_SubRegIndex,
2442     OR_Register,
2443     OR_TempRegister,
2444     OR_ComplexPattern,
2445     OR_Custom,
2446     OR_CustomOperand
2447   };
2448 
2449 protected:
2450   RendererKind Kind;
2451 
2452 public:
2453   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2454   virtual ~OperandRenderer() {}
2455 
2456   RendererKind getKind() const { return Kind; }
2457 
2458   virtual void emitRenderOpcodes(MatchTable &Table,
2459                                  RuleMatcher &Rule) const = 0;
2460 };
2461 
2462 /// A CopyRenderer emits code to copy a single operand from an existing
2463 /// instruction to the one being built.
2464 class CopyRenderer : public OperandRenderer {
2465 protected:
2466   unsigned NewInsnID;
2467   /// The name of the operand.
2468   const StringRef SymbolicName;
2469 
2470 public:
2471   CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2472       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
2473         SymbolicName(SymbolicName) {
2474     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2475   }
2476 
2477   static bool classof(const OperandRenderer *R) {
2478     return R->getKind() == OR_Copy;
2479   }
2480 
2481   const StringRef getSymbolicName() const { return SymbolicName; }
2482 
2483   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2484     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2485     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2486     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2487           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2488           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2489           << MatchTable::IntValue(Operand.getOpIdx())
2490           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2491   }
2492 };
2493 
2494 /// A CopyRenderer emits code to copy a virtual register to a specific physical
2495 /// register.
2496 class CopyPhysRegRenderer : public OperandRenderer {
2497 protected:
2498   unsigned NewInsnID;
2499   Record *PhysReg;
2500 
2501 public:
2502   CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2503       : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2504         PhysReg(Reg) {
2505     assert(PhysReg);
2506   }
2507 
2508   static bool classof(const OperandRenderer *R) {
2509     return R->getKind() == OR_CopyPhysReg;
2510   }
2511 
2512   Record *getPhysReg() const { return PhysReg; }
2513 
2514   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2515     const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2516     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2517     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2518           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2519           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2520           << MatchTable::IntValue(Operand.getOpIdx())
2521           << MatchTable::Comment(PhysReg->getName())
2522           << MatchTable::LineBreak;
2523   }
2524 };
2525 
2526 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2527 /// existing instruction to the one being built. If the operand turns out to be
2528 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2529 class CopyOrAddZeroRegRenderer : public OperandRenderer {
2530 protected:
2531   unsigned NewInsnID;
2532   /// The name of the operand.
2533   const StringRef SymbolicName;
2534   const Record *ZeroRegisterDef;
2535 
2536 public:
2537   CopyOrAddZeroRegRenderer(unsigned NewInsnID,
2538                            StringRef SymbolicName, Record *ZeroRegisterDef)
2539       : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2540         SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2541     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2542   }
2543 
2544   static bool classof(const OperandRenderer *R) {
2545     return R->getKind() == OR_CopyOrAddZeroReg;
2546   }
2547 
2548   const StringRef getSymbolicName() const { return SymbolicName; }
2549 
2550   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2551     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2552     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2553     Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2554           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2555           << MatchTable::Comment("OldInsnID")
2556           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2557           << MatchTable::IntValue(Operand.getOpIdx())
2558           << MatchTable::NamedValue(
2559                  (ZeroRegisterDef->getValue("Namespace")
2560                       ? ZeroRegisterDef->getValueAsString("Namespace")
2561                       : ""),
2562                  ZeroRegisterDef->getName())
2563           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2564   }
2565 };
2566 
2567 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2568 /// an extended immediate operand.
2569 class CopyConstantAsImmRenderer : public OperandRenderer {
2570 protected:
2571   unsigned NewInsnID;
2572   /// The name of the operand.
2573   const std::string SymbolicName;
2574   bool Signed;
2575 
2576 public:
2577   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2578       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2579         SymbolicName(SymbolicName), Signed(true) {}
2580 
2581   static bool classof(const OperandRenderer *R) {
2582     return R->getKind() == OR_CopyConstantAsImm;
2583   }
2584 
2585   const StringRef getSymbolicName() const { return SymbolicName; }
2586 
2587   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2588     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2589     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2590     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2591                                        : "GIR_CopyConstantAsUImm")
2592           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2593           << MatchTable::Comment("OldInsnID")
2594           << MatchTable::IntValue(OldInsnVarID)
2595           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2596   }
2597 };
2598 
2599 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2600 /// instruction to an extended immediate operand.
2601 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2602 protected:
2603   unsigned NewInsnID;
2604   /// The name of the operand.
2605   const std::string SymbolicName;
2606 
2607 public:
2608   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2609       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2610         SymbolicName(SymbolicName) {}
2611 
2612   static bool classof(const OperandRenderer *R) {
2613     return R->getKind() == OR_CopyFConstantAsFPImm;
2614   }
2615 
2616   const StringRef getSymbolicName() const { return SymbolicName; }
2617 
2618   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2619     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2620     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2621     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2622           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2623           << MatchTable::Comment("OldInsnID")
2624           << MatchTable::IntValue(OldInsnVarID)
2625           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2626   }
2627 };
2628 
2629 /// A CopySubRegRenderer emits code to copy a single register operand from an
2630 /// existing instruction to the one being built and indicate that only a
2631 /// subregister should be copied.
2632 class CopySubRegRenderer : public OperandRenderer {
2633 protected:
2634   unsigned NewInsnID;
2635   /// The name of the operand.
2636   const StringRef SymbolicName;
2637   /// The subregister to extract.
2638   const CodeGenSubRegIndex *SubReg;
2639 
2640 public:
2641   CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2642                      const CodeGenSubRegIndex *SubReg)
2643       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
2644         SymbolicName(SymbolicName), SubReg(SubReg) {}
2645 
2646   static bool classof(const OperandRenderer *R) {
2647     return R->getKind() == OR_CopySubReg;
2648   }
2649 
2650   const StringRef getSymbolicName() const { return SymbolicName; }
2651 
2652   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2653     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2654     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2655     Table << MatchTable::Opcode("GIR_CopySubReg")
2656           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2657           << MatchTable::Comment("OldInsnID")
2658           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2659           << MatchTable::IntValue(Operand.getOpIdx())
2660           << MatchTable::Comment("SubRegIdx")
2661           << MatchTable::IntValue(SubReg->EnumValue)
2662           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2663   }
2664 };
2665 
2666 /// Adds a specific physical register to the instruction being built.
2667 /// This is typically useful for WZR/XZR on AArch64.
2668 class AddRegisterRenderer : public OperandRenderer {
2669 protected:
2670   unsigned InsnID;
2671   const Record *RegisterDef;
2672   bool IsDef;
2673 
2674 public:
2675   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2676                       bool IsDef = false)
2677       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2678         IsDef(IsDef) {}
2679 
2680   static bool classof(const OperandRenderer *R) {
2681     return R->getKind() == OR_Register;
2682   }
2683 
2684   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2685     Table << MatchTable::Opcode("GIR_AddRegister")
2686           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2687           << MatchTable::NamedValue(
2688                  (RegisterDef->getValue("Namespace")
2689                       ? RegisterDef->getValueAsString("Namespace")
2690                       : ""),
2691                  RegisterDef->getName())
2692           << MatchTable::Comment("AddRegisterRegFlags");
2693 
2694     // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2695     // really needed for a physical register reference. We can pack the
2696     // register and flags in a single field.
2697     if (IsDef)
2698       Table << MatchTable::NamedValue("RegState::Define");
2699     else
2700       Table << MatchTable::IntValue(0);
2701     Table << MatchTable::LineBreak;
2702   }
2703 };
2704 
2705 /// Adds a specific temporary virtual register to the instruction being built.
2706 /// This is used to chain instructions together when emitting multiple
2707 /// instructions.
2708 class TempRegRenderer : public OperandRenderer {
2709 protected:
2710   unsigned InsnID;
2711   unsigned TempRegID;
2712   const CodeGenSubRegIndex *SubRegIdx;
2713   bool IsDef;
2714   bool IsDead;
2715 
2716 public:
2717   TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
2718                   const CodeGenSubRegIndex *SubReg = nullptr,
2719                   bool IsDead = false)
2720       : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2721         SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
2722 
2723   static bool classof(const OperandRenderer *R) {
2724     return R->getKind() == OR_TempRegister;
2725   }
2726 
2727   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2728     if (SubRegIdx) {
2729       assert(!IsDef);
2730       Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2731     } else
2732       Table << MatchTable::Opcode("GIR_AddTempRegister");
2733 
2734     Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2735           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2736           << MatchTable::Comment("TempRegFlags");
2737 
2738     if (IsDef) {
2739       SmallString<32> RegFlags;
2740       RegFlags += "RegState::Define";
2741       if (IsDead)
2742         RegFlags += "|RegState::Dead";
2743       Table << MatchTable::NamedValue(RegFlags);
2744     } else
2745       Table << MatchTable::IntValue(0);
2746 
2747     if (SubRegIdx)
2748       Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
2749     Table << MatchTable::LineBreak;
2750   }
2751 };
2752 
2753 /// Adds a specific immediate to the instruction being built.
2754 class ImmRenderer : public OperandRenderer {
2755 protected:
2756   unsigned InsnID;
2757   int64_t Imm;
2758 
2759 public:
2760   ImmRenderer(unsigned InsnID, int64_t Imm)
2761       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
2762 
2763   static bool classof(const OperandRenderer *R) {
2764     return R->getKind() == OR_Imm;
2765   }
2766 
2767   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2768     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2769           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2770           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
2771   }
2772 };
2773 
2774 /// Adds an enum value for a subreg index to the instruction being built.
2775 class SubRegIndexRenderer : public OperandRenderer {
2776 protected:
2777   unsigned InsnID;
2778   const CodeGenSubRegIndex *SubRegIdx;
2779 
2780 public:
2781   SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2782       : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2783 
2784   static bool classof(const OperandRenderer *R) {
2785     return R->getKind() == OR_SubRegIndex;
2786   }
2787 
2788   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2789     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2790           << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2791           << MatchTable::IntValue(SubRegIdx->EnumValue)
2792           << MatchTable::LineBreak;
2793   }
2794 };
2795 
2796 /// Adds operands by calling a renderer function supplied by the ComplexPattern
2797 /// matcher function.
2798 class RenderComplexPatternOperand : public OperandRenderer {
2799 private:
2800   unsigned InsnID;
2801   const Record &TheDef;
2802   /// The name of the operand.
2803   const StringRef SymbolicName;
2804   /// The renderer number. This must be unique within a rule since it's used to
2805   /// identify a temporary variable to hold the renderer function.
2806   unsigned RendererID;
2807   /// When provided, this is the suboperand of the ComplexPattern operand to
2808   /// render. Otherwise all the suboperands will be rendered.
2809   Optional<unsigned> SubOperand;
2810 
2811   unsigned getNumOperands() const {
2812     return TheDef.getValueAsDag("Operands")->getNumArgs();
2813   }
2814 
2815 public:
2816   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
2817                               StringRef SymbolicName, unsigned RendererID,
2818                               Optional<unsigned> SubOperand = None)
2819       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
2820         SymbolicName(SymbolicName), RendererID(RendererID),
2821         SubOperand(SubOperand) {}
2822 
2823   static bool classof(const OperandRenderer *R) {
2824     return R->getKind() == OR_ComplexPattern;
2825   }
2826 
2827   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2828     Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2829                                                       : "GIR_ComplexRenderer")
2830           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2831           << MatchTable::Comment("RendererID")
2832           << MatchTable::IntValue(RendererID);
2833     if (SubOperand.hasValue())
2834       Table << MatchTable::Comment("SubOperand")
2835             << MatchTable::IntValue(SubOperand.getValue());
2836     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2837   }
2838 };
2839 
2840 class CustomRenderer : public OperandRenderer {
2841 protected:
2842   unsigned InsnID;
2843   const Record &Renderer;
2844   /// The name of the operand.
2845   const std::string SymbolicName;
2846 
2847 public:
2848   CustomRenderer(unsigned InsnID, const Record &Renderer,
2849                  StringRef SymbolicName)
2850       : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2851         SymbolicName(SymbolicName) {}
2852 
2853   static bool classof(const OperandRenderer *R) {
2854     return R->getKind() == OR_Custom;
2855   }
2856 
2857   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2858     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2859     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2860     Table << MatchTable::Opcode("GIR_CustomRenderer")
2861           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2862           << MatchTable::Comment("OldInsnID")
2863           << MatchTable::IntValue(OldInsnVarID)
2864           << MatchTable::Comment("Renderer")
2865           << MatchTable::NamedValue(
2866                  "GICR_" + Renderer.getValueAsString("RendererFn").str())
2867           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2868   }
2869 };
2870 
2871 class CustomOperandRenderer : public OperandRenderer {
2872 protected:
2873   unsigned InsnID;
2874   const Record &Renderer;
2875   /// The name of the operand.
2876   const std::string SymbolicName;
2877 
2878 public:
2879   CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2880                         StringRef SymbolicName)
2881       : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2882         SymbolicName(SymbolicName) {}
2883 
2884   static bool classof(const OperandRenderer *R) {
2885     return R->getKind() == OR_CustomOperand;
2886   }
2887 
2888   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2889     const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2890     Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2891           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2892           << MatchTable::Comment("OldInsnID")
2893           << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2894           << MatchTable::Comment("OpIdx")
2895           << MatchTable::IntValue(OpdMatcher.getOpIdx())
2896           << MatchTable::Comment("OperandRenderer")
2897           << MatchTable::NamedValue(
2898             "GICR_" + Renderer.getValueAsString("RendererFn").str())
2899           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2900   }
2901 };
2902 
2903 /// An action taken when all Matcher predicates succeeded for a parent rule.
2904 ///
2905 /// Typical actions include:
2906 /// * Changing the opcode of an instruction.
2907 /// * Adding an operand to an instruction.
2908 class MatchAction {
2909 public:
2910   virtual ~MatchAction() {}
2911 
2912   /// Emit the MatchTable opcodes to implement the action.
2913   virtual void emitActionOpcodes(MatchTable &Table,
2914                                  RuleMatcher &Rule) const = 0;
2915 };
2916 
2917 /// Generates a comment describing the matched rule being acted upon.
2918 class DebugCommentAction : public MatchAction {
2919 private:
2920   std::string S;
2921 
2922 public:
2923   DebugCommentAction(StringRef S) : S(std::string(S)) {}
2924 
2925   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2926     Table << MatchTable::Comment(S) << MatchTable::LineBreak;
2927   }
2928 };
2929 
2930 /// Generates code to build an instruction or mutate an existing instruction
2931 /// into the desired instruction when this is possible.
2932 class BuildMIAction : public MatchAction {
2933 private:
2934   unsigned InsnID;
2935   const CodeGenInstruction *I;
2936   InstructionMatcher *Matched;
2937   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2938 
2939   /// True if the instruction can be built solely by mutating the opcode.
2940   bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2941     if (!Insn)
2942       return false;
2943 
2944     if (OperandRenderers.size() != Insn->getNumOperands())
2945       return false;
2946 
2947     for (const auto &Renderer : enumerate(OperandRenderers)) {
2948       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
2949         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
2950         if (Insn != &OM.getInstructionMatcher() ||
2951             OM.getOpIdx() != Renderer.index())
2952           return false;
2953       } else
2954         return false;
2955     }
2956 
2957     return true;
2958   }
2959 
2960 public:
2961   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2962       : InsnID(InsnID), I(I), Matched(nullptr) {}
2963 
2964   unsigned getInsnID() const { return InsnID; }
2965   const CodeGenInstruction *getCGI() const { return I; }
2966 
2967   void chooseInsnToMutate(RuleMatcher &Rule) {
2968     for (auto *MutateCandidate : Rule.mutatable_insns()) {
2969       if (canMutate(Rule, MutateCandidate)) {
2970         // Take the first one we're offered that we're able to mutate.
2971         Rule.reserveInsnMatcherForMutation(MutateCandidate);
2972         Matched = MutateCandidate;
2973         return;
2974       }
2975     }
2976   }
2977 
2978   template <class Kind, class... Args>
2979   Kind &addRenderer(Args&&... args) {
2980     OperandRenderers.emplace_back(
2981         std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
2982     return *static_cast<Kind *>(OperandRenderers.back().get());
2983   }
2984 
2985   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2986     if (Matched) {
2987       assert(canMutate(Rule, Matched) &&
2988              "Arranged to mutate an insn that isn't mutatable");
2989 
2990       unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
2991       Table << MatchTable::Opcode("GIR_MutateOpcode")
2992             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2993             << MatchTable::Comment("RecycleInsnID")
2994             << MatchTable::IntValue(RecycleInsnID)
2995             << MatchTable::Comment("Opcode")
2996             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2997             << MatchTable::LineBreak;
2998 
2999       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
3000         for (auto Def : I->ImplicitDefs) {
3001           auto Namespace = Def->getValue("Namespace")
3002                                ? Def->getValueAsString("Namespace")
3003                                : "";
3004           Table << MatchTable::Opcode("GIR_AddImplicitDef")
3005                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3006                 << MatchTable::NamedValue(Namespace, Def->getName())
3007                 << MatchTable::LineBreak;
3008         }
3009         for (auto Use : I->ImplicitUses) {
3010           auto Namespace = Use->getValue("Namespace")
3011                                ? Use->getValueAsString("Namespace")
3012                                : "";
3013           Table << MatchTable::Opcode("GIR_AddImplicitUse")
3014                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3015                 << MatchTable::NamedValue(Namespace, Use->getName())
3016                 << MatchTable::LineBreak;
3017         }
3018       }
3019       return;
3020     }
3021 
3022     // TODO: Simple permutation looks like it could be almost as common as
3023     //       mutation due to commutative operations.
3024 
3025     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
3026           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
3027           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3028           << MatchTable::LineBreak;
3029     for (const auto &Renderer : OperandRenderers)
3030       Renderer->emitRenderOpcodes(Table, Rule);
3031 
3032     if (I->mayLoad || I->mayStore) {
3033       Table << MatchTable::Opcode("GIR_MergeMemOperands")
3034             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3035             << MatchTable::Comment("MergeInsnID's");
3036       // Emit the ID's for all the instructions that are matched by this rule.
3037       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
3038       //       some other means of having a memoperand. Also limit this to
3039       //       emitted instructions that expect to have a memoperand too. For
3040       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
3041       //       sign-extend instructions shouldn't put the memoperand on the
3042       //       sign-extend since it has no effect there.
3043       std::vector<unsigned> MergeInsnIDs;
3044       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
3045         MergeInsnIDs.push_back(IDMatcherPair.second);
3046       llvm::sort(MergeInsnIDs);
3047       for (const auto &MergeInsnID : MergeInsnIDs)
3048         Table << MatchTable::IntValue(MergeInsnID);
3049       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
3050             << MatchTable::LineBreak;
3051     }
3052 
3053     // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
3054     //        better for combines. Particularly when there are multiple match
3055     //        roots.
3056     if (InsnID == 0)
3057       Table << MatchTable::Opcode("GIR_EraseFromParent")
3058             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3059             << MatchTable::LineBreak;
3060   }
3061 };
3062 
3063 /// Generates code to constrain the operands of an output instruction to the
3064 /// register classes specified by the definition of that instruction.
3065 class ConstrainOperandsToDefinitionAction : public MatchAction {
3066   unsigned InsnID;
3067 
3068 public:
3069   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
3070 
3071   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3072     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
3073           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3074           << MatchTable::LineBreak;
3075   }
3076 };
3077 
3078 /// Generates code to constrain the specified operand of an output instruction
3079 /// to the specified register class.
3080 class ConstrainOperandToRegClassAction : public MatchAction {
3081   unsigned InsnID;
3082   unsigned OpIdx;
3083   const CodeGenRegisterClass &RC;
3084 
3085 public:
3086   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
3087                                    const CodeGenRegisterClass &RC)
3088       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
3089 
3090   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3091     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3092           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3093           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
3094           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3095           << MatchTable::LineBreak;
3096   }
3097 };
3098 
3099 /// Generates code to create a temporary register which can be used to chain
3100 /// instructions together.
3101 class MakeTempRegisterAction : public MatchAction {
3102 private:
3103   LLTCodeGen Ty;
3104   unsigned TempRegID;
3105 
3106 public:
3107   MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
3108       : Ty(Ty), TempRegID(TempRegID) {
3109     KnownTypes.insert(Ty);
3110   }
3111 
3112   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3113     Table << MatchTable::Opcode("GIR_MakeTempReg")
3114           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3115           << MatchTable::Comment("TypeID")
3116           << MatchTable::NamedValue(Ty.getCxxEnumValue())
3117           << MatchTable::LineBreak;
3118   }
3119 };
3120 
3121 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
3122   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
3123   MutatableInsns.insert(Matchers.back().get());
3124   return *Matchers.back();
3125 }
3126 
3127 void RuleMatcher::addRequiredFeature(Record *Feature) {
3128   RequiredFeatures.push_back(Feature);
3129 }
3130 
3131 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3132   return RequiredFeatures;
3133 }
3134 
3135 // Emplaces an action of the specified Kind at the end of the action list.
3136 //
3137 // Returns a reference to the newly created action.
3138 //
3139 // Like std::vector::emplace_back(), may invalidate all iterators if the new
3140 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
3141 // iterator.
3142 template <class Kind, class... Args>
3143 Kind &RuleMatcher::addAction(Args &&... args) {
3144   Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
3145   return *static_cast<Kind *>(Actions.back().get());
3146 }
3147 
3148 // Emplaces an action of the specified Kind before the given insertion point.
3149 //
3150 // Returns an iterator pointing at the newly created instruction.
3151 //
3152 // Like std::vector::insert(), may invalidate all iterators if the new size
3153 // exceeds the capacity. Otherwise, only invalidates the iterators from the
3154 // insertion point onwards.
3155 template <class Kind, class... Args>
3156 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3157                                           Args &&... args) {
3158   return Actions.emplace(InsertPt,
3159                          std::make_unique<Kind>(std::forward<Args>(args)...));
3160 }
3161 
3162 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
3163   unsigned NewInsnVarID = NextInsnVarID++;
3164   InsnVariableIDs[&Matcher] = NewInsnVarID;
3165   return NewInsnVarID;
3166 }
3167 
3168 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
3169   const auto &I = InsnVariableIDs.find(&InsnMatcher);
3170   if (I != InsnVariableIDs.end())
3171     return I->second;
3172   llvm_unreachable("Matched Insn was not captured in a local variable");
3173 }
3174 
3175 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3176   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3177     DefinedOperands[SymbolicName] = &OM;
3178     return;
3179   }
3180 
3181   // If the operand is already defined, then we must ensure both references in
3182   // the matcher have the exact same node.
3183   OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3184 }
3185 
3186 void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3187   if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3188     PhysRegOperands[Reg] = &OM;
3189     return;
3190   }
3191 }
3192 
3193 InstructionMatcher &
3194 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3195   for (const auto &I : InsnVariableIDs)
3196     if (I.first->getSymbolicName() == SymbolicName)
3197       return *I.first;
3198   llvm_unreachable(
3199       ("Failed to lookup instruction " + SymbolicName).str().c_str());
3200 }
3201 
3202 const OperandMatcher &
3203 RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3204   const auto &I = PhysRegOperands.find(Reg);
3205 
3206   if (I == PhysRegOperands.end()) {
3207     PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3208                     " was not declared in matcher");
3209   }
3210 
3211   return *I->second;
3212 }
3213 
3214 const OperandMatcher &
3215 RuleMatcher::getOperandMatcher(StringRef Name) const {
3216   const auto &I = DefinedOperands.find(Name);
3217 
3218   if (I == DefinedOperands.end())
3219     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3220 
3221   return *I->second;
3222 }
3223 
3224 void RuleMatcher::emit(MatchTable &Table) {
3225   if (Matchers.empty())
3226     llvm_unreachable("Unexpected empty matcher!");
3227 
3228   // The representation supports rules that require multiple roots such as:
3229   //    %ptr(p0) = ...
3230   //    %elt0(s32) = G_LOAD %ptr
3231   //    %1(p0) = G_ADD %ptr, 4
3232   //    %elt1(s32) = G_LOAD p0 %1
3233   // which could be usefully folded into:
3234   //    %ptr(p0) = ...
3235   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3236   // on some targets but we don't need to make use of that yet.
3237   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
3238 
3239   unsigned LabelID = Table.allocateLabelID();
3240   Table << MatchTable::Opcode("GIM_Try", +1)
3241         << MatchTable::Comment("On fail goto")
3242         << MatchTable::JumpTarget(LabelID)
3243         << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
3244         << MatchTable::LineBreak;
3245 
3246   if (!RequiredFeatures.empty()) {
3247     Table << MatchTable::Opcode("GIM_CheckFeatures")
3248           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3249           << MatchTable::LineBreak;
3250   }
3251 
3252   Matchers.front()->emitPredicateOpcodes(Table, *this);
3253 
3254   // We must also check if it's safe to fold the matched instructions.
3255   if (InsnVariableIDs.size() >= 2) {
3256     // Invert the map to create stable ordering (by var names)
3257     SmallVector<unsigned, 2> InsnIDs;
3258     for (const auto &Pair : InsnVariableIDs) {
3259       // Skip the root node since it isn't moving anywhere. Everything else is
3260       // sinking to meet it.
3261       if (Pair.first == Matchers.front().get())
3262         continue;
3263 
3264       InsnIDs.push_back(Pair.second);
3265     }
3266     llvm::sort(InsnIDs);
3267 
3268     for (const auto &InsnID : InsnIDs) {
3269       // Reject the difficult cases until we have a more accurate check.
3270       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3271             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3272             << MatchTable::LineBreak;
3273 
3274       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3275       //        account for unsafe cases.
3276       //
3277       //        Example:
3278       //          MI1--> %0 = ...
3279       //                 %1 = ... %0
3280       //          MI0--> %2 = ... %0
3281       //          It's not safe to erase MI1. We currently handle this by not
3282       //          erasing %0 (even when it's dead).
3283       //
3284       //        Example:
3285       //          MI1--> %0 = load volatile @a
3286       //                 %1 = load volatile @a
3287       //          MI0--> %2 = ... %0
3288       //          It's not safe to sink %0's def past %1. We currently handle
3289       //          this by rejecting all loads.
3290       //
3291       //        Example:
3292       //          MI1--> %0 = load @a
3293       //                 %1 = store @a
3294       //          MI0--> %2 = ... %0
3295       //          It's not safe to sink %0's def past %1. We currently handle
3296       //          this by rejecting all loads.
3297       //
3298       //        Example:
3299       //                   G_CONDBR %cond, @BB1
3300       //                 BB0:
3301       //          MI1-->   %0 = load @a
3302       //                   G_BR @BB1
3303       //                 BB1:
3304       //          MI0-->   %2 = ... %0
3305       //          It's not always safe to sink %0 across control flow. In this
3306       //          case it may introduce a memory fault. We currentl handle this
3307       //          by rejecting all loads.
3308     }
3309   }
3310 
3311   for (const auto &PM : EpilogueMatchers)
3312     PM->emitPredicateOpcodes(Table, *this);
3313 
3314   for (const auto &MA : Actions)
3315     MA->emitActionOpcodes(Table, *this);
3316 
3317   if (Table.isWithCoverage())
3318     Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3319           << MatchTable::LineBreak;
3320   else
3321     Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3322           << MatchTable::LineBreak;
3323 
3324   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
3325         << MatchTable::Label(LabelID);
3326   ++NumPatternEmitted;
3327 }
3328 
3329 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3330   // Rules involving more match roots have higher priority.
3331   if (Matchers.size() > B.Matchers.size())
3332     return true;
3333   if (Matchers.size() < B.Matchers.size())
3334     return false;
3335 
3336   for (auto Matcher : zip(Matchers, B.Matchers)) {
3337     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3338       return true;
3339     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3340       return false;
3341   }
3342 
3343   return false;
3344 }
3345 
3346 unsigned RuleMatcher::countRendererFns() const {
3347   return std::accumulate(
3348       Matchers.begin(), Matchers.end(), 0,
3349       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
3350         return A + Matcher->countRendererFns();
3351       });
3352 }
3353 
3354 bool OperandPredicateMatcher::isHigherPriorityThan(
3355     const OperandPredicateMatcher &B) const {
3356   // Generally speaking, an instruction is more important than an Int or a
3357   // LiteralInt because it can cover more nodes but theres an exception to
3358   // this. G_CONSTANT's are less important than either of those two because they
3359   // are more permissive.
3360 
3361   const InstructionOperandMatcher *AOM =
3362       dyn_cast<InstructionOperandMatcher>(this);
3363   const InstructionOperandMatcher *BOM =
3364       dyn_cast<InstructionOperandMatcher>(&B);
3365   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3366   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3367 
3368   if (AOM && BOM) {
3369     // The relative priorities between a G_CONSTANT and any other instruction
3370     // don't actually matter but this code is needed to ensure a strict weak
3371     // ordering. This is particularly important on Windows where the rules will
3372     // be incorrectly sorted without it.
3373     if (AIsConstantInsn != BIsConstantInsn)
3374       return AIsConstantInsn < BIsConstantInsn;
3375     return false;
3376   }
3377 
3378   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3379     return false;
3380   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3381     return true;
3382 
3383   return Kind < B.Kind;
3384 }
3385 
3386 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
3387                                               RuleMatcher &Rule) const {
3388   const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
3389   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
3390   assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
3391 
3392   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3393         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3394         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3395         << MatchTable::Comment("OtherMI")
3396         << MatchTable::IntValue(OtherInsnVarID)
3397         << MatchTable::Comment("OtherOpIdx")
3398         << MatchTable::IntValue(OtherOM.getOpIdx())
3399         << MatchTable::LineBreak;
3400 }
3401 
3402 //===- GlobalISelEmitter class --------------------------------------------===//
3403 
3404 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3405   ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3406   if (ChildTypes.size() != 1)
3407     return failedImport("Dst pattern child has multiple results");
3408 
3409   Optional<LLTCodeGen> MaybeOpTy;
3410   if (ChildTypes.front().isMachineValueType()) {
3411     MaybeOpTy =
3412       MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3413   }
3414 
3415   if (!MaybeOpTy)
3416     return failedImport("Dst operand has an unsupported type");
3417   return *MaybeOpTy;
3418 }
3419 
3420 class GlobalISelEmitter {
3421 public:
3422   explicit GlobalISelEmitter(RecordKeeper &RK);
3423   void run(raw_ostream &OS);
3424 
3425 private:
3426   const RecordKeeper &RK;
3427   const CodeGenDAGPatterns CGP;
3428   const CodeGenTarget &Target;
3429   CodeGenRegBank &CGRegs;
3430 
3431   /// Keep track of the equivalence between SDNodes and Instruction by mapping
3432   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3433   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
3434   /// This is defined using 'GINodeEquiv' in the target description.
3435   DenseMap<Record *, Record *> NodeEquivs;
3436 
3437   /// Keep track of the equivalence between ComplexPattern's and
3438   /// GIComplexOperandMatcher. Map entries are specified by subclassing
3439   /// GIComplexPatternEquiv.
3440   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3441 
3442   /// Keep track of the equivalence between SDNodeXForm's and
3443   /// GICustomOperandRenderer. Map entries are specified by subclassing
3444   /// GISDNodeXFormEquiv.
3445   DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3446 
3447   /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3448   /// This adds compatibility for RuleMatchers to use this for ordering rules.
3449   DenseMap<uint64_t, int> RuleMatcherScores;
3450 
3451   // Map of predicates to their subtarget features.
3452   SubtargetFeatureInfoMap SubtargetFeatures;
3453 
3454   // Rule coverage information.
3455   Optional<CodeGenCoverage> RuleCoverage;
3456 
3457   void gatherOpcodeValues();
3458   void gatherTypeIDValues();
3459   void gatherNodeEquivs();
3460 
3461   Record *findNodeEquiv(Record *N) const;
3462   const CodeGenInstruction *getEquivNode(Record &Equiv,
3463                                          const TreePatternNode *N) const;
3464 
3465   Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
3466   Expected<InstructionMatcher &>
3467   createAndImportSelDAGMatcher(RuleMatcher &Rule,
3468                                InstructionMatcher &InsnMatcher,
3469                                const TreePatternNode *Src, unsigned &TempOpIdx);
3470   Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3471                                            unsigned &TempOpIdx) const;
3472   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3473                            const TreePatternNode *SrcChild,
3474                            bool OperandIsAPointer, bool OperandIsImmArg,
3475                            unsigned OpIdx, unsigned &TempOpIdx);
3476 
3477   Expected<BuildMIAction &> createAndImportInstructionRenderer(
3478       RuleMatcher &M, InstructionMatcher &InsnMatcher,
3479       const TreePatternNode *Src, const TreePatternNode *Dst);
3480   Expected<action_iterator> createAndImportSubInstructionRenderer(
3481       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3482       unsigned TempReg);
3483   Expected<action_iterator>
3484   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
3485                             const TreePatternNode *Dst);
3486 
3487   Expected<action_iterator>
3488   importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3489                              BuildMIAction &DstMIBuilder,
3490                              const TreePatternNode *Dst);
3491 
3492   Expected<action_iterator>
3493   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3494                              BuildMIAction &DstMIBuilder,
3495                              const llvm::TreePatternNode *Dst);
3496   Expected<action_iterator>
3497   importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3498                             BuildMIAction &DstMIBuilder,
3499                             TreePatternNode *DstChild);
3500   Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3501                                       BuildMIAction &DstMIBuilder,
3502                                       DagInit *DefaultOps) const;
3503   Error
3504   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3505                              const std::vector<Record *> &ImplicitDefs) const;
3506 
3507   void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3508                            StringRef TypeIdentifier, StringRef ArgType,
3509                            StringRef ArgName, StringRef AdditionalDeclarations,
3510                            std::function<bool(const Record *R)> Filter);
3511   void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3512                            StringRef ArgType,
3513                            std::function<bool(const Record *R)> Filter);
3514   void emitMIPredicateFns(raw_ostream &OS);
3515 
3516   /// Analyze pattern \p P, returning a matcher for it if possible.
3517   /// Otherwise, return an Error explaining why we don't support it.
3518   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
3519 
3520   void declareSubtargetFeature(Record *Predicate);
3521 
3522   MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3523                              bool WithCoverage);
3524 
3525   /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3526   /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3527   /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3528   /// If no register class is found, return None.
3529   Optional<const CodeGenRegisterClass *>
3530   inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3531                                  TreePatternNode *SuperRegNode,
3532                                  TreePatternNode *SubRegIdxNode);
3533   Optional<CodeGenSubRegIndex *>
3534   inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
3535 
3536   /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3537   /// Return None if no such class exists.
3538   Optional<const CodeGenRegisterClass *>
3539   inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3540                           TreePatternNode *SubRegIdxNode);
3541 
3542   /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3543   Optional<const CodeGenRegisterClass *>
3544   getRegClassFromLeaf(TreePatternNode *Leaf);
3545 
3546   /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3547   /// otherwise.
3548   Optional<const CodeGenRegisterClass *>
3549   inferRegClassFromPattern(TreePatternNode *N);
3550 
3551   // Add builtin predicates.
3552   Expected<InstructionMatcher &>
3553   addBuiltinPredicates(const Record *SrcGIEquivOrNull,
3554                        const TreePredicateFn &Predicate,
3555                        InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
3556 
3557 public:
3558   /// Takes a sequence of \p Rules and group them based on the predicates
3559   /// they share. \p MatcherStorage is used as a memory container
3560   /// for the group that are created as part of this process.
3561   ///
3562   /// What this optimization does looks like if GroupT = GroupMatcher:
3563   /// Output without optimization:
3564   /// \verbatim
3565   /// # R1
3566   ///  # predicate A
3567   ///  # predicate B
3568   ///  ...
3569   /// # R2
3570   ///  # predicate A // <-- effectively this is going to be checked twice.
3571   ///                //     Once in R1 and once in R2.
3572   ///  # predicate C
3573   /// \endverbatim
3574   /// Output with optimization:
3575   /// \verbatim
3576   /// # Group1_2
3577   ///  # predicate A // <-- Check is now shared.
3578   ///  # R1
3579   ///   # predicate B
3580   ///  # R2
3581   ///   # predicate C
3582   /// \endverbatim
3583   template <class GroupT>
3584   static std::vector<Matcher *> optimizeRules(
3585       ArrayRef<Matcher *> Rules,
3586       std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
3587 };
3588 
3589 void GlobalISelEmitter::gatherOpcodeValues() {
3590   InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3591 }
3592 
3593 void GlobalISelEmitter::gatherTypeIDValues() {
3594   LLTOperandMatcher::initTypeIDValuesMap();
3595 }
3596 
3597 void GlobalISelEmitter::gatherNodeEquivs() {
3598   assert(NodeEquivs.empty());
3599   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
3600     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
3601 
3602   assert(ComplexPatternEquivs.empty());
3603   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3604     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3605     if (!SelDAGEquiv)
3606       continue;
3607     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3608  }
3609 
3610  assert(SDNodeXFormEquivs.empty());
3611  for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3612    Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3613    if (!SelDAGEquiv)
3614      continue;
3615    SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3616  }
3617 }
3618 
3619 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
3620   return NodeEquivs.lookup(N);
3621 }
3622 
3623 const CodeGenInstruction *
3624 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3625   if (N->getNumChildren() >= 1) {
3626     // setcc operation maps to two different G_* instructions based on the type.
3627     if (!Equiv.isValueUnset("IfFloatingPoint") &&
3628         MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3629       return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3630   }
3631 
3632   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3633     const TreePredicateFn &Predicate = Call.Fn;
3634     if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3635         Predicate.isSignExtLoad())
3636       return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3637     if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3638         Predicate.isZeroExtLoad())
3639       return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3640   }
3641 
3642   return &Target.getInstruction(Equiv.getValueAsDef("I"));
3643 }
3644 
3645 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
3646     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3647       CGRegs(Target.getRegBank()) {}
3648 
3649 //===- Emitter ------------------------------------------------------------===//
3650 
3651 Error
3652 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
3653                                         ArrayRef<Predicate> Predicates) {
3654   for (const Predicate &P : Predicates) {
3655     if (!P.Def || P.getCondString().empty())
3656       continue;
3657     declareSubtargetFeature(P.Def);
3658     M.addRequiredFeature(P.Def);
3659   }
3660 
3661   return Error::success();
3662 }
3663 
3664 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
3665     const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
3666     InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
3667   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3668     if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3669       SmallVector<unsigned, 4> ParsedAddrSpaces;
3670 
3671       for (Init *Val : AddrSpaces->getValues()) {
3672         IntInit *IntVal = dyn_cast<IntInit>(Val);
3673         if (!IntVal)
3674           return failedImport("Address space is not an integer");
3675         ParsedAddrSpaces.push_back(IntVal->getValue());
3676       }
3677 
3678       if (!ParsedAddrSpaces.empty()) {
3679         InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3680             0, ParsedAddrSpaces);
3681       }
3682     }
3683 
3684     int64_t MinAlign = Predicate.getMinAlignment();
3685     if (MinAlign > 0)
3686       InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3687   }
3688 
3689   // G_LOAD is used for both non-extending and any-extending loads.
3690   if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3691     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3692         0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3693     return InsnMatcher;
3694   }
3695   if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3696     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3697         0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3698     return InsnMatcher;
3699   }
3700 
3701   if (Predicate.isStore()) {
3702     if (Predicate.isTruncStore()) {
3703       // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3704       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3705           0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3706       return InsnMatcher;
3707     }
3708     if (Predicate.isNonTruncStore()) {
3709       // We need to check the sizes match here otherwise we could incorrectly
3710       // match truncating stores with non-truncating ones.
3711       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3712           0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3713     }
3714   }
3715 
3716   // No check required. We already did it by swapping the opcode.
3717   if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3718       Predicate.isSignExtLoad())
3719     return InsnMatcher;
3720 
3721   // No check required. We already did it by swapping the opcode.
3722   if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3723       Predicate.isZeroExtLoad())
3724     return InsnMatcher;
3725 
3726   // No check required. G_STORE by itself is a non-extending store.
3727   if (Predicate.isNonTruncStore())
3728     return InsnMatcher;
3729 
3730   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3731     if (Predicate.getMemoryVT() != nullptr) {
3732       Optional<LLTCodeGen> MemTyOrNone =
3733           MVTToLLT(getValueType(Predicate.getMemoryVT()));
3734 
3735       if (!MemTyOrNone)
3736         return failedImport("MemVT could not be converted to LLT");
3737 
3738       // MMO's work in bytes so we must take care of unusual types like i1
3739       // don't round down.
3740       unsigned MemSizeInBits =
3741           llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3742 
3743       InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
3744                                                            MemSizeInBits / 8);
3745       return InsnMatcher;
3746     }
3747   }
3748 
3749   if (Predicate.isLoad() || Predicate.isStore()) {
3750     // No check required. A G_LOAD/G_STORE is an unindexed load.
3751     if (Predicate.isUnindexed())
3752       return InsnMatcher;
3753   }
3754 
3755   if (Predicate.isAtomic()) {
3756     if (Predicate.isAtomicOrderingMonotonic()) {
3757       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
3758       return InsnMatcher;
3759     }
3760     if (Predicate.isAtomicOrderingAcquire()) {
3761       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3762       return InsnMatcher;
3763     }
3764     if (Predicate.isAtomicOrderingRelease()) {
3765       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3766       return InsnMatcher;
3767     }
3768     if (Predicate.isAtomicOrderingAcquireRelease()) {
3769       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3770           "AcquireRelease");
3771       return InsnMatcher;
3772     }
3773     if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3774       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3775           "SequentiallyConsistent");
3776       return InsnMatcher;
3777     }
3778   }
3779 
3780   if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3781     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3782         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3783     return InsnMatcher;
3784   }
3785   if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3786     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3787         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3788     return InsnMatcher;
3789   }
3790 
3791   if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3792     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3793         "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3794     return InsnMatcher;
3795   }
3796   if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3797     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3798         "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3799     return InsnMatcher;
3800   }
3801   HasAddedMatcher = false;
3802   return InsnMatcher;
3803 }
3804 
3805 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3806     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3807     const TreePatternNode *Src, unsigned &TempOpIdx) {
3808   Record *SrcGIEquivOrNull = nullptr;
3809   const CodeGenInstruction *SrcGIOrNull = nullptr;
3810 
3811   // Start with the defined operands (i.e., the results of the root operator).
3812   if (Src->getExtTypes().size() > 1)
3813     return failedImport("Src pattern has multiple results");
3814 
3815   if (Src->isLeaf()) {
3816     Init *SrcInit = Src->getLeafValue();
3817     if (isa<IntInit>(SrcInit)) {
3818       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3819           &Target.getInstruction(RK.getDef("G_CONSTANT")));
3820     } else
3821       return failedImport(
3822           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3823   } else {
3824     SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
3825     if (!SrcGIEquivOrNull)
3826       return failedImport("Pattern operator lacks an equivalent Instruction" +
3827                           explainOperator(Src->getOperator()));
3828     SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
3829 
3830     // The operators look good: match the opcode
3831     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3832   }
3833 
3834   unsigned OpIdx = 0;
3835   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3836     // Results don't have a name unless they are the root node. The caller will
3837     // set the name if appropriate.
3838     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3839     if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3840       return failedImport(toString(std::move(Error)) +
3841                           " for result of Src pattern operator");
3842   }
3843 
3844   for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3845     const TreePredicateFn &Predicate = Call.Fn;
3846     bool HasAddedBuiltinMatcher = true;
3847     if (Predicate.isAlwaysTrue())
3848       continue;
3849 
3850     if (Predicate.isImmediatePattern()) {
3851       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3852       continue;
3853     }
3854 
3855     auto InsnMatcherOrError = addBuiltinPredicates(
3856         SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
3857     if (auto Error = InsnMatcherOrError.takeError())
3858       return std::move(Error);
3859 
3860     if (Predicate.hasGISelPredicateCode()) {
3861       InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3862       continue;
3863     }
3864     if (!HasAddedBuiltinMatcher) {
3865       return failedImport("Src pattern child has predicate (" +
3866                           explainPredicates(Src) + ")");
3867     }
3868   }
3869 
3870   bool IsAtomic = false;
3871   if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3872     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
3873   else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3874     IsAtomic = true;
3875     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3876       "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3877   }
3878 
3879   if (Src->isLeaf()) {
3880     Init *SrcInit = Src->getLeafValue();
3881     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
3882       OperandMatcher &OM =
3883           InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
3884       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3885     } else
3886       return failedImport(
3887           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3888   } else {
3889     assert(SrcGIOrNull &&
3890            "Expected to have already found an equivalent Instruction");
3891     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3892         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3893       // imm/fpimm still have operands but we don't need to do anything with it
3894       // here since we don't support ImmLeaf predicates yet. However, we still
3895       // need to note the hidden operand to get GIM_CheckNumOperands correct.
3896       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3897       return InsnMatcher;
3898     }
3899 
3900     // Special case because the operand order is changed from setcc. The
3901     // predicate operand needs to be swapped from the last operand to the first
3902     // source.
3903 
3904     unsigned NumChildren = Src->getNumChildren();
3905     bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3906 
3907     if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3908       TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3909       if (SrcChild->isLeaf()) {
3910         DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3911         Record *CCDef = DI ? DI->getDef() : nullptr;
3912         if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3913           return failedImport("Unable to handle CondCode");
3914 
3915         OperandMatcher &OM =
3916           InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3917         StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3918                                       CCDef->getValueAsString("ICmpPredicate");
3919 
3920         if (!PredType.empty()) {
3921           OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
3922           // Process the other 2 operands normally.
3923           --NumChildren;
3924         }
3925       }
3926     }
3927 
3928     // Hack around an unfortunate mistake in how atomic store (and really
3929     // atomicrmw in general) operands were ordered. A ISD::STORE used the order
3930     // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
3931     // <pointer>, <stored value>. In GlobalISel there's just the one store
3932     // opcode, so we need to swap the operands here to get the right type check.
3933     if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
3934       assert(NumChildren == 2 && "wrong operands for atomic store");
3935 
3936       TreePatternNode *PtrChild = Src->getChild(0);
3937       TreePatternNode *ValueChild = Src->getChild(1);
3938 
3939       if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
3940                                           false, 1, TempOpIdx))
3941         return std::move(Error);
3942 
3943       if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
3944                                           false, 0, TempOpIdx))
3945         return std::move(Error);
3946       return InsnMatcher;
3947     }
3948 
3949     // Match the used operands (i.e. the children of the operator).
3950     bool IsIntrinsic =
3951         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3952         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3953     const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3954     if (IsIntrinsic && !II)
3955       return failedImport("Expected IntInit containing intrinsic ID)");
3956 
3957     for (unsigned i = 0; i != NumChildren; ++i) {
3958       TreePatternNode *SrcChild = Src->getChild(i);
3959 
3960       // We need to determine the meaning of a literal integer based on the
3961       // context. If this is a field required to be an immediate (such as an
3962       // immarg intrinsic argument), the required predicates are different than
3963       // a constant which may be materialized in a register. If we have an
3964       // argument that is required to be an immediate, we should not emit an LLT
3965       // type check, and should not be looking for a G_CONSTANT defined
3966       // register.
3967       bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
3968 
3969       // SelectionDAG allows pointers to be represented with iN since it doesn't
3970       // distinguish between pointers and integers but they are different types in GlobalISel.
3971       // Coerce integers to pointers to address space 0 if the context indicates a pointer.
3972       //
3973       bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
3974 
3975       if (IsIntrinsic) {
3976         // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3977         // following the defs is an intrinsic ID.
3978         if (i == 0) {
3979           OperandMatcher &OM =
3980               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3981           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
3982           continue;
3983         }
3984 
3985         // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
3986         //
3987         // Note that we have to look at the i-1th parameter, because we don't
3988         // have the intrinsic ID in the intrinsic's parameter list.
3989         OperandIsAPointer |= II->isParamAPointer(i - 1);
3990         OperandIsImmArg |= II->isParamImmArg(i - 1);
3991       }
3992 
3993       if (auto Error =
3994               importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3995                                  OperandIsImmArg, OpIdx++, TempOpIdx))
3996         return std::move(Error);
3997     }
3998   }
3999 
4000   return InsnMatcher;
4001 }
4002 
4003 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
4004     OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
4005   const auto &ComplexPattern = ComplexPatternEquivs.find(R);
4006   if (ComplexPattern == ComplexPatternEquivs.end())
4007     return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
4008                         ") not mapped to GlobalISel");
4009 
4010   OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
4011   TempOpIdx++;
4012   return Error::success();
4013 }
4014 
4015 // Get the name to use for a pattern operand. For an anonymous physical register
4016 // input, this should use the register name.
4017 static StringRef getSrcChildName(const TreePatternNode *SrcChild,
4018                                  Record *&PhysReg) {
4019   StringRef SrcChildName = SrcChild->getName();
4020   if (SrcChildName.empty() && SrcChild->isLeaf()) {
4021     if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4022       auto *ChildRec = ChildDefInit->getDef();
4023       if (ChildRec->isSubClassOf("Register")) {
4024         SrcChildName = ChildRec->getName();
4025         PhysReg = ChildRec;
4026       }
4027     }
4028   }
4029 
4030   return SrcChildName;
4031 }
4032 
4033 Error GlobalISelEmitter::importChildMatcher(
4034     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
4035     const TreePatternNode *SrcChild, bool OperandIsAPointer,
4036     bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
4037 
4038   Record *PhysReg = nullptr;
4039   StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
4040 
4041   OperandMatcher &OM =
4042       PhysReg
4043           ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
4044           : InsnMatcher.addOperand(OpIdx, std::string(SrcChildName), TempOpIdx);
4045   if (OM.isSameAsAnotherOperand())
4046     return Error::success();
4047 
4048   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
4049   if (ChildTypes.size() != 1)
4050     return failedImport("Src pattern child has multiple results");
4051 
4052   // Check MBB's before the type check since they are not a known type.
4053   if (!SrcChild->isLeaf()) {
4054     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
4055       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
4056       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4057         OM.addPredicate<MBBOperandMatcher>();
4058         return Error::success();
4059       }
4060       if (SrcChild->getOperator()->getName() == "timm") {
4061         OM.addPredicate<ImmOperandMatcher>();
4062         return Error::success();
4063       }
4064     }
4065   }
4066 
4067   // Immediate arguments have no meaningful type to check as they don't have
4068   // registers.
4069   if (!OperandIsImmArg) {
4070     if (auto Error =
4071             OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
4072       return failedImport(toString(std::move(Error)) + " for Src operand (" +
4073                           to_string(*SrcChild) + ")");
4074   }
4075 
4076   // Check for nested instructions.
4077   if (!SrcChild->isLeaf()) {
4078     if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
4079       // When a ComplexPattern is used as an operator, it should do the same
4080       // thing as when used as a leaf. However, the children of the operator
4081       // name the sub-operands that make up the complex operand and we must
4082       // prepare to reference them in the renderer too.
4083       unsigned RendererID = TempOpIdx;
4084       if (auto Error = importComplexPatternOperandMatcher(
4085               OM, SrcChild->getOperator(), TempOpIdx))
4086         return Error;
4087 
4088       for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
4089         auto *SubOperand = SrcChild->getChild(i);
4090         if (!SubOperand->getName().empty()) {
4091           if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
4092                                                         SrcChild->getOperator(),
4093                                                         RendererID, i))
4094             return Error;
4095         }
4096       }
4097 
4098       return Error::success();
4099     }
4100 
4101     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4102         InsnMatcher.getRuleMatcher(), SrcChild->getName());
4103     if (!MaybeInsnOperand.hasValue()) {
4104       // This isn't strictly true. If the user were to provide exactly the same
4105       // matchers as the original operand then we could allow it. However, it's
4106       // simpler to not permit the redundant specification.
4107       return failedImport("Nested instruction cannot be the same as another operand");
4108     }
4109 
4110     // Map the node to a gMIR instruction.
4111     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4112     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
4113         Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
4114     if (auto Error = InsnMatcherOrError.takeError())
4115       return Error;
4116 
4117     return Error::success();
4118   }
4119 
4120   if (SrcChild->hasAnyPredicate())
4121     return failedImport("Src pattern child has unsupported predicate");
4122 
4123   // Check for constant immediates.
4124   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
4125     if (OperandIsImmArg) {
4126       // Checks for argument directly in operand list
4127       OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
4128     } else {
4129       // Checks for materialized constant
4130       OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
4131     }
4132     return Error::success();
4133   }
4134 
4135   // Check for def's like register classes or ComplexPattern's.
4136   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4137     auto *ChildRec = ChildDefInit->getDef();
4138 
4139     // Check for register classes.
4140     if (ChildRec->isSubClassOf("RegisterClass") ||
4141         ChildRec->isSubClassOf("RegisterOperand")) {
4142       OM.addPredicate<RegisterBankOperandMatcher>(
4143           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
4144       return Error::success();
4145     }
4146 
4147     if (ChildRec->isSubClassOf("Register")) {
4148       // This just be emitted as a copy to the specific register.
4149       ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
4150       const CodeGenRegisterClass *RC
4151         = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
4152       if (!RC) {
4153         return failedImport(
4154           "Could not determine physical register class of pattern source");
4155       }
4156 
4157       OM.addPredicate<RegisterBankOperandMatcher>(*RC);
4158       return Error::success();
4159     }
4160 
4161     // Check for ValueType.
4162     if (ChildRec->isSubClassOf("ValueType")) {
4163       // We already added a type check as standard practice so this doesn't need
4164       // to do anything.
4165       return Error::success();
4166     }
4167 
4168     // Check for ComplexPattern's.
4169     if (ChildRec->isSubClassOf("ComplexPattern"))
4170       return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
4171 
4172     if (ChildRec->isSubClassOf("ImmLeaf")) {
4173       return failedImport(
4174           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
4175     }
4176 
4177     // Place holder for SRCVALUE nodes. Nothing to do here.
4178     if (ChildRec->getName() == "srcvalue")
4179       return Error::success();
4180 
4181     const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
4182     if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
4183       auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4184           InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
4185       InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4186 
4187       ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
4188 
4189       const CodeGenInstruction &BuildVector
4190         = Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
4191       const CodeGenInstruction &BuildVectorTrunc
4192         = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
4193 
4194       // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
4195       // as an alternative.
4196       InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
4197       makeArrayRef({&BuildVector, &BuildVectorTrunc}));
4198 
4199       // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
4200       // theoretically not emit any opcode check, but getOpcodeMatcher currently
4201       // has to succeed.
4202       OperandMatcher &OM =
4203           InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
4204       if (auto Error =
4205               OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
4206         return failedImport(toString(std::move(Error)) +
4207                             " for result of Src pattern operator");
4208 
4209       InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
4210           ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
4211                       : VectorSplatImmPredicateMatcher::AllZeros);
4212       return Error::success();
4213     }
4214 
4215     return failedImport(
4216         "Src pattern child def is an unsupported tablegen class");
4217   }
4218 
4219   return failedImport("Src pattern child is an unsupported kind");
4220 }
4221 
4222 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4223     action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
4224     TreePatternNode *DstChild) {
4225 
4226   const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
4227   if (SubOperand.hasValue()) {
4228     DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4229         *std::get<0>(*SubOperand), DstChild->getName(),
4230         std::get<1>(*SubOperand), std::get<2>(*SubOperand));
4231     return InsertPt;
4232   }
4233 
4234   if (!DstChild->isLeaf()) {
4235     if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4236       auto Child = DstChild->getChild(0);
4237       auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
4238       if (I != SDNodeXFormEquivs.end()) {
4239         Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4240         if (XFormOpc->getName() == "timm") {
4241           // If this is a TargetConstant, there won't be a corresponding
4242           // instruction to transform. Instead, this will refer directly to an
4243           // operand in an instruction's operand list.
4244           DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4245                                                           Child->getName());
4246         } else {
4247           DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4248                                                    Child->getName());
4249         }
4250 
4251         return InsertPt;
4252       }
4253       return failedImport("SDNodeXForm " + Child->getName() +
4254                           " has no custom renderer");
4255     }
4256 
4257     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4258     // inline, but in MI it's just another operand.
4259     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4260       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
4261       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4262         DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4263         return InsertPt;
4264       }
4265     }
4266 
4267     // Similarly, imm is an operator in TreePatternNode's view but must be
4268     // rendered as operands.
4269     // FIXME: The target should be able to choose sign-extended when appropriate
4270     //        (e.g. on Mips).
4271     if (DstChild->getOperator()->getName() == "timm") {
4272       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4273       return InsertPt;
4274     } else if (DstChild->getOperator()->getName() == "imm") {
4275       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
4276       return InsertPt;
4277     } else if (DstChild->getOperator()->getName() == "fpimm") {
4278       DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
4279           DstChild->getName());
4280       return InsertPt;
4281     }
4282 
4283     if (DstChild->getOperator()->isSubClassOf("Instruction")) {
4284       auto OpTy = getInstResultType(DstChild);
4285       if (!OpTy)
4286         return OpTy.takeError();
4287 
4288       unsigned TempRegID = Rule.allocateTempRegID();
4289       InsertPt = Rule.insertAction<MakeTempRegisterAction>(
4290           InsertPt, *OpTy, TempRegID);
4291       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4292 
4293       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4294           ++InsertPt, Rule, DstChild, TempRegID);
4295       if (auto Error = InsertPtOrError.takeError())
4296         return std::move(Error);
4297       return InsertPtOrError.get();
4298     }
4299 
4300     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
4301   }
4302 
4303   // It could be a specific immediate in which case we should just check for
4304   // that immediate.
4305   if (const IntInit *ChildIntInit =
4306           dyn_cast<IntInit>(DstChild->getLeafValue())) {
4307     DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4308     return InsertPt;
4309   }
4310 
4311   // Otherwise, we're looking for a bog-standard RegisterClass operand.
4312   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
4313     auto *ChildRec = ChildDefInit->getDef();
4314 
4315     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
4316     if (ChildTypes.size() != 1)
4317       return failedImport("Dst pattern child has multiple results");
4318 
4319     Optional<LLTCodeGen> OpTyOrNone = None;
4320     if (ChildTypes.front().isMachineValueType())
4321       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
4322     if (!OpTyOrNone)
4323       return failedImport("Dst operand has an unsupported type");
4324 
4325     if (ChildRec->isSubClassOf("Register")) {
4326       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
4327       return InsertPt;
4328     }
4329 
4330     if (ChildRec->isSubClassOf("RegisterClass") ||
4331         ChildRec->isSubClassOf("RegisterOperand") ||
4332         ChildRec->isSubClassOf("ValueType")) {
4333       if (ChildRec->isSubClassOf("RegisterOperand") &&
4334           !ChildRec->isValueUnset("GIZeroRegister")) {
4335         DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
4336             DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
4337         return InsertPt;
4338       }
4339 
4340       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4341       return InsertPt;
4342     }
4343 
4344     if (ChildRec->isSubClassOf("SubRegIndex")) {
4345       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4346       DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4347       return InsertPt;
4348     }
4349 
4350     if (ChildRec->isSubClassOf("ComplexPattern")) {
4351       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4352       if (ComplexPattern == ComplexPatternEquivs.end())
4353         return failedImport(
4354             "SelectionDAG ComplexPattern not mapped to GlobalISel");
4355 
4356       const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
4357       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4358           *ComplexPattern->second, DstChild->getName(),
4359           OM.getAllocatedTemporariesBaseID());
4360       return InsertPt;
4361     }
4362 
4363     return failedImport(
4364         "Dst pattern child def is an unsupported tablegen class");
4365   }
4366 
4367   return failedImport("Dst pattern child is an unsupported kind");
4368 }
4369 
4370 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
4371     RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4372     const TreePatternNode *Dst) {
4373   auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4374   if (auto Error = InsertPtOrError.takeError())
4375     return std::move(Error);
4376 
4377   action_iterator InsertPt = InsertPtOrError.get();
4378   BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
4379 
4380   for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4381     InsertPt = M.insertAction<BuildMIAction>(
4382         InsertPt, M.allocateOutputInsnID(),
4383         &Target.getInstruction(RK.getDef("COPY")));
4384     BuildMIAction &CopyToPhysRegMIBuilder =
4385         *static_cast<BuildMIAction *>(InsertPt->get());
4386     CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4387                                                             true);
4388     CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4389   }
4390 
4391   if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
4392                        .takeError())
4393     return std::move(Error);
4394 
4395   if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4396                        .takeError())
4397     return std::move(Error);
4398 
4399   return DstMIBuilder;
4400 }
4401 
4402 Expected<action_iterator>
4403 GlobalISelEmitter::createAndImportSubInstructionRenderer(
4404     const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
4405     unsigned TempRegID) {
4406   auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4407 
4408   // TODO: Assert there's exactly one result.
4409 
4410   if (auto Error = InsertPtOrError.takeError())
4411     return std::move(Error);
4412 
4413   BuildMIAction &DstMIBuilder =
4414       *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4415 
4416   // Assign the result to TempReg.
4417   DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4418 
4419   InsertPtOrError =
4420       importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
4421   if (auto Error = InsertPtOrError.takeError())
4422     return std::move(Error);
4423 
4424   // We need to make sure that when we import an INSERT_SUBREG as a
4425   // subinstruction that it ends up being constrained to the correct super
4426   // register and subregister classes.
4427   auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4428   if (OpName == "INSERT_SUBREG") {
4429     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4430     if (!SubClass)
4431       return failedImport(
4432           "Cannot infer register class from INSERT_SUBREG operand #1");
4433     Optional<const CodeGenRegisterClass *> SuperClass =
4434         inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4435                                        Dst->getChild(2));
4436     if (!SuperClass)
4437       return failedImport(
4438           "Cannot infer register class for INSERT_SUBREG operand #0");
4439     // The destination and the super register source of an INSERT_SUBREG must
4440     // be the same register class.
4441     M.insertAction<ConstrainOperandToRegClassAction>(
4442         InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4443     M.insertAction<ConstrainOperandToRegClassAction>(
4444         InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4445     M.insertAction<ConstrainOperandToRegClassAction>(
4446         InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4447     return InsertPtOrError.get();
4448   }
4449 
4450   if (OpName == "EXTRACT_SUBREG") {
4451     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4452     // instructions, the result register class is controlled by the
4453     // subregisters of the operand. As a result, we must constrain the result
4454     // class rather than check that it's already the right one.
4455     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4456     if (!SuperClass)
4457       return failedImport(
4458         "Cannot infer register class from EXTRACT_SUBREG operand #0");
4459 
4460     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4461     if (!SubIdx)
4462       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4463 
4464     const auto SrcRCDstRCPair =
4465       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4466     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4467     M.insertAction<ConstrainOperandToRegClassAction>(
4468       InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4469     M.insertAction<ConstrainOperandToRegClassAction>(
4470       InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4471 
4472     // We're done with this pattern!  It's eligible for GISel emission; return
4473     // it.
4474     return InsertPtOrError.get();
4475   }
4476 
4477   // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4478   // subinstruction.
4479   if (OpName == "SUBREG_TO_REG") {
4480     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4481     if (!SubClass)
4482       return failedImport(
4483         "Cannot infer register class from SUBREG_TO_REG child #1");
4484     auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4485                                               Dst->getChild(2));
4486     if (!SuperClass)
4487       return failedImport(
4488         "Cannot infer register class for SUBREG_TO_REG operand #0");
4489     M.insertAction<ConstrainOperandToRegClassAction>(
4490       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4491     M.insertAction<ConstrainOperandToRegClassAction>(
4492       InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4493     return InsertPtOrError.get();
4494   }
4495 
4496   if (OpName == "REG_SEQUENCE") {
4497     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4498     M.insertAction<ConstrainOperandToRegClassAction>(
4499       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4500 
4501     unsigned Num = Dst->getNumChildren();
4502     for (unsigned I = 1; I != Num; I += 2) {
4503       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4504 
4505       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4506       if (!SubIdx)
4507         return failedImport("REG_SEQUENCE child is not a subreg index");
4508 
4509       const auto SrcRCDstRCPair =
4510         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4511       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4512       M.insertAction<ConstrainOperandToRegClassAction>(
4513         InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4514     }
4515 
4516     return InsertPtOrError.get();
4517   }
4518 
4519   M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4520                                                       DstMIBuilder.getInsnID());
4521   return InsertPtOrError.get();
4522 }
4523 
4524 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
4525     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4526   Record *DstOp = Dst->getOperator();
4527   if (!DstOp->isSubClassOf("Instruction")) {
4528     if (DstOp->isSubClassOf("ValueType"))
4529       return failedImport(
4530           "Pattern operator isn't an instruction (it's a ValueType)");
4531     return failedImport("Pattern operator isn't an instruction");
4532   }
4533   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
4534 
4535   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
4536   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
4537   StringRef Name = DstI->TheDef->getName();
4538   if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
4539     DstI = &Target.getInstruction(RK.getDef("COPY"));
4540 
4541   return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4542                                        DstI);
4543 }
4544 
4545 Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
4546     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4547     const TreePatternNode *Dst) {
4548   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4549   const unsigned NumDefs = DstI->Operands.NumDefs;
4550   if (NumDefs == 0)
4551     return InsertPt;
4552 
4553   DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
4554 
4555   // Some instructions have multiple defs, but are missing a type entry
4556   // (e.g. s_cc_out operands).
4557   if (Dst->getExtTypes().size() < NumDefs)
4558     return failedImport("unhandled discarded def");
4559 
4560   // Patterns only handle a single result, so any result after the first is an
4561   // implicitly dead def.
4562   for (unsigned I = 1; I < NumDefs; ++I) {
4563     const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
4564     if (!ExtTy.isMachineValueType())
4565       return failedImport("unsupported typeset");
4566 
4567     auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
4568     if (!OpTy)
4569       return failedImport("unsupported type");
4570 
4571     unsigned TempRegID = M.allocateTempRegID();
4572     InsertPt =
4573       M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
4574     DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
4575   }
4576 
4577   return InsertPt;
4578 }
4579 
4580 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4581     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4582     const llvm::TreePatternNode *Dst) {
4583   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4584   CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
4585 
4586   StringRef Name = OrigDstI->TheDef->getName();
4587   unsigned ExpectedDstINumUses = Dst->getNumChildren();
4588 
4589   // EXTRACT_SUBREG needs to use a subregister COPY.
4590   if (Name == "EXTRACT_SUBREG") {
4591     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4592     if (!SubRegInit)
4593       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4594 
4595     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4596     TreePatternNode *ValChild = Dst->getChild(0);
4597     if (!ValChild->isLeaf()) {
4598       // We really have to handle the source instruction, and then insert a
4599       // copy from the subregister.
4600       auto ExtractSrcTy = getInstResultType(ValChild);
4601       if (!ExtractSrcTy)
4602         return ExtractSrcTy.takeError();
4603 
4604       unsigned TempRegID = M.allocateTempRegID();
4605       InsertPt = M.insertAction<MakeTempRegisterAction>(
4606         InsertPt, *ExtractSrcTy, TempRegID);
4607 
4608       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4609         ++InsertPt, M, ValChild, TempRegID);
4610       if (auto Error = InsertPtOrError.takeError())
4611         return std::move(Error);
4612 
4613       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
4614       return InsertPt;
4615     }
4616 
4617     // If this is a source operand, this is just a subregister copy.
4618     Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4619     if (!RCDef)
4620       return failedImport("EXTRACT_SUBREG child #0 could not "
4621                           "be coerced to a register class");
4622 
4623     CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4624 
4625     const auto SrcRCDstRCPair =
4626       RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4627     if (SrcRCDstRCPair.hasValue()) {
4628       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4629       if (SrcRCDstRCPair->first != RC)
4630         return failedImport("EXTRACT_SUBREG requires an additional COPY");
4631     }
4632 
4633     DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4634                                                  SubIdx);
4635     return InsertPt;
4636   }
4637 
4638   if (Name == "REG_SEQUENCE") {
4639     if (!Dst->getChild(0)->isLeaf())
4640       return failedImport("REG_SEQUENCE child #0 is not a leaf");
4641 
4642     Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4643     if (!RCDef)
4644       return failedImport("REG_SEQUENCE child #0 could not "
4645                           "be coerced to a register class");
4646 
4647     if ((ExpectedDstINumUses - 1) % 2 != 0)
4648       return failedImport("Malformed REG_SEQUENCE");
4649 
4650     for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4651       TreePatternNode *ValChild = Dst->getChild(I);
4652       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4653 
4654       if (DefInit *SubRegInit =
4655               dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4656         CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4657 
4658         auto InsertPtOrError =
4659             importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4660         if (auto Error = InsertPtOrError.takeError())
4661           return std::move(Error);
4662         InsertPt = InsertPtOrError.get();
4663         DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4664       }
4665     }
4666 
4667     return InsertPt;
4668   }
4669 
4670   // Render the explicit uses.
4671   unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
4672   if (Name == "COPY_TO_REGCLASS") {
4673     DstINumUses--; // Ignore the class constraint.
4674     ExpectedDstINumUses--;
4675   }
4676 
4677   // NumResults - This is the number of results produced by the instruction in
4678   // the "outs" list.
4679   unsigned NumResults = OrigDstI->Operands.NumDefs;
4680 
4681   // Number of operands we know the output instruction must have. If it is
4682   // variadic, we could have more operands.
4683   unsigned NumFixedOperands = DstI->Operands.size();
4684 
4685   // Loop over all of the fixed operands of the instruction pattern, emitting
4686   // code to fill them all in. The node 'N' usually has number children equal to
4687   // the number of input operands of the instruction.  However, in cases where
4688   // there are predicate operands for an instruction, we need to fill in the
4689   // 'execute always' values. Match up the node operands to the instruction
4690   // operands to do this.
4691   unsigned Child = 0;
4692 
4693   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4694   // number of operands at the end of the list which have default values.
4695   // Those can come from the pattern if it provides enough arguments, or be
4696   // filled in with the default if the pattern hasn't provided them. But any
4697   // operand with a default value _before_ the last mandatory one will be
4698   // filled in with their defaults unconditionally.
4699   unsigned NonOverridableOperands = NumFixedOperands;
4700   while (NonOverridableOperands > NumResults &&
4701          CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4702     --NonOverridableOperands;
4703 
4704   unsigned NumDefaultOps = 0;
4705   for (unsigned I = 0; I != DstINumUses; ++I) {
4706     unsigned InstOpNo = DstI->Operands.NumDefs + I;
4707 
4708     // Determine what to emit for this operand.
4709     Record *OperandNode = DstI->Operands[InstOpNo].Rec;
4710 
4711     // If the operand has default values, introduce them now.
4712     if (CGP.operandHasDefault(OperandNode) &&
4713         (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4714       // This is a predicate or optional def operand which the pattern has not
4715       // overridden, or which we aren't letting it override; emit the 'default
4716       // ops' operands.
4717 
4718       const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
4719       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
4720       if (auto Error = importDefaultOperandRenderers(
4721             InsertPt, M, DstMIBuilder, DefaultOps))
4722         return std::move(Error);
4723       ++NumDefaultOps;
4724       continue;
4725     }
4726 
4727     auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
4728                                                      Dst->getChild(Child));
4729     if (auto Error = InsertPtOrError.takeError())
4730       return std::move(Error);
4731     InsertPt = InsertPtOrError.get();
4732     ++Child;
4733   }
4734 
4735   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
4736     return failedImport("Expected " + llvm::to_string(DstINumUses) +
4737                         " used operands but found " +
4738                         llvm::to_string(ExpectedDstINumUses) +
4739                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
4740                         " default ones");
4741 
4742   return InsertPt;
4743 }
4744 
4745 Error GlobalISelEmitter::importDefaultOperandRenderers(
4746     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4747     DagInit *DefaultOps) const {
4748   for (const auto *DefaultOp : DefaultOps->getArgs()) {
4749     Optional<LLTCodeGen> OpTyOrNone = None;
4750 
4751     // Look through ValueType operators.
4752     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4753       if (const DefInit *DefaultDagOperator =
4754               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
4755         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
4756           OpTyOrNone = MVTToLLT(getValueType(
4757                                   DefaultDagOperator->getDef()));
4758           DefaultOp = DefaultDagOp->getArg(0);
4759         }
4760       }
4761     }
4762 
4763     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
4764       auto Def = DefaultDefOp->getDef();
4765       if (Def->getName() == "undef_tied_input") {
4766         unsigned TempRegID = M.allocateTempRegID();
4767         M.insertAction<MakeTempRegisterAction>(
4768           InsertPt, OpTyOrNone.getValue(), TempRegID);
4769         InsertPt = M.insertAction<BuildMIAction>(
4770           InsertPt, M.allocateOutputInsnID(),
4771           &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4772         BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4773           InsertPt->get());
4774         IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4775         DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4776       } else {
4777         DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4778       }
4779       continue;
4780     }
4781 
4782     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
4783       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
4784       continue;
4785     }
4786 
4787     return failedImport("Could not add default op");
4788   }
4789 
4790   return Error::success();
4791 }
4792 
4793 Error GlobalISelEmitter::importImplicitDefRenderers(
4794     BuildMIAction &DstMIBuilder,
4795     const std::vector<Record *> &ImplicitDefs) const {
4796   if (!ImplicitDefs.empty())
4797     return failedImport("Pattern defines a physical register");
4798   return Error::success();
4799 }
4800 
4801 Optional<const CodeGenRegisterClass *>
4802 GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4803   assert(Leaf && "Expected node?");
4804   assert(Leaf->isLeaf() && "Expected leaf?");
4805   Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4806   if (!RCRec)
4807     return None;
4808   CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4809   if (!RC)
4810     return None;
4811   return RC;
4812 }
4813 
4814 Optional<const CodeGenRegisterClass *>
4815 GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4816   if (!N)
4817     return None;
4818 
4819   if (N->isLeaf())
4820     return getRegClassFromLeaf(N);
4821 
4822   // We don't have a leaf node, so we have to try and infer something. Check
4823   // that we have an instruction that we an infer something from.
4824 
4825   // Only handle things that produce a single type.
4826   if (N->getNumTypes() != 1)
4827     return None;
4828   Record *OpRec = N->getOperator();
4829 
4830   // We only want instructions.
4831   if (!OpRec->isSubClassOf("Instruction"))
4832     return None;
4833 
4834   // Don't want to try and infer things when there could potentially be more
4835   // than one candidate register class.
4836   auto &Inst = Target.getInstruction(OpRec);
4837   if (Inst.Operands.NumDefs > 1)
4838     return None;
4839 
4840   // Handle any special-case instructions which we can safely infer register
4841   // classes from.
4842   StringRef InstName = Inst.TheDef->getName();
4843   bool IsRegSequence = InstName == "REG_SEQUENCE";
4844   if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
4845     // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4846     // has the desired register class as the first child.
4847     TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
4848     if (!RCChild->isLeaf())
4849       return None;
4850     return getRegClassFromLeaf(RCChild);
4851   }
4852 
4853   // Handle destination record types that we can safely infer a register class
4854   // from.
4855   const auto &DstIOperand = Inst.Operands[0];
4856   Record *DstIOpRec = DstIOperand.Rec;
4857   if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4858     DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4859     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4860     return &RC;
4861   }
4862 
4863   if (DstIOpRec->isSubClassOf("RegisterClass")) {
4864     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4865     return &RC;
4866   }
4867 
4868   return None;
4869 }
4870 
4871 Optional<const CodeGenRegisterClass *>
4872 GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
4873                                            TreePatternNode *SubRegIdxNode) {
4874   assert(SubRegIdxNode && "Expected subregister index node!");
4875   // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4876   if (!Ty.isValueTypeByHwMode(false))
4877     return None;
4878   if (!SubRegIdxNode->isLeaf())
4879     return None;
4880   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4881   if (!SubRegInit)
4882     return None;
4883   CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4884 
4885   // Use the information we found above to find a minimal register class which
4886   // supports the subregister and type we want.
4887   auto RC =
4888       Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4889   if (!RC)
4890     return None;
4891   return *RC;
4892 }
4893 
4894 Optional<const CodeGenRegisterClass *>
4895 GlobalISelEmitter::inferSuperRegisterClassForNode(
4896     const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4897     TreePatternNode *SubRegIdxNode) {
4898   assert(SuperRegNode && "Expected super register node!");
4899   // Check if we already have a defined register class for the super register
4900   // node. If we do, then we should preserve that rather than inferring anything
4901   // from the subregister index node. We can assume that whoever wrote the
4902   // pattern in the first place made sure that the super register and
4903   // subregister are compatible.
4904   if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4905           inferRegClassFromPattern(SuperRegNode))
4906     return *SuperRegisterClass;
4907   return inferSuperRegisterClass(Ty, SubRegIdxNode);
4908 }
4909 
4910 Optional<CodeGenSubRegIndex *>
4911 GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4912   if (!SubRegIdxNode->isLeaf())
4913     return None;
4914 
4915   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4916   if (!SubRegInit)
4917     return None;
4918   return CGRegs.getSubRegIdx(SubRegInit->getDef());
4919 }
4920 
4921 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
4922   // Keep track of the matchers and actions to emit.
4923   int Score = P.getPatternComplexity(CGP);
4924   RuleMatcher M(P.getSrcRecord()->getLoc());
4925   RuleMatcherScores[M.getRuleID()] = Score;
4926   M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4927                                   "  =>  " +
4928                                   llvm::to_string(*P.getDstPattern()));
4929 
4930   if (auto Error = importRulePredicates(M, P.getPredicates()))
4931     return std::move(Error);
4932 
4933   // Next, analyze the pattern operators.
4934   TreePatternNode *Src = P.getSrcPattern();
4935   TreePatternNode *Dst = P.getDstPattern();
4936 
4937   // If the root of either pattern isn't a simple operator, ignore it.
4938   if (auto Err = isTrivialOperatorNode(Dst))
4939     return failedImport("Dst pattern root isn't a trivial operator (" +
4940                         toString(std::move(Err)) + ")");
4941   if (auto Err = isTrivialOperatorNode(Src))
4942     return failedImport("Src pattern root isn't a trivial operator (" +
4943                         toString(std::move(Err)) + ")");
4944 
4945   // The different predicates and matchers created during
4946   // addInstructionMatcher use the RuleMatcher M to set up their
4947   // instruction ID (InsnVarID) that are going to be used when
4948   // M is going to be emitted.
4949   // However, the code doing the emission still relies on the IDs
4950   // returned during that process by the RuleMatcher when issuing
4951   // the recordInsn opcodes.
4952   // Because of that:
4953   // 1. The order in which we created the predicates
4954   //    and such must be the same as the order in which we emit them,
4955   //    and
4956   // 2. We need to reset the generation of the IDs in M somewhere between
4957   //    addInstructionMatcher and emit
4958   //
4959   // FIXME: Long term, we don't want to have to rely on this implicit
4960   // naming being the same. One possible solution would be to have
4961   // explicit operator for operation capture and reference those.
4962   // The plus side is that it would expose opportunities to share
4963   // the capture accross rules. The downside is that it would
4964   // introduce a dependency between predicates (captures must happen
4965   // before their first use.)
4966   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
4967   unsigned TempOpIdx = 0;
4968   auto InsnMatcherOrError =
4969       createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
4970   if (auto Error = InsnMatcherOrError.takeError())
4971     return std::move(Error);
4972   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4973 
4974   if (Dst->isLeaf()) {
4975     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
4976 
4977     const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4978     if (RCDef) {
4979       // We need to replace the def and all its uses with the specified
4980       // operand. However, we must also insert COPY's wherever needed.
4981       // For now, emit a copy and let the register allocator clean up.
4982       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4983       const auto &DstIOperand = DstI.Operands[0];
4984 
4985       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4986       OM0.setSymbolicName(DstIOperand.Name);
4987       M.defineOperand(OM0.getSymbolicName(), OM0);
4988       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4989 
4990       auto &DstMIBuilder =
4991           M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4992       DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
4993       DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
4994       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4995 
4996       // We're done with this pattern!  It's eligible for GISel emission; return
4997       // it.
4998       ++NumPatternImported;
4999       return std::move(M);
5000     }
5001 
5002     return failedImport("Dst pattern root isn't a known leaf");
5003   }
5004 
5005   // Start with the defined operands (i.e., the results of the root operator).
5006   Record *DstOp = Dst->getOperator();
5007   if (!DstOp->isSubClassOf("Instruction"))
5008     return failedImport("Pattern operator isn't an instruction");
5009 
5010   auto &DstI = Target.getInstruction(DstOp);
5011   StringRef DstIName = DstI.TheDef->getName();
5012 
5013   if (DstI.Operands.NumDefs < Src->getExtTypes().size())
5014     return failedImport("Src pattern result has more defs than dst MI (" +
5015                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
5016                         to_string(DstI.Operands.NumDefs) + " def(s))");
5017 
5018   // The root of the match also has constraints on the register bank so that it
5019   // matches the result instruction.
5020   unsigned OpIdx = 0;
5021   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
5022     (void)VTy;
5023 
5024     const auto &DstIOperand = DstI.Operands[OpIdx];
5025     Record *DstIOpRec = DstIOperand.Rec;
5026     if (DstIName == "COPY_TO_REGCLASS") {
5027       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
5028 
5029       if (DstIOpRec == nullptr)
5030         return failedImport(
5031             "COPY_TO_REGCLASS operand #1 isn't a register class");
5032     } else if (DstIName == "REG_SEQUENCE") {
5033       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
5034       if (DstIOpRec == nullptr)
5035         return failedImport("REG_SEQUENCE operand #0 isn't a register class");
5036     } else if (DstIName == "EXTRACT_SUBREG") {
5037       auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
5038       if (!InferredClass)
5039         return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
5040 
5041       // We can assume that a subregister is in the same bank as it's super
5042       // register.
5043       DstIOpRec = (*InferredClass)->getDef();
5044     } else if (DstIName == "INSERT_SUBREG") {
5045       auto MaybeSuperClass = inferSuperRegisterClassForNode(
5046           VTy, Dst->getChild(0), Dst->getChild(2));
5047       if (!MaybeSuperClass)
5048         return failedImport(
5049             "Cannot infer register class for INSERT_SUBREG operand #0");
5050       // Move to the next pattern here, because the register class we found
5051       // doesn't necessarily have a record associated with it. So, we can't
5052       // set DstIOpRec using this.
5053       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5054       OM.setSymbolicName(DstIOperand.Name);
5055       M.defineOperand(OM.getSymbolicName(), OM);
5056       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
5057       ++OpIdx;
5058       continue;
5059     } else if (DstIName == "SUBREG_TO_REG") {
5060       auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
5061       if (!MaybeRegClass)
5062         return failedImport(
5063             "Cannot infer register class for SUBREG_TO_REG operand #0");
5064       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5065       OM.setSymbolicName(DstIOperand.Name);
5066       M.defineOperand(OM.getSymbolicName(), OM);
5067       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
5068       ++OpIdx;
5069       continue;
5070     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
5071       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
5072     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
5073       return failedImport("Dst MI def isn't a register class" +
5074                           to_string(*Dst));
5075 
5076     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5077     OM.setSymbolicName(DstIOperand.Name);
5078     M.defineOperand(OM.getSymbolicName(), OM);
5079     OM.addPredicate<RegisterBankOperandMatcher>(
5080         Target.getRegisterClass(DstIOpRec));
5081     ++OpIdx;
5082   }
5083 
5084   auto DstMIBuilderOrError =
5085       createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
5086   if (auto Error = DstMIBuilderOrError.takeError())
5087     return std::move(Error);
5088   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
5089 
5090   // Render the implicit defs.
5091   // These are only added to the root of the result.
5092   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
5093     return std::move(Error);
5094 
5095   DstMIBuilder.chooseInsnToMutate(M);
5096 
5097   // Constrain the registers to classes. This is normally derived from the
5098   // emitted instruction but a few instructions require special handling.
5099   if (DstIName == "COPY_TO_REGCLASS") {
5100     // COPY_TO_REGCLASS does not provide operand constraints itself but the
5101     // result is constrained to the class given by the second child.
5102     Record *DstIOpRec =
5103         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
5104 
5105     if (DstIOpRec == nullptr)
5106       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
5107 
5108     M.addAction<ConstrainOperandToRegClassAction>(
5109         0, 0, Target.getRegisterClass(DstIOpRec));
5110 
5111     // We're done with this pattern!  It's eligible for GISel emission; return
5112     // it.
5113     ++NumPatternImported;
5114     return std::move(M);
5115   }
5116 
5117   if (DstIName == "EXTRACT_SUBREG") {
5118     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5119     if (!SuperClass)
5120       return failedImport(
5121         "Cannot infer register class from EXTRACT_SUBREG operand #0");
5122 
5123     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
5124     if (!SubIdx)
5125       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
5126 
5127     // It would be nice to leave this constraint implicit but we're required
5128     // to pick a register class so constrain the result to a register class
5129     // that can hold the correct MVT.
5130     //
5131     // FIXME: This may introduce an extra copy if the chosen class doesn't
5132     //        actually contain the subregisters.
5133     assert(Src->getExtTypes().size() == 1 &&
5134              "Expected Src of EXTRACT_SUBREG to have one result type");
5135 
5136     const auto SrcRCDstRCPair =
5137       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5138     if (!SrcRCDstRCPair) {
5139       return failedImport("subreg index is incompatible "
5140                           "with inferred reg class");
5141     }
5142 
5143     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
5144     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
5145     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
5146 
5147     // We're done with this pattern!  It's eligible for GISel emission; return
5148     // it.
5149     ++NumPatternImported;
5150     return std::move(M);
5151   }
5152 
5153   if (DstIName == "INSERT_SUBREG") {
5154     assert(Src->getExtTypes().size() == 1 &&
5155            "Expected Src of INSERT_SUBREG to have one result type");
5156     // We need to constrain the destination, a super regsister source, and a
5157     // subregister source.
5158     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5159     if (!SubClass)
5160       return failedImport(
5161           "Cannot infer register class from INSERT_SUBREG operand #1");
5162     auto SuperClass = inferSuperRegisterClassForNode(
5163         Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
5164     if (!SuperClass)
5165       return failedImport(
5166           "Cannot infer register class for INSERT_SUBREG operand #0");
5167     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5168     M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
5169     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5170     ++NumPatternImported;
5171     return std::move(M);
5172   }
5173 
5174   if (DstIName == "SUBREG_TO_REG") {
5175     // We need to constrain the destination and subregister source.
5176     assert(Src->getExtTypes().size() == 1 &&
5177            "Expected Src of SUBREG_TO_REG to have one result type");
5178 
5179     // Attempt to infer the subregister source from the first child. If it has
5180     // an explicitly given register class, we'll use that. Otherwise, we will
5181     // fail.
5182     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5183     if (!SubClass)
5184       return failedImport(
5185           "Cannot infer register class from SUBREG_TO_REG child #1");
5186     // We don't have a child to look at that might have a super register node.
5187     auto SuperClass =
5188         inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
5189     if (!SuperClass)
5190       return failedImport(
5191           "Cannot infer register class for SUBREG_TO_REG operand #0");
5192     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5193     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5194     ++NumPatternImported;
5195     return std::move(M);
5196   }
5197 
5198   if (DstIName == "REG_SEQUENCE") {
5199     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5200 
5201     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5202 
5203     unsigned Num = Dst->getNumChildren();
5204     for (unsigned I = 1; I != Num; I += 2) {
5205       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
5206 
5207       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
5208       if (!SubIdx)
5209         return failedImport("REG_SEQUENCE child is not a subreg index");
5210 
5211       const auto SrcRCDstRCPair =
5212         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5213 
5214       M.addAction<ConstrainOperandToRegClassAction>(0, I,
5215                                                     *SrcRCDstRCPair->second);
5216     }
5217 
5218     ++NumPatternImported;
5219     return std::move(M);
5220   }
5221 
5222   M.addAction<ConstrainOperandsToDefinitionAction>(0);
5223 
5224   // We're done with this pattern!  It's eligible for GISel emission; return it.
5225   ++NumPatternImported;
5226   return std::move(M);
5227 }
5228 
5229 // Emit imm predicate table and an enum to reference them with.
5230 // The 'Predicate_' part of the name is redundant but eliminating it is more
5231 // trouble than it's worth.
5232 void GlobalISelEmitter::emitCxxPredicateFns(
5233     raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
5234     StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
5235     std::function<bool(const Record *R)> Filter) {
5236   std::vector<const Record *> MatchedRecords;
5237   const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
5238   std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5239                [&](Record *Record) {
5240                  return !Record->getValueAsString(CodeFieldName).empty() &&
5241                         Filter(Record);
5242                });
5243 
5244   if (!MatchedRecords.empty()) {
5245     OS << "// PatFrag predicates.\n"
5246        << "enum {\n";
5247     std::string EnumeratorSeparator =
5248         (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5249     for (const auto *Record : MatchedRecords) {
5250       OS << "  GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5251          << EnumeratorSeparator;
5252       EnumeratorSeparator = ",\n";
5253     }
5254     OS << "};\n";
5255   }
5256 
5257   OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5258      << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
5259      << ArgName << ") const {\n"
5260      << AdditionalDeclarations;
5261   if (!AdditionalDeclarations.empty())
5262     OS << "\n";
5263   if (!MatchedRecords.empty())
5264     OS << "  switch (PredicateID) {\n";
5265   for (const auto *Record : MatchedRecords) {
5266     OS << "  case GIPFP_" << TypeIdentifier << "_Predicate_"
5267        << Record->getName() << ": {\n"
5268        << "    " << Record->getValueAsString(CodeFieldName) << "\n"
5269        << "    llvm_unreachable(\"" << CodeFieldName
5270        << " should have returned\");\n"
5271        << "    return false;\n"
5272        << "  }\n";
5273   }
5274   if (!MatchedRecords.empty())
5275     OS << "  }\n";
5276   OS << "  llvm_unreachable(\"Unknown predicate\");\n"
5277      << "  return false;\n"
5278      << "}\n";
5279 }
5280 
5281 void GlobalISelEmitter::emitImmPredicateFns(
5282     raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5283     std::function<bool(const Record *R)> Filter) {
5284   return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
5285                              "Imm", "", Filter);
5286 }
5287 
5288 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5289   return emitCxxPredicateFns(
5290       OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
5291       "  const MachineFunction &MF = *MI.getParent()->getParent();\n"
5292       "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5293       "  (void)MRI;",
5294       [](const Record *R) { return true; });
5295 }
5296 
5297 template <class GroupT>
5298 std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
5299     ArrayRef<Matcher *> Rules,
5300     std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5301 
5302   std::vector<Matcher *> OptRules;
5303   std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
5304   assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5305   unsigned NumGroups = 0;
5306 
5307   auto ProcessCurrentGroup = [&]() {
5308     if (CurrentGroup->empty())
5309       // An empty group is good to be reused:
5310       return;
5311 
5312     // If the group isn't large enough to provide any benefit, move all the
5313     // added rules out of it and make sure to re-create the group to properly
5314     // re-initialize it:
5315     if (CurrentGroup->size() < 2)
5316       for (Matcher *M : CurrentGroup->matchers())
5317         OptRules.push_back(M);
5318     else {
5319       CurrentGroup->finalize();
5320       OptRules.push_back(CurrentGroup.get());
5321       MatcherStorage.emplace_back(std::move(CurrentGroup));
5322       ++NumGroups;
5323     }
5324     CurrentGroup = std::make_unique<GroupT>();
5325   };
5326   for (Matcher *Rule : Rules) {
5327     // Greedily add as many matchers as possible to the current group:
5328     if (CurrentGroup->addMatcher(*Rule))
5329       continue;
5330 
5331     ProcessCurrentGroup();
5332     assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5333 
5334     // Try to add the pending matcher to a newly created empty group:
5335     if (!CurrentGroup->addMatcher(*Rule))
5336       // If we couldn't add the matcher to an empty group, that group type
5337       // doesn't support that kind of matchers at all, so just skip it:
5338       OptRules.push_back(Rule);
5339   }
5340   ProcessCurrentGroup();
5341 
5342   LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
5343   assert(CurrentGroup->empty() && "The last group wasn't properly processed");
5344   return OptRules;
5345 }
5346 
5347 MatchTable
5348 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
5349                                    bool Optimize, bool WithCoverage) {
5350   std::vector<Matcher *> InputRules;
5351   for (Matcher &Rule : Rules)
5352     InputRules.push_back(&Rule);
5353 
5354   if (!Optimize)
5355     return MatchTable::buildTable(InputRules, WithCoverage);
5356 
5357   unsigned CurrentOrdering = 0;
5358   StringMap<unsigned> OpcodeOrder;
5359   for (RuleMatcher &Rule : Rules) {
5360     const StringRef Opcode = Rule.getOpcode();
5361     assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5362     if (OpcodeOrder.count(Opcode) == 0)
5363       OpcodeOrder[Opcode] = CurrentOrdering++;
5364   }
5365 
5366   std::stable_sort(InputRules.begin(), InputRules.end(),
5367                    [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5368                      auto *L = static_cast<const RuleMatcher *>(A);
5369                      auto *R = static_cast<const RuleMatcher *>(B);
5370                      return std::make_tuple(OpcodeOrder[L->getOpcode()],
5371                                             L->getNumOperands()) <
5372                             std::make_tuple(OpcodeOrder[R->getOpcode()],
5373                                             R->getNumOperands());
5374                    });
5375 
5376   for (Matcher *Rule : InputRules)
5377     Rule->optimize();
5378 
5379   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
5380   std::vector<Matcher *> OptRules =
5381       optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5382 
5383   for (Matcher *Rule : OptRules)
5384     Rule->optimize();
5385 
5386   OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5387 
5388   return MatchTable::buildTable(OptRules, WithCoverage);
5389 }
5390 
5391 void GroupMatcher::optimize() {
5392   // Make sure we only sort by a specific predicate within a range of rules that
5393   // all have that predicate checked against a specific value (not a wildcard):
5394   auto F = Matchers.begin();
5395   auto T = F;
5396   auto E = Matchers.end();
5397   while (T != E) {
5398     while (T != E) {
5399       auto *R = static_cast<RuleMatcher *>(*T);
5400       if (!R->getFirstConditionAsRootType().get().isValid())
5401         break;
5402       ++T;
5403     }
5404     std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5405       auto *L = static_cast<RuleMatcher *>(A);
5406       auto *R = static_cast<RuleMatcher *>(B);
5407       return L->getFirstConditionAsRootType() <
5408              R->getFirstConditionAsRootType();
5409     });
5410     if (T != E)
5411       F = ++T;
5412   }
5413   GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5414       .swap(Matchers);
5415   GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5416       .swap(Matchers);
5417 }
5418 
5419 void GlobalISelEmitter::run(raw_ostream &OS) {
5420   if (!UseCoverageFile.empty()) {
5421     RuleCoverage = CodeGenCoverage();
5422     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5423     if (!RuleCoverageBufOrErr) {
5424       PrintWarning(SMLoc(), "Missing rule coverage data");
5425       RuleCoverage = None;
5426     } else {
5427       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5428         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5429         RuleCoverage = None;
5430       }
5431     }
5432   }
5433 
5434   // Track the run-time opcode values
5435   gatherOpcodeValues();
5436   // Track the run-time LLT ID values
5437   gatherTypeIDValues();
5438 
5439   // Track the GINodeEquiv definitions.
5440   gatherNodeEquivs();
5441 
5442   emitSourceFileHeader(("Global Instruction Selector for the " +
5443                        Target.getName() + " target").str(), OS);
5444   std::vector<RuleMatcher> Rules;
5445   // Look through the SelectionDAG patterns we found, possibly emitting some.
5446   for (const PatternToMatch &Pat : CGP.ptms()) {
5447     ++NumPatternTotal;
5448 
5449     auto MatcherOrErr = runOnPattern(Pat);
5450 
5451     // The pattern analysis can fail, indicating an unsupported pattern.
5452     // Report that if we've been asked to do so.
5453     if (auto Err = MatcherOrErr.takeError()) {
5454       if (WarnOnSkippedPatterns) {
5455         PrintWarning(Pat.getSrcRecord()->getLoc(),
5456                      "Skipped pattern: " + toString(std::move(Err)));
5457       } else {
5458         consumeError(std::move(Err));
5459       }
5460       ++NumPatternImportsSkipped;
5461       continue;
5462     }
5463 
5464     if (RuleCoverage) {
5465       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5466         ++NumPatternsTested;
5467       else
5468         PrintWarning(Pat.getSrcRecord()->getLoc(),
5469                      "Pattern is not covered by a test");
5470     }
5471     Rules.push_back(std::move(MatcherOrErr.get()));
5472   }
5473 
5474   // Comparison function to order records by name.
5475   auto orderByName = [](const Record *A, const Record *B) {
5476     return A->getName() < B->getName();
5477   };
5478 
5479   std::vector<Record *> ComplexPredicates =
5480       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
5481   llvm::sort(ComplexPredicates, orderByName);
5482 
5483   std::vector<Record *> CustomRendererFns =
5484       RK.getAllDerivedDefinitions("GICustomOperandRenderer");
5485   llvm::sort(CustomRendererFns, orderByName);
5486 
5487   unsigned MaxTemporaries = 0;
5488   for (const auto &Rule : Rules)
5489     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
5490 
5491   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5492      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5493      << ";\n"
5494      << "using PredicateBitset = "
5495         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5496      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5497 
5498   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5499      << "  mutable MatcherState State;\n"
5500      << "  typedef "
5501         "ComplexRendererFns("
5502      << Target.getName()
5503      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
5504 
5505      << "  typedef void(" << Target.getName()
5506      << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5507         "MachineInstr&, int) "
5508         "const;\n"
5509      << "  const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5510         "CustomRendererFn> "
5511         "ISelInfo;\n";
5512   OS << "  static " << Target.getName()
5513      << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
5514      << "  static " << Target.getName()
5515      << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
5516      << "  bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
5517         "override;\n"
5518      << "  bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
5519         "const override;\n"
5520      << "  bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
5521         "&Imm) const override;\n"
5522      << "  const int64_t *getMatchTable() const override;\n"
5523      << "  bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5524         "const override;\n"
5525      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
5526 
5527   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5528      << ", State(" << MaxTemporaries << "),\n"
5529      << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5530      << ", ComplexPredicateFns, CustomRenderers)\n"
5531      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
5532 
5533   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5534   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5535                                                            OS);
5536 
5537   // Separate subtarget features by how often they must be recomputed.
5538   SubtargetFeatureInfoMap ModuleFeatures;
5539   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5540                std::inserter(ModuleFeatures, ModuleFeatures.end()),
5541                [](const SubtargetFeatureInfoMap::value_type &X) {
5542                  return !X.second.mustRecomputePerFunction();
5543                });
5544   SubtargetFeatureInfoMap FunctionFeatures;
5545   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5546                std::inserter(FunctionFeatures, FunctionFeatures.end()),
5547                [](const SubtargetFeatureInfoMap::value_type &X) {
5548                  return X.second.mustRecomputePerFunction();
5549                });
5550 
5551   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5552     Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5553       ModuleFeatures, OS);
5554 
5555 
5556   OS << "void " << Target.getName() << "InstructionSelector"
5557     "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5558     "  AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5559     "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5560     "}\n";
5561 
5562   if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5563     // TODO: Implement PGSO.
5564     OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5565     OS << "    return MF->getFunction().hasOptSize();\n";
5566     OS << "}\n\n";
5567   }
5568 
5569   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5570       Target.getName(), "InstructionSelector",
5571       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5572       "const MachineFunction *MF");
5573 
5574   // Emit a table containing the LLT objects needed by the matcher and an enum
5575   // for the matcher to reference them with.
5576   std::vector<LLTCodeGen> TypeObjects;
5577   for (const auto &Ty : KnownTypes)
5578     TypeObjects.push_back(Ty);
5579   llvm::sort(TypeObjects);
5580   OS << "// LLT Objects.\n"
5581      << "enum {\n";
5582   for (const auto &TypeObject : TypeObjects) {
5583     OS << "  ";
5584     TypeObject.emitCxxEnumValue(OS);
5585     OS << ",\n";
5586   }
5587   OS << "};\n";
5588   OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
5589      << "const static LLT TypeObjects[] = {\n";
5590   for (const auto &TypeObject : TypeObjects) {
5591     OS << "  ";
5592     TypeObject.emitCxxConstructorCall(OS);
5593     OS << ",\n";
5594   }
5595   OS << "};\n\n";
5596 
5597   // Emit a table containing the PredicateBitsets objects needed by the matcher
5598   // and an enum for the matcher to reference them with.
5599   std::vector<std::vector<Record *>> FeatureBitsets;
5600   for (auto &Rule : Rules)
5601     FeatureBitsets.push_back(Rule.getRequiredFeatures());
5602   llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5603                                  const std::vector<Record *> &B) {
5604     if (A.size() < B.size())
5605       return true;
5606     if (A.size() > B.size())
5607       return false;
5608     for (auto Pair : zip(A, B)) {
5609       if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5610         return true;
5611       if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
5612         return false;
5613     }
5614     return false;
5615   });
5616   FeatureBitsets.erase(
5617       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5618       FeatureBitsets.end());
5619   OS << "// Feature bitsets.\n"
5620      << "enum {\n"
5621      << "  GIFBS_Invalid,\n";
5622   for (const auto &FeatureBitset : FeatureBitsets) {
5623     if (FeatureBitset.empty())
5624       continue;
5625     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5626   }
5627   OS << "};\n"
5628      << "const static PredicateBitset FeatureBitsets[] {\n"
5629      << "  {}, // GIFBS_Invalid\n";
5630   for (const auto &FeatureBitset : FeatureBitsets) {
5631     if (FeatureBitset.empty())
5632       continue;
5633     OS << "  {";
5634     for (const auto &Feature : FeatureBitset) {
5635       const auto &I = SubtargetFeatures.find(Feature);
5636       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5637       OS << I->second.getEnumBitName() << ", ";
5638     }
5639     OS << "},\n";
5640   }
5641   OS << "};\n\n";
5642 
5643   // Emit complex predicate table and an enum to reference them with.
5644   OS << "// ComplexPattern predicates.\n"
5645      << "enum {\n"
5646      << "  GICP_Invalid,\n";
5647   for (const auto &Record : ComplexPredicates)
5648     OS << "  GICP_" << Record->getName() << ",\n";
5649   OS << "};\n"
5650      << "// See constructor for table contents\n\n";
5651 
5652   emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
5653     bool Unset;
5654     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5655            !R->getValueAsBit("IsAPInt");
5656   });
5657   emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
5658     bool Unset;
5659     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5660   });
5661   emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
5662     return R->getValueAsBit("IsAPInt");
5663   });
5664   emitMIPredicateFns(OS);
5665   OS << "\n";
5666 
5667   OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5668      << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5669      << "  nullptr, // GICP_Invalid\n";
5670   for (const auto &Record : ComplexPredicates)
5671     OS << "  &" << Target.getName()
5672        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5673        << ", // " << Record->getName() << "\n";
5674   OS << "};\n\n";
5675 
5676   OS << "// Custom renderers.\n"
5677      << "enum {\n"
5678      << "  GICR_Invalid,\n";
5679   for (const auto &Record : CustomRendererFns)
5680     OS << "  GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5681   OS << "};\n";
5682 
5683   OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5684      << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5685      << "  nullptr, // GICR_Invalid\n";
5686   for (const auto &Record : CustomRendererFns)
5687     OS << "  &" << Target.getName()
5688        << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5689        << ", // " << Record->getName() << "\n";
5690   OS << "};\n\n";
5691 
5692   llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
5693     int ScoreA = RuleMatcherScores[A.getRuleID()];
5694     int ScoreB = RuleMatcherScores[B.getRuleID()];
5695     if (ScoreA > ScoreB)
5696       return true;
5697     if (ScoreB > ScoreA)
5698       return false;
5699     if (A.isHigherPriorityThan(B)) {
5700       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5701                                            "and less important at "
5702                                            "the same time");
5703       return true;
5704     }
5705     return false;
5706   });
5707 
5708   OS << "bool " << Target.getName()
5709      << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5710         "&CoverageInfo) const {\n"
5711      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
5712      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5713      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5714      << "  NewMIVector OutMIs;\n"
5715      << "  State.MIs.clear();\n"
5716      << "  State.MIs.push_back(&I);\n\n"
5717      << "  if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5718      << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5719      << ", CoverageInfo)) {\n"
5720      << "    return true;\n"
5721      << "  }\n\n"
5722      << "  return false;\n"
5723      << "}\n\n";
5724 
5725   const MatchTable Table =
5726       buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
5727   OS << "const int64_t *" << Target.getName()
5728      << "InstructionSelector::getMatchTable() const {\n";
5729   Table.emitDeclaration(OS);
5730   OS << "  return ";
5731   Table.emitUse(OS);
5732   OS << ";\n}\n";
5733   OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
5734 
5735   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5736      << "PredicateBitset AvailableModuleFeatures;\n"
5737      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5738      << "PredicateBitset getAvailableFeatures() const {\n"
5739      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5740      << "}\n"
5741      << "PredicateBitset\n"
5742      << "computeAvailableModuleFeatures(const " << Target.getName()
5743      << "Subtarget *Subtarget) const;\n"
5744      << "PredicateBitset\n"
5745      << "computeAvailableFunctionFeatures(const " << Target.getName()
5746      << "Subtarget *Subtarget,\n"
5747      << "                                 const MachineFunction *MF) const;\n"
5748      << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
5749      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5750 
5751   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5752      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5753      << "AvailableFunctionFeatures()\n"
5754      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
5755 }
5756 
5757 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5758   if (SubtargetFeatures.count(Predicate) == 0)
5759     SubtargetFeatures.emplace(
5760         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5761 }
5762 
5763 void RuleMatcher::optimize() {
5764   for (auto &Item : InsnVariableIDs) {
5765     InstructionMatcher &InsnMatcher = *Item.first;
5766     for (auto &OM : InsnMatcher.operands()) {
5767       // Complex Patterns are usually expensive and they relatively rarely fail
5768       // on their own: more often we end up throwing away all the work done by a
5769       // matching part of a complex pattern because some other part of the
5770       // enclosing pattern didn't match. All of this makes it beneficial to
5771       // delay complex patterns until the very end of the rule matching,
5772       // especially for targets having lots of complex patterns.
5773       for (auto &OP : OM->predicates())
5774         if (isa<ComplexPatternOperandMatcher>(OP))
5775           EpilogueMatchers.emplace_back(std::move(OP));
5776       OM->eraseNullPredicates();
5777     }
5778     InsnMatcher.optimize();
5779   }
5780   llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5781                                   const std::unique_ptr<PredicateMatcher> &R) {
5782     return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5783            std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5784   });
5785 }
5786 
5787 bool RuleMatcher::hasFirstCondition() const {
5788   if (insnmatchers_empty())
5789     return false;
5790   InstructionMatcher &Matcher = insnmatchers_front();
5791   if (!Matcher.predicates_empty())
5792     return true;
5793   for (auto &OM : Matcher.operands())
5794     for (auto &OP : OM->predicates())
5795       if (!isa<InstructionOperandMatcher>(OP))
5796         return true;
5797   return false;
5798 }
5799 
5800 const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5801   assert(!insnmatchers_empty() &&
5802          "Trying to get a condition from an empty RuleMatcher");
5803 
5804   InstructionMatcher &Matcher = insnmatchers_front();
5805   if (!Matcher.predicates_empty())
5806     return **Matcher.predicates_begin();
5807   // If there is no more predicate on the instruction itself, look at its
5808   // operands.
5809   for (auto &OM : Matcher.operands())
5810     for (auto &OP : OM->predicates())
5811       if (!isa<InstructionOperandMatcher>(OP))
5812         return *OP;
5813 
5814   llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5815                    "no conditions");
5816 }
5817 
5818 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5819   assert(!insnmatchers_empty() &&
5820          "Trying to pop a condition from an empty RuleMatcher");
5821 
5822   InstructionMatcher &Matcher = insnmatchers_front();
5823   if (!Matcher.predicates_empty())
5824     return Matcher.predicates_pop_front();
5825   // If there is no more predicate on the instruction itself, look at its
5826   // operands.
5827   for (auto &OM : Matcher.operands())
5828     for (auto &OP : OM->predicates())
5829       if (!isa<InstructionOperandMatcher>(OP)) {
5830         std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5831         OM->eraseNullPredicates();
5832         return Result;
5833       }
5834 
5835   llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5836                    "no conditions");
5837 }
5838 
5839 bool GroupMatcher::candidateConditionMatches(
5840     const PredicateMatcher &Predicate) const {
5841 
5842   if (empty()) {
5843     // Sharing predicates for nested instructions is not supported yet as we
5844     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5845     // only work on the original root instruction (InsnVarID == 0):
5846     if (Predicate.getInsnVarID() != 0)
5847       return false;
5848     // ... otherwise an empty group can handle any predicate with no specific
5849     // requirements:
5850     return true;
5851   }
5852 
5853   const Matcher &Representative = **Matchers.begin();
5854   const auto &RepresentativeCondition = Representative.getFirstCondition();
5855   // ... if not empty, the group can only accomodate matchers with the exact
5856   // same first condition:
5857   return Predicate.isIdentical(RepresentativeCondition);
5858 }
5859 
5860 bool GroupMatcher::addMatcher(Matcher &Candidate) {
5861   if (!Candidate.hasFirstCondition())
5862     return false;
5863 
5864   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5865   if (!candidateConditionMatches(Predicate))
5866     return false;
5867 
5868   Matchers.push_back(&Candidate);
5869   return true;
5870 }
5871 
5872 void GroupMatcher::finalize() {
5873   assert(Conditions.empty() && "Already finalized?");
5874   if (empty())
5875     return;
5876 
5877   Matcher &FirstRule = **Matchers.begin();
5878   for (;;) {
5879     // All the checks are expected to succeed during the first iteration:
5880     for (const auto &Rule : Matchers)
5881       if (!Rule->hasFirstCondition())
5882         return;
5883     const auto &FirstCondition = FirstRule.getFirstCondition();
5884     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5885       if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5886         return;
5887 
5888     Conditions.push_back(FirstRule.popFirstCondition());
5889     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5890       Matchers[I]->popFirstCondition();
5891   }
5892 }
5893 
5894 void GroupMatcher::emit(MatchTable &Table) {
5895   unsigned LabelID = ~0U;
5896   if (!Conditions.empty()) {
5897     LabelID = Table.allocateLabelID();
5898     Table << MatchTable::Opcode("GIM_Try", +1)
5899           << MatchTable::Comment("On fail goto")
5900           << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
5901   }
5902   for (auto &Condition : Conditions)
5903     Condition->emitPredicateOpcodes(
5904         Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5905 
5906   for (const auto &M : Matchers)
5907     M->emit(Table);
5908 
5909   // Exit the group
5910   if (!Conditions.empty())
5911     Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
5912           << MatchTable::Label(LabelID);
5913 }
5914 
5915 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
5916   return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
5917 }
5918 
5919 bool SwitchMatcher::candidateConditionMatches(
5920     const PredicateMatcher &Predicate) const {
5921 
5922   if (empty()) {
5923     // Sharing predicates for nested instructions is not supported yet as we
5924     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5925     // only work on the original root instruction (InsnVarID == 0):
5926     if (Predicate.getInsnVarID() != 0)
5927       return false;
5928     // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5929     // could fail as not all the types of conditions are supported:
5930     if (!isSupportedPredicateType(Predicate))
5931       return false;
5932     // ... or the condition might not have a proper implementation of
5933     // getValue() / isIdenticalDownToValue() yet:
5934     if (!Predicate.hasValue())
5935       return false;
5936     // ... otherwise an empty Switch can accomodate the condition with no
5937     // further requirements:
5938     return true;
5939   }
5940 
5941   const Matcher &CaseRepresentative = **Matchers.begin();
5942   const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5943   // Switch-cases must share the same kind of condition and path to the value it
5944   // checks:
5945   if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5946     return false;
5947 
5948   const auto Value = Predicate.getValue();
5949   // ... but be unique with respect to the actual value they check:
5950   return Values.count(Value) == 0;
5951 }
5952 
5953 bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5954   if (!Candidate.hasFirstCondition())
5955     return false;
5956 
5957   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5958   if (!candidateConditionMatches(Predicate))
5959     return false;
5960   const auto Value = Predicate.getValue();
5961   Values.insert(Value);
5962 
5963   Matchers.push_back(&Candidate);
5964   return true;
5965 }
5966 
5967 void SwitchMatcher::finalize() {
5968   assert(Condition == nullptr && "Already finalized");
5969   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5970   if (empty())
5971     return;
5972 
5973   std::stable_sort(Matchers.begin(), Matchers.end(),
5974                    [](const Matcher *L, const Matcher *R) {
5975                      return L->getFirstCondition().getValue() <
5976                             R->getFirstCondition().getValue();
5977                    });
5978   Condition = Matchers[0]->popFirstCondition();
5979   for (unsigned I = 1, E = Values.size(); I < E; ++I)
5980     Matchers[I]->popFirstCondition();
5981 }
5982 
5983 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5984                                                  MatchTable &Table) {
5985   assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5986 
5987   if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5988     Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5989           << MatchTable::IntValue(Condition->getInsnVarID());
5990     return;
5991   }
5992   if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5993     Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5994           << MatchTable::IntValue(Condition->getInsnVarID())
5995           << MatchTable::Comment("Op")
5996           << MatchTable::IntValue(Condition->getOpIdx());
5997     return;
5998   }
5999 
6000   llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
6001                    "predicate type that is claimed to be supported");
6002 }
6003 
6004 void SwitchMatcher::emit(MatchTable &Table) {
6005   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6006   if (empty())
6007     return;
6008   assert(Condition != nullptr &&
6009          "Broken SwitchMatcher, hasn't been finalized?");
6010 
6011   std::vector<unsigned> LabelIDs(Values.size());
6012   std::generate(LabelIDs.begin(), LabelIDs.end(),
6013                 [&Table]() { return Table.allocateLabelID(); });
6014   const unsigned Default = Table.allocateLabelID();
6015 
6016   const int64_t LowerBound = Values.begin()->getRawValue();
6017   const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
6018 
6019   emitPredicateSpecificOpcodes(*Condition, Table);
6020 
6021   Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
6022         << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
6023         << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
6024 
6025   int64_t J = LowerBound;
6026   auto VI = Values.begin();
6027   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6028     auto V = *VI++;
6029     while (J++ < V.getRawValue())
6030       Table << MatchTable::IntValue(0);
6031     V.turnIntoComment();
6032     Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
6033   }
6034   Table << MatchTable::LineBreak;
6035 
6036   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6037     Table << MatchTable::Label(LabelIDs[I]);
6038     Matchers[I]->emit(Table);
6039     Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
6040   }
6041   Table << MatchTable::Label(Default);
6042 }
6043 
6044 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
6045 
6046 } // end anonymous namespace
6047 
6048 //===----------------------------------------------------------------------===//
6049 
6050 namespace llvm {
6051 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
6052   GlobalISelEmitter(RK).run(OS);
6053 }
6054 } // End llvm namespace
6055