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