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