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   const CodeGenInstruction *I;
1675 
1676   static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1677 
1678 public:
1679   static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1680     OpcodeValues.clear();
1681 
1682     unsigned OpcodeValue = 0;
1683     for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1684       OpcodeValues[I] = OpcodeValue++;
1685   }
1686 
1687   InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1688       : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
1689 
1690   static bool classof(const PredicateMatcher *P) {
1691     return P->getKind() == IPM_Opcode;
1692   }
1693 
1694   bool isIdentical(const PredicateMatcher &B) const override {
1695     return InstructionPredicateMatcher::isIdentical(B) &&
1696            I == cast<InstructionOpcodeMatcher>(&B)->I;
1697   }
1698   MatchTableRecord getValue() const override {
1699     const auto VI = OpcodeValues.find(I);
1700     if (VI != OpcodeValues.end())
1701       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1702                                     VI->second);
1703     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1704   }
1705   bool hasValue() const override { return OpcodeValues.count(I); }
1706 
1707   void emitPredicateOpcodes(MatchTable &Table,
1708                             RuleMatcher &Rule) const override {
1709     Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1710           << MatchTable::IntValue(InsnVarID) << getValue()
1711           << MatchTable::LineBreak;
1712   }
1713 
1714   /// Compare the priority of this object and B.
1715   ///
1716   /// Returns true if this object is more important than B.
1717   bool
1718   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1719     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1720       return true;
1721     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1722       return false;
1723 
1724     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1725     // this is cosmetic at the moment, we may want to drive a similar ordering
1726     // using instruction frequency information to improve compile time.
1727     if (const InstructionOpcodeMatcher *BO =
1728             dyn_cast<InstructionOpcodeMatcher>(&B))
1729       return I->TheDef->getName() < BO->I->TheDef->getName();
1730 
1731     return false;
1732   };
1733 
1734   bool isConstantInstruction() const {
1735     return I->TheDef->getName() == "G_CONSTANT";
1736   }
1737 
1738   StringRef getOpcode() const { return I->TheDef->getName(); }
1739   bool isVariadicNumOperands() const { return I->Operands.isVariadic; }
1740 
1741   StringRef getOperandType(unsigned OpIdx) const {
1742     return I->Operands[OpIdx].OperandType;
1743   }
1744 };
1745 
1746 DenseMap<const CodeGenInstruction *, unsigned>
1747     InstructionOpcodeMatcher::OpcodeValues;
1748 
1749 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1750   unsigned NumOperands = 0;
1751 
1752 public:
1753   InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1754       : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1755         NumOperands(NumOperands) {}
1756 
1757   static bool classof(const PredicateMatcher *P) {
1758     return P->getKind() == IPM_NumOperands;
1759   }
1760 
1761   bool isIdentical(const PredicateMatcher &B) const override {
1762     return InstructionPredicateMatcher::isIdentical(B) &&
1763            NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1764   }
1765 
1766   void emitPredicateOpcodes(MatchTable &Table,
1767                             RuleMatcher &Rule) const override {
1768     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1769           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1770           << MatchTable::Comment("Expected")
1771           << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1772   }
1773 };
1774 
1775 /// Generates code to check that this instruction is a constant whose value
1776 /// meets an immediate predicate.
1777 ///
1778 /// Immediates are slightly odd since they are typically used like an operand
1779 /// but are represented as an operator internally. We typically write simm8:$src
1780 /// in a tablegen pattern, but this is just syntactic sugar for
1781 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1782 /// that will be matched and the predicate (which is attached to the imm
1783 /// operator) that will be tested. In SelectionDAG this describes a
1784 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1785 ///
1786 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1787 /// this representation, the immediate could be tested with an
1788 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1789 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1790 /// there are two implementation issues with producing that matcher
1791 /// configuration from the SelectionDAG pattern:
1792 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1793 ///   were we to sink the immediate predicate to the operand we would have to
1794 ///   have two partial implementations of PatFrag support, one for immediates
1795 ///   and one for non-immediates.
1796 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1797 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1798 ///   would also have to complicate (or duplicate) the code that descends and
1799 ///   creates matchers for the subtree.
1800 /// Overall, it's simpler to handle it in the place it was found.
1801 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1802 protected:
1803   TreePredicateFn Predicate;
1804 
1805 public:
1806   InstructionImmPredicateMatcher(unsigned InsnVarID,
1807                                  const TreePredicateFn &Predicate)
1808       : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1809         Predicate(Predicate) {}
1810 
1811   bool isIdentical(const PredicateMatcher &B) const override {
1812     return InstructionPredicateMatcher::isIdentical(B) &&
1813            Predicate.getOrigPatFragRecord() ==
1814                cast<InstructionImmPredicateMatcher>(&B)
1815                    ->Predicate.getOrigPatFragRecord();
1816   }
1817 
1818   static bool classof(const PredicateMatcher *P) {
1819     return P->getKind() == IPM_ImmPredicate;
1820   }
1821 
1822   void emitPredicateOpcodes(MatchTable &Table,
1823                             RuleMatcher &Rule) const override {
1824     Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
1825           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1826           << MatchTable::Comment("Predicate")
1827           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1828           << MatchTable::LineBreak;
1829   }
1830 };
1831 
1832 /// Generates code to check that a memory instruction has a atomic ordering
1833 /// MachineMemoryOperand.
1834 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1835 public:
1836   enum AOComparator {
1837     AO_Exactly,
1838     AO_OrStronger,
1839     AO_WeakerThan,
1840   };
1841 
1842 protected:
1843   StringRef Order;
1844   AOComparator Comparator;
1845 
1846 public:
1847   AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
1848                                     AOComparator Comparator = AO_Exactly)
1849       : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1850         Order(Order), Comparator(Comparator) {}
1851 
1852   static bool classof(const PredicateMatcher *P) {
1853     return P->getKind() == IPM_AtomicOrderingMMO;
1854   }
1855 
1856   bool isIdentical(const PredicateMatcher &B) const override {
1857     if (!InstructionPredicateMatcher::isIdentical(B))
1858       return false;
1859     const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1860     return Order == R.Order && Comparator == R.Comparator;
1861   }
1862 
1863   void emitPredicateOpcodes(MatchTable &Table,
1864                             RuleMatcher &Rule) const override {
1865     StringRef Opcode = "GIM_CheckAtomicOrdering";
1866 
1867     if (Comparator == AO_OrStronger)
1868       Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1869     if (Comparator == AO_WeakerThan)
1870       Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1871 
1872     Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1873           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
1874           << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
1875           << MatchTable::LineBreak;
1876   }
1877 };
1878 
1879 /// Generates code to check that the size of an MMO is exactly N bytes.
1880 class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1881 protected:
1882   unsigned MMOIdx;
1883   uint64_t Size;
1884 
1885 public:
1886   MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1887       : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1888         MMOIdx(MMOIdx), Size(Size) {}
1889 
1890   static bool classof(const PredicateMatcher *P) {
1891     return P->getKind() == IPM_MemoryLLTSize;
1892   }
1893   bool isIdentical(const PredicateMatcher &B) const override {
1894     return InstructionPredicateMatcher::isIdentical(B) &&
1895            MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1896            Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1897   }
1898 
1899   void emitPredicateOpcodes(MatchTable &Table,
1900                             RuleMatcher &Rule) const override {
1901     Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1902           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1903           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1904           << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1905           << MatchTable::LineBreak;
1906   }
1907 };
1908 
1909 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1910 protected:
1911   unsigned MMOIdx;
1912   SmallVector<unsigned, 4> AddrSpaces;
1913 
1914 public:
1915   MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1916                                      ArrayRef<unsigned> AddrSpaces)
1917       : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1918         MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1919 
1920   static bool classof(const PredicateMatcher *P) {
1921     return P->getKind() == IPM_MemoryAddressSpace;
1922   }
1923   bool isIdentical(const PredicateMatcher &B) const override {
1924     if (!InstructionPredicateMatcher::isIdentical(B))
1925       return false;
1926     auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1927     return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1928   }
1929 
1930   void emitPredicateOpcodes(MatchTable &Table,
1931                             RuleMatcher &Rule) const override {
1932     Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1933           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1934           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1935         // Encode number of address spaces to expect.
1936           << MatchTable::Comment("NumAddrSpace")
1937           << MatchTable::IntValue(AddrSpaces.size());
1938     for (unsigned AS : AddrSpaces)
1939       Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1940 
1941     Table << MatchTable::LineBreak;
1942   }
1943 };
1944 
1945 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1946 protected:
1947   unsigned MMOIdx;
1948   int MinAlign;
1949 
1950 public:
1951   MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1952                                   int MinAlign)
1953       : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1954         MMOIdx(MMOIdx), MinAlign(MinAlign) {
1955     assert(MinAlign > 0);
1956   }
1957 
1958   static bool classof(const PredicateMatcher *P) {
1959     return P->getKind() == IPM_MemoryAlignment;
1960   }
1961 
1962   bool isIdentical(const PredicateMatcher &B) const override {
1963     if (!InstructionPredicateMatcher::isIdentical(B))
1964       return false;
1965     auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1966     return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1967   }
1968 
1969   void emitPredicateOpcodes(MatchTable &Table,
1970                             RuleMatcher &Rule) const override {
1971     Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1972           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1973           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1974           << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1975           << MatchTable::LineBreak;
1976   }
1977 };
1978 
1979 /// Generates code to check that the size of an MMO is less-than, equal-to, or
1980 /// greater than a given LLT.
1981 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1982 public:
1983   enum RelationKind {
1984     GreaterThan,
1985     EqualTo,
1986     LessThan,
1987   };
1988 
1989 protected:
1990   unsigned MMOIdx;
1991   RelationKind Relation;
1992   unsigned OpIdx;
1993 
1994 public:
1995   MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1996                                   enum RelationKind Relation,
1997                                   unsigned OpIdx)
1998       : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1999         MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
2000 
2001   static bool classof(const PredicateMatcher *P) {
2002     return P->getKind() == IPM_MemoryVsLLTSize;
2003   }
2004   bool isIdentical(const PredicateMatcher &B) const override {
2005     return InstructionPredicateMatcher::isIdentical(B) &&
2006            MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2007            Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2008            OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2009   }
2010 
2011   void emitPredicateOpcodes(MatchTable &Table,
2012                             RuleMatcher &Rule) const override {
2013     Table << MatchTable::Opcode(Relation == EqualTo
2014                                     ? "GIM_CheckMemorySizeEqualToLLT"
2015                                     : Relation == GreaterThan
2016                                           ? "GIM_CheckMemorySizeGreaterThanLLT"
2017                                           : "GIM_CheckMemorySizeLessThanLLT")
2018           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2019           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2020           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2021           << MatchTable::LineBreak;
2022   }
2023 };
2024 
2025 // Matcher for immAllOnesV/immAllZerosV
2026 class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
2027 public:
2028   enum SplatKind {
2029     AllZeros,
2030     AllOnes
2031   };
2032 
2033 private:
2034   SplatKind Kind;
2035 
2036 public:
2037   VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
2038       : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
2039 
2040   static bool classof(const PredicateMatcher *P) {
2041     return P->getKind() == IPM_VectorSplatImm;
2042   }
2043 
2044   bool isIdentical(const PredicateMatcher &B) const override {
2045     return InstructionPredicateMatcher::isIdentical(B) &&
2046            Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
2047   }
2048 
2049   void emitPredicateOpcodes(MatchTable &Table,
2050                             RuleMatcher &Rule) const override {
2051     if (Kind == AllOnes)
2052       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
2053     else
2054       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
2055 
2056     Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
2057     Table << MatchTable::LineBreak;
2058   }
2059 };
2060 
2061 /// Generates code to check an arbitrary C++ instruction predicate.
2062 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2063 protected:
2064   TreePredicateFn Predicate;
2065 
2066 public:
2067   GenericInstructionPredicateMatcher(unsigned InsnVarID,
2068                                      TreePredicateFn Predicate)
2069       : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2070         Predicate(Predicate) {}
2071 
2072   static bool classof(const InstructionPredicateMatcher *P) {
2073     return P->getKind() == IPM_GenericPredicate;
2074   }
2075   bool isIdentical(const PredicateMatcher &B) const override {
2076     return InstructionPredicateMatcher::isIdentical(B) &&
2077            Predicate ==
2078                static_cast<const GenericInstructionPredicateMatcher &>(B)
2079                    .Predicate;
2080   }
2081   void emitPredicateOpcodes(MatchTable &Table,
2082                             RuleMatcher &Rule) const override {
2083     Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2084           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2085           << MatchTable::Comment("FnId")
2086           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2087           << MatchTable::LineBreak;
2088   }
2089 };
2090 
2091 /// Generates code to check that a set of predicates and operands match for a
2092 /// particular instruction.
2093 ///
2094 /// Typical predicates include:
2095 /// * Has a specific opcode.
2096 /// * Has an nsw/nuw flag or doesn't.
2097 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
2098 protected:
2099   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
2100 
2101   RuleMatcher &Rule;
2102 
2103   /// The operands to match. All rendered operands must be present even if the
2104   /// condition is always true.
2105   OperandVec Operands;
2106   bool NumOperandsCheck = true;
2107 
2108   std::string SymbolicName;
2109   unsigned InsnVarID;
2110 
2111   /// PhysRegInputs - List list has an entry for each explicitly specified
2112   /// physreg input to the pattern.  The first elt is the Register node, the
2113   /// second is the recorded slot number the input pattern match saved it in.
2114   SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2115 
2116 public:
2117   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
2118                      bool NumOpsCheck = true)
2119       : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
2120     // We create a new instruction matcher.
2121     // Get a new ID for that instruction.
2122     InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2123   }
2124 
2125   /// Construct a new instruction predicate and add it to the matcher.
2126   template <class Kind, class... Args>
2127   Optional<Kind *> addPredicate(Args &&... args) {
2128     Predicates.emplace_back(
2129         std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
2130     return static_cast<Kind *>(Predicates.back().get());
2131   }
2132 
2133   RuleMatcher &getRuleMatcher() const { return Rule; }
2134 
2135   unsigned getInsnVarID() const { return InsnVarID; }
2136 
2137   /// Add an operand to the matcher.
2138   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2139                              unsigned AllocatedTemporariesBaseID) {
2140     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2141                                              AllocatedTemporariesBaseID));
2142     if (!SymbolicName.empty())
2143       Rule.defineOperand(SymbolicName, *Operands.back());
2144 
2145     return *Operands.back();
2146   }
2147 
2148   OperandMatcher &getOperand(unsigned OpIdx) {
2149     auto I = std::find_if(Operands.begin(), Operands.end(),
2150                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
2151                             return X->getOpIdx() == OpIdx;
2152                           });
2153     if (I != Operands.end())
2154       return **I;
2155     llvm_unreachable("Failed to lookup operand");
2156   }
2157 
2158   OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2159                                   unsigned TempOpIdx) {
2160     assert(SymbolicName.empty());
2161     OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2162     Operands.emplace_back(OM);
2163     Rule.definePhysRegOperand(Reg, *OM);
2164     PhysRegInputs.emplace_back(Reg, OpIdx);
2165     return *OM;
2166   }
2167 
2168   ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2169     return PhysRegInputs;
2170   }
2171 
2172   StringRef getSymbolicName() const { return SymbolicName; }
2173   unsigned getNumOperands() const { return Operands.size(); }
2174   OperandVec::iterator operands_begin() { return Operands.begin(); }
2175   OperandVec::iterator operands_end() { return Operands.end(); }
2176   iterator_range<OperandVec::iterator> operands() {
2177     return make_range(operands_begin(), operands_end());
2178   }
2179   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2180   OperandVec::const_iterator operands_end() const { return Operands.end(); }
2181   iterator_range<OperandVec::const_iterator> operands() const {
2182     return make_range(operands_begin(), operands_end());
2183   }
2184   bool operands_empty() const { return Operands.empty(); }
2185 
2186   void pop_front() { Operands.erase(Operands.begin()); }
2187 
2188   void optimize();
2189 
2190   /// Emit MatchTable opcodes that test whether the instruction named in
2191   /// InsnVarName matches all the predicates and all the operands.
2192   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
2193     if (NumOperandsCheck)
2194       InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2195           .emitPredicateOpcodes(Table, Rule);
2196 
2197     // First emit all instruction level predicates need to be verified before we
2198     // can verify operands.
2199     emitFilteredPredicateListOpcodes(
2200       [](const PredicateMatcher &P) {
2201         return !P.dependsOnOperands();
2202       }, Table, Rule);
2203 
2204     // Emit all operand constraints.
2205     for (const auto &Operand : Operands)
2206       Operand->emitPredicateOpcodes(Table, Rule);
2207 
2208     // All of the tablegen defined predicates should now be matched. Now emit
2209     // any custom predicates that rely on all generated checks.
2210     emitFilteredPredicateListOpcodes(
2211       [](const PredicateMatcher &P) {
2212         return P.dependsOnOperands();
2213       }, Table, Rule);
2214   }
2215 
2216   /// Compare the priority of this object and B.
2217   ///
2218   /// Returns true if this object is more important than B.
2219   bool isHigherPriorityThan(InstructionMatcher &B) {
2220     // Instruction matchers involving more operands have higher priority.
2221     if (Operands.size() > B.Operands.size())
2222       return true;
2223     if (Operands.size() < B.Operands.size())
2224       return false;
2225 
2226     for (auto &&P : zip(predicates(), B.predicates())) {
2227       auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2228       auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2229       if (L->isHigherPriorityThan(*R))
2230         return true;
2231       if (R->isHigherPriorityThan(*L))
2232         return false;
2233     }
2234 
2235     for (auto Operand : zip(Operands, B.Operands)) {
2236       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
2237         return true;
2238       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
2239         return false;
2240     }
2241 
2242     return false;
2243   };
2244 
2245   /// Report the maximum number of temporary operands needed by the instruction
2246   /// matcher.
2247   unsigned countRendererFns() {
2248     return std::accumulate(
2249                predicates().begin(), predicates().end(), 0,
2250                [](unsigned A,
2251                   const std::unique_ptr<PredicateMatcher> &Predicate) {
2252                  return A + Predicate->countRendererFns();
2253                }) +
2254            std::accumulate(
2255                Operands.begin(), Operands.end(), 0,
2256                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
2257                  return A + Operand->countRendererFns();
2258                });
2259   }
2260 
2261   InstructionOpcodeMatcher &getOpcodeMatcher() {
2262     for (auto &P : predicates())
2263       if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2264         return *OpMatcher;
2265     llvm_unreachable("Didn't find an opcode matcher");
2266   }
2267 
2268   bool isConstantInstruction() {
2269     return getOpcodeMatcher().isConstantInstruction();
2270   }
2271 
2272   StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
2273 };
2274 
2275 StringRef RuleMatcher::getOpcode() const {
2276   return Matchers.front()->getOpcode();
2277 }
2278 
2279 unsigned RuleMatcher::getNumOperands() const {
2280   return Matchers.front()->getNumOperands();
2281 }
2282 
2283 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2284   InstructionMatcher &InsnMatcher = *Matchers.front();
2285   if (!InsnMatcher.predicates_empty())
2286     if (const auto *TM =
2287             dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2288       if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2289         return TM->getTy();
2290   return {};
2291 }
2292 
2293 /// Generates code to check that the operand is a register defined by an
2294 /// instruction that matches the given instruction matcher.
2295 ///
2296 /// For example, the pattern:
2297 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2298 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2299 /// the:
2300 ///   (G_ADD $src1, $src2)
2301 /// subpattern.
2302 class InstructionOperandMatcher : public OperandPredicateMatcher {
2303 protected:
2304   std::unique_ptr<InstructionMatcher> InsnMatcher;
2305 
2306 public:
2307   InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2308                             RuleMatcher &Rule, StringRef SymbolicName,
2309                             bool NumOpsCheck = true)
2310       : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
2311         InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
2312 
2313   static bool classof(const PredicateMatcher *P) {
2314     return P->getKind() == OPM_Instruction;
2315   }
2316 
2317   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2318 
2319   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2320     const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2321     Table << MatchTable::Opcode("GIM_RecordInsn")
2322           << MatchTable::Comment("DefineMI")
2323           << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2324           << MatchTable::IntValue(getInsnVarID())
2325           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2326           << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2327           << MatchTable::LineBreak;
2328   }
2329 
2330   void emitPredicateOpcodes(MatchTable &Table,
2331                             RuleMatcher &Rule) const override {
2332     emitCaptureOpcodes(Table, Rule);
2333     InsnMatcher->emitPredicateOpcodes(Table, Rule);
2334   }
2335 
2336   bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2337     if (OperandPredicateMatcher::isHigherPriorityThan(B))
2338       return true;
2339     if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2340       return false;
2341 
2342     if (const InstructionOperandMatcher *BP =
2343             dyn_cast<InstructionOperandMatcher>(&B))
2344       if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2345         return true;
2346     return false;
2347   }
2348 };
2349 
2350 void InstructionMatcher::optimize() {
2351   SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2352   const auto &OpcMatcher = getOpcodeMatcher();
2353 
2354   Stash.push_back(predicates_pop_front());
2355   if (Stash.back().get() == &OpcMatcher) {
2356     if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
2357       Stash.emplace_back(
2358           new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2359     NumOperandsCheck = false;
2360 
2361     for (auto &OM : Operands)
2362       for (auto &OP : OM->predicates())
2363         if (isa<IntrinsicIDOperandMatcher>(OP)) {
2364           Stash.push_back(std::move(OP));
2365           OM->eraseNullPredicates();
2366           break;
2367         }
2368   }
2369 
2370   if (InsnVarID > 0) {
2371     assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2372     for (auto &OP : Operands[0]->predicates())
2373       OP.reset();
2374     Operands[0]->eraseNullPredicates();
2375   }
2376   for (auto &OM : Operands) {
2377     for (auto &OP : OM->predicates())
2378       if (isa<LLTOperandMatcher>(OP))
2379         Stash.push_back(std::move(OP));
2380     OM->eraseNullPredicates();
2381   }
2382   while (!Stash.empty())
2383     prependPredicate(Stash.pop_back_val());
2384 }
2385 
2386 //===- Actions ------------------------------------------------------------===//
2387 class OperandRenderer {
2388 public:
2389   enum RendererKind {
2390     OR_Copy,
2391     OR_CopyOrAddZeroReg,
2392     OR_CopySubReg,
2393     OR_CopyPhysReg,
2394     OR_CopyConstantAsImm,
2395     OR_CopyFConstantAsFPImm,
2396     OR_Imm,
2397     OR_SubRegIndex,
2398     OR_Register,
2399     OR_TempRegister,
2400     OR_ComplexPattern,
2401     OR_Custom,
2402     OR_CustomOperand
2403   };
2404 
2405 protected:
2406   RendererKind Kind;
2407 
2408 public:
2409   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2410   virtual ~OperandRenderer() {}
2411 
2412   RendererKind getKind() const { return Kind; }
2413 
2414   virtual void emitRenderOpcodes(MatchTable &Table,
2415                                  RuleMatcher &Rule) const = 0;
2416 };
2417 
2418 /// A CopyRenderer emits code to copy a single operand from an existing
2419 /// instruction to the one being built.
2420 class CopyRenderer : public OperandRenderer {
2421 protected:
2422   unsigned NewInsnID;
2423   /// The name of the operand.
2424   const StringRef SymbolicName;
2425 
2426 public:
2427   CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2428       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
2429         SymbolicName(SymbolicName) {
2430     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2431   }
2432 
2433   static bool classof(const OperandRenderer *R) {
2434     return R->getKind() == OR_Copy;
2435   }
2436 
2437   const StringRef getSymbolicName() const { return SymbolicName; }
2438 
2439   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2440     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2441     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2442     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2443           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2444           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2445           << MatchTable::IntValue(Operand.getOpIdx())
2446           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2447   }
2448 };
2449 
2450 /// A CopyRenderer emits code to copy a virtual register to a specific physical
2451 /// register.
2452 class CopyPhysRegRenderer : public OperandRenderer {
2453 protected:
2454   unsigned NewInsnID;
2455   Record *PhysReg;
2456 
2457 public:
2458   CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2459       : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2460         PhysReg(Reg) {
2461     assert(PhysReg);
2462   }
2463 
2464   static bool classof(const OperandRenderer *R) {
2465     return R->getKind() == OR_CopyPhysReg;
2466   }
2467 
2468   Record *getPhysReg() const { return PhysReg; }
2469 
2470   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2471     const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2472     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2473     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2474           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2475           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2476           << MatchTable::IntValue(Operand.getOpIdx())
2477           << MatchTable::Comment(PhysReg->getName())
2478           << MatchTable::LineBreak;
2479   }
2480 };
2481 
2482 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2483 /// existing instruction to the one being built. If the operand turns out to be
2484 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2485 class CopyOrAddZeroRegRenderer : public OperandRenderer {
2486 protected:
2487   unsigned NewInsnID;
2488   /// The name of the operand.
2489   const StringRef SymbolicName;
2490   const Record *ZeroRegisterDef;
2491 
2492 public:
2493   CopyOrAddZeroRegRenderer(unsigned NewInsnID,
2494                            StringRef SymbolicName, Record *ZeroRegisterDef)
2495       : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2496         SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2497     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2498   }
2499 
2500   static bool classof(const OperandRenderer *R) {
2501     return R->getKind() == OR_CopyOrAddZeroReg;
2502   }
2503 
2504   const StringRef getSymbolicName() const { return SymbolicName; }
2505 
2506   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2507     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2508     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2509     Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2510           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2511           << MatchTable::Comment("OldInsnID")
2512           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2513           << MatchTable::IntValue(Operand.getOpIdx())
2514           << MatchTable::NamedValue(
2515                  (ZeroRegisterDef->getValue("Namespace")
2516                       ? ZeroRegisterDef->getValueAsString("Namespace")
2517                       : ""),
2518                  ZeroRegisterDef->getName())
2519           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2520   }
2521 };
2522 
2523 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2524 /// an extended immediate operand.
2525 class CopyConstantAsImmRenderer : public OperandRenderer {
2526 protected:
2527   unsigned NewInsnID;
2528   /// The name of the operand.
2529   const std::string SymbolicName;
2530   bool Signed;
2531 
2532 public:
2533   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2534       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2535         SymbolicName(SymbolicName), Signed(true) {}
2536 
2537   static bool classof(const OperandRenderer *R) {
2538     return R->getKind() == OR_CopyConstantAsImm;
2539   }
2540 
2541   const StringRef getSymbolicName() const { return SymbolicName; }
2542 
2543   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2544     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2545     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2546     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2547                                        : "GIR_CopyConstantAsUImm")
2548           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2549           << MatchTable::Comment("OldInsnID")
2550           << MatchTable::IntValue(OldInsnVarID)
2551           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2552   }
2553 };
2554 
2555 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2556 /// instruction to an extended immediate operand.
2557 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2558 protected:
2559   unsigned NewInsnID;
2560   /// The name of the operand.
2561   const std::string SymbolicName;
2562 
2563 public:
2564   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2565       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2566         SymbolicName(SymbolicName) {}
2567 
2568   static bool classof(const OperandRenderer *R) {
2569     return R->getKind() == OR_CopyFConstantAsFPImm;
2570   }
2571 
2572   const StringRef getSymbolicName() const { return SymbolicName; }
2573 
2574   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2575     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2576     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2577     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2578           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2579           << MatchTable::Comment("OldInsnID")
2580           << MatchTable::IntValue(OldInsnVarID)
2581           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2582   }
2583 };
2584 
2585 /// A CopySubRegRenderer emits code to copy a single register operand from an
2586 /// existing instruction to the one being built and indicate that only a
2587 /// subregister should be copied.
2588 class CopySubRegRenderer : public OperandRenderer {
2589 protected:
2590   unsigned NewInsnID;
2591   /// The name of the operand.
2592   const StringRef SymbolicName;
2593   /// The subregister to extract.
2594   const CodeGenSubRegIndex *SubReg;
2595 
2596 public:
2597   CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2598                      const CodeGenSubRegIndex *SubReg)
2599       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
2600         SymbolicName(SymbolicName), SubReg(SubReg) {}
2601 
2602   static bool classof(const OperandRenderer *R) {
2603     return R->getKind() == OR_CopySubReg;
2604   }
2605 
2606   const StringRef getSymbolicName() const { return SymbolicName; }
2607 
2608   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2609     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2610     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2611     Table << MatchTable::Opcode("GIR_CopySubReg")
2612           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2613           << MatchTable::Comment("OldInsnID")
2614           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2615           << MatchTable::IntValue(Operand.getOpIdx())
2616           << MatchTable::Comment("SubRegIdx")
2617           << MatchTable::IntValue(SubReg->EnumValue)
2618           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2619   }
2620 };
2621 
2622 /// Adds a specific physical register to the instruction being built.
2623 /// This is typically useful for WZR/XZR on AArch64.
2624 class AddRegisterRenderer : public OperandRenderer {
2625 protected:
2626   unsigned InsnID;
2627   const Record *RegisterDef;
2628   bool IsDef;
2629 
2630 public:
2631   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2632                       bool IsDef = false)
2633       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2634         IsDef(IsDef) {}
2635 
2636   static bool classof(const OperandRenderer *R) {
2637     return R->getKind() == OR_Register;
2638   }
2639 
2640   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2641     Table << MatchTable::Opcode("GIR_AddRegister")
2642           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2643           << MatchTable::NamedValue(
2644                  (RegisterDef->getValue("Namespace")
2645                       ? RegisterDef->getValueAsString("Namespace")
2646                       : ""),
2647                  RegisterDef->getName())
2648           << MatchTable::Comment("AddRegisterRegFlags");
2649 
2650     // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2651     // really needed for a physical register reference. We can pack the
2652     // register and flags in a single field.
2653     if (IsDef)
2654       Table << MatchTable::NamedValue("RegState::Define");
2655     else
2656       Table << MatchTable::IntValue(0);
2657     Table << MatchTable::LineBreak;
2658   }
2659 };
2660 
2661 /// Adds a specific temporary virtual register to the instruction being built.
2662 /// This is used to chain instructions together when emitting multiple
2663 /// instructions.
2664 class TempRegRenderer : public OperandRenderer {
2665 protected:
2666   unsigned InsnID;
2667   unsigned TempRegID;
2668   const CodeGenSubRegIndex *SubRegIdx;
2669   bool IsDef;
2670   bool IsDead;
2671 
2672 public:
2673   TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
2674                   const CodeGenSubRegIndex *SubReg = nullptr,
2675                   bool IsDead = false)
2676       : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2677         SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
2678 
2679   static bool classof(const OperandRenderer *R) {
2680     return R->getKind() == OR_TempRegister;
2681   }
2682 
2683   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2684     if (SubRegIdx) {
2685       assert(!IsDef);
2686       Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2687     } else
2688       Table << MatchTable::Opcode("GIR_AddTempRegister");
2689 
2690     Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2691           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2692           << MatchTable::Comment("TempRegFlags");
2693 
2694     if (IsDef) {
2695       SmallString<32> RegFlags;
2696       RegFlags += "RegState::Define";
2697       if (IsDead)
2698         RegFlags += "|RegState::Dead";
2699       Table << MatchTable::NamedValue(RegFlags);
2700     } else
2701       Table << MatchTable::IntValue(0);
2702 
2703     if (SubRegIdx)
2704       Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
2705     Table << MatchTable::LineBreak;
2706   }
2707 };
2708 
2709 /// Adds a specific immediate to the instruction being built.
2710 class ImmRenderer : public OperandRenderer {
2711 protected:
2712   unsigned InsnID;
2713   int64_t Imm;
2714 
2715 public:
2716   ImmRenderer(unsigned InsnID, int64_t Imm)
2717       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
2718 
2719   static bool classof(const OperandRenderer *R) {
2720     return R->getKind() == OR_Imm;
2721   }
2722 
2723   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2724     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2725           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2726           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
2727   }
2728 };
2729 
2730 /// Adds an enum value for a subreg index to the instruction being built.
2731 class SubRegIndexRenderer : public OperandRenderer {
2732 protected:
2733   unsigned InsnID;
2734   const CodeGenSubRegIndex *SubRegIdx;
2735 
2736 public:
2737   SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2738       : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2739 
2740   static bool classof(const OperandRenderer *R) {
2741     return R->getKind() == OR_SubRegIndex;
2742   }
2743 
2744   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2745     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2746           << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2747           << MatchTable::IntValue(SubRegIdx->EnumValue)
2748           << MatchTable::LineBreak;
2749   }
2750 };
2751 
2752 /// Adds operands by calling a renderer function supplied by the ComplexPattern
2753 /// matcher function.
2754 class RenderComplexPatternOperand : public OperandRenderer {
2755 private:
2756   unsigned InsnID;
2757   const Record &TheDef;
2758   /// The name of the operand.
2759   const StringRef SymbolicName;
2760   /// The renderer number. This must be unique within a rule since it's used to
2761   /// identify a temporary variable to hold the renderer function.
2762   unsigned RendererID;
2763   /// When provided, this is the suboperand of the ComplexPattern operand to
2764   /// render. Otherwise all the suboperands will be rendered.
2765   Optional<unsigned> SubOperand;
2766 
2767   unsigned getNumOperands() const {
2768     return TheDef.getValueAsDag("Operands")->getNumArgs();
2769   }
2770 
2771 public:
2772   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
2773                               StringRef SymbolicName, unsigned RendererID,
2774                               Optional<unsigned> SubOperand = None)
2775       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
2776         SymbolicName(SymbolicName), RendererID(RendererID),
2777         SubOperand(SubOperand) {}
2778 
2779   static bool classof(const OperandRenderer *R) {
2780     return R->getKind() == OR_ComplexPattern;
2781   }
2782 
2783   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2784     Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2785                                                       : "GIR_ComplexRenderer")
2786           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2787           << MatchTable::Comment("RendererID")
2788           << MatchTable::IntValue(RendererID);
2789     if (SubOperand.hasValue())
2790       Table << MatchTable::Comment("SubOperand")
2791             << MatchTable::IntValue(SubOperand.getValue());
2792     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2793   }
2794 };
2795 
2796 class CustomRenderer : public OperandRenderer {
2797 protected:
2798   unsigned InsnID;
2799   const Record &Renderer;
2800   /// The name of the operand.
2801   const std::string SymbolicName;
2802 
2803 public:
2804   CustomRenderer(unsigned InsnID, const Record &Renderer,
2805                  StringRef SymbolicName)
2806       : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2807         SymbolicName(SymbolicName) {}
2808 
2809   static bool classof(const OperandRenderer *R) {
2810     return R->getKind() == OR_Custom;
2811   }
2812 
2813   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2814     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2815     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2816     Table << MatchTable::Opcode("GIR_CustomRenderer")
2817           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2818           << MatchTable::Comment("OldInsnID")
2819           << MatchTable::IntValue(OldInsnVarID)
2820           << MatchTable::Comment("Renderer")
2821           << MatchTable::NamedValue(
2822                  "GICR_" + Renderer.getValueAsString("RendererFn").str())
2823           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2824   }
2825 };
2826 
2827 class CustomOperandRenderer : public OperandRenderer {
2828 protected:
2829   unsigned InsnID;
2830   const Record &Renderer;
2831   /// The name of the operand.
2832   const std::string SymbolicName;
2833 
2834 public:
2835   CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2836                         StringRef SymbolicName)
2837       : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2838         SymbolicName(SymbolicName) {}
2839 
2840   static bool classof(const OperandRenderer *R) {
2841     return R->getKind() == OR_CustomOperand;
2842   }
2843 
2844   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2845     const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2846     Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2847           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2848           << MatchTable::Comment("OldInsnID")
2849           << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2850           << MatchTable::Comment("OpIdx")
2851           << MatchTable::IntValue(OpdMatcher.getOpIdx())
2852           << MatchTable::Comment("OperandRenderer")
2853           << MatchTable::NamedValue(
2854             "GICR_" + Renderer.getValueAsString("RendererFn").str())
2855           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2856   }
2857 };
2858 
2859 /// An action taken when all Matcher predicates succeeded for a parent rule.
2860 ///
2861 /// Typical actions include:
2862 /// * Changing the opcode of an instruction.
2863 /// * Adding an operand to an instruction.
2864 class MatchAction {
2865 public:
2866   virtual ~MatchAction() {}
2867 
2868   /// Emit the MatchTable opcodes to implement the action.
2869   virtual void emitActionOpcodes(MatchTable &Table,
2870                                  RuleMatcher &Rule) const = 0;
2871 };
2872 
2873 /// Generates a comment describing the matched rule being acted upon.
2874 class DebugCommentAction : public MatchAction {
2875 private:
2876   std::string S;
2877 
2878 public:
2879   DebugCommentAction(StringRef S) : S(std::string(S)) {}
2880 
2881   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2882     Table << MatchTable::Comment(S) << MatchTable::LineBreak;
2883   }
2884 };
2885 
2886 /// Generates code to build an instruction or mutate an existing instruction
2887 /// into the desired instruction when this is possible.
2888 class BuildMIAction : public MatchAction {
2889 private:
2890   unsigned InsnID;
2891   const CodeGenInstruction *I;
2892   InstructionMatcher *Matched;
2893   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2894 
2895   /// True if the instruction can be built solely by mutating the opcode.
2896   bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2897     if (!Insn)
2898       return false;
2899 
2900     if (OperandRenderers.size() != Insn->getNumOperands())
2901       return false;
2902 
2903     for (const auto &Renderer : enumerate(OperandRenderers)) {
2904       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
2905         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
2906         if (Insn != &OM.getInstructionMatcher() ||
2907             OM.getOpIdx() != Renderer.index())
2908           return false;
2909       } else
2910         return false;
2911     }
2912 
2913     return true;
2914   }
2915 
2916 public:
2917   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2918       : InsnID(InsnID), I(I), Matched(nullptr) {}
2919 
2920   unsigned getInsnID() const { return InsnID; }
2921   const CodeGenInstruction *getCGI() const { return I; }
2922 
2923   void chooseInsnToMutate(RuleMatcher &Rule) {
2924     for (auto *MutateCandidate : Rule.mutatable_insns()) {
2925       if (canMutate(Rule, MutateCandidate)) {
2926         // Take the first one we're offered that we're able to mutate.
2927         Rule.reserveInsnMatcherForMutation(MutateCandidate);
2928         Matched = MutateCandidate;
2929         return;
2930       }
2931     }
2932   }
2933 
2934   template <class Kind, class... Args>
2935   Kind &addRenderer(Args&&... args) {
2936     OperandRenderers.emplace_back(
2937         std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
2938     return *static_cast<Kind *>(OperandRenderers.back().get());
2939   }
2940 
2941   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2942     if (Matched) {
2943       assert(canMutate(Rule, Matched) &&
2944              "Arranged to mutate an insn that isn't mutatable");
2945 
2946       unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
2947       Table << MatchTable::Opcode("GIR_MutateOpcode")
2948             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2949             << MatchTable::Comment("RecycleInsnID")
2950             << MatchTable::IntValue(RecycleInsnID)
2951             << MatchTable::Comment("Opcode")
2952             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2953             << MatchTable::LineBreak;
2954 
2955       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
2956         for (auto Def : I->ImplicitDefs) {
2957           auto Namespace = Def->getValue("Namespace")
2958                                ? Def->getValueAsString("Namespace")
2959                                : "";
2960           Table << MatchTable::Opcode("GIR_AddImplicitDef")
2961                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2962                 << MatchTable::NamedValue(Namespace, Def->getName())
2963                 << MatchTable::LineBreak;
2964         }
2965         for (auto Use : I->ImplicitUses) {
2966           auto Namespace = Use->getValue("Namespace")
2967                                ? Use->getValueAsString("Namespace")
2968                                : "";
2969           Table << MatchTable::Opcode("GIR_AddImplicitUse")
2970                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2971                 << MatchTable::NamedValue(Namespace, Use->getName())
2972                 << MatchTable::LineBreak;
2973         }
2974       }
2975       return;
2976     }
2977 
2978     // TODO: Simple permutation looks like it could be almost as common as
2979     //       mutation due to commutative operations.
2980 
2981     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2982           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2983           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2984           << MatchTable::LineBreak;
2985     for (const auto &Renderer : OperandRenderers)
2986       Renderer->emitRenderOpcodes(Table, Rule);
2987 
2988     if (I->mayLoad || I->mayStore) {
2989       Table << MatchTable::Opcode("GIR_MergeMemOperands")
2990             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2991             << MatchTable::Comment("MergeInsnID's");
2992       // Emit the ID's for all the instructions that are matched by this rule.
2993       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2994       //       some other means of having a memoperand. Also limit this to
2995       //       emitted instructions that expect to have a memoperand too. For
2996       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
2997       //       sign-extend instructions shouldn't put the memoperand on the
2998       //       sign-extend since it has no effect there.
2999       std::vector<unsigned> MergeInsnIDs;
3000       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
3001         MergeInsnIDs.push_back(IDMatcherPair.second);
3002       llvm::sort(MergeInsnIDs);
3003       for (const auto &MergeInsnID : MergeInsnIDs)
3004         Table << MatchTable::IntValue(MergeInsnID);
3005       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
3006             << MatchTable::LineBreak;
3007     }
3008 
3009     // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
3010     //        better for combines. Particularly when there are multiple match
3011     //        roots.
3012     if (InsnID == 0)
3013       Table << MatchTable::Opcode("GIR_EraseFromParent")
3014             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3015             << MatchTable::LineBreak;
3016   }
3017 };
3018 
3019 /// Generates code to constrain the operands of an output instruction to the
3020 /// register classes specified by the definition of that instruction.
3021 class ConstrainOperandsToDefinitionAction : public MatchAction {
3022   unsigned InsnID;
3023 
3024 public:
3025   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
3026 
3027   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3028     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
3029           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3030           << MatchTable::LineBreak;
3031   }
3032 };
3033 
3034 /// Generates code to constrain the specified operand of an output instruction
3035 /// to the specified register class.
3036 class ConstrainOperandToRegClassAction : public MatchAction {
3037   unsigned InsnID;
3038   unsigned OpIdx;
3039   const CodeGenRegisterClass &RC;
3040 
3041 public:
3042   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
3043                                    const CodeGenRegisterClass &RC)
3044       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
3045 
3046   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3047     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3048           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3049           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
3050           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3051           << MatchTable::LineBreak;
3052   }
3053 };
3054 
3055 /// Generates code to create a temporary register which can be used to chain
3056 /// instructions together.
3057 class MakeTempRegisterAction : public MatchAction {
3058 private:
3059   LLTCodeGen Ty;
3060   unsigned TempRegID;
3061 
3062 public:
3063   MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
3064       : Ty(Ty), TempRegID(TempRegID) {
3065     KnownTypes.insert(Ty);
3066   }
3067 
3068   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3069     Table << MatchTable::Opcode("GIR_MakeTempReg")
3070           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3071           << MatchTable::Comment("TypeID")
3072           << MatchTable::NamedValue(Ty.getCxxEnumValue())
3073           << MatchTable::LineBreak;
3074   }
3075 };
3076 
3077 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
3078   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
3079   MutatableInsns.insert(Matchers.back().get());
3080   return *Matchers.back();
3081 }
3082 
3083 void RuleMatcher::addRequiredFeature(Record *Feature) {
3084   RequiredFeatures.push_back(Feature);
3085 }
3086 
3087 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3088   return RequiredFeatures;
3089 }
3090 
3091 // Emplaces an action of the specified Kind at the end of the action list.
3092 //
3093 // Returns a reference to the newly created action.
3094 //
3095 // Like std::vector::emplace_back(), may invalidate all iterators if the new
3096 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
3097 // iterator.
3098 template <class Kind, class... Args>
3099 Kind &RuleMatcher::addAction(Args &&... args) {
3100   Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
3101   return *static_cast<Kind *>(Actions.back().get());
3102 }
3103 
3104 // Emplaces an action of the specified Kind before the given insertion point.
3105 //
3106 // Returns an iterator pointing at the newly created instruction.
3107 //
3108 // Like std::vector::insert(), may invalidate all iterators if the new size
3109 // exceeds the capacity. Otherwise, only invalidates the iterators from the
3110 // insertion point onwards.
3111 template <class Kind, class... Args>
3112 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3113                                           Args &&... args) {
3114   return Actions.emplace(InsertPt,
3115                          std::make_unique<Kind>(std::forward<Args>(args)...));
3116 }
3117 
3118 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
3119   unsigned NewInsnVarID = NextInsnVarID++;
3120   InsnVariableIDs[&Matcher] = NewInsnVarID;
3121   return NewInsnVarID;
3122 }
3123 
3124 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
3125   const auto &I = InsnVariableIDs.find(&InsnMatcher);
3126   if (I != InsnVariableIDs.end())
3127     return I->second;
3128   llvm_unreachable("Matched Insn was not captured in a local variable");
3129 }
3130 
3131 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3132   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3133     DefinedOperands[SymbolicName] = &OM;
3134     return;
3135   }
3136 
3137   // If the operand is already defined, then we must ensure both references in
3138   // the matcher have the exact same node.
3139   OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3140 }
3141 
3142 void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3143   if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3144     PhysRegOperands[Reg] = &OM;
3145     return;
3146   }
3147 }
3148 
3149 InstructionMatcher &
3150 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3151   for (const auto &I : InsnVariableIDs)
3152     if (I.first->getSymbolicName() == SymbolicName)
3153       return *I.first;
3154   llvm_unreachable(
3155       ("Failed to lookup instruction " + SymbolicName).str().c_str());
3156 }
3157 
3158 const OperandMatcher &
3159 RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3160   const auto &I = PhysRegOperands.find(Reg);
3161 
3162   if (I == PhysRegOperands.end()) {
3163     PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3164                     " was not declared in matcher");
3165   }
3166 
3167   return *I->second;
3168 }
3169 
3170 const OperandMatcher &
3171 RuleMatcher::getOperandMatcher(StringRef Name) const {
3172   const auto &I = DefinedOperands.find(Name);
3173 
3174   if (I == DefinedOperands.end())
3175     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3176 
3177   return *I->second;
3178 }
3179 
3180 void RuleMatcher::emit(MatchTable &Table) {
3181   if (Matchers.empty())
3182     llvm_unreachable("Unexpected empty matcher!");
3183 
3184   // The representation supports rules that require multiple roots such as:
3185   //    %ptr(p0) = ...
3186   //    %elt0(s32) = G_LOAD %ptr
3187   //    %1(p0) = G_ADD %ptr, 4
3188   //    %elt1(s32) = G_LOAD p0 %1
3189   // which could be usefully folded into:
3190   //    %ptr(p0) = ...
3191   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3192   // on some targets but we don't need to make use of that yet.
3193   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
3194 
3195   unsigned LabelID = Table.allocateLabelID();
3196   Table << MatchTable::Opcode("GIM_Try", +1)
3197         << MatchTable::Comment("On fail goto")
3198         << MatchTable::JumpTarget(LabelID)
3199         << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
3200         << MatchTable::LineBreak;
3201 
3202   if (!RequiredFeatures.empty()) {
3203     Table << MatchTable::Opcode("GIM_CheckFeatures")
3204           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3205           << MatchTable::LineBreak;
3206   }
3207 
3208   Matchers.front()->emitPredicateOpcodes(Table, *this);
3209 
3210   // We must also check if it's safe to fold the matched instructions.
3211   if (InsnVariableIDs.size() >= 2) {
3212     // Invert the map to create stable ordering (by var names)
3213     SmallVector<unsigned, 2> InsnIDs;
3214     for (const auto &Pair : InsnVariableIDs) {
3215       // Skip the root node since it isn't moving anywhere. Everything else is
3216       // sinking to meet it.
3217       if (Pair.first == Matchers.front().get())
3218         continue;
3219 
3220       InsnIDs.push_back(Pair.second);
3221     }
3222     llvm::sort(InsnIDs);
3223 
3224     for (const auto &InsnID : InsnIDs) {
3225       // Reject the difficult cases until we have a more accurate check.
3226       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3227             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3228             << MatchTable::LineBreak;
3229 
3230       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3231       //        account for unsafe cases.
3232       //
3233       //        Example:
3234       //          MI1--> %0 = ...
3235       //                 %1 = ... %0
3236       //          MI0--> %2 = ... %0
3237       //          It's not safe to erase MI1. We currently handle this by not
3238       //          erasing %0 (even when it's dead).
3239       //
3240       //        Example:
3241       //          MI1--> %0 = load volatile @a
3242       //                 %1 = load volatile @a
3243       //          MI0--> %2 = ... %0
3244       //          It's not safe to sink %0's def past %1. We currently handle
3245       //          this by rejecting all loads.
3246       //
3247       //        Example:
3248       //          MI1--> %0 = load @a
3249       //                 %1 = store @a
3250       //          MI0--> %2 = ... %0
3251       //          It's not safe to sink %0's def past %1. We currently handle
3252       //          this by rejecting all loads.
3253       //
3254       //        Example:
3255       //                   G_CONDBR %cond, @BB1
3256       //                 BB0:
3257       //          MI1-->   %0 = load @a
3258       //                   G_BR @BB1
3259       //                 BB1:
3260       //          MI0-->   %2 = ... %0
3261       //          It's not always safe to sink %0 across control flow. In this
3262       //          case it may introduce a memory fault. We currentl handle this
3263       //          by rejecting all loads.
3264     }
3265   }
3266 
3267   for (const auto &PM : EpilogueMatchers)
3268     PM->emitPredicateOpcodes(Table, *this);
3269 
3270   for (const auto &MA : Actions)
3271     MA->emitActionOpcodes(Table, *this);
3272 
3273   if (Table.isWithCoverage())
3274     Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3275           << MatchTable::LineBreak;
3276   else
3277     Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3278           << MatchTable::LineBreak;
3279 
3280   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
3281         << MatchTable::Label(LabelID);
3282   ++NumPatternEmitted;
3283 }
3284 
3285 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3286   // Rules involving more match roots have higher priority.
3287   if (Matchers.size() > B.Matchers.size())
3288     return true;
3289   if (Matchers.size() < B.Matchers.size())
3290     return false;
3291 
3292   for (auto Matcher : zip(Matchers, B.Matchers)) {
3293     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3294       return true;
3295     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3296       return false;
3297   }
3298 
3299   return false;
3300 }
3301 
3302 unsigned RuleMatcher::countRendererFns() const {
3303   return std::accumulate(
3304       Matchers.begin(), Matchers.end(), 0,
3305       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
3306         return A + Matcher->countRendererFns();
3307       });
3308 }
3309 
3310 bool OperandPredicateMatcher::isHigherPriorityThan(
3311     const OperandPredicateMatcher &B) const {
3312   // Generally speaking, an instruction is more important than an Int or a
3313   // LiteralInt because it can cover more nodes but theres an exception to
3314   // this. G_CONSTANT's are less important than either of those two because they
3315   // are more permissive.
3316 
3317   const InstructionOperandMatcher *AOM =
3318       dyn_cast<InstructionOperandMatcher>(this);
3319   const InstructionOperandMatcher *BOM =
3320       dyn_cast<InstructionOperandMatcher>(&B);
3321   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3322   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3323 
3324   if (AOM && BOM) {
3325     // The relative priorities between a G_CONSTANT and any other instruction
3326     // don't actually matter but this code is needed to ensure a strict weak
3327     // ordering. This is particularly important on Windows where the rules will
3328     // be incorrectly sorted without it.
3329     if (AIsConstantInsn != BIsConstantInsn)
3330       return AIsConstantInsn < BIsConstantInsn;
3331     return false;
3332   }
3333 
3334   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3335     return false;
3336   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3337     return true;
3338 
3339   return Kind < B.Kind;
3340 }
3341 
3342 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
3343                                               RuleMatcher &Rule) const {
3344   const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
3345   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
3346   assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
3347 
3348   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3349         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3350         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3351         << MatchTable::Comment("OtherMI")
3352         << MatchTable::IntValue(OtherInsnVarID)
3353         << MatchTable::Comment("OtherOpIdx")
3354         << MatchTable::IntValue(OtherOM.getOpIdx())
3355         << MatchTable::LineBreak;
3356 }
3357 
3358 //===- GlobalISelEmitter class --------------------------------------------===//
3359 
3360 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3361   ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3362   if (ChildTypes.size() != 1)
3363     return failedImport("Dst pattern child has multiple results");
3364 
3365   Optional<LLTCodeGen> MaybeOpTy;
3366   if (ChildTypes.front().isMachineValueType()) {
3367     MaybeOpTy =
3368       MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3369   }
3370 
3371   if (!MaybeOpTy)
3372     return failedImport("Dst operand has an unsupported type");
3373   return *MaybeOpTy;
3374 }
3375 
3376 class GlobalISelEmitter {
3377 public:
3378   explicit GlobalISelEmitter(RecordKeeper &RK);
3379   void run(raw_ostream &OS);
3380 
3381 private:
3382   const RecordKeeper &RK;
3383   const CodeGenDAGPatterns CGP;
3384   const CodeGenTarget &Target;
3385   CodeGenRegBank &CGRegs;
3386 
3387   /// Keep track of the equivalence between SDNodes and Instruction by mapping
3388   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3389   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
3390   /// This is defined using 'GINodeEquiv' in the target description.
3391   DenseMap<Record *, Record *> NodeEquivs;
3392 
3393   /// Keep track of the equivalence between ComplexPattern's and
3394   /// GIComplexOperandMatcher. Map entries are specified by subclassing
3395   /// GIComplexPatternEquiv.
3396   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3397 
3398   /// Keep track of the equivalence between SDNodeXForm's and
3399   /// GICustomOperandRenderer. Map entries are specified by subclassing
3400   /// GISDNodeXFormEquiv.
3401   DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3402 
3403   /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3404   /// This adds compatibility for RuleMatchers to use this for ordering rules.
3405   DenseMap<uint64_t, int> RuleMatcherScores;
3406 
3407   // Map of predicates to their subtarget features.
3408   SubtargetFeatureInfoMap SubtargetFeatures;
3409 
3410   // Rule coverage information.
3411   Optional<CodeGenCoverage> RuleCoverage;
3412 
3413   void gatherOpcodeValues();
3414   void gatherTypeIDValues();
3415   void gatherNodeEquivs();
3416 
3417   Record *findNodeEquiv(Record *N) const;
3418   const CodeGenInstruction *getEquivNode(Record &Equiv,
3419                                          const TreePatternNode *N) const;
3420 
3421   Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
3422   Expected<InstructionMatcher &>
3423   createAndImportSelDAGMatcher(RuleMatcher &Rule,
3424                                InstructionMatcher &InsnMatcher,
3425                                const TreePatternNode *Src, unsigned &TempOpIdx);
3426   Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3427                                            unsigned &TempOpIdx) const;
3428   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3429                            const TreePatternNode *SrcChild,
3430                            bool OperandIsAPointer, bool OperandIsImmArg,
3431                            unsigned OpIdx, unsigned &TempOpIdx);
3432 
3433   Expected<BuildMIAction &> createAndImportInstructionRenderer(
3434       RuleMatcher &M, InstructionMatcher &InsnMatcher,
3435       const TreePatternNode *Src, const TreePatternNode *Dst);
3436   Expected<action_iterator> createAndImportSubInstructionRenderer(
3437       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3438       unsigned TempReg);
3439   Expected<action_iterator>
3440   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
3441                             const TreePatternNode *Dst);
3442 
3443   Expected<action_iterator>
3444   importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3445                              BuildMIAction &DstMIBuilder,
3446                              const TreePatternNode *Dst);
3447 
3448   Expected<action_iterator>
3449   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3450                              BuildMIAction &DstMIBuilder,
3451                              const llvm::TreePatternNode *Dst);
3452   Expected<action_iterator>
3453   importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3454                             BuildMIAction &DstMIBuilder,
3455                             TreePatternNode *DstChild);
3456   Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3457                                       BuildMIAction &DstMIBuilder,
3458                                       DagInit *DefaultOps) const;
3459   Error
3460   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3461                              const std::vector<Record *> &ImplicitDefs) const;
3462 
3463   void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3464                            StringRef TypeIdentifier, StringRef ArgType,
3465                            StringRef ArgName, StringRef AdditionalDeclarations,
3466                            std::function<bool(const Record *R)> Filter);
3467   void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3468                            StringRef ArgType,
3469                            std::function<bool(const Record *R)> Filter);
3470   void emitMIPredicateFns(raw_ostream &OS);
3471 
3472   /// Analyze pattern \p P, returning a matcher for it if possible.
3473   /// Otherwise, return an Error explaining why we don't support it.
3474   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
3475 
3476   void declareSubtargetFeature(Record *Predicate);
3477 
3478   MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3479                              bool WithCoverage);
3480 
3481   /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3482   /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3483   /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3484   /// If no register class is found, return None.
3485   Optional<const CodeGenRegisterClass *>
3486   inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3487                                  TreePatternNode *SuperRegNode,
3488                                  TreePatternNode *SubRegIdxNode);
3489   Optional<CodeGenSubRegIndex *>
3490   inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
3491 
3492   /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3493   /// Return None if no such class exists.
3494   Optional<const CodeGenRegisterClass *>
3495   inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3496                           TreePatternNode *SubRegIdxNode);
3497 
3498   /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3499   Optional<const CodeGenRegisterClass *>
3500   getRegClassFromLeaf(TreePatternNode *Leaf);
3501 
3502   /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3503   /// otherwise.
3504   Optional<const CodeGenRegisterClass *>
3505   inferRegClassFromPattern(TreePatternNode *N);
3506 
3507   // Add builtin predicates.
3508   Expected<InstructionMatcher &>
3509   addBuiltinPredicates(const Record *SrcGIEquivOrNull,
3510                        const TreePredicateFn &Predicate,
3511                        InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
3512 
3513 public:
3514   /// Takes a sequence of \p Rules and group them based on the predicates
3515   /// they share. \p MatcherStorage is used as a memory container
3516   /// for the group that are created as part of this process.
3517   ///
3518   /// What this optimization does looks like if GroupT = GroupMatcher:
3519   /// Output without optimization:
3520   /// \verbatim
3521   /// # R1
3522   ///  # predicate A
3523   ///  # predicate B
3524   ///  ...
3525   /// # R2
3526   ///  # predicate A // <-- effectively this is going to be checked twice.
3527   ///                //     Once in R1 and once in R2.
3528   ///  # predicate C
3529   /// \endverbatim
3530   /// Output with optimization:
3531   /// \verbatim
3532   /// # Group1_2
3533   ///  # predicate A // <-- Check is now shared.
3534   ///  # R1
3535   ///   # predicate B
3536   ///  # R2
3537   ///   # predicate C
3538   /// \endverbatim
3539   template <class GroupT>
3540   static std::vector<Matcher *> optimizeRules(
3541       ArrayRef<Matcher *> Rules,
3542       std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
3543 };
3544 
3545 void GlobalISelEmitter::gatherOpcodeValues() {
3546   InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3547 }
3548 
3549 void GlobalISelEmitter::gatherTypeIDValues() {
3550   LLTOperandMatcher::initTypeIDValuesMap();
3551 }
3552 
3553 void GlobalISelEmitter::gatherNodeEquivs() {
3554   assert(NodeEquivs.empty());
3555   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
3556     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
3557 
3558   assert(ComplexPatternEquivs.empty());
3559   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3560     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3561     if (!SelDAGEquiv)
3562       continue;
3563     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3564  }
3565 
3566  assert(SDNodeXFormEquivs.empty());
3567  for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3568    Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3569    if (!SelDAGEquiv)
3570      continue;
3571    SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3572  }
3573 }
3574 
3575 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
3576   return NodeEquivs.lookup(N);
3577 }
3578 
3579 const CodeGenInstruction *
3580 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3581   if (N->getNumChildren() >= 1) {
3582     // setcc operation maps to two different G_* instructions based on the type.
3583     if (!Equiv.isValueUnset("IfFloatingPoint") &&
3584         MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3585       return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3586   }
3587 
3588   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3589     const TreePredicateFn &Predicate = Call.Fn;
3590     if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3591         Predicate.isSignExtLoad())
3592       return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3593     if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3594         Predicate.isZeroExtLoad())
3595       return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3596   }
3597 
3598   return &Target.getInstruction(Equiv.getValueAsDef("I"));
3599 }
3600 
3601 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
3602     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3603       CGRegs(Target.getRegBank()) {}
3604 
3605 //===- Emitter ------------------------------------------------------------===//
3606 
3607 Error
3608 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
3609                                         ArrayRef<Predicate> Predicates) {
3610   for (const Predicate &P : Predicates) {
3611     if (!P.Def || P.getCondString().empty())
3612       continue;
3613     declareSubtargetFeature(P.Def);
3614     M.addRequiredFeature(P.Def);
3615   }
3616 
3617   return Error::success();
3618 }
3619 
3620 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
3621     const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
3622     InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
3623   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3624     if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3625       SmallVector<unsigned, 4> ParsedAddrSpaces;
3626 
3627       for (Init *Val : AddrSpaces->getValues()) {
3628         IntInit *IntVal = dyn_cast<IntInit>(Val);
3629         if (!IntVal)
3630           return failedImport("Address space is not an integer");
3631         ParsedAddrSpaces.push_back(IntVal->getValue());
3632       }
3633 
3634       if (!ParsedAddrSpaces.empty()) {
3635         InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3636             0, ParsedAddrSpaces);
3637       }
3638     }
3639 
3640     int64_t MinAlign = Predicate.getMinAlignment();
3641     if (MinAlign > 0)
3642       InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3643   }
3644 
3645   // G_LOAD is used for both non-extending and any-extending loads.
3646   if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3647     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3648         0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3649     return InsnMatcher;
3650   }
3651   if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3652     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3653         0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3654     return InsnMatcher;
3655   }
3656 
3657   if (Predicate.isStore()) {
3658     if (Predicate.isTruncStore()) {
3659       // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3660       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3661           0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3662       return InsnMatcher;
3663     }
3664     if (Predicate.isNonTruncStore()) {
3665       // We need to check the sizes match here otherwise we could incorrectly
3666       // match truncating stores with non-truncating ones.
3667       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3668           0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3669     }
3670   }
3671 
3672   // No check required. We already did it by swapping the opcode.
3673   if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3674       Predicate.isSignExtLoad())
3675     return InsnMatcher;
3676 
3677   // No check required. We already did it by swapping the opcode.
3678   if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3679       Predicate.isZeroExtLoad())
3680     return InsnMatcher;
3681 
3682   // No check required. G_STORE by itself is a non-extending store.
3683   if (Predicate.isNonTruncStore())
3684     return InsnMatcher;
3685 
3686   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3687     if (Predicate.getMemoryVT() != nullptr) {
3688       Optional<LLTCodeGen> MemTyOrNone =
3689           MVTToLLT(getValueType(Predicate.getMemoryVT()));
3690 
3691       if (!MemTyOrNone)
3692         return failedImport("MemVT could not be converted to LLT");
3693 
3694       // MMO's work in bytes so we must take care of unusual types like i1
3695       // don't round down.
3696       unsigned MemSizeInBits =
3697           llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3698 
3699       InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
3700                                                            MemSizeInBits / 8);
3701       return InsnMatcher;
3702     }
3703   }
3704 
3705   if (Predicate.isLoad() || Predicate.isStore()) {
3706     // No check required. A G_LOAD/G_STORE is an unindexed load.
3707     if (Predicate.isUnindexed())
3708       return InsnMatcher;
3709   }
3710 
3711   if (Predicate.isAtomic()) {
3712     if (Predicate.isAtomicOrderingMonotonic()) {
3713       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
3714       return InsnMatcher;
3715     }
3716     if (Predicate.isAtomicOrderingAcquire()) {
3717       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3718       return InsnMatcher;
3719     }
3720     if (Predicate.isAtomicOrderingRelease()) {
3721       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3722       return InsnMatcher;
3723     }
3724     if (Predicate.isAtomicOrderingAcquireRelease()) {
3725       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3726           "AcquireRelease");
3727       return InsnMatcher;
3728     }
3729     if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3730       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3731           "SequentiallyConsistent");
3732       return InsnMatcher;
3733     }
3734   }
3735 
3736   if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3737     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3738         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3739     return InsnMatcher;
3740   }
3741   if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3742     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3743         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3744     return InsnMatcher;
3745   }
3746 
3747   if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3748     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3749         "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3750     return InsnMatcher;
3751   }
3752   if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3753     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3754         "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3755     return InsnMatcher;
3756   }
3757   HasAddedMatcher = false;
3758   return InsnMatcher;
3759 }
3760 
3761 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3762     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3763     const TreePatternNode *Src, unsigned &TempOpIdx) {
3764   Record *SrcGIEquivOrNull = nullptr;
3765   const CodeGenInstruction *SrcGIOrNull = nullptr;
3766 
3767   // Start with the defined operands (i.e., the results of the root operator).
3768   if (Src->getExtTypes().size() > 1)
3769     return failedImport("Src pattern has multiple results");
3770 
3771   if (Src->isLeaf()) {
3772     Init *SrcInit = Src->getLeafValue();
3773     if (isa<IntInit>(SrcInit)) {
3774       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3775           &Target.getInstruction(RK.getDef("G_CONSTANT")));
3776     } else
3777       return failedImport(
3778           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3779   } else {
3780     SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
3781     if (!SrcGIEquivOrNull)
3782       return failedImport("Pattern operator lacks an equivalent Instruction" +
3783                           explainOperator(Src->getOperator()));
3784     SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
3785 
3786     // The operators look good: match the opcode
3787     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3788   }
3789 
3790   unsigned OpIdx = 0;
3791   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3792     // Results don't have a name unless they are the root node. The caller will
3793     // set the name if appropriate.
3794     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3795     if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3796       return failedImport(toString(std::move(Error)) +
3797                           " for result of Src pattern operator");
3798   }
3799 
3800   for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3801     const TreePredicateFn &Predicate = Call.Fn;
3802     bool HasAddedBuiltinMatcher = true;
3803     if (Predicate.isAlwaysTrue())
3804       continue;
3805 
3806     if (Predicate.isImmediatePattern()) {
3807       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3808       continue;
3809     }
3810 
3811     auto InsnMatcherOrError = addBuiltinPredicates(
3812         SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
3813     if (auto Error = InsnMatcherOrError.takeError())
3814       return std::move(Error);
3815 
3816     if (Predicate.hasGISelPredicateCode()) {
3817       InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3818       continue;
3819     }
3820     if (!HasAddedBuiltinMatcher) {
3821       return failedImport("Src pattern child has predicate (" +
3822                           explainPredicates(Src) + ")");
3823     }
3824   }
3825 
3826   bool IsAtomic = false;
3827   if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3828     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
3829   else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3830     IsAtomic = true;
3831     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3832       "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3833   }
3834 
3835   if (Src->isLeaf()) {
3836     Init *SrcInit = Src->getLeafValue();
3837     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
3838       OperandMatcher &OM =
3839           InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
3840       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3841     } else
3842       return failedImport(
3843           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3844   } else {
3845     assert(SrcGIOrNull &&
3846            "Expected to have already found an equivalent Instruction");
3847     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3848         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3849       // imm/fpimm still have operands but we don't need to do anything with it
3850       // here since we don't support ImmLeaf predicates yet. However, we still
3851       // need to note the hidden operand to get GIM_CheckNumOperands correct.
3852       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3853       return InsnMatcher;
3854     }
3855 
3856     // Special case because the operand order is changed from setcc. The
3857     // predicate operand needs to be swapped from the last operand to the first
3858     // source.
3859 
3860     unsigned NumChildren = Src->getNumChildren();
3861     bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3862 
3863     if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3864       TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3865       if (SrcChild->isLeaf()) {
3866         DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3867         Record *CCDef = DI ? DI->getDef() : nullptr;
3868         if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3869           return failedImport("Unable to handle CondCode");
3870 
3871         OperandMatcher &OM =
3872           InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3873         StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3874                                       CCDef->getValueAsString("ICmpPredicate");
3875 
3876         if (!PredType.empty()) {
3877           OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
3878           // Process the other 2 operands normally.
3879           --NumChildren;
3880         }
3881       }
3882     }
3883 
3884     // Hack around an unfortunate mistake in how atomic store (and really
3885     // atomicrmw in general) operands were ordered. A ISD::STORE used the order
3886     // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
3887     // <pointer>, <stored value>. In GlobalISel there's just the one store
3888     // opcode, so we need to swap the operands here to get the right type check.
3889     if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
3890       assert(NumChildren == 2 && "wrong operands for atomic store");
3891 
3892       TreePatternNode *PtrChild = Src->getChild(0);
3893       TreePatternNode *ValueChild = Src->getChild(1);
3894 
3895       if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
3896                                           false, 1, TempOpIdx))
3897         return std::move(Error);
3898 
3899       if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
3900                                           false, 0, TempOpIdx))
3901         return std::move(Error);
3902       return InsnMatcher;
3903     }
3904 
3905     // Match the used operands (i.e. the children of the operator).
3906     bool IsIntrinsic =
3907         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3908         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3909     const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3910     if (IsIntrinsic && !II)
3911       return failedImport("Expected IntInit containing intrinsic ID)");
3912 
3913     for (unsigned i = 0; i != NumChildren; ++i) {
3914       TreePatternNode *SrcChild = Src->getChild(i);
3915 
3916       // We need to determine the meaning of a literal integer based on the
3917       // context. If this is a field required to be an immediate (such as an
3918       // immarg intrinsic argument), the required predicates are different than
3919       // a constant which may be materialized in a register. If we have an
3920       // argument that is required to be an immediate, we should not emit an LLT
3921       // type check, and should not be looking for a G_CONSTANT defined
3922       // register.
3923       bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
3924 
3925       // SelectionDAG allows pointers to be represented with iN since it doesn't
3926       // distinguish between pointers and integers but they are different types in GlobalISel.
3927       // Coerce integers to pointers to address space 0 if the context indicates a pointer.
3928       //
3929       bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
3930 
3931       if (IsIntrinsic) {
3932         // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3933         // following the defs is an intrinsic ID.
3934         if (i == 0) {
3935           OperandMatcher &OM =
3936               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3937           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
3938           continue;
3939         }
3940 
3941         // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
3942         //
3943         // Note that we have to look at the i-1th parameter, because we don't
3944         // have the intrinsic ID in the intrinsic's parameter list.
3945         OperandIsAPointer |= II->isParamAPointer(i - 1);
3946         OperandIsImmArg |= II->isParamImmArg(i - 1);
3947       }
3948 
3949       if (auto Error =
3950               importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3951                                  OperandIsImmArg, OpIdx++, TempOpIdx))
3952         return std::move(Error);
3953     }
3954   }
3955 
3956   return InsnMatcher;
3957 }
3958 
3959 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3960     OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3961   const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3962   if (ComplexPattern == ComplexPatternEquivs.end())
3963     return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3964                         ") not mapped to GlobalISel");
3965 
3966   OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3967   TempOpIdx++;
3968   return Error::success();
3969 }
3970 
3971 // Get the name to use for a pattern operand. For an anonymous physical register
3972 // input, this should use the register name.
3973 static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3974                                  Record *&PhysReg) {
3975   StringRef SrcChildName = SrcChild->getName();
3976   if (SrcChildName.empty() && SrcChild->isLeaf()) {
3977     if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3978       auto *ChildRec = ChildDefInit->getDef();
3979       if (ChildRec->isSubClassOf("Register")) {
3980         SrcChildName = ChildRec->getName();
3981         PhysReg = ChildRec;
3982       }
3983     }
3984   }
3985 
3986   return SrcChildName;
3987 }
3988 
3989 Error GlobalISelEmitter::importChildMatcher(
3990     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3991     const TreePatternNode *SrcChild, bool OperandIsAPointer,
3992     bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
3993 
3994   Record *PhysReg = nullptr;
3995   StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3996 
3997   OperandMatcher &OM =
3998       PhysReg
3999           ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
4000           : InsnMatcher.addOperand(OpIdx, std::string(SrcChildName), TempOpIdx);
4001   if (OM.isSameAsAnotherOperand())
4002     return Error::success();
4003 
4004   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
4005   if (ChildTypes.size() != 1)
4006     return failedImport("Src pattern child has multiple results");
4007 
4008   // Check MBB's before the type check since they are not a known type.
4009   if (!SrcChild->isLeaf()) {
4010     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
4011       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
4012       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4013         OM.addPredicate<MBBOperandMatcher>();
4014         return Error::success();
4015       }
4016       if (SrcChild->getOperator()->getName() == "timm") {
4017         OM.addPredicate<ImmOperandMatcher>();
4018         return Error::success();
4019       }
4020     }
4021   }
4022 
4023   // Immediate arguments have no meaningful type to check as they don't have
4024   // registers.
4025   if (!OperandIsImmArg) {
4026     if (auto Error =
4027             OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
4028       return failedImport(toString(std::move(Error)) + " for Src operand (" +
4029                           to_string(*SrcChild) + ")");
4030   }
4031 
4032   // Check for nested instructions.
4033   if (!SrcChild->isLeaf()) {
4034     if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
4035       // When a ComplexPattern is used as an operator, it should do the same
4036       // thing as when used as a leaf. However, the children of the operator
4037       // name the sub-operands that make up the complex operand and we must
4038       // prepare to reference them in the renderer too.
4039       unsigned RendererID = TempOpIdx;
4040       if (auto Error = importComplexPatternOperandMatcher(
4041               OM, SrcChild->getOperator(), TempOpIdx))
4042         return Error;
4043 
4044       for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
4045         auto *SubOperand = SrcChild->getChild(i);
4046         if (!SubOperand->getName().empty()) {
4047           if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
4048                                                         SrcChild->getOperator(),
4049                                                         RendererID, i))
4050             return Error;
4051         }
4052       }
4053 
4054       return Error::success();
4055     }
4056 
4057     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4058         InsnMatcher.getRuleMatcher(), SrcChild->getName());
4059     if (!MaybeInsnOperand.hasValue()) {
4060       // This isn't strictly true. If the user were to provide exactly the same
4061       // matchers as the original operand then we could allow it. However, it's
4062       // simpler to not permit the redundant specification.
4063       return failedImport("Nested instruction cannot be the same as another operand");
4064     }
4065 
4066     // Map the node to a gMIR instruction.
4067     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4068     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
4069         Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
4070     if (auto Error = InsnMatcherOrError.takeError())
4071       return Error;
4072 
4073     return Error::success();
4074   }
4075 
4076   if (SrcChild->hasAnyPredicate())
4077     return failedImport("Src pattern child has unsupported predicate");
4078 
4079   // Check for constant immediates.
4080   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
4081     if (OperandIsImmArg) {
4082       // Checks for argument directly in operand list
4083       OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
4084     } else {
4085       // Checks for materialized constant
4086       OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
4087     }
4088     return Error::success();
4089   }
4090 
4091   // Check for def's like register classes or ComplexPattern's.
4092   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4093     auto *ChildRec = ChildDefInit->getDef();
4094 
4095     // Check for register classes.
4096     if (ChildRec->isSubClassOf("RegisterClass") ||
4097         ChildRec->isSubClassOf("RegisterOperand")) {
4098       OM.addPredicate<RegisterBankOperandMatcher>(
4099           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
4100       return Error::success();
4101     }
4102 
4103     if (ChildRec->isSubClassOf("Register")) {
4104       // This just be emitted as a copy to the specific register.
4105       ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
4106       const CodeGenRegisterClass *RC
4107         = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
4108       if (!RC) {
4109         return failedImport(
4110           "Could not determine physical register class of pattern source");
4111       }
4112 
4113       OM.addPredicate<RegisterBankOperandMatcher>(*RC);
4114       return Error::success();
4115     }
4116 
4117     // Check for ValueType.
4118     if (ChildRec->isSubClassOf("ValueType")) {
4119       // We already added a type check as standard practice so this doesn't need
4120       // to do anything.
4121       return Error::success();
4122     }
4123 
4124     // Check for ComplexPattern's.
4125     if (ChildRec->isSubClassOf("ComplexPattern"))
4126       return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
4127 
4128     if (ChildRec->isSubClassOf("ImmLeaf")) {
4129       return failedImport(
4130           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
4131     }
4132 
4133     // Place holder for SRCVALUE nodes. Nothing to do here.
4134     if (ChildRec->getName() == "srcvalue")
4135       return Error::success();
4136 
4137     const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
4138     if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
4139       auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4140           InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
4141       InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4142 
4143       ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
4144       InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
4145           &Target.getInstruction(RK.getDef("G_BUILD_VECTOR")));
4146 
4147       // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
4148       // theoretically not emit any opcode check, but getOpcodeMatcher currently
4149       // has to succeed.
4150       OperandMatcher &OM =
4151           InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
4152       if (auto Error =
4153               OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
4154         return failedImport(toString(std::move(Error)) +
4155                             " for result of Src pattern operator");
4156 
4157       InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
4158           ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
4159                       : VectorSplatImmPredicateMatcher::AllZeros);
4160       return Error::success();
4161     }
4162 
4163     return failedImport(
4164         "Src pattern child def is an unsupported tablegen class");
4165   }
4166 
4167   return failedImport("Src pattern child is an unsupported kind");
4168 }
4169 
4170 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4171     action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
4172     TreePatternNode *DstChild) {
4173 
4174   const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
4175   if (SubOperand.hasValue()) {
4176     DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4177         *std::get<0>(*SubOperand), DstChild->getName(),
4178         std::get<1>(*SubOperand), std::get<2>(*SubOperand));
4179     return InsertPt;
4180   }
4181 
4182   if (!DstChild->isLeaf()) {
4183     if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4184       auto Child = DstChild->getChild(0);
4185       auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
4186       if (I != SDNodeXFormEquivs.end()) {
4187         Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4188         if (XFormOpc->getName() == "timm") {
4189           // If this is a TargetConstant, there won't be a corresponding
4190           // instruction to transform. Instead, this will refer directly to an
4191           // operand in an instruction's operand list.
4192           DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4193                                                           Child->getName());
4194         } else {
4195           DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4196                                                    Child->getName());
4197         }
4198 
4199         return InsertPt;
4200       }
4201       return failedImport("SDNodeXForm " + Child->getName() +
4202                           " has no custom renderer");
4203     }
4204 
4205     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4206     // inline, but in MI it's just another operand.
4207     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4208       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
4209       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4210         DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4211         return InsertPt;
4212       }
4213     }
4214 
4215     // Similarly, imm is an operator in TreePatternNode's view but must be
4216     // rendered as operands.
4217     // FIXME: The target should be able to choose sign-extended when appropriate
4218     //        (e.g. on Mips).
4219     if (DstChild->getOperator()->getName() == "timm") {
4220       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4221       return InsertPt;
4222     } else if (DstChild->getOperator()->getName() == "imm") {
4223       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
4224       return InsertPt;
4225     } else if (DstChild->getOperator()->getName() == "fpimm") {
4226       DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
4227           DstChild->getName());
4228       return InsertPt;
4229     }
4230 
4231     if (DstChild->getOperator()->isSubClassOf("Instruction")) {
4232       auto OpTy = getInstResultType(DstChild);
4233       if (!OpTy)
4234         return OpTy.takeError();
4235 
4236       unsigned TempRegID = Rule.allocateTempRegID();
4237       InsertPt = Rule.insertAction<MakeTempRegisterAction>(
4238           InsertPt, *OpTy, TempRegID);
4239       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4240 
4241       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4242           ++InsertPt, Rule, DstChild, TempRegID);
4243       if (auto Error = InsertPtOrError.takeError())
4244         return std::move(Error);
4245       return InsertPtOrError.get();
4246     }
4247 
4248     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
4249   }
4250 
4251   // It could be a specific immediate in which case we should just check for
4252   // that immediate.
4253   if (const IntInit *ChildIntInit =
4254           dyn_cast<IntInit>(DstChild->getLeafValue())) {
4255     DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4256     return InsertPt;
4257   }
4258 
4259   // Otherwise, we're looking for a bog-standard RegisterClass operand.
4260   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
4261     auto *ChildRec = ChildDefInit->getDef();
4262 
4263     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
4264     if (ChildTypes.size() != 1)
4265       return failedImport("Dst pattern child has multiple results");
4266 
4267     Optional<LLTCodeGen> OpTyOrNone = None;
4268     if (ChildTypes.front().isMachineValueType())
4269       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
4270     if (!OpTyOrNone)
4271       return failedImport("Dst operand has an unsupported type");
4272 
4273     if (ChildRec->isSubClassOf("Register")) {
4274       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
4275       return InsertPt;
4276     }
4277 
4278     if (ChildRec->isSubClassOf("RegisterClass") ||
4279         ChildRec->isSubClassOf("RegisterOperand") ||
4280         ChildRec->isSubClassOf("ValueType")) {
4281       if (ChildRec->isSubClassOf("RegisterOperand") &&
4282           !ChildRec->isValueUnset("GIZeroRegister")) {
4283         DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
4284             DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
4285         return InsertPt;
4286       }
4287 
4288       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4289       return InsertPt;
4290     }
4291 
4292     if (ChildRec->isSubClassOf("SubRegIndex")) {
4293       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4294       DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4295       return InsertPt;
4296     }
4297 
4298     if (ChildRec->isSubClassOf("ComplexPattern")) {
4299       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4300       if (ComplexPattern == ComplexPatternEquivs.end())
4301         return failedImport(
4302             "SelectionDAG ComplexPattern not mapped to GlobalISel");
4303 
4304       const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
4305       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4306           *ComplexPattern->second, DstChild->getName(),
4307           OM.getAllocatedTemporariesBaseID());
4308       return InsertPt;
4309     }
4310 
4311     return failedImport(
4312         "Dst pattern child def is an unsupported tablegen class");
4313   }
4314 
4315   return failedImport("Dst pattern child is an unsupported kind");
4316 }
4317 
4318 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
4319     RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4320     const TreePatternNode *Dst) {
4321   auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4322   if (auto Error = InsertPtOrError.takeError())
4323     return std::move(Error);
4324 
4325   action_iterator InsertPt = InsertPtOrError.get();
4326   BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
4327 
4328   for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4329     InsertPt = M.insertAction<BuildMIAction>(
4330         InsertPt, M.allocateOutputInsnID(),
4331         &Target.getInstruction(RK.getDef("COPY")));
4332     BuildMIAction &CopyToPhysRegMIBuilder =
4333         *static_cast<BuildMIAction *>(InsertPt->get());
4334     CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4335                                                             true);
4336     CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4337   }
4338 
4339   if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
4340                        .takeError())
4341     return std::move(Error);
4342 
4343   if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4344                        .takeError())
4345     return std::move(Error);
4346 
4347   return DstMIBuilder;
4348 }
4349 
4350 Expected<action_iterator>
4351 GlobalISelEmitter::createAndImportSubInstructionRenderer(
4352     const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
4353     unsigned TempRegID) {
4354   auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4355 
4356   // TODO: Assert there's exactly one result.
4357 
4358   if (auto Error = InsertPtOrError.takeError())
4359     return std::move(Error);
4360 
4361   BuildMIAction &DstMIBuilder =
4362       *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4363 
4364   // Assign the result to TempReg.
4365   DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4366 
4367   InsertPtOrError =
4368       importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
4369   if (auto Error = InsertPtOrError.takeError())
4370     return std::move(Error);
4371 
4372   // We need to make sure that when we import an INSERT_SUBREG as a
4373   // subinstruction that it ends up being constrained to the correct super
4374   // register and subregister classes.
4375   auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4376   if (OpName == "INSERT_SUBREG") {
4377     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4378     if (!SubClass)
4379       return failedImport(
4380           "Cannot infer register class from INSERT_SUBREG operand #1");
4381     Optional<const CodeGenRegisterClass *> SuperClass =
4382         inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4383                                        Dst->getChild(2));
4384     if (!SuperClass)
4385       return failedImport(
4386           "Cannot infer register class for INSERT_SUBREG operand #0");
4387     // The destination and the super register source of an INSERT_SUBREG must
4388     // be the same register class.
4389     M.insertAction<ConstrainOperandToRegClassAction>(
4390         InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4391     M.insertAction<ConstrainOperandToRegClassAction>(
4392         InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4393     M.insertAction<ConstrainOperandToRegClassAction>(
4394         InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4395     return InsertPtOrError.get();
4396   }
4397 
4398   if (OpName == "EXTRACT_SUBREG") {
4399     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4400     // instructions, the result register class is controlled by the
4401     // subregisters of the operand. As a result, we must constrain the result
4402     // class rather than check that it's already the right one.
4403     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4404     if (!SuperClass)
4405       return failedImport(
4406         "Cannot infer register class from EXTRACT_SUBREG operand #0");
4407 
4408     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4409     if (!SubIdx)
4410       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4411 
4412     const auto SrcRCDstRCPair =
4413       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4414     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4415     M.insertAction<ConstrainOperandToRegClassAction>(
4416       InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4417     M.insertAction<ConstrainOperandToRegClassAction>(
4418       InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4419 
4420     // We're done with this pattern!  It's eligible for GISel emission; return
4421     // it.
4422     return InsertPtOrError.get();
4423   }
4424 
4425   // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4426   // subinstruction.
4427   if (OpName == "SUBREG_TO_REG") {
4428     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4429     if (!SubClass)
4430       return failedImport(
4431         "Cannot infer register class from SUBREG_TO_REG child #1");
4432     auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4433                                               Dst->getChild(2));
4434     if (!SuperClass)
4435       return failedImport(
4436         "Cannot infer register class for SUBREG_TO_REG operand #0");
4437     M.insertAction<ConstrainOperandToRegClassAction>(
4438       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4439     M.insertAction<ConstrainOperandToRegClassAction>(
4440       InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4441     return InsertPtOrError.get();
4442   }
4443 
4444   if (OpName == "REG_SEQUENCE") {
4445     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4446     M.insertAction<ConstrainOperandToRegClassAction>(
4447       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4448 
4449     unsigned Num = Dst->getNumChildren();
4450     for (unsigned I = 1; I != Num; I += 2) {
4451       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4452 
4453       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4454       if (!SubIdx)
4455         return failedImport("REG_SEQUENCE child is not a subreg index");
4456 
4457       const auto SrcRCDstRCPair =
4458         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4459       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4460       M.insertAction<ConstrainOperandToRegClassAction>(
4461         InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4462     }
4463 
4464     return InsertPtOrError.get();
4465   }
4466 
4467   M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4468                                                       DstMIBuilder.getInsnID());
4469   return InsertPtOrError.get();
4470 }
4471 
4472 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
4473     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4474   Record *DstOp = Dst->getOperator();
4475   if (!DstOp->isSubClassOf("Instruction")) {
4476     if (DstOp->isSubClassOf("ValueType"))
4477       return failedImport(
4478           "Pattern operator isn't an instruction (it's a ValueType)");
4479     return failedImport("Pattern operator isn't an instruction");
4480   }
4481   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
4482 
4483   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
4484   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
4485   StringRef Name = DstI->TheDef->getName();
4486   if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
4487     DstI = &Target.getInstruction(RK.getDef("COPY"));
4488 
4489   return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4490                                        DstI);
4491 }
4492 
4493 Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
4494     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4495     const TreePatternNode *Dst) {
4496   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4497   const unsigned NumDefs = DstI->Operands.NumDefs;
4498   if (NumDefs == 0)
4499     return InsertPt;
4500 
4501   DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
4502 
4503   // Some instructions have multiple defs, but are missing a type entry
4504   // (e.g. s_cc_out operands).
4505   if (Dst->getExtTypes().size() < NumDefs)
4506     return failedImport("unhandled discarded def");
4507 
4508   // Patterns only handle a single result, so any result after the first is an
4509   // implicitly dead def.
4510   for (unsigned I = 1; I < NumDefs; ++I) {
4511     const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
4512     if (!ExtTy.isMachineValueType())
4513       return failedImport("unsupported typeset");
4514 
4515     auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
4516     if (!OpTy)
4517       return failedImport("unsupported type");
4518 
4519     unsigned TempRegID = M.allocateTempRegID();
4520     InsertPt =
4521       M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
4522     DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
4523   }
4524 
4525   return InsertPt;
4526 }
4527 
4528 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4529     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4530     const llvm::TreePatternNode *Dst) {
4531   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4532   CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
4533 
4534   StringRef Name = OrigDstI->TheDef->getName();
4535   unsigned ExpectedDstINumUses = Dst->getNumChildren();
4536 
4537   // EXTRACT_SUBREG needs to use a subregister COPY.
4538   if (Name == "EXTRACT_SUBREG") {
4539     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4540     if (!SubRegInit)
4541       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4542 
4543     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4544     TreePatternNode *ValChild = Dst->getChild(0);
4545     if (!ValChild->isLeaf()) {
4546       // We really have to handle the source instruction, and then insert a
4547       // copy from the subregister.
4548       auto ExtractSrcTy = getInstResultType(ValChild);
4549       if (!ExtractSrcTy)
4550         return ExtractSrcTy.takeError();
4551 
4552       unsigned TempRegID = M.allocateTempRegID();
4553       InsertPt = M.insertAction<MakeTempRegisterAction>(
4554         InsertPt, *ExtractSrcTy, TempRegID);
4555 
4556       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4557         ++InsertPt, M, ValChild, TempRegID);
4558       if (auto Error = InsertPtOrError.takeError())
4559         return std::move(Error);
4560 
4561       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
4562       return InsertPt;
4563     }
4564 
4565     // If this is a source operand, this is just a subregister copy.
4566     Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4567     if (!RCDef)
4568       return failedImport("EXTRACT_SUBREG child #0 could not "
4569                           "be coerced to a register class");
4570 
4571     CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4572 
4573     const auto SrcRCDstRCPair =
4574       RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4575     if (SrcRCDstRCPair.hasValue()) {
4576       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4577       if (SrcRCDstRCPair->first != RC)
4578         return failedImport("EXTRACT_SUBREG requires an additional COPY");
4579     }
4580 
4581     DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4582                                                  SubIdx);
4583     return InsertPt;
4584   }
4585 
4586   if (Name == "REG_SEQUENCE") {
4587     if (!Dst->getChild(0)->isLeaf())
4588       return failedImport("REG_SEQUENCE child #0 is not a leaf");
4589 
4590     Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4591     if (!RCDef)
4592       return failedImport("REG_SEQUENCE child #0 could not "
4593                           "be coerced to a register class");
4594 
4595     if ((ExpectedDstINumUses - 1) % 2 != 0)
4596       return failedImport("Malformed REG_SEQUENCE");
4597 
4598     for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4599       TreePatternNode *ValChild = Dst->getChild(I);
4600       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4601 
4602       if (DefInit *SubRegInit =
4603               dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4604         CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4605 
4606         auto InsertPtOrError =
4607             importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4608         if (auto Error = InsertPtOrError.takeError())
4609           return std::move(Error);
4610         InsertPt = InsertPtOrError.get();
4611         DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4612       }
4613     }
4614 
4615     return InsertPt;
4616   }
4617 
4618   // Render the explicit uses.
4619   unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
4620   if (Name == "COPY_TO_REGCLASS") {
4621     DstINumUses--; // Ignore the class constraint.
4622     ExpectedDstINumUses--;
4623   }
4624 
4625   // NumResults - This is the number of results produced by the instruction in
4626   // the "outs" list.
4627   unsigned NumResults = OrigDstI->Operands.NumDefs;
4628 
4629   // Number of operands we know the output instruction must have. If it is
4630   // variadic, we could have more operands.
4631   unsigned NumFixedOperands = DstI->Operands.size();
4632 
4633   // Loop over all of the fixed operands of the instruction pattern, emitting
4634   // code to fill them all in. The node 'N' usually has number children equal to
4635   // the number of input operands of the instruction.  However, in cases where
4636   // there are predicate operands for an instruction, we need to fill in the
4637   // 'execute always' values. Match up the node operands to the instruction
4638   // operands to do this.
4639   unsigned Child = 0;
4640 
4641   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4642   // number of operands at the end of the list which have default values.
4643   // Those can come from the pattern if it provides enough arguments, or be
4644   // filled in with the default if the pattern hasn't provided them. But any
4645   // operand with a default value _before_ the last mandatory one will be
4646   // filled in with their defaults unconditionally.
4647   unsigned NonOverridableOperands = NumFixedOperands;
4648   while (NonOverridableOperands > NumResults &&
4649          CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4650     --NonOverridableOperands;
4651 
4652   unsigned NumDefaultOps = 0;
4653   for (unsigned I = 0; I != DstINumUses; ++I) {
4654     unsigned InstOpNo = DstI->Operands.NumDefs + I;
4655 
4656     // Determine what to emit for this operand.
4657     Record *OperandNode = DstI->Operands[InstOpNo].Rec;
4658 
4659     // If the operand has default values, introduce them now.
4660     if (CGP.operandHasDefault(OperandNode) &&
4661         (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4662       // This is a predicate or optional def operand which the pattern has not
4663       // overridden, or which we aren't letting it override; emit the 'default
4664       // ops' operands.
4665 
4666       const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
4667       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
4668       if (auto Error = importDefaultOperandRenderers(
4669             InsertPt, M, DstMIBuilder, DefaultOps))
4670         return std::move(Error);
4671       ++NumDefaultOps;
4672       continue;
4673     }
4674 
4675     auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
4676                                                      Dst->getChild(Child));
4677     if (auto Error = InsertPtOrError.takeError())
4678       return std::move(Error);
4679     InsertPt = InsertPtOrError.get();
4680     ++Child;
4681   }
4682 
4683   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
4684     return failedImport("Expected " + llvm::to_string(DstINumUses) +
4685                         " used operands but found " +
4686                         llvm::to_string(ExpectedDstINumUses) +
4687                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
4688                         " default ones");
4689 
4690   return InsertPt;
4691 }
4692 
4693 Error GlobalISelEmitter::importDefaultOperandRenderers(
4694     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4695     DagInit *DefaultOps) const {
4696   for (const auto *DefaultOp : DefaultOps->getArgs()) {
4697     Optional<LLTCodeGen> OpTyOrNone = None;
4698 
4699     // Look through ValueType operators.
4700     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4701       if (const DefInit *DefaultDagOperator =
4702               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
4703         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
4704           OpTyOrNone = MVTToLLT(getValueType(
4705                                   DefaultDagOperator->getDef()));
4706           DefaultOp = DefaultDagOp->getArg(0);
4707         }
4708       }
4709     }
4710 
4711     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
4712       auto Def = DefaultDefOp->getDef();
4713       if (Def->getName() == "undef_tied_input") {
4714         unsigned TempRegID = M.allocateTempRegID();
4715         M.insertAction<MakeTempRegisterAction>(
4716           InsertPt, OpTyOrNone.getValue(), TempRegID);
4717         InsertPt = M.insertAction<BuildMIAction>(
4718           InsertPt, M.allocateOutputInsnID(),
4719           &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4720         BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4721           InsertPt->get());
4722         IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4723         DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4724       } else {
4725         DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4726       }
4727       continue;
4728     }
4729 
4730     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
4731       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
4732       continue;
4733     }
4734 
4735     return failedImport("Could not add default op");
4736   }
4737 
4738   return Error::success();
4739 }
4740 
4741 Error GlobalISelEmitter::importImplicitDefRenderers(
4742     BuildMIAction &DstMIBuilder,
4743     const std::vector<Record *> &ImplicitDefs) const {
4744   if (!ImplicitDefs.empty())
4745     return failedImport("Pattern defines a physical register");
4746   return Error::success();
4747 }
4748 
4749 Optional<const CodeGenRegisterClass *>
4750 GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4751   assert(Leaf && "Expected node?");
4752   assert(Leaf->isLeaf() && "Expected leaf?");
4753   Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4754   if (!RCRec)
4755     return None;
4756   CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4757   if (!RC)
4758     return None;
4759   return RC;
4760 }
4761 
4762 Optional<const CodeGenRegisterClass *>
4763 GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4764   if (!N)
4765     return None;
4766 
4767   if (N->isLeaf())
4768     return getRegClassFromLeaf(N);
4769 
4770   // We don't have a leaf node, so we have to try and infer something. Check
4771   // that we have an instruction that we an infer something from.
4772 
4773   // Only handle things that produce a single type.
4774   if (N->getNumTypes() != 1)
4775     return None;
4776   Record *OpRec = N->getOperator();
4777 
4778   // We only want instructions.
4779   if (!OpRec->isSubClassOf("Instruction"))
4780     return None;
4781 
4782   // Don't want to try and infer things when there could potentially be more
4783   // than one candidate register class.
4784   auto &Inst = Target.getInstruction(OpRec);
4785   if (Inst.Operands.NumDefs > 1)
4786     return None;
4787 
4788   // Handle any special-case instructions which we can safely infer register
4789   // classes from.
4790   StringRef InstName = Inst.TheDef->getName();
4791   bool IsRegSequence = InstName == "REG_SEQUENCE";
4792   if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
4793     // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4794     // has the desired register class as the first child.
4795     TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
4796     if (!RCChild->isLeaf())
4797       return None;
4798     return getRegClassFromLeaf(RCChild);
4799   }
4800 
4801   // Handle destination record types that we can safely infer a register class
4802   // from.
4803   const auto &DstIOperand = Inst.Operands[0];
4804   Record *DstIOpRec = DstIOperand.Rec;
4805   if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4806     DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4807     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4808     return &RC;
4809   }
4810 
4811   if (DstIOpRec->isSubClassOf("RegisterClass")) {
4812     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4813     return &RC;
4814   }
4815 
4816   return None;
4817 }
4818 
4819 Optional<const CodeGenRegisterClass *>
4820 GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
4821                                            TreePatternNode *SubRegIdxNode) {
4822   assert(SubRegIdxNode && "Expected subregister index node!");
4823   // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4824   if (!Ty.isValueTypeByHwMode(false))
4825     return None;
4826   if (!SubRegIdxNode->isLeaf())
4827     return None;
4828   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4829   if (!SubRegInit)
4830     return None;
4831   CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4832 
4833   // Use the information we found above to find a minimal register class which
4834   // supports the subregister and type we want.
4835   auto RC =
4836       Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4837   if (!RC)
4838     return None;
4839   return *RC;
4840 }
4841 
4842 Optional<const CodeGenRegisterClass *>
4843 GlobalISelEmitter::inferSuperRegisterClassForNode(
4844     const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4845     TreePatternNode *SubRegIdxNode) {
4846   assert(SuperRegNode && "Expected super register node!");
4847   // Check if we already have a defined register class for the super register
4848   // node. If we do, then we should preserve that rather than inferring anything
4849   // from the subregister index node. We can assume that whoever wrote the
4850   // pattern in the first place made sure that the super register and
4851   // subregister are compatible.
4852   if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4853           inferRegClassFromPattern(SuperRegNode))
4854     return *SuperRegisterClass;
4855   return inferSuperRegisterClass(Ty, SubRegIdxNode);
4856 }
4857 
4858 Optional<CodeGenSubRegIndex *>
4859 GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4860   if (!SubRegIdxNode->isLeaf())
4861     return None;
4862 
4863   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4864   if (!SubRegInit)
4865     return None;
4866   return CGRegs.getSubRegIdx(SubRegInit->getDef());
4867 }
4868 
4869 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
4870   // Keep track of the matchers and actions to emit.
4871   int Score = P.getPatternComplexity(CGP);
4872   RuleMatcher M(P.getSrcRecord()->getLoc());
4873   RuleMatcherScores[M.getRuleID()] = Score;
4874   M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4875                                   "  =>  " +
4876                                   llvm::to_string(*P.getDstPattern()));
4877 
4878   if (auto Error = importRulePredicates(M, P.getPredicates()))
4879     return std::move(Error);
4880 
4881   // Next, analyze the pattern operators.
4882   TreePatternNode *Src = P.getSrcPattern();
4883   TreePatternNode *Dst = P.getDstPattern();
4884 
4885   // If the root of either pattern isn't a simple operator, ignore it.
4886   if (auto Err = isTrivialOperatorNode(Dst))
4887     return failedImport("Dst pattern root isn't a trivial operator (" +
4888                         toString(std::move(Err)) + ")");
4889   if (auto Err = isTrivialOperatorNode(Src))
4890     return failedImport("Src pattern root isn't a trivial operator (" +
4891                         toString(std::move(Err)) + ")");
4892 
4893   // The different predicates and matchers created during
4894   // addInstructionMatcher use the RuleMatcher M to set up their
4895   // instruction ID (InsnVarID) that are going to be used when
4896   // M is going to be emitted.
4897   // However, the code doing the emission still relies on the IDs
4898   // returned during that process by the RuleMatcher when issuing
4899   // the recordInsn opcodes.
4900   // Because of that:
4901   // 1. The order in which we created the predicates
4902   //    and such must be the same as the order in which we emit them,
4903   //    and
4904   // 2. We need to reset the generation of the IDs in M somewhere between
4905   //    addInstructionMatcher and emit
4906   //
4907   // FIXME: Long term, we don't want to have to rely on this implicit
4908   // naming being the same. One possible solution would be to have
4909   // explicit operator for operation capture and reference those.
4910   // The plus side is that it would expose opportunities to share
4911   // the capture accross rules. The downside is that it would
4912   // introduce a dependency between predicates (captures must happen
4913   // before their first use.)
4914   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
4915   unsigned TempOpIdx = 0;
4916   auto InsnMatcherOrError =
4917       createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
4918   if (auto Error = InsnMatcherOrError.takeError())
4919     return std::move(Error);
4920   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4921 
4922   if (Dst->isLeaf()) {
4923     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
4924 
4925     const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4926     if (RCDef) {
4927       // We need to replace the def and all its uses with the specified
4928       // operand. However, we must also insert COPY's wherever needed.
4929       // For now, emit a copy and let the register allocator clean up.
4930       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4931       const auto &DstIOperand = DstI.Operands[0];
4932 
4933       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4934       OM0.setSymbolicName(DstIOperand.Name);
4935       M.defineOperand(OM0.getSymbolicName(), OM0);
4936       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4937 
4938       auto &DstMIBuilder =
4939           M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4940       DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
4941       DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
4942       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4943 
4944       // We're done with this pattern!  It's eligible for GISel emission; return
4945       // it.
4946       ++NumPatternImported;
4947       return std::move(M);
4948     }
4949 
4950     return failedImport("Dst pattern root isn't a known leaf");
4951   }
4952 
4953   // Start with the defined operands (i.e., the results of the root operator).
4954   Record *DstOp = Dst->getOperator();
4955   if (!DstOp->isSubClassOf("Instruction"))
4956     return failedImport("Pattern operator isn't an instruction");
4957 
4958   auto &DstI = Target.getInstruction(DstOp);
4959   StringRef DstIName = DstI.TheDef->getName();
4960 
4961   if (DstI.Operands.NumDefs < Src->getExtTypes().size())
4962     return failedImport("Src pattern result has more defs than dst MI (" +
4963                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
4964                         to_string(DstI.Operands.NumDefs) + " def(s))");
4965 
4966   // The root of the match also has constraints on the register bank so that it
4967   // matches the result instruction.
4968   unsigned OpIdx = 0;
4969   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
4970     (void)VTy;
4971 
4972     const auto &DstIOperand = DstI.Operands[OpIdx];
4973     Record *DstIOpRec = DstIOperand.Rec;
4974     if (DstIName == "COPY_TO_REGCLASS") {
4975       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
4976 
4977       if (DstIOpRec == nullptr)
4978         return failedImport(
4979             "COPY_TO_REGCLASS operand #1 isn't a register class");
4980     } else if (DstIName == "REG_SEQUENCE") {
4981       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4982       if (DstIOpRec == nullptr)
4983         return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4984     } else if (DstIName == "EXTRACT_SUBREG") {
4985       auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
4986       if (!InferredClass)
4987         return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
4988 
4989       // We can assume that a subregister is in the same bank as it's super
4990       // register.
4991       DstIOpRec = (*InferredClass)->getDef();
4992     } else if (DstIName == "INSERT_SUBREG") {
4993       auto MaybeSuperClass = inferSuperRegisterClassForNode(
4994           VTy, Dst->getChild(0), Dst->getChild(2));
4995       if (!MaybeSuperClass)
4996         return failedImport(
4997             "Cannot infer register class for INSERT_SUBREG operand #0");
4998       // Move to the next pattern here, because the register class we found
4999       // doesn't necessarily have a record associated with it. So, we can't
5000       // set DstIOpRec using this.
5001       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5002       OM.setSymbolicName(DstIOperand.Name);
5003       M.defineOperand(OM.getSymbolicName(), OM);
5004       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
5005       ++OpIdx;
5006       continue;
5007     } else if (DstIName == "SUBREG_TO_REG") {
5008       auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
5009       if (!MaybeRegClass)
5010         return failedImport(
5011             "Cannot infer register class for SUBREG_TO_REG operand #0");
5012       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5013       OM.setSymbolicName(DstIOperand.Name);
5014       M.defineOperand(OM.getSymbolicName(), OM);
5015       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
5016       ++OpIdx;
5017       continue;
5018     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
5019       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
5020     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
5021       return failedImport("Dst MI def isn't a register class" +
5022                           to_string(*Dst));
5023 
5024     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5025     OM.setSymbolicName(DstIOperand.Name);
5026     M.defineOperand(OM.getSymbolicName(), OM);
5027     OM.addPredicate<RegisterBankOperandMatcher>(
5028         Target.getRegisterClass(DstIOpRec));
5029     ++OpIdx;
5030   }
5031 
5032   auto DstMIBuilderOrError =
5033       createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
5034   if (auto Error = DstMIBuilderOrError.takeError())
5035     return std::move(Error);
5036   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
5037 
5038   // Render the implicit defs.
5039   // These are only added to the root of the result.
5040   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
5041     return std::move(Error);
5042 
5043   DstMIBuilder.chooseInsnToMutate(M);
5044 
5045   // Constrain the registers to classes. This is normally derived from the
5046   // emitted instruction but a few instructions require special handling.
5047   if (DstIName == "COPY_TO_REGCLASS") {
5048     // COPY_TO_REGCLASS does not provide operand constraints itself but the
5049     // result is constrained to the class given by the second child.
5050     Record *DstIOpRec =
5051         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
5052 
5053     if (DstIOpRec == nullptr)
5054       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
5055 
5056     M.addAction<ConstrainOperandToRegClassAction>(
5057         0, 0, Target.getRegisterClass(DstIOpRec));
5058 
5059     // We're done with this pattern!  It's eligible for GISel emission; return
5060     // it.
5061     ++NumPatternImported;
5062     return std::move(M);
5063   }
5064 
5065   if (DstIName == "EXTRACT_SUBREG") {
5066     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5067     if (!SuperClass)
5068       return failedImport(
5069         "Cannot infer register class from EXTRACT_SUBREG operand #0");
5070 
5071     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
5072     if (!SubIdx)
5073       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
5074 
5075     // It would be nice to leave this constraint implicit but we're required
5076     // to pick a register class so constrain the result to a register class
5077     // that can hold the correct MVT.
5078     //
5079     // FIXME: This may introduce an extra copy if the chosen class doesn't
5080     //        actually contain the subregisters.
5081     assert(Src->getExtTypes().size() == 1 &&
5082              "Expected Src of EXTRACT_SUBREG to have one result type");
5083 
5084     const auto SrcRCDstRCPair =
5085       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5086     if (!SrcRCDstRCPair) {
5087       return failedImport("subreg index is incompatible "
5088                           "with inferred reg class");
5089     }
5090 
5091     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
5092     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
5093     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
5094 
5095     // We're done with this pattern!  It's eligible for GISel emission; return
5096     // it.
5097     ++NumPatternImported;
5098     return std::move(M);
5099   }
5100 
5101   if (DstIName == "INSERT_SUBREG") {
5102     assert(Src->getExtTypes().size() == 1 &&
5103            "Expected Src of INSERT_SUBREG to have one result type");
5104     // We need to constrain the destination, a super regsister source, and a
5105     // subregister source.
5106     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5107     if (!SubClass)
5108       return failedImport(
5109           "Cannot infer register class from INSERT_SUBREG operand #1");
5110     auto SuperClass = inferSuperRegisterClassForNode(
5111         Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
5112     if (!SuperClass)
5113       return failedImport(
5114           "Cannot infer register class for INSERT_SUBREG operand #0");
5115     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5116     M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
5117     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5118     ++NumPatternImported;
5119     return std::move(M);
5120   }
5121 
5122   if (DstIName == "SUBREG_TO_REG") {
5123     // We need to constrain the destination and subregister source.
5124     assert(Src->getExtTypes().size() == 1 &&
5125            "Expected Src of SUBREG_TO_REG to have one result type");
5126 
5127     // Attempt to infer the subregister source from the first child. If it has
5128     // an explicitly given register class, we'll use that. Otherwise, we will
5129     // fail.
5130     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5131     if (!SubClass)
5132       return failedImport(
5133           "Cannot infer register class from SUBREG_TO_REG child #1");
5134     // We don't have a child to look at that might have a super register node.
5135     auto SuperClass =
5136         inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
5137     if (!SuperClass)
5138       return failedImport(
5139           "Cannot infer register class for SUBREG_TO_REG operand #0");
5140     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5141     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5142     ++NumPatternImported;
5143     return std::move(M);
5144   }
5145 
5146   if (DstIName == "REG_SEQUENCE") {
5147     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5148 
5149     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5150 
5151     unsigned Num = Dst->getNumChildren();
5152     for (unsigned I = 1; I != Num; I += 2) {
5153       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
5154 
5155       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
5156       if (!SubIdx)
5157         return failedImport("REG_SEQUENCE child is not a subreg index");
5158 
5159       const auto SrcRCDstRCPair =
5160         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5161 
5162       M.addAction<ConstrainOperandToRegClassAction>(0, I,
5163                                                     *SrcRCDstRCPair->second);
5164     }
5165 
5166     ++NumPatternImported;
5167     return std::move(M);
5168   }
5169 
5170   M.addAction<ConstrainOperandsToDefinitionAction>(0);
5171 
5172   // We're done with this pattern!  It's eligible for GISel emission; return it.
5173   ++NumPatternImported;
5174   return std::move(M);
5175 }
5176 
5177 // Emit imm predicate table and an enum to reference them with.
5178 // The 'Predicate_' part of the name is redundant but eliminating it is more
5179 // trouble than it's worth.
5180 void GlobalISelEmitter::emitCxxPredicateFns(
5181     raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
5182     StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
5183     std::function<bool(const Record *R)> Filter) {
5184   std::vector<const Record *> MatchedRecords;
5185   const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
5186   std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5187                [&](Record *Record) {
5188                  return !Record->getValueAsString(CodeFieldName).empty() &&
5189                         Filter(Record);
5190                });
5191 
5192   if (!MatchedRecords.empty()) {
5193     OS << "// PatFrag predicates.\n"
5194        << "enum {\n";
5195     std::string EnumeratorSeparator =
5196         (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5197     for (const auto *Record : MatchedRecords) {
5198       OS << "  GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5199          << EnumeratorSeparator;
5200       EnumeratorSeparator = ",\n";
5201     }
5202     OS << "};\n";
5203   }
5204 
5205   OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5206      << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
5207      << ArgName << ") const {\n"
5208      << AdditionalDeclarations;
5209   if (!AdditionalDeclarations.empty())
5210     OS << "\n";
5211   if (!MatchedRecords.empty())
5212     OS << "  switch (PredicateID) {\n";
5213   for (const auto *Record : MatchedRecords) {
5214     OS << "  case GIPFP_" << TypeIdentifier << "_Predicate_"
5215        << Record->getName() << ": {\n"
5216        << "    " << Record->getValueAsString(CodeFieldName) << "\n"
5217        << "    llvm_unreachable(\"" << CodeFieldName
5218        << " should have returned\");\n"
5219        << "    return false;\n"
5220        << "  }\n";
5221   }
5222   if (!MatchedRecords.empty())
5223     OS << "  }\n";
5224   OS << "  llvm_unreachable(\"Unknown predicate\");\n"
5225      << "  return false;\n"
5226      << "}\n";
5227 }
5228 
5229 void GlobalISelEmitter::emitImmPredicateFns(
5230     raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5231     std::function<bool(const Record *R)> Filter) {
5232   return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
5233                              "Imm", "", Filter);
5234 }
5235 
5236 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5237   return emitCxxPredicateFns(
5238       OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
5239       "  const MachineFunction &MF = *MI.getParent()->getParent();\n"
5240       "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5241       "  (void)MRI;",
5242       [](const Record *R) { return true; });
5243 }
5244 
5245 template <class GroupT>
5246 std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
5247     ArrayRef<Matcher *> Rules,
5248     std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5249 
5250   std::vector<Matcher *> OptRules;
5251   std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
5252   assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5253   unsigned NumGroups = 0;
5254 
5255   auto ProcessCurrentGroup = [&]() {
5256     if (CurrentGroup->empty())
5257       // An empty group is good to be reused:
5258       return;
5259 
5260     // If the group isn't large enough to provide any benefit, move all the
5261     // added rules out of it and make sure to re-create the group to properly
5262     // re-initialize it:
5263     if (CurrentGroup->size() < 2)
5264       for (Matcher *M : CurrentGroup->matchers())
5265         OptRules.push_back(M);
5266     else {
5267       CurrentGroup->finalize();
5268       OptRules.push_back(CurrentGroup.get());
5269       MatcherStorage.emplace_back(std::move(CurrentGroup));
5270       ++NumGroups;
5271     }
5272     CurrentGroup = std::make_unique<GroupT>();
5273   };
5274   for (Matcher *Rule : Rules) {
5275     // Greedily add as many matchers as possible to the current group:
5276     if (CurrentGroup->addMatcher(*Rule))
5277       continue;
5278 
5279     ProcessCurrentGroup();
5280     assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5281 
5282     // Try to add the pending matcher to a newly created empty group:
5283     if (!CurrentGroup->addMatcher(*Rule))
5284       // If we couldn't add the matcher to an empty group, that group type
5285       // doesn't support that kind of matchers at all, so just skip it:
5286       OptRules.push_back(Rule);
5287   }
5288   ProcessCurrentGroup();
5289 
5290   LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
5291   assert(CurrentGroup->empty() && "The last group wasn't properly processed");
5292   return OptRules;
5293 }
5294 
5295 MatchTable
5296 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
5297                                    bool Optimize, bool WithCoverage) {
5298   std::vector<Matcher *> InputRules;
5299   for (Matcher &Rule : Rules)
5300     InputRules.push_back(&Rule);
5301 
5302   if (!Optimize)
5303     return MatchTable::buildTable(InputRules, WithCoverage);
5304 
5305   unsigned CurrentOrdering = 0;
5306   StringMap<unsigned> OpcodeOrder;
5307   for (RuleMatcher &Rule : Rules) {
5308     const StringRef Opcode = Rule.getOpcode();
5309     assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5310     if (OpcodeOrder.count(Opcode) == 0)
5311       OpcodeOrder[Opcode] = CurrentOrdering++;
5312   }
5313 
5314   std::stable_sort(InputRules.begin(), InputRules.end(),
5315                    [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5316                      auto *L = static_cast<const RuleMatcher *>(A);
5317                      auto *R = static_cast<const RuleMatcher *>(B);
5318                      return std::make_tuple(OpcodeOrder[L->getOpcode()],
5319                                             L->getNumOperands()) <
5320                             std::make_tuple(OpcodeOrder[R->getOpcode()],
5321                                             R->getNumOperands());
5322                    });
5323 
5324   for (Matcher *Rule : InputRules)
5325     Rule->optimize();
5326 
5327   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
5328   std::vector<Matcher *> OptRules =
5329       optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5330 
5331   for (Matcher *Rule : OptRules)
5332     Rule->optimize();
5333 
5334   OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5335 
5336   return MatchTable::buildTable(OptRules, WithCoverage);
5337 }
5338 
5339 void GroupMatcher::optimize() {
5340   // Make sure we only sort by a specific predicate within a range of rules that
5341   // all have that predicate checked against a specific value (not a wildcard):
5342   auto F = Matchers.begin();
5343   auto T = F;
5344   auto E = Matchers.end();
5345   while (T != E) {
5346     while (T != E) {
5347       auto *R = static_cast<RuleMatcher *>(*T);
5348       if (!R->getFirstConditionAsRootType().get().isValid())
5349         break;
5350       ++T;
5351     }
5352     std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5353       auto *L = static_cast<RuleMatcher *>(A);
5354       auto *R = static_cast<RuleMatcher *>(B);
5355       return L->getFirstConditionAsRootType() <
5356              R->getFirstConditionAsRootType();
5357     });
5358     if (T != E)
5359       F = ++T;
5360   }
5361   GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5362       .swap(Matchers);
5363   GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5364       .swap(Matchers);
5365 }
5366 
5367 void GlobalISelEmitter::run(raw_ostream &OS) {
5368   if (!UseCoverageFile.empty()) {
5369     RuleCoverage = CodeGenCoverage();
5370     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5371     if (!RuleCoverageBufOrErr) {
5372       PrintWarning(SMLoc(), "Missing rule coverage data");
5373       RuleCoverage = None;
5374     } else {
5375       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5376         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5377         RuleCoverage = None;
5378       }
5379     }
5380   }
5381 
5382   // Track the run-time opcode values
5383   gatherOpcodeValues();
5384   // Track the run-time LLT ID values
5385   gatherTypeIDValues();
5386 
5387   // Track the GINodeEquiv definitions.
5388   gatherNodeEquivs();
5389 
5390   emitSourceFileHeader(("Global Instruction Selector for the " +
5391                        Target.getName() + " target").str(), OS);
5392   std::vector<RuleMatcher> Rules;
5393   // Look through the SelectionDAG patterns we found, possibly emitting some.
5394   for (const PatternToMatch &Pat : CGP.ptms()) {
5395     ++NumPatternTotal;
5396 
5397     auto MatcherOrErr = runOnPattern(Pat);
5398 
5399     // The pattern analysis can fail, indicating an unsupported pattern.
5400     // Report that if we've been asked to do so.
5401     if (auto Err = MatcherOrErr.takeError()) {
5402       if (WarnOnSkippedPatterns) {
5403         PrintWarning(Pat.getSrcRecord()->getLoc(),
5404                      "Skipped pattern: " + toString(std::move(Err)));
5405       } else {
5406         consumeError(std::move(Err));
5407       }
5408       ++NumPatternImportsSkipped;
5409       continue;
5410     }
5411 
5412     if (RuleCoverage) {
5413       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5414         ++NumPatternsTested;
5415       else
5416         PrintWarning(Pat.getSrcRecord()->getLoc(),
5417                      "Pattern is not covered by a test");
5418     }
5419     Rules.push_back(std::move(MatcherOrErr.get()));
5420   }
5421 
5422   // Comparison function to order records by name.
5423   auto orderByName = [](const Record *A, const Record *B) {
5424     return A->getName() < B->getName();
5425   };
5426 
5427   std::vector<Record *> ComplexPredicates =
5428       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
5429   llvm::sort(ComplexPredicates, orderByName);
5430 
5431   std::vector<Record *> CustomRendererFns =
5432       RK.getAllDerivedDefinitions("GICustomOperandRenderer");
5433   llvm::sort(CustomRendererFns, orderByName);
5434 
5435   unsigned MaxTemporaries = 0;
5436   for (const auto &Rule : Rules)
5437     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
5438 
5439   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5440      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5441      << ";\n"
5442      << "using PredicateBitset = "
5443         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5444      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5445 
5446   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5447      << "  mutable MatcherState State;\n"
5448      << "  typedef "
5449         "ComplexRendererFns("
5450      << Target.getName()
5451      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
5452 
5453      << "  typedef void(" << Target.getName()
5454      << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5455         "MachineInstr&, int) "
5456         "const;\n"
5457      << "  const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5458         "CustomRendererFn> "
5459         "ISelInfo;\n";
5460   OS << "  static " << Target.getName()
5461      << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
5462      << "  static " << Target.getName()
5463      << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
5464      << "  bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
5465         "override;\n"
5466      << "  bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
5467         "const override;\n"
5468      << "  bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
5469         "&Imm) const override;\n"
5470      << "  const int64_t *getMatchTable() const override;\n"
5471      << "  bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5472         "const override;\n"
5473      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
5474 
5475   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5476      << ", State(" << MaxTemporaries << "),\n"
5477      << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5478      << ", ComplexPredicateFns, CustomRenderers)\n"
5479      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
5480 
5481   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5482   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5483                                                            OS);
5484 
5485   // Separate subtarget features by how often they must be recomputed.
5486   SubtargetFeatureInfoMap ModuleFeatures;
5487   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5488                std::inserter(ModuleFeatures, ModuleFeatures.end()),
5489                [](const SubtargetFeatureInfoMap::value_type &X) {
5490                  return !X.second.mustRecomputePerFunction();
5491                });
5492   SubtargetFeatureInfoMap FunctionFeatures;
5493   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5494                std::inserter(FunctionFeatures, FunctionFeatures.end()),
5495                [](const SubtargetFeatureInfoMap::value_type &X) {
5496                  return X.second.mustRecomputePerFunction();
5497                });
5498 
5499   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5500     Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5501       ModuleFeatures, OS);
5502 
5503 
5504   OS << "void " << Target.getName() << "InstructionSelector"
5505     "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5506     "  AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5507     "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5508     "}\n";
5509 
5510   if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5511     // TODO: Implement PGSO.
5512     OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5513     OS << "    return MF->getFunction().hasOptSize();\n";
5514     OS << "}\n\n";
5515   }
5516 
5517   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5518       Target.getName(), "InstructionSelector",
5519       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5520       "const MachineFunction *MF");
5521 
5522   // Emit a table containing the LLT objects needed by the matcher and an enum
5523   // for the matcher to reference them with.
5524   std::vector<LLTCodeGen> TypeObjects;
5525   for (const auto &Ty : KnownTypes)
5526     TypeObjects.push_back(Ty);
5527   llvm::sort(TypeObjects);
5528   OS << "// LLT Objects.\n"
5529      << "enum {\n";
5530   for (const auto &TypeObject : TypeObjects) {
5531     OS << "  ";
5532     TypeObject.emitCxxEnumValue(OS);
5533     OS << ",\n";
5534   }
5535   OS << "};\n";
5536   OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
5537      << "const static LLT TypeObjects[] = {\n";
5538   for (const auto &TypeObject : TypeObjects) {
5539     OS << "  ";
5540     TypeObject.emitCxxConstructorCall(OS);
5541     OS << ",\n";
5542   }
5543   OS << "};\n\n";
5544 
5545   // Emit a table containing the PredicateBitsets objects needed by the matcher
5546   // and an enum for the matcher to reference them with.
5547   std::vector<std::vector<Record *>> FeatureBitsets;
5548   for (auto &Rule : Rules)
5549     FeatureBitsets.push_back(Rule.getRequiredFeatures());
5550   llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5551                                  const std::vector<Record *> &B) {
5552     if (A.size() < B.size())
5553       return true;
5554     if (A.size() > B.size())
5555       return false;
5556     for (auto Pair : zip(A, B)) {
5557       if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5558         return true;
5559       if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
5560         return false;
5561     }
5562     return false;
5563   });
5564   FeatureBitsets.erase(
5565       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5566       FeatureBitsets.end());
5567   OS << "// Feature bitsets.\n"
5568      << "enum {\n"
5569      << "  GIFBS_Invalid,\n";
5570   for (const auto &FeatureBitset : FeatureBitsets) {
5571     if (FeatureBitset.empty())
5572       continue;
5573     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5574   }
5575   OS << "};\n"
5576      << "const static PredicateBitset FeatureBitsets[] {\n"
5577      << "  {}, // GIFBS_Invalid\n";
5578   for (const auto &FeatureBitset : FeatureBitsets) {
5579     if (FeatureBitset.empty())
5580       continue;
5581     OS << "  {";
5582     for (const auto &Feature : FeatureBitset) {
5583       const auto &I = SubtargetFeatures.find(Feature);
5584       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5585       OS << I->second.getEnumBitName() << ", ";
5586     }
5587     OS << "},\n";
5588   }
5589   OS << "};\n\n";
5590 
5591   // Emit complex predicate table and an enum to reference them with.
5592   OS << "// ComplexPattern predicates.\n"
5593      << "enum {\n"
5594      << "  GICP_Invalid,\n";
5595   for (const auto &Record : ComplexPredicates)
5596     OS << "  GICP_" << Record->getName() << ",\n";
5597   OS << "};\n"
5598      << "// See constructor for table contents\n\n";
5599 
5600   emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
5601     bool Unset;
5602     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5603            !R->getValueAsBit("IsAPInt");
5604   });
5605   emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
5606     bool Unset;
5607     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5608   });
5609   emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
5610     return R->getValueAsBit("IsAPInt");
5611   });
5612   emitMIPredicateFns(OS);
5613   OS << "\n";
5614 
5615   OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5616      << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5617      << "  nullptr, // GICP_Invalid\n";
5618   for (const auto &Record : ComplexPredicates)
5619     OS << "  &" << Target.getName()
5620        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5621        << ", // " << Record->getName() << "\n";
5622   OS << "};\n\n";
5623 
5624   OS << "// Custom renderers.\n"
5625      << "enum {\n"
5626      << "  GICR_Invalid,\n";
5627   for (const auto &Record : CustomRendererFns)
5628     OS << "  GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5629   OS << "};\n";
5630 
5631   OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5632      << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5633      << "  nullptr, // GICR_Invalid\n";
5634   for (const auto &Record : CustomRendererFns)
5635     OS << "  &" << Target.getName()
5636        << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5637        << ", // " << Record->getName() << "\n";
5638   OS << "};\n\n";
5639 
5640   llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
5641     int ScoreA = RuleMatcherScores[A.getRuleID()];
5642     int ScoreB = RuleMatcherScores[B.getRuleID()];
5643     if (ScoreA > ScoreB)
5644       return true;
5645     if (ScoreB > ScoreA)
5646       return false;
5647     if (A.isHigherPriorityThan(B)) {
5648       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5649                                            "and less important at "
5650                                            "the same time");
5651       return true;
5652     }
5653     return false;
5654   });
5655 
5656   OS << "bool " << Target.getName()
5657      << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5658         "&CoverageInfo) const {\n"
5659      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
5660      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5661      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5662      << "  NewMIVector OutMIs;\n"
5663      << "  State.MIs.clear();\n"
5664      << "  State.MIs.push_back(&I);\n\n"
5665      << "  if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5666      << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5667      << ", CoverageInfo)) {\n"
5668      << "    return true;\n"
5669      << "  }\n\n"
5670      << "  return false;\n"
5671      << "}\n\n";
5672 
5673   const MatchTable Table =
5674       buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
5675   OS << "const int64_t *" << Target.getName()
5676      << "InstructionSelector::getMatchTable() const {\n";
5677   Table.emitDeclaration(OS);
5678   OS << "  return ";
5679   Table.emitUse(OS);
5680   OS << ";\n}\n";
5681   OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
5682 
5683   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5684      << "PredicateBitset AvailableModuleFeatures;\n"
5685      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5686      << "PredicateBitset getAvailableFeatures() const {\n"
5687      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5688      << "}\n"
5689      << "PredicateBitset\n"
5690      << "computeAvailableModuleFeatures(const " << Target.getName()
5691      << "Subtarget *Subtarget) const;\n"
5692      << "PredicateBitset\n"
5693      << "computeAvailableFunctionFeatures(const " << Target.getName()
5694      << "Subtarget *Subtarget,\n"
5695      << "                                 const MachineFunction *MF) const;\n"
5696      << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
5697      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5698 
5699   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5700      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5701      << "AvailableFunctionFeatures()\n"
5702      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
5703 }
5704 
5705 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5706   if (SubtargetFeatures.count(Predicate) == 0)
5707     SubtargetFeatures.emplace(
5708         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5709 }
5710 
5711 void RuleMatcher::optimize() {
5712   for (auto &Item : InsnVariableIDs) {
5713     InstructionMatcher &InsnMatcher = *Item.first;
5714     for (auto &OM : InsnMatcher.operands()) {
5715       // Complex Patterns are usually expensive and they relatively rarely fail
5716       // on their own: more often we end up throwing away all the work done by a
5717       // matching part of a complex pattern because some other part of the
5718       // enclosing pattern didn't match. All of this makes it beneficial to
5719       // delay complex patterns until the very end of the rule matching,
5720       // especially for targets having lots of complex patterns.
5721       for (auto &OP : OM->predicates())
5722         if (isa<ComplexPatternOperandMatcher>(OP))
5723           EpilogueMatchers.emplace_back(std::move(OP));
5724       OM->eraseNullPredicates();
5725     }
5726     InsnMatcher.optimize();
5727   }
5728   llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5729                                   const std::unique_ptr<PredicateMatcher> &R) {
5730     return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5731            std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5732   });
5733 }
5734 
5735 bool RuleMatcher::hasFirstCondition() const {
5736   if (insnmatchers_empty())
5737     return false;
5738   InstructionMatcher &Matcher = insnmatchers_front();
5739   if (!Matcher.predicates_empty())
5740     return true;
5741   for (auto &OM : Matcher.operands())
5742     for (auto &OP : OM->predicates())
5743       if (!isa<InstructionOperandMatcher>(OP))
5744         return true;
5745   return false;
5746 }
5747 
5748 const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5749   assert(!insnmatchers_empty() &&
5750          "Trying to get a condition from an empty RuleMatcher");
5751 
5752   InstructionMatcher &Matcher = insnmatchers_front();
5753   if (!Matcher.predicates_empty())
5754     return **Matcher.predicates_begin();
5755   // If there is no more predicate on the instruction itself, look at its
5756   // operands.
5757   for (auto &OM : Matcher.operands())
5758     for (auto &OP : OM->predicates())
5759       if (!isa<InstructionOperandMatcher>(OP))
5760         return *OP;
5761 
5762   llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5763                    "no conditions");
5764 }
5765 
5766 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5767   assert(!insnmatchers_empty() &&
5768          "Trying to pop a condition from an empty RuleMatcher");
5769 
5770   InstructionMatcher &Matcher = insnmatchers_front();
5771   if (!Matcher.predicates_empty())
5772     return Matcher.predicates_pop_front();
5773   // If there is no more predicate on the instruction itself, look at its
5774   // operands.
5775   for (auto &OM : Matcher.operands())
5776     for (auto &OP : OM->predicates())
5777       if (!isa<InstructionOperandMatcher>(OP)) {
5778         std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5779         OM->eraseNullPredicates();
5780         return Result;
5781       }
5782 
5783   llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5784                    "no conditions");
5785 }
5786 
5787 bool GroupMatcher::candidateConditionMatches(
5788     const PredicateMatcher &Predicate) const {
5789 
5790   if (empty()) {
5791     // Sharing predicates for nested instructions is not supported yet as we
5792     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5793     // only work on the original root instruction (InsnVarID == 0):
5794     if (Predicate.getInsnVarID() != 0)
5795       return false;
5796     // ... otherwise an empty group can handle any predicate with no specific
5797     // requirements:
5798     return true;
5799   }
5800 
5801   const Matcher &Representative = **Matchers.begin();
5802   const auto &RepresentativeCondition = Representative.getFirstCondition();
5803   // ... if not empty, the group can only accomodate matchers with the exact
5804   // same first condition:
5805   return Predicate.isIdentical(RepresentativeCondition);
5806 }
5807 
5808 bool GroupMatcher::addMatcher(Matcher &Candidate) {
5809   if (!Candidate.hasFirstCondition())
5810     return false;
5811 
5812   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5813   if (!candidateConditionMatches(Predicate))
5814     return false;
5815 
5816   Matchers.push_back(&Candidate);
5817   return true;
5818 }
5819 
5820 void GroupMatcher::finalize() {
5821   assert(Conditions.empty() && "Already finalized?");
5822   if (empty())
5823     return;
5824 
5825   Matcher &FirstRule = **Matchers.begin();
5826   for (;;) {
5827     // All the checks are expected to succeed during the first iteration:
5828     for (const auto &Rule : Matchers)
5829       if (!Rule->hasFirstCondition())
5830         return;
5831     const auto &FirstCondition = FirstRule.getFirstCondition();
5832     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5833       if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5834         return;
5835 
5836     Conditions.push_back(FirstRule.popFirstCondition());
5837     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5838       Matchers[I]->popFirstCondition();
5839   }
5840 }
5841 
5842 void GroupMatcher::emit(MatchTable &Table) {
5843   unsigned LabelID = ~0U;
5844   if (!Conditions.empty()) {
5845     LabelID = Table.allocateLabelID();
5846     Table << MatchTable::Opcode("GIM_Try", +1)
5847           << MatchTable::Comment("On fail goto")
5848           << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
5849   }
5850   for (auto &Condition : Conditions)
5851     Condition->emitPredicateOpcodes(
5852         Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5853 
5854   for (const auto &M : Matchers)
5855     M->emit(Table);
5856 
5857   // Exit the group
5858   if (!Conditions.empty())
5859     Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
5860           << MatchTable::Label(LabelID);
5861 }
5862 
5863 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
5864   return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
5865 }
5866 
5867 bool SwitchMatcher::candidateConditionMatches(
5868     const PredicateMatcher &Predicate) const {
5869 
5870   if (empty()) {
5871     // Sharing predicates for nested instructions is not supported yet as we
5872     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5873     // only work on the original root instruction (InsnVarID == 0):
5874     if (Predicate.getInsnVarID() != 0)
5875       return false;
5876     // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5877     // could fail as not all the types of conditions are supported:
5878     if (!isSupportedPredicateType(Predicate))
5879       return false;
5880     // ... or the condition might not have a proper implementation of
5881     // getValue() / isIdenticalDownToValue() yet:
5882     if (!Predicate.hasValue())
5883       return false;
5884     // ... otherwise an empty Switch can accomodate the condition with no
5885     // further requirements:
5886     return true;
5887   }
5888 
5889   const Matcher &CaseRepresentative = **Matchers.begin();
5890   const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5891   // Switch-cases must share the same kind of condition and path to the value it
5892   // checks:
5893   if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5894     return false;
5895 
5896   const auto Value = Predicate.getValue();
5897   // ... but be unique with respect to the actual value they check:
5898   return Values.count(Value) == 0;
5899 }
5900 
5901 bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5902   if (!Candidate.hasFirstCondition())
5903     return false;
5904 
5905   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5906   if (!candidateConditionMatches(Predicate))
5907     return false;
5908   const auto Value = Predicate.getValue();
5909   Values.insert(Value);
5910 
5911   Matchers.push_back(&Candidate);
5912   return true;
5913 }
5914 
5915 void SwitchMatcher::finalize() {
5916   assert(Condition == nullptr && "Already finalized");
5917   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5918   if (empty())
5919     return;
5920 
5921   std::stable_sort(Matchers.begin(), Matchers.end(),
5922                    [](const Matcher *L, const Matcher *R) {
5923                      return L->getFirstCondition().getValue() <
5924                             R->getFirstCondition().getValue();
5925                    });
5926   Condition = Matchers[0]->popFirstCondition();
5927   for (unsigned I = 1, E = Values.size(); I < E; ++I)
5928     Matchers[I]->popFirstCondition();
5929 }
5930 
5931 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5932                                                  MatchTable &Table) {
5933   assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5934 
5935   if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5936     Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5937           << MatchTable::IntValue(Condition->getInsnVarID());
5938     return;
5939   }
5940   if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5941     Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5942           << MatchTable::IntValue(Condition->getInsnVarID())
5943           << MatchTable::Comment("Op")
5944           << MatchTable::IntValue(Condition->getOpIdx());
5945     return;
5946   }
5947 
5948   llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5949                    "predicate type that is claimed to be supported");
5950 }
5951 
5952 void SwitchMatcher::emit(MatchTable &Table) {
5953   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5954   if (empty())
5955     return;
5956   assert(Condition != nullptr &&
5957          "Broken SwitchMatcher, hasn't been finalized?");
5958 
5959   std::vector<unsigned> LabelIDs(Values.size());
5960   std::generate(LabelIDs.begin(), LabelIDs.end(),
5961                 [&Table]() { return Table.allocateLabelID(); });
5962   const unsigned Default = Table.allocateLabelID();
5963 
5964   const int64_t LowerBound = Values.begin()->getRawValue();
5965   const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5966 
5967   emitPredicateSpecificOpcodes(*Condition, Table);
5968 
5969   Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5970         << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5971         << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5972 
5973   int64_t J = LowerBound;
5974   auto VI = Values.begin();
5975   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5976     auto V = *VI++;
5977     while (J++ < V.getRawValue())
5978       Table << MatchTable::IntValue(0);
5979     V.turnIntoComment();
5980     Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5981   }
5982   Table << MatchTable::LineBreak;
5983 
5984   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5985     Table << MatchTable::Label(LabelIDs[I]);
5986     Matchers[I]->emit(Table);
5987     Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5988   }
5989   Table << MatchTable::Label(Default);
5990 }
5991 
5992 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
5993 
5994 } // end anonymous namespace
5995 
5996 //===----------------------------------------------------------------------===//
5997 
5998 namespace llvm {
5999 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
6000   GlobalISelEmitter(RK).run(OS);
6001 }
6002 } // End llvm namespace
6003