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