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 "CodeGenInstruction.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CodeGenCoverage.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/LowLevelTypeImpl.h"
41 #include "llvm/Support/MachineValueType.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <numeric>
47 #include <string>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
56 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57 
58 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59 
60 static cl::opt<bool> WarnOnSkippedPatterns(
61     "warn-on-skipped-patterns",
62     cl::desc("Explain why a pattern was skipped for inclusion "
63              "in the GlobalISel selector"),
64     cl::init(false), cl::cat(GlobalISelEmitterCat));
65 
66 static cl::opt<bool> GenerateCoverage(
67     "instrument-gisel-coverage",
68     cl::desc("Generate coverage instrumentation for GlobalISel"),
69     cl::init(false), cl::cat(GlobalISelEmitterCat));
70 
71 static cl::opt<std::string> UseCoverageFile(
72     "gisel-coverage-file", cl::init(""),
73     cl::desc("Specify file to retrieve coverage information from"),
74     cl::cat(GlobalISelEmitterCat));
75 
76 static cl::opt<bool> OptimizeMatchTable(
77     "optimize-match-table",
78     cl::desc("Generate an optimized version of the match table"),
79     cl::init(true), cl::cat(GlobalISelEmitterCat));
80 
81 namespace {
82 //===- Helper functions ---------------------------------------------------===//
83 
84 /// Get the name of the enum value used to number the predicate function.
85 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
86   if (Predicate.hasGISelPredicateCode())
87     return "GIPFP_MI_" + Predicate.getFnName();
88   return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
89          Predicate.getFnName();
90 }
91 
92 /// Get the opcode used to check this predicate.
93 std::string getMatchOpcodeForImmPredicate(const TreePredicateFn &Predicate) {
94   return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
95 }
96 
97 /// This class stands in for LLT wherever we want to tablegen-erate an
98 /// equivalent at compiler run-time.
99 class LLTCodeGen {
100 private:
101   LLT Ty;
102 
103 public:
104   LLTCodeGen() = default;
105   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106 
107   std::string getCxxEnumValue() const {
108     std::string Str;
109     raw_string_ostream OS(Str);
110 
111     emitCxxEnumValue(OS);
112     return Str;
113   }
114 
115   void emitCxxEnumValue(raw_ostream &OS) const {
116     if (Ty.isScalar()) {
117       OS << "GILLT_s" << Ty.getSizeInBits();
118       return;
119     }
120     if (Ty.isVector()) {
121       OS << (Ty.isScalable() ? "GILLT_nxv" : "GILLT_v")
122          << Ty.getElementCount().getKnownMinValue() << "s"
123          << Ty.getScalarSizeInBits();
124       return;
125     }
126     if (Ty.isPointer()) {
127       OS << "GILLT_p" << Ty.getAddressSpace();
128       if (Ty.getSizeInBits() > 0)
129         OS << "s" << Ty.getSizeInBits();
130       return;
131     }
132     llvm_unreachable("Unhandled LLT");
133   }
134 
135   void emitCxxConstructorCall(raw_ostream &OS) const {
136     if (Ty.isScalar()) {
137       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
138       return;
139     }
140     if (Ty.isVector()) {
141       OS << "LLT::vector("
142          << (Ty.isScalable() ? "ElementCount::getScalable("
143                              : "ElementCount::getFixed(")
144          << Ty.getElementCount().getKnownMinValue() << "), "
145          << Ty.getScalarSizeInBits() << ")";
146       return;
147     }
148     if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
149       OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
150          << Ty.getSizeInBits() << ")";
151       return;
152     }
153     llvm_unreachable("Unhandled LLT");
154   }
155 
156   const LLT &get() const { return Ty; }
157 
158   /// This ordering is used for std::unique() and llvm::sort(). There's no
159   /// particular logic behind the order but either A < B or B < A must be
160   /// true if A != B.
161   bool operator<(const LLTCodeGen &Other) const {
162     if (Ty.isValid() != Other.Ty.isValid())
163       return Ty.isValid() < Other.Ty.isValid();
164     if (!Ty.isValid())
165       return false;
166 
167     if (Ty.isVector() != Other.Ty.isVector())
168       return Ty.isVector() < Other.Ty.isVector();
169     if (Ty.isScalar() != Other.Ty.isScalar())
170       return Ty.isScalar() < Other.Ty.isScalar();
171     if (Ty.isPointer() != Other.Ty.isPointer())
172       return Ty.isPointer() < Other.Ty.isPointer();
173 
174     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
175       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
176 
177     if (Ty.isVector() && Ty.getElementCount() != Other.Ty.getElementCount())
178       return std::make_tuple(Ty.isScalable(),
179                              Ty.getElementCount().getKnownMinValue()) <
180              std::make_tuple(Other.Ty.isScalable(),
181                              Other.Ty.getElementCount().getKnownMinValue());
182 
183     assert((!Ty.isVector() || Ty.isScalable() == Other.Ty.isScalable()) &&
184            "Unexpected mismatch of scalable property");
185     return Ty.isVector()
186                ? std::make_tuple(Ty.isScalable(),
187                                  Ty.getSizeInBits().getKnownMinSize()) <
188                      std::make_tuple(Other.Ty.isScalable(),
189                                      Other.Ty.getSizeInBits().getKnownMinSize())
190                : Ty.getSizeInBits().getFixedSize() <
191                      Other.Ty.getSizeInBits().getFixedSize();
192   }
193 
194   bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
195 };
196 
197 // Track all types that are used so we can emit the corresponding enum.
198 std::set<LLTCodeGen> KnownTypes;
199 
200 class InstructionMatcher;
201 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
202 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
203 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
204   MVT VT(SVT);
205 
206   if (VT.isVector() && !VT.getVectorElementCount().isScalar())
207     return LLTCodeGen(
208         LLT::vector(VT.getVectorElementCount(), VT.getScalarSizeInBits()));
209 
210   if (VT.isInteger() || VT.isFloatingPoint())
211     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
212 
213   return None;
214 }
215 
216 static std::string explainPredicates(const TreePatternNode *N) {
217   std::string Explanation;
218   StringRef Separator = "";
219   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
220     const TreePredicateFn &P = Call.Fn;
221     Explanation +=
222         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
223     Separator = ", ";
224 
225     if (P.isAlwaysTrue())
226       Explanation += " always-true";
227     if (P.isImmediatePattern())
228       Explanation += " immediate";
229 
230     if (P.isUnindexed())
231       Explanation += " unindexed";
232 
233     if (P.isNonExtLoad())
234       Explanation += " non-extload";
235     if (P.isAnyExtLoad())
236       Explanation += " extload";
237     if (P.isSignExtLoad())
238       Explanation += " sextload";
239     if (P.isZeroExtLoad())
240       Explanation += " zextload";
241 
242     if (P.isNonTruncStore())
243       Explanation += " non-truncstore";
244     if (P.isTruncStore())
245       Explanation += " truncstore";
246 
247     if (Record *VT = P.getMemoryVT())
248       Explanation += (" MemVT=" + VT->getName()).str();
249     if (Record *VT = P.getScalarMemoryVT())
250       Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
251 
252     if (ListInit *AddrSpaces = P.getAddressSpaces()) {
253       raw_string_ostream OS(Explanation);
254       OS << " AddressSpaces=[";
255 
256       StringRef AddrSpaceSeparator;
257       for (Init *Val : AddrSpaces->getValues()) {
258         IntInit *IntVal = dyn_cast<IntInit>(Val);
259         if (!IntVal)
260           continue;
261 
262         OS << AddrSpaceSeparator << IntVal->getValue();
263         AddrSpaceSeparator = ", ";
264       }
265 
266       OS << ']';
267     }
268 
269     int64_t MinAlign = P.getMinAlignment();
270     if (MinAlign > 0)
271       Explanation += " MinAlign=" + utostr(MinAlign);
272 
273     if (P.isAtomicOrderingMonotonic())
274       Explanation += " monotonic";
275     if (P.isAtomicOrderingAcquire())
276       Explanation += " acquire";
277     if (P.isAtomicOrderingRelease())
278       Explanation += " release";
279     if (P.isAtomicOrderingAcquireRelease())
280       Explanation += " acq_rel";
281     if (P.isAtomicOrderingSequentiallyConsistent())
282       Explanation += " seq_cst";
283     if (P.isAtomicOrderingAcquireOrStronger())
284       Explanation += " >=acquire";
285     if (P.isAtomicOrderingWeakerThanAcquire())
286       Explanation += " <acquire";
287     if (P.isAtomicOrderingReleaseOrStronger())
288       Explanation += " >=release";
289     if (P.isAtomicOrderingWeakerThanRelease())
290       Explanation += " <release";
291   }
292   return Explanation;
293 }
294 
295 std::string explainOperator(Record *Operator) {
296   if (Operator->isSubClassOf("SDNode"))
297     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
298 
299   if (Operator->isSubClassOf("Intrinsic"))
300     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
301 
302   if (Operator->isSubClassOf("ComplexPattern"))
303     return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
304             ")")
305         .str();
306 
307   if (Operator->isSubClassOf("SDNodeXForm"))
308     return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
309             ")")
310         .str();
311 
312   return (" (Operator " + Operator->getName() + " not understood)").str();
313 }
314 
315 /// Helper function to let the emitter report skip reason error messages.
316 static Error failedImport(const Twine &Reason) {
317   return make_error<StringError>(Reason, inconvertibleErrorCode());
318 }
319 
320 static Error isTrivialOperatorNode(const TreePatternNode *N) {
321   std::string Explanation;
322   std::string Separator;
323 
324   bool HasUnsupportedPredicate = false;
325   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
326     const TreePredicateFn &Predicate = Call.Fn;
327 
328     if (Predicate.isAlwaysTrue())
329       continue;
330 
331     if (Predicate.isImmediatePattern())
332       continue;
333 
334     if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
335         Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
336       continue;
337 
338     if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
339       continue;
340 
341     if (Predicate.isLoad() && Predicate.getMemoryVT())
342       continue;
343 
344     if (Predicate.isLoad() || Predicate.isStore()) {
345       if (Predicate.isUnindexed())
346         continue;
347     }
348 
349     if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
350       const ListInit *AddrSpaces = Predicate.getAddressSpaces();
351       if (AddrSpaces && !AddrSpaces->empty())
352         continue;
353 
354       if (Predicate.getMinAlignment() > 0)
355         continue;
356     }
357 
358     if (Predicate.isAtomic() && Predicate.getMemoryVT())
359       continue;
360 
361     if (Predicate.isAtomic() &&
362         (Predicate.isAtomicOrderingMonotonic() ||
363          Predicate.isAtomicOrderingAcquire() ||
364          Predicate.isAtomicOrderingRelease() ||
365          Predicate.isAtomicOrderingAcquireRelease() ||
366          Predicate.isAtomicOrderingSequentiallyConsistent() ||
367          Predicate.isAtomicOrderingAcquireOrStronger() ||
368          Predicate.isAtomicOrderingWeakerThanAcquire() ||
369          Predicate.isAtomicOrderingReleaseOrStronger() ||
370          Predicate.isAtomicOrderingWeakerThanRelease()))
371       continue;
372 
373     if (Predicate.hasGISelPredicateCode())
374       continue;
375 
376     HasUnsupportedPredicate = true;
377     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
378     Separator = ", ";
379     Explanation += (Separator + "first-failing:" +
380                     Predicate.getOrigPatFragRecord()->getRecord()->getName())
381                        .str();
382     break;
383   }
384 
385   if (!HasUnsupportedPredicate)
386     return Error::success();
387 
388   return failedImport(Explanation);
389 }
390 
391 static Record *getInitValueAsRegClass(Init *V) {
392   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
393     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
394       return VDefInit->getDef()->getValueAsDef("RegClass");
395     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
396       return VDefInit->getDef();
397   }
398   return nullptr;
399 }
400 
401 std::string
402 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
403   std::string Name = "GIFBS";
404   for (const auto &Feature : FeatureBitset)
405     Name += ("_" + Feature->getName()).str();
406   return Name;
407 }
408 
409 static std::string getScopedName(unsigned Scope, const std::string &Name) {
410   return ("pred:" + Twine(Scope) + ":" + Name).str();
411 }
412 
413 //===- MatchTable Helpers -------------------------------------------------===//
414 
415 class MatchTable;
416 
417 /// A record to be stored in a MatchTable.
418 ///
419 /// This class represents any and all output that may be required to emit the
420 /// MatchTable. Instances  are most often configured to represent an opcode or
421 /// value that will be emitted to the table with some formatting but it can also
422 /// represent commas, comments, and other formatting instructions.
423 struct MatchTableRecord {
424   enum RecordFlagsBits {
425     MTRF_None = 0x0,
426     /// Causes EmitStr to be formatted as comment when emitted.
427     MTRF_Comment = 0x1,
428     /// Causes the record value to be followed by a comma when emitted.
429     MTRF_CommaFollows = 0x2,
430     /// Causes the record value to be followed by a line break when emitted.
431     MTRF_LineBreakFollows = 0x4,
432     /// Indicates that the record defines a label and causes an additional
433     /// comment to be emitted containing the index of the label.
434     MTRF_Label = 0x8,
435     /// Causes the record to be emitted as the index of the label specified by
436     /// LabelID along with a comment indicating where that label is.
437     MTRF_JumpTarget = 0x10,
438     /// Causes the formatter to add a level of indentation before emitting the
439     /// record.
440     MTRF_Indent = 0x20,
441     /// Causes the formatter to remove a level of indentation after emitting the
442     /// record.
443     MTRF_Outdent = 0x40,
444   };
445 
446   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
447   /// reference or define.
448   unsigned LabelID;
449   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
450   /// value, a label name.
451   std::string EmitStr;
452 
453 private:
454   /// The number of MatchTable elements described by this record. Comments are 0
455   /// while values are typically 1. Values >1 may occur when we need to emit
456   /// values that exceed the size of a MatchTable element.
457   unsigned NumElements;
458 
459 public:
460   /// A bitfield of RecordFlagsBits flags.
461   unsigned Flags;
462 
463   /// The actual run-time value, if known
464   int64_t RawValue;
465 
466   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
467                    unsigned NumElements, unsigned Flags,
468                    int64_t RawValue = std::numeric_limits<int64_t>::min())
469       : LabelID(LabelID_.getValueOr(~0u)), EmitStr(EmitStr),
470         NumElements(NumElements), Flags(Flags), RawValue(RawValue) {
471     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
472            "This value is reserved for non-labels");
473   }
474   MatchTableRecord(const MatchTableRecord &Other) = default;
475   MatchTableRecord(MatchTableRecord &&Other) = default;
476 
477   /// Useful if a Match Table Record gets optimized out
478   void turnIntoComment() {
479     Flags |= MTRF_Comment;
480     Flags &= ~MTRF_CommaFollows;
481     NumElements = 0;
482   }
483 
484   /// For Jump Table generation purposes
485   bool operator<(const MatchTableRecord &Other) const {
486     return RawValue < Other.RawValue;
487   }
488   int64_t getRawValue() const { return RawValue; }
489 
490   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
491             const MatchTable &Table) const;
492   unsigned size() const { return NumElements; }
493 };
494 
495 class Matcher;
496 
497 /// Holds the contents of a generated MatchTable to enable formatting and the
498 /// necessary index tracking needed to support GIM_Try.
499 class MatchTable {
500   /// An unique identifier for the table. The generated table will be named
501   /// MatchTable${ID}.
502   unsigned ID;
503   /// The records that make up the table. Also includes comments describing the
504   /// values being emitted and line breaks to format it.
505   std::vector<MatchTableRecord> Contents;
506   /// The currently defined labels.
507   DenseMap<unsigned, unsigned> LabelMap;
508   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
509   unsigned CurrentSize = 0;
510   /// A unique identifier for a MatchTable label.
511   unsigned CurrentLabelID = 0;
512   /// Determines if the table should be instrumented for rule coverage tracking.
513   bool IsWithCoverage;
514 
515 public:
516   static MatchTableRecord LineBreak;
517   static MatchTableRecord Comment(StringRef Comment) {
518     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
519   }
520   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
521     unsigned ExtraFlags = 0;
522     if (IndentAdjust > 0)
523       ExtraFlags |= MatchTableRecord::MTRF_Indent;
524     if (IndentAdjust < 0)
525       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
526 
527     return MatchTableRecord(None, Opcode, 1,
528                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
529   }
530   static MatchTableRecord NamedValue(StringRef NamedValue) {
531     return MatchTableRecord(None, NamedValue, 1,
532                             MatchTableRecord::MTRF_CommaFollows);
533   }
534   static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
535     return MatchTableRecord(None, NamedValue, 1,
536                             MatchTableRecord::MTRF_CommaFollows, RawValue);
537   }
538   static MatchTableRecord NamedValue(StringRef Namespace,
539                                      StringRef NamedValue) {
540     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
541                             MatchTableRecord::MTRF_CommaFollows);
542   }
543   static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
544                                      int64_t RawValue) {
545     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
546                             MatchTableRecord::MTRF_CommaFollows, RawValue);
547   }
548   static MatchTableRecord IntValue(int64_t IntValue) {
549     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
550                             MatchTableRecord::MTRF_CommaFollows);
551   }
552   static MatchTableRecord Label(unsigned LabelID) {
553     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
554                             MatchTableRecord::MTRF_Label |
555                                 MatchTableRecord::MTRF_Comment |
556                                 MatchTableRecord::MTRF_LineBreakFollows);
557   }
558   static MatchTableRecord JumpTarget(unsigned LabelID) {
559     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
560                             MatchTableRecord::MTRF_JumpTarget |
561                                 MatchTableRecord::MTRF_Comment |
562                                 MatchTableRecord::MTRF_CommaFollows);
563   }
564 
565   static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
566 
567   MatchTable(bool WithCoverage, unsigned ID = 0)
568       : ID(ID), IsWithCoverage(WithCoverage) {}
569 
570   bool isWithCoverage() const { return IsWithCoverage; }
571 
572   void push_back(const MatchTableRecord &Value) {
573     if (Value.Flags & MatchTableRecord::MTRF_Label)
574       defineLabel(Value.LabelID);
575     Contents.push_back(Value);
576     CurrentSize += Value.size();
577   }
578 
579   unsigned allocateLabelID() { return CurrentLabelID++; }
580 
581   void defineLabel(unsigned LabelID) {
582     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
583   }
584 
585   unsigned getLabelIndex(unsigned LabelID) const {
586     const auto I = LabelMap.find(LabelID);
587     assert(I != LabelMap.end() && "Use of undeclared label");
588     return I->second;
589   }
590 
591   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
592 
593   void emitDeclaration(raw_ostream &OS) const {
594     unsigned Indentation = 4;
595     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
596     LineBreak.emit(OS, true, *this);
597     OS << std::string(Indentation, ' ');
598 
599     for (auto I = Contents.begin(), E = Contents.end(); I != E;
600          ++I) {
601       bool LineBreakIsNext = false;
602       const auto &NextI = std::next(I);
603 
604       if (NextI != E) {
605         if (NextI->EmitStr == "" &&
606             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
607           LineBreakIsNext = true;
608       }
609 
610       if (I->Flags & MatchTableRecord::MTRF_Indent)
611         Indentation += 2;
612 
613       I->emit(OS, LineBreakIsNext, *this);
614       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
615         OS << std::string(Indentation, ' ');
616 
617       if (I->Flags & MatchTableRecord::MTRF_Outdent)
618         Indentation -= 2;
619     }
620     OS << "};\n";
621   }
622 };
623 
624 MatchTableRecord MatchTable::LineBreak = {
625     None, "" /* Emit String */, 0 /* Elements */,
626     MatchTableRecord::MTRF_LineBreakFollows};
627 
628 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
629                             const MatchTable &Table) const {
630   bool UseLineComment =
631       LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
632   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
633     UseLineComment = false;
634 
635   if (Flags & MTRF_Comment)
636     OS << (UseLineComment ? "// " : "/*");
637 
638   OS << EmitStr;
639   if (Flags & MTRF_Label)
640     OS << ": @" << Table.getLabelIndex(LabelID);
641 
642   if ((Flags & MTRF_Comment) && !UseLineComment)
643     OS << "*/";
644 
645   if (Flags & MTRF_JumpTarget) {
646     if (Flags & MTRF_Comment)
647       OS << " ";
648     OS << Table.getLabelIndex(LabelID);
649   }
650 
651   if (Flags & MTRF_CommaFollows) {
652     OS << ",";
653     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
654       OS << " ";
655   }
656 
657   if (Flags & MTRF_LineBreakFollows)
658     OS << "\n";
659 }
660 
661 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
662   Table.push_back(Value);
663   return Table;
664 }
665 
666 //===- Matchers -----------------------------------------------------------===//
667 
668 class OperandMatcher;
669 class MatchAction;
670 class PredicateMatcher;
671 
672 class Matcher {
673 public:
674   virtual ~Matcher() = default;
675   virtual void optimize() {}
676   virtual void emit(MatchTable &Table) = 0;
677 
678   virtual bool hasFirstCondition() const = 0;
679   virtual const PredicateMatcher &getFirstCondition() const = 0;
680   virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
681 };
682 
683 MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
684                                   bool WithCoverage) {
685   MatchTable Table(WithCoverage);
686   for (Matcher *Rule : Rules)
687     Rule->emit(Table);
688 
689   return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
690 }
691 
692 class GroupMatcher final : public Matcher {
693   /// Conditions that form a common prefix of all the matchers contained.
694   SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
695 
696   /// All the nested matchers, sharing a common prefix.
697   std::vector<Matcher *> Matchers;
698 
699   /// An owning collection for any auxiliary matchers created while optimizing
700   /// nested matchers contained.
701   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
702 
703 public:
704   /// Add a matcher to the collection of nested matchers if it meets the
705   /// requirements, and return true. If it doesn't, do nothing and return false.
706   ///
707   /// Expected to preserve its argument, so it could be moved out later on.
708   bool addMatcher(Matcher &Candidate);
709 
710   /// Mark the matcher as fully-built and ensure any invariants expected by both
711   /// optimize() and emit(...) methods. Generally, both sequences of calls
712   /// are expected to lead to a sensible result:
713   ///
714   /// addMatcher(...)*; finalize(); optimize(); emit(...); and
715   /// addMatcher(...)*; finalize(); emit(...);
716   ///
717   /// or generally
718   ///
719   /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
720   ///
721   /// Multiple calls to optimize() are expected to be handled gracefully, though
722   /// optimize() is not expected to be idempotent. Multiple calls to finalize()
723   /// aren't generally supported. emit(...) is expected to be non-mutating and
724   /// producing the exact same results upon repeated calls.
725   ///
726   /// addMatcher() calls after the finalize() call are not supported.
727   ///
728   /// finalize() and optimize() are both allowed to mutate the contained
729   /// matchers, so moving them out after finalize() is not supported.
730   void finalize();
731   void optimize() override;
732   void emit(MatchTable &Table) override;
733 
734   /// Could be used to move out the matchers added previously, unless finalize()
735   /// has been already called. If any of the matchers are moved out, the group
736   /// becomes safe to destroy, but not safe to re-use for anything else.
737   iterator_range<std::vector<Matcher *>::iterator> matchers() {
738     return make_range(Matchers.begin(), Matchers.end());
739   }
740   size_t size() const { return Matchers.size(); }
741   bool empty() const { return Matchers.empty(); }
742 
743   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
744     assert(!Conditions.empty() &&
745            "Trying to pop a condition from a condition-less group");
746     std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
747     Conditions.erase(Conditions.begin());
748     return P;
749   }
750   const PredicateMatcher &getFirstCondition() const override {
751     assert(!Conditions.empty() &&
752            "Trying to get a condition from a condition-less group");
753     return *Conditions.front();
754   }
755   bool hasFirstCondition() const override { return !Conditions.empty(); }
756 
757 private:
758   /// See if a candidate matcher could be added to this group solely by
759   /// analyzing its first condition.
760   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
761 };
762 
763 class SwitchMatcher : public Matcher {
764   /// All the nested matchers, representing distinct switch-cases. The first
765   /// conditions (as Matcher::getFirstCondition() reports) of all the nested
766   /// matchers must share the same type and path to a value they check, in other
767   /// words, be isIdenticalDownToValue, but have different values they check
768   /// against.
769   std::vector<Matcher *> Matchers;
770 
771   /// The representative condition, with a type and a path (InsnVarID and OpIdx
772   /// in most cases)  shared by all the matchers contained.
773   std::unique_ptr<PredicateMatcher> Condition = nullptr;
774 
775   /// Temporary set used to check that the case values don't repeat within the
776   /// same switch.
777   std::set<MatchTableRecord> Values;
778 
779   /// An owning collection for any auxiliary matchers created while optimizing
780   /// nested matchers contained.
781   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
782 
783 public:
784   bool addMatcher(Matcher &Candidate);
785 
786   void finalize();
787   void emit(MatchTable &Table) override;
788 
789   iterator_range<std::vector<Matcher *>::iterator> matchers() {
790     return make_range(Matchers.begin(), Matchers.end());
791   }
792   size_t size() const { return Matchers.size(); }
793   bool empty() const { return Matchers.empty(); }
794 
795   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
796     // SwitchMatcher doesn't have a common first condition for its cases, as all
797     // the cases only share a kind of a value (a type and a path to it) they
798     // match, but deliberately differ in the actual value they match.
799     llvm_unreachable("Trying to pop a condition from a condition-less group");
800   }
801   const PredicateMatcher &getFirstCondition() const override {
802     llvm_unreachable("Trying to pop a condition from a condition-less group");
803   }
804   bool hasFirstCondition() const override { return false; }
805 
806 private:
807   /// See if the predicate type has a Switch-implementation for it.
808   static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
809 
810   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
811 
812   /// emit()-helper
813   static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
814                                            MatchTable &Table);
815 };
816 
817 /// Generates code to check that a match rule matches.
818 class RuleMatcher : public Matcher {
819 public:
820   using ActionList = std::list<std::unique_ptr<MatchAction>>;
821   using action_iterator = ActionList::iterator;
822 
823 protected:
824   /// A list of matchers that all need to succeed for the current rule to match.
825   /// FIXME: This currently supports a single match position but could be
826   /// extended to support multiple positions to support div/rem fusion or
827   /// load-multiple instructions.
828   using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
829   MatchersTy Matchers;
830 
831   /// A list of actions that need to be taken when all predicates in this rule
832   /// have succeeded.
833   ActionList Actions;
834 
835   using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
836 
837   /// A map of instruction matchers to the local variables
838   DefinedInsnVariablesMap InsnVariableIDs;
839 
840   using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
841 
842   // The set of instruction matchers that have not yet been claimed for mutation
843   // by a BuildMI.
844   MutatableInsnSet MutatableInsns;
845 
846   /// A map of named operands defined by the matchers that may be referenced by
847   /// the renderers.
848   StringMap<OperandMatcher *> DefinedOperands;
849 
850   /// A map of anonymous physical register operands defined by the matchers that
851   /// may be referenced by the renderers.
852   DenseMap<Record *, OperandMatcher *> PhysRegOperands;
853 
854   /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
855   unsigned NextInsnVarID;
856 
857   /// ID for the next output instruction allocated with allocateOutputInsnID()
858   unsigned NextOutputInsnID;
859 
860   /// ID for the next temporary register ID allocated with allocateTempRegID()
861   unsigned NextTempRegID;
862 
863   std::vector<Record *> RequiredFeatures;
864   std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
865 
866   ArrayRef<SMLoc> SrcLoc;
867 
868   typedef std::tuple<Record *, unsigned, unsigned>
869       DefinedComplexPatternSubOperand;
870   typedef StringMap<DefinedComplexPatternSubOperand>
871       DefinedComplexPatternSubOperandMap;
872   /// A map of Symbolic Names to ComplexPattern sub-operands.
873   DefinedComplexPatternSubOperandMap ComplexSubOperands;
874   /// A map used to for multiple referenced error check of ComplexSubOperand.
875   /// ComplexSubOperand can't be referenced multiple from different operands,
876   /// however multiple references from same operand are allowed since that is
877   /// how 'same operand checks' are generated.
878   StringMap<std::string> ComplexSubOperandsParentName;
879 
880   uint64_t RuleID;
881   static uint64_t NextRuleID;
882 
883 public:
884   RuleMatcher(ArrayRef<SMLoc> SrcLoc)
885       : NextInsnVarID(0), NextOutputInsnID(0), NextTempRegID(0), SrcLoc(SrcLoc),
886         RuleID(NextRuleID++) {}
887   RuleMatcher(RuleMatcher &&Other) = default;
888   RuleMatcher &operator=(RuleMatcher &&Other) = default;
889 
890   uint64_t getRuleID() const { return RuleID; }
891 
892   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
893   void addRequiredFeature(Record *Feature);
894   const std::vector<Record *> &getRequiredFeatures() const;
895 
896   template <class Kind, class... Args> Kind &addAction(Args &&... args);
897   template <class Kind, class... Args>
898   action_iterator insertAction(action_iterator InsertPt, Args &&... args);
899 
900   /// Define an instruction without emitting any code to do so.
901   unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
902 
903   unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
904   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
905     return InsnVariableIDs.begin();
906   }
907   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
908     return InsnVariableIDs.end();
909   }
910   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
911   defined_insn_vars() const {
912     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
913   }
914 
915   MutatableInsnSet::const_iterator mutatable_insns_begin() const {
916     return MutatableInsns.begin();
917   }
918   MutatableInsnSet::const_iterator mutatable_insns_end() const {
919     return MutatableInsns.end();
920   }
921   iterator_range<typename MutatableInsnSet::const_iterator>
922   mutatable_insns() const {
923     return make_range(mutatable_insns_begin(), mutatable_insns_end());
924   }
925   void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
926     bool R = MutatableInsns.erase(InsnMatcher);
927     assert(R && "Reserving a mutatable insn that isn't available");
928     (void)R;
929   }
930 
931   action_iterator actions_begin() { return Actions.begin(); }
932   action_iterator actions_end() { return Actions.end(); }
933   iterator_range<action_iterator> actions() {
934     return make_range(actions_begin(), actions_end());
935   }
936 
937   void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
938 
939   void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
940 
941   Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
942                                 unsigned RendererID, unsigned SubOperandID,
943                                 StringRef ParentSymbolicName) {
944     std::string ParentName(ParentSymbolicName);
945     if (ComplexSubOperands.count(SymbolicName)) {
946       const std::string &RecordedParentName =
947           ComplexSubOperandsParentName[SymbolicName];
948       if (RecordedParentName != ParentName)
949         return failedImport("Error: Complex suboperand " + SymbolicName +
950                             " referenced by different operands: " +
951                             RecordedParentName + " and " + ParentName + ".");
952       // Complex suboperand referenced more than once from same the operand is
953       // used to generate 'same operand check'. Emitting of
954       // GIR_ComplexSubOperandRenderer for them is already handled.
955       return Error::success();
956     }
957 
958     ComplexSubOperands[SymbolicName] =
959         std::make_tuple(ComplexPattern, RendererID, SubOperandID);
960     ComplexSubOperandsParentName[SymbolicName] = ParentName;
961 
962     return Error::success();
963   }
964 
965   Optional<DefinedComplexPatternSubOperand>
966   getComplexSubOperand(StringRef SymbolicName) const {
967     const auto &I = ComplexSubOperands.find(SymbolicName);
968     if (I == ComplexSubOperands.end())
969       return None;
970     return I->second;
971   }
972 
973   InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
974   const OperandMatcher &getOperandMatcher(StringRef Name) const;
975   const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
976 
977   void optimize() override;
978   void emit(MatchTable &Table) override;
979 
980   /// Compare the priority of this object and B.
981   ///
982   /// Returns true if this object is more important than B.
983   bool isHigherPriorityThan(const RuleMatcher &B) const;
984 
985   /// Report the maximum number of temporary operands needed by the rule
986   /// matcher.
987   unsigned countRendererFns() const;
988 
989   std::unique_ptr<PredicateMatcher> popFirstCondition() override;
990   const PredicateMatcher &getFirstCondition() const override;
991   LLTCodeGen getFirstConditionAsRootType();
992   bool hasFirstCondition() const override;
993   unsigned getNumOperands() const;
994   StringRef getOpcode() const;
995 
996   // FIXME: Remove this as soon as possible
997   InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
998 
999   unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
1000   unsigned allocateTempRegID() { return NextTempRegID++; }
1001 
1002   iterator_range<MatchersTy::iterator> insnmatchers() {
1003     return make_range(Matchers.begin(), Matchers.end());
1004   }
1005   bool insnmatchers_empty() const { return Matchers.empty(); }
1006   void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
1007 };
1008 
1009 uint64_t RuleMatcher::NextRuleID = 0;
1010 
1011 using action_iterator = RuleMatcher::action_iterator;
1012 
1013 template <class PredicateTy> class PredicateListMatcher {
1014 private:
1015   /// Template instantiations should specialize this to return a string to use
1016   /// for the comment emitted when there are no predicates.
1017   std::string getNoPredicateComment() const;
1018 
1019 protected:
1020   using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
1021   PredicatesTy Predicates;
1022 
1023   /// Track if the list of predicates was manipulated by one of the optimization
1024   /// methods.
1025   bool Optimized = false;
1026 
1027 public:
1028   typename PredicatesTy::iterator predicates_begin() {
1029     return Predicates.begin();
1030   }
1031   typename PredicatesTy::iterator predicates_end() {
1032     return Predicates.end();
1033   }
1034   iterator_range<typename PredicatesTy::iterator> predicates() {
1035     return make_range(predicates_begin(), predicates_end());
1036   }
1037   typename PredicatesTy::size_type predicates_size() const {
1038     return Predicates.size();
1039   }
1040   bool predicates_empty() const { return Predicates.empty(); }
1041 
1042   std::unique_ptr<PredicateTy> predicates_pop_front() {
1043     std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
1044     Predicates.pop_front();
1045     Optimized = true;
1046     return Front;
1047   }
1048 
1049   void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1050     Predicates.push_front(std::move(Predicate));
1051   }
1052 
1053   void eraseNullPredicates() {
1054     const auto NewEnd =
1055         std::stable_partition(Predicates.begin(), Predicates.end(),
1056                               std::logical_not<std::unique_ptr<PredicateTy>>());
1057     if (NewEnd != Predicates.begin()) {
1058       Predicates.erase(Predicates.begin(), NewEnd);
1059       Optimized = true;
1060     }
1061   }
1062 
1063   /// Emit MatchTable opcodes that tests whether all the predicates are met.
1064   template <class... Args>
1065   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1066     if (Predicates.empty() && !Optimized) {
1067       Table << MatchTable::Comment(getNoPredicateComment())
1068             << MatchTable::LineBreak;
1069       return;
1070     }
1071 
1072     for (const auto &Predicate : predicates())
1073       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1074   }
1075 
1076   /// Provide a function to avoid emitting certain predicates. This is used to
1077   /// defer some predicate checks until after others
1078   using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
1079 
1080   /// Emit MatchTable opcodes for predicates which satisfy \p
1081   /// ShouldEmitPredicate. This should be called multiple times to ensure all
1082   /// predicates are eventually added to the match table.
1083   template <class... Args>
1084   void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
1085                                         MatchTable &Table, Args &&... args) {
1086     if (Predicates.empty() && !Optimized) {
1087       Table << MatchTable::Comment(getNoPredicateComment())
1088             << MatchTable::LineBreak;
1089       return;
1090     }
1091 
1092     for (const auto &Predicate : predicates()) {
1093       if (ShouldEmitPredicate(*Predicate))
1094         Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1095     }
1096   }
1097 };
1098 
1099 class PredicateMatcher {
1100 public:
1101   /// This enum is used for RTTI and also defines the priority that is given to
1102   /// the predicate when generating the matcher code. Kinds with higher priority
1103   /// must be tested first.
1104   ///
1105   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1106   /// but OPM_Int must have priority over OPM_RegBank since constant integers
1107   /// are represented by a virtual register defined by a G_CONSTANT instruction.
1108   ///
1109   /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1110   /// are currently not compared between each other.
1111   enum PredicateKind {
1112     IPM_Opcode,
1113     IPM_NumOperands,
1114     IPM_ImmPredicate,
1115     IPM_Imm,
1116     IPM_AtomicOrderingMMO,
1117     IPM_MemoryLLTSize,
1118     IPM_MemoryVsLLTSize,
1119     IPM_MemoryAddressSpace,
1120     IPM_MemoryAlignment,
1121     IPM_VectorSplatImm,
1122     IPM_GenericPredicate,
1123     OPM_SameOperand,
1124     OPM_ComplexPattern,
1125     OPM_IntrinsicID,
1126     OPM_CmpPredicate,
1127     OPM_Instruction,
1128     OPM_Int,
1129     OPM_LiteralInt,
1130     OPM_LLT,
1131     OPM_PointerToAny,
1132     OPM_RegBank,
1133     OPM_MBB,
1134     OPM_RecordNamedOperand,
1135   };
1136 
1137 protected:
1138   PredicateKind Kind;
1139   unsigned InsnVarID;
1140   unsigned OpIdx;
1141 
1142 public:
1143   PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1144       : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
1145 
1146   unsigned getInsnVarID() const { return InsnVarID; }
1147   unsigned getOpIdx() const { return OpIdx; }
1148 
1149   virtual ~PredicateMatcher() = default;
1150   /// Emit MatchTable opcodes that check the predicate for the given operand.
1151   virtual void emitPredicateOpcodes(MatchTable &Table,
1152                                     RuleMatcher &Rule) const = 0;
1153 
1154   PredicateKind getKind() const { return Kind; }
1155 
1156   bool dependsOnOperands() const {
1157     // Custom predicates really depend on the context pattern of the
1158     // instruction, not just the individual instruction. This therefore
1159     // implicitly depends on all other pattern constraints.
1160     return Kind == IPM_GenericPredicate;
1161   }
1162 
1163   virtual bool isIdentical(const PredicateMatcher &B) const {
1164     return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1165            OpIdx == B.OpIdx;
1166   }
1167 
1168   virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1169     return hasValue() && PredicateMatcher::isIdentical(B);
1170   }
1171 
1172   virtual MatchTableRecord getValue() const {
1173     assert(hasValue() && "Can not get a value of a value-less predicate!");
1174     llvm_unreachable("Not implemented yet");
1175   }
1176   virtual bool hasValue() const { return false; }
1177 
1178   /// Report the maximum number of temporary operands needed by the predicate
1179   /// matcher.
1180   virtual unsigned countRendererFns() const { return 0; }
1181 };
1182 
1183 /// Generates code to check a predicate of an operand.
1184 ///
1185 /// Typical predicates include:
1186 /// * Operand is a particular register.
1187 /// * Operand is assigned a particular register bank.
1188 /// * Operand is an MBB.
1189 class OperandPredicateMatcher : public PredicateMatcher {
1190 public:
1191   OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1192                           unsigned OpIdx)
1193       : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
1194   virtual ~OperandPredicateMatcher() {}
1195 
1196   /// Compare the priority of this object and B.
1197   ///
1198   /// Returns true if this object is more important than B.
1199   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
1200 };
1201 
1202 template <>
1203 std::string
1204 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1205   return "No operand predicates";
1206 }
1207 
1208 /// Generates code to check that a register operand is defined by the same exact
1209 /// one as another.
1210 class SameOperandMatcher : public OperandPredicateMatcher {
1211   std::string MatchingName;
1212   unsigned OrigOpIdx;
1213 
1214 public:
1215   SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName,
1216                      unsigned OrigOpIdx)
1217       : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1218         MatchingName(MatchingName), OrigOpIdx(OrigOpIdx) {}
1219 
1220   static bool classof(const PredicateMatcher *P) {
1221     return P->getKind() == OPM_SameOperand;
1222   }
1223 
1224   void emitPredicateOpcodes(MatchTable &Table,
1225                             RuleMatcher &Rule) const override;
1226 
1227   bool isIdentical(const PredicateMatcher &B) const override {
1228     return OperandPredicateMatcher::isIdentical(B) &&
1229            OrigOpIdx == cast<SameOperandMatcher>(&B)->OrigOpIdx &&
1230            MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1231   }
1232 };
1233 
1234 /// Generates code to check that an operand is a particular LLT.
1235 class LLTOperandMatcher : public OperandPredicateMatcher {
1236 protected:
1237   LLTCodeGen Ty;
1238 
1239 public:
1240   static std::map<LLTCodeGen, unsigned> TypeIDValues;
1241 
1242   static void initTypeIDValuesMap() {
1243     TypeIDValues.clear();
1244 
1245     unsigned ID = 0;
1246     for (const LLTCodeGen &LLTy : KnownTypes)
1247       TypeIDValues[LLTy] = ID++;
1248   }
1249 
1250   LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
1251       : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
1252     KnownTypes.insert(Ty);
1253   }
1254 
1255   static bool classof(const PredicateMatcher *P) {
1256     return P->getKind() == OPM_LLT;
1257   }
1258   bool isIdentical(const PredicateMatcher &B) const override {
1259     return OperandPredicateMatcher::isIdentical(B) &&
1260            Ty == cast<LLTOperandMatcher>(&B)->Ty;
1261   }
1262   MatchTableRecord getValue() const override {
1263     const auto VI = TypeIDValues.find(Ty);
1264     if (VI == TypeIDValues.end())
1265       return MatchTable::NamedValue(getTy().getCxxEnumValue());
1266     return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1267   }
1268   bool hasValue() const override {
1269     if (TypeIDValues.size() != KnownTypes.size())
1270       initTypeIDValuesMap();
1271     return TypeIDValues.count(Ty);
1272   }
1273 
1274   LLTCodeGen getTy() const { return Ty; }
1275 
1276   void emitPredicateOpcodes(MatchTable &Table,
1277                             RuleMatcher &Rule) const override {
1278     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1279           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1280           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
1281           << getValue() << MatchTable::LineBreak;
1282   }
1283 };
1284 
1285 std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1286 
1287 /// Generates code to check that an operand is a pointer to any address space.
1288 ///
1289 /// In SelectionDAG, the types did not describe pointers or address spaces. As a
1290 /// result, iN is used to describe a pointer of N bits to any address space and
1291 /// PatFrag predicates are typically used to constrain the address space. There's
1292 /// no reliable means to derive the missing type information from the pattern so
1293 /// imported rules must test the components of a pointer separately.
1294 ///
1295 /// If SizeInBits is zero, then the pointer size will be obtained from the
1296 /// subtarget.
1297 class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1298 protected:
1299   unsigned SizeInBits;
1300 
1301 public:
1302   PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1303                              unsigned SizeInBits)
1304       : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1305         SizeInBits(SizeInBits) {}
1306 
1307   static bool classof(const PredicateMatcher *P) {
1308     return P->getKind() == OPM_PointerToAny;
1309   }
1310 
1311   bool isIdentical(const PredicateMatcher &B) const override {
1312     return OperandPredicateMatcher::isIdentical(B) &&
1313            SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits;
1314   }
1315 
1316   void emitPredicateOpcodes(MatchTable &Table,
1317                             RuleMatcher &Rule) const override {
1318     Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1319           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1320           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1321           << MatchTable::Comment("SizeInBits")
1322           << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1323   }
1324 };
1325 
1326 /// Generates code to record named operand in RecordedOperands list at StoreIdx.
1327 /// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as
1328 /// an argument to predicate's c++ code once all operands have been matched.
1329 class RecordNamedOperandMatcher : public OperandPredicateMatcher {
1330 protected:
1331   unsigned StoreIdx;
1332   std::string Name;
1333 
1334 public:
1335   RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1336                             unsigned StoreIdx, StringRef Name)
1337       : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx),
1338         StoreIdx(StoreIdx), Name(Name) {}
1339 
1340   static bool classof(const PredicateMatcher *P) {
1341     return P->getKind() == OPM_RecordNamedOperand;
1342   }
1343 
1344   bool isIdentical(const PredicateMatcher &B) const override {
1345     return OperandPredicateMatcher::isIdentical(B) &&
1346            StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx &&
1347            Name == cast<RecordNamedOperandMatcher>(&B)->Name;
1348   }
1349 
1350   void emitPredicateOpcodes(MatchTable &Table,
1351                             RuleMatcher &Rule) const override {
1352     Table << MatchTable::Opcode("GIM_RecordNamedOperand")
1353           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1354           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1355           << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx)
1356           << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak;
1357   }
1358 };
1359 
1360 /// Generates code to check that an operand is a particular target constant.
1361 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1362 protected:
1363   const OperandMatcher &Operand;
1364   const Record &TheDef;
1365 
1366   unsigned getAllocatedTemporariesBaseID() const;
1367 
1368 public:
1369   bool isIdentical(const PredicateMatcher &B) const override { return false; }
1370 
1371   ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1372                                const OperandMatcher &Operand,
1373                                const Record &TheDef)
1374       : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1375         Operand(Operand), TheDef(TheDef) {}
1376 
1377   static bool classof(const PredicateMatcher *P) {
1378     return P->getKind() == OPM_ComplexPattern;
1379   }
1380 
1381   void emitPredicateOpcodes(MatchTable &Table,
1382                             RuleMatcher &Rule) const override {
1383     unsigned ID = getAllocatedTemporariesBaseID();
1384     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1385           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1386           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1387           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1388           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1389           << MatchTable::LineBreak;
1390   }
1391 
1392   unsigned countRendererFns() const override {
1393     return 1;
1394   }
1395 };
1396 
1397 /// Generates code to check that an operand is in a particular register bank.
1398 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1399 protected:
1400   const CodeGenRegisterClass &RC;
1401 
1402 public:
1403   RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1404                              const CodeGenRegisterClass &RC)
1405       : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
1406 
1407   bool isIdentical(const PredicateMatcher &B) const override {
1408     return OperandPredicateMatcher::isIdentical(B) &&
1409            RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1410   }
1411 
1412   static bool classof(const PredicateMatcher *P) {
1413     return P->getKind() == OPM_RegBank;
1414   }
1415 
1416   void emitPredicateOpcodes(MatchTable &Table,
1417                             RuleMatcher &Rule) const override {
1418     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1419           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1420           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1421           << MatchTable::Comment("RC")
1422           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1423           << MatchTable::LineBreak;
1424   }
1425 };
1426 
1427 /// Generates code to check that an operand is a basic block.
1428 class MBBOperandMatcher : public OperandPredicateMatcher {
1429 public:
1430   MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1431       : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
1432 
1433   static bool classof(const PredicateMatcher *P) {
1434     return P->getKind() == OPM_MBB;
1435   }
1436 
1437   void emitPredicateOpcodes(MatchTable &Table,
1438                             RuleMatcher &Rule) const override {
1439     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1440           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1441           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1442   }
1443 };
1444 
1445 class ImmOperandMatcher : public OperandPredicateMatcher {
1446 public:
1447   ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1448       : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1449 
1450   static bool classof(const PredicateMatcher *P) {
1451     return P->getKind() == IPM_Imm;
1452   }
1453 
1454   void emitPredicateOpcodes(MatchTable &Table,
1455                             RuleMatcher &Rule) const override {
1456     Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1457           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1458           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1459   }
1460 };
1461 
1462 /// Generates code to check that an operand is a G_CONSTANT with a particular
1463 /// int.
1464 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
1465 protected:
1466   int64_t Value;
1467 
1468 public:
1469   ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1470       : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
1471 
1472   bool isIdentical(const PredicateMatcher &B) const override {
1473     return OperandPredicateMatcher::isIdentical(B) &&
1474            Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1475   }
1476 
1477   static bool classof(const PredicateMatcher *P) {
1478     return P->getKind() == OPM_Int;
1479   }
1480 
1481   void emitPredicateOpcodes(MatchTable &Table,
1482                             RuleMatcher &Rule) const override {
1483     Table << MatchTable::Opcode("GIM_CheckConstantInt")
1484           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1485           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1486           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1487   }
1488 };
1489 
1490 /// Generates code to check that an operand is a raw int (where MO.isImm() or
1491 /// MO.isCImm() is true).
1492 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1493 protected:
1494   int64_t Value;
1495 
1496 public:
1497   LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1498       : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1499         Value(Value) {}
1500 
1501   bool isIdentical(const PredicateMatcher &B) const override {
1502     return OperandPredicateMatcher::isIdentical(B) &&
1503            Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1504   }
1505 
1506   static bool classof(const PredicateMatcher *P) {
1507     return P->getKind() == OPM_LiteralInt;
1508   }
1509 
1510   void emitPredicateOpcodes(MatchTable &Table,
1511                             RuleMatcher &Rule) const override {
1512     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1513           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1514           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1515           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1516   }
1517 };
1518 
1519 /// Generates code to check that an operand is an CmpInst predicate
1520 class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1521 protected:
1522   std::string PredName;
1523 
1524 public:
1525   CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1526                              std::string P)
1527     : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1528 
1529   bool isIdentical(const PredicateMatcher &B) const override {
1530     return OperandPredicateMatcher::isIdentical(B) &&
1531            PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1532   }
1533 
1534   static bool classof(const PredicateMatcher *P) {
1535     return P->getKind() == OPM_CmpPredicate;
1536   }
1537 
1538   void emitPredicateOpcodes(MatchTable &Table,
1539                             RuleMatcher &Rule) const override {
1540     Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1541           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1542           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1543           << MatchTable::Comment("Predicate")
1544           << MatchTable::NamedValue("CmpInst", PredName)
1545           << MatchTable::LineBreak;
1546   }
1547 };
1548 
1549 /// Generates code to check that an operand is an intrinsic ID.
1550 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1551 protected:
1552   const CodeGenIntrinsic *II;
1553 
1554 public:
1555   IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1556                             const CodeGenIntrinsic *II)
1557       : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
1558 
1559   bool isIdentical(const PredicateMatcher &B) const override {
1560     return OperandPredicateMatcher::isIdentical(B) &&
1561            II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1562   }
1563 
1564   static bool classof(const PredicateMatcher *P) {
1565     return P->getKind() == OPM_IntrinsicID;
1566   }
1567 
1568   void emitPredicateOpcodes(MatchTable &Table,
1569                             RuleMatcher &Rule) const override {
1570     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1571           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1572           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1573           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1574           << MatchTable::LineBreak;
1575   }
1576 };
1577 
1578 /// Generates code to check that this operand is an immediate whose value meets
1579 /// an immediate predicate.
1580 class OperandImmPredicateMatcher : public OperandPredicateMatcher {
1581 protected:
1582   TreePredicateFn Predicate;
1583 
1584 public:
1585   OperandImmPredicateMatcher(unsigned InsnVarID, unsigned OpIdx,
1586                              const TreePredicateFn &Predicate)
1587       : OperandPredicateMatcher(IPM_ImmPredicate, InsnVarID, OpIdx),
1588         Predicate(Predicate) {}
1589 
1590   bool isIdentical(const PredicateMatcher &B) const override {
1591     return OperandPredicateMatcher::isIdentical(B) &&
1592            Predicate.getOrigPatFragRecord() ==
1593                cast<OperandImmPredicateMatcher>(&B)
1594                    ->Predicate.getOrigPatFragRecord();
1595   }
1596 
1597   static bool classof(const PredicateMatcher *P) {
1598     return P->getKind() == IPM_ImmPredicate;
1599   }
1600 
1601   void emitPredicateOpcodes(MatchTable &Table,
1602                             RuleMatcher &Rule) const override {
1603     Table << MatchTable::Opcode("GIM_CheckImmOperandPredicate")
1604           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1605           << MatchTable::Comment("MO") << MatchTable::IntValue(OpIdx)
1606           << MatchTable::Comment("Predicate")
1607           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1608           << MatchTable::LineBreak;
1609   }
1610 };
1611 
1612 /// Generates code to check that a set of predicates match for a particular
1613 /// operand.
1614 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1615 protected:
1616   InstructionMatcher &Insn;
1617   unsigned OpIdx;
1618   std::string SymbolicName;
1619 
1620   /// The index of the first temporary variable allocated to this operand. The
1621   /// number of allocated temporaries can be found with
1622   /// countRendererFns().
1623   unsigned AllocatedTemporariesBaseID;
1624 
1625 public:
1626   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
1627                  const std::string &SymbolicName,
1628                  unsigned AllocatedTemporariesBaseID)
1629       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1630         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
1631 
1632   bool hasSymbolicName() const { return !SymbolicName.empty(); }
1633   StringRef getSymbolicName() const { return SymbolicName; }
1634   void setSymbolicName(StringRef Name) {
1635     assert(SymbolicName.empty() && "Operand already has a symbolic name");
1636     SymbolicName = std::string(Name);
1637   }
1638 
1639   /// Construct a new operand predicate and add it to the matcher.
1640   template <class Kind, class... Args>
1641   Optional<Kind *> addPredicate(Args &&... args) {
1642     if (isSameAsAnotherOperand())
1643       return None;
1644     Predicates.emplace_back(std::make_unique<Kind>(
1645         getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1646     return static_cast<Kind *>(Predicates.back().get());
1647   }
1648 
1649   unsigned getOpIdx() const { return OpIdx; }
1650   unsigned getInsnVarID() const;
1651 
1652   std::string getOperandExpr(unsigned InsnVarID) const {
1653     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1654            llvm::to_string(OpIdx) + ")";
1655   }
1656 
1657   InstructionMatcher &getInstructionMatcher() const { return Insn; }
1658 
1659   Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1660                               bool OperandIsAPointer);
1661 
1662   /// Emit MatchTable opcodes that test whether the instruction named in
1663   /// InsnVarID matches all the predicates and all the operands.
1664   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1665     if (!Optimized) {
1666       std::string Comment;
1667       raw_string_ostream CommentOS(Comment);
1668       CommentOS << "MIs[" << getInsnVarID() << "] ";
1669       if (SymbolicName.empty())
1670         CommentOS << "Operand " << OpIdx;
1671       else
1672         CommentOS << SymbolicName;
1673       Table << MatchTable::Comment(Comment) << MatchTable::LineBreak;
1674     }
1675 
1676     emitPredicateListOpcodes(Table, Rule);
1677   }
1678 
1679   /// Compare the priority of this object and B.
1680   ///
1681   /// Returns true if this object is more important than B.
1682   bool isHigherPriorityThan(OperandMatcher &B) {
1683     // Operand matchers involving more predicates have higher priority.
1684     if (predicates_size() > B.predicates_size())
1685       return true;
1686     if (predicates_size() < B.predicates_size())
1687       return false;
1688 
1689     // This assumes that predicates are added in a consistent order.
1690     for (auto &&Predicate : zip(predicates(), B.predicates())) {
1691       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1692         return true;
1693       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1694         return false;
1695     }
1696 
1697     return false;
1698   };
1699 
1700   /// Report the maximum number of temporary operands needed by the operand
1701   /// matcher.
1702   unsigned countRendererFns() {
1703     return std::accumulate(
1704         predicates().begin(), predicates().end(), 0,
1705         [](unsigned A,
1706            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
1707           return A + Predicate->countRendererFns();
1708         });
1709   }
1710 
1711   unsigned getAllocatedTemporariesBaseID() const {
1712     return AllocatedTemporariesBaseID;
1713   }
1714 
1715   bool isSameAsAnotherOperand() {
1716     for (const auto &Predicate : predicates())
1717       if (isa<SameOperandMatcher>(Predicate))
1718         return true;
1719     return false;
1720   }
1721 };
1722 
1723 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1724                                             bool OperandIsAPointer) {
1725   if (!VTy.isMachineValueType())
1726     return failedImport("unsupported typeset");
1727 
1728   if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1729     addPredicate<PointerToAnyOperandMatcher>(0);
1730     return Error::success();
1731   }
1732 
1733   auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1734   if (!OpTyOrNone)
1735     return failedImport("unsupported type");
1736 
1737   if (OperandIsAPointer)
1738     addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1739   else if (VTy.isPointer())
1740     addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1741                                                  OpTyOrNone->get().getSizeInBits()));
1742   else
1743     addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1744   return Error::success();
1745 }
1746 
1747 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1748   return Operand.getAllocatedTemporariesBaseID();
1749 }
1750 
1751 /// Generates code to check a predicate on an instruction.
1752 ///
1753 /// Typical predicates include:
1754 /// * The opcode of the instruction is a particular value.
1755 /// * The nsw/nuw flag is/isn't set.
1756 class InstructionPredicateMatcher : public PredicateMatcher {
1757 public:
1758   InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1759       : PredicateMatcher(Kind, InsnVarID) {}
1760   virtual ~InstructionPredicateMatcher() {}
1761 
1762   /// Compare the priority of this object and B.
1763   ///
1764   /// Returns true if this object is more important than B.
1765   virtual bool
1766   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
1767     return Kind < B.Kind;
1768   };
1769 };
1770 
1771 template <>
1772 std::string
1773 PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
1774   return "No instruction predicates";
1775 }
1776 
1777 /// Generates code to check the opcode of an instruction.
1778 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1779 protected:
1780   // Allow matching one to several, similar opcodes that share properties. This
1781   // is to handle patterns where one SelectionDAG operation maps to multiple
1782   // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
1783   // is treated as the canonical opcode.
1784   SmallVector<const CodeGenInstruction *, 2> Insts;
1785 
1786   static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1787 
1788 
1789   MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
1790     const auto VI = OpcodeValues.find(I);
1791     if (VI != OpcodeValues.end())
1792       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1793                                     VI->second);
1794     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1795   }
1796 
1797 public:
1798   static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1799     OpcodeValues.clear();
1800 
1801     unsigned OpcodeValue = 0;
1802     for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1803       OpcodeValues[I] = OpcodeValue++;
1804   }
1805 
1806   InstructionOpcodeMatcher(unsigned InsnVarID,
1807                            ArrayRef<const CodeGenInstruction *> I)
1808       : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
1809         Insts(I.begin(), I.end()) {
1810     assert((Insts.size() == 1 || Insts.size() == 2) &&
1811            "unexpected number of opcode alternatives");
1812   }
1813 
1814   static bool classof(const PredicateMatcher *P) {
1815     return P->getKind() == IPM_Opcode;
1816   }
1817 
1818   bool isIdentical(const PredicateMatcher &B) const override {
1819     return InstructionPredicateMatcher::isIdentical(B) &&
1820            Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
1821   }
1822 
1823   bool hasValue() const override {
1824     return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
1825   }
1826 
1827   // TODO: This is used for the SwitchMatcher optimization. We should be able to
1828   // return a list of the opcodes to match.
1829   MatchTableRecord getValue() const override {
1830     assert(Insts.size() == 1);
1831 
1832     const CodeGenInstruction *I = Insts[0];
1833     const auto VI = OpcodeValues.find(I);
1834     if (VI != OpcodeValues.end())
1835       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1836                                     VI->second);
1837     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1838   }
1839 
1840   void emitPredicateOpcodes(MatchTable &Table,
1841                             RuleMatcher &Rule) const override {
1842     StringRef CheckType = Insts.size() == 1 ?
1843                           "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
1844     Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
1845           << MatchTable::IntValue(InsnVarID);
1846 
1847     for (const CodeGenInstruction *I : Insts)
1848       Table << getInstValue(I);
1849     Table << MatchTable::LineBreak;
1850   }
1851 
1852   /// Compare the priority of this object and B.
1853   ///
1854   /// Returns true if this object is more important than B.
1855   bool
1856   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1857     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1858       return true;
1859     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1860       return false;
1861 
1862     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1863     // this is cosmetic at the moment, we may want to drive a similar ordering
1864     // using instruction frequency information to improve compile time.
1865     if (const InstructionOpcodeMatcher *BO =
1866             dyn_cast<InstructionOpcodeMatcher>(&B))
1867       return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
1868 
1869     return false;
1870   };
1871 
1872   bool isConstantInstruction() const {
1873     return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
1874   }
1875 
1876   // The first opcode is the canonical opcode, and later are alternatives.
1877   StringRef getOpcode() const {
1878     return Insts[0]->TheDef->getName();
1879   }
1880 
1881   ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
1882     return Insts;
1883   }
1884 
1885   bool isVariadicNumOperands() const {
1886     // If one is variadic, they all should be.
1887     return Insts[0]->Operands.isVariadic;
1888   }
1889 
1890   StringRef getOperandType(unsigned OpIdx) const {
1891     // Types expected to be uniform for all alternatives.
1892     return Insts[0]->Operands[OpIdx].OperandType;
1893   }
1894 };
1895 
1896 DenseMap<const CodeGenInstruction *, unsigned>
1897     InstructionOpcodeMatcher::OpcodeValues;
1898 
1899 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1900   unsigned NumOperands = 0;
1901 
1902 public:
1903   InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1904       : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1905         NumOperands(NumOperands) {}
1906 
1907   static bool classof(const PredicateMatcher *P) {
1908     return P->getKind() == IPM_NumOperands;
1909   }
1910 
1911   bool isIdentical(const PredicateMatcher &B) const override {
1912     return InstructionPredicateMatcher::isIdentical(B) &&
1913            NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1914   }
1915 
1916   void emitPredicateOpcodes(MatchTable &Table,
1917                             RuleMatcher &Rule) const override {
1918     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1919           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1920           << MatchTable::Comment("Expected")
1921           << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1922   }
1923 };
1924 
1925 /// Generates code to check that this instruction is a constant whose value
1926 /// meets an immediate predicate.
1927 ///
1928 /// Immediates are slightly odd since they are typically used like an operand
1929 /// but are represented as an operator internally. We typically write simm8:$src
1930 /// in a tablegen pattern, but this is just syntactic sugar for
1931 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1932 /// that will be matched and the predicate (which is attached to the imm
1933 /// operator) that will be tested. In SelectionDAG this describes a
1934 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1935 ///
1936 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1937 /// this representation, the immediate could be tested with an
1938 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1939 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1940 /// there are two implementation issues with producing that matcher
1941 /// configuration from the SelectionDAG pattern:
1942 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1943 ///   were we to sink the immediate predicate to the operand we would have to
1944 ///   have two partial implementations of PatFrag support, one for immediates
1945 ///   and one for non-immediates.
1946 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1947 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1948 ///   would also have to complicate (or duplicate) the code that descends and
1949 ///   creates matchers for the subtree.
1950 /// Overall, it's simpler to handle it in the place it was found.
1951 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1952 protected:
1953   TreePredicateFn Predicate;
1954 
1955 public:
1956   InstructionImmPredicateMatcher(unsigned InsnVarID,
1957                                  const TreePredicateFn &Predicate)
1958       : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1959         Predicate(Predicate) {}
1960 
1961   bool isIdentical(const PredicateMatcher &B) const override {
1962     return InstructionPredicateMatcher::isIdentical(B) &&
1963            Predicate.getOrigPatFragRecord() ==
1964                cast<InstructionImmPredicateMatcher>(&B)
1965                    ->Predicate.getOrigPatFragRecord();
1966   }
1967 
1968   static bool classof(const PredicateMatcher *P) {
1969     return P->getKind() == IPM_ImmPredicate;
1970   }
1971 
1972   void emitPredicateOpcodes(MatchTable &Table,
1973                             RuleMatcher &Rule) const override {
1974     Table << MatchTable::Opcode(getMatchOpcodeForImmPredicate(Predicate))
1975           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1976           << MatchTable::Comment("Predicate")
1977           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1978           << MatchTable::LineBreak;
1979   }
1980 };
1981 
1982 /// Generates code to check that a memory instruction has a atomic ordering
1983 /// MachineMemoryOperand.
1984 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1985 public:
1986   enum AOComparator {
1987     AO_Exactly,
1988     AO_OrStronger,
1989     AO_WeakerThan,
1990   };
1991 
1992 protected:
1993   StringRef Order;
1994   AOComparator Comparator;
1995 
1996 public:
1997   AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
1998                                     AOComparator Comparator = AO_Exactly)
1999       : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
2000         Order(Order), Comparator(Comparator) {}
2001 
2002   static bool classof(const PredicateMatcher *P) {
2003     return P->getKind() == IPM_AtomicOrderingMMO;
2004   }
2005 
2006   bool isIdentical(const PredicateMatcher &B) const override {
2007     if (!InstructionPredicateMatcher::isIdentical(B))
2008       return false;
2009     const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
2010     return Order == R.Order && Comparator == R.Comparator;
2011   }
2012 
2013   void emitPredicateOpcodes(MatchTable &Table,
2014                             RuleMatcher &Rule) const override {
2015     StringRef Opcode = "GIM_CheckAtomicOrdering";
2016 
2017     if (Comparator == AO_OrStronger)
2018       Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
2019     if (Comparator == AO_WeakerThan)
2020       Opcode = "GIM_CheckAtomicOrderingWeakerThan";
2021 
2022     Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
2023           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
2024           << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
2025           << MatchTable::LineBreak;
2026   }
2027 };
2028 
2029 /// Generates code to check that the size of an MMO is exactly N bytes.
2030 class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
2031 protected:
2032   unsigned MMOIdx;
2033   uint64_t Size;
2034 
2035 public:
2036   MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
2037       : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
2038         MMOIdx(MMOIdx), Size(Size) {}
2039 
2040   static bool classof(const PredicateMatcher *P) {
2041     return P->getKind() == IPM_MemoryLLTSize;
2042   }
2043   bool isIdentical(const PredicateMatcher &B) const override {
2044     return InstructionPredicateMatcher::isIdentical(B) &&
2045            MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
2046            Size == cast<MemorySizePredicateMatcher>(&B)->Size;
2047   }
2048 
2049   void emitPredicateOpcodes(MatchTable &Table,
2050                             RuleMatcher &Rule) const override {
2051     Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
2052           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2053           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2054           << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
2055           << MatchTable::LineBreak;
2056   }
2057 };
2058 
2059 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
2060 protected:
2061   unsigned MMOIdx;
2062   SmallVector<unsigned, 4> AddrSpaces;
2063 
2064 public:
2065   MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2066                                      ArrayRef<unsigned> AddrSpaces)
2067       : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
2068         MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
2069 
2070   static bool classof(const PredicateMatcher *P) {
2071     return P->getKind() == IPM_MemoryAddressSpace;
2072   }
2073   bool isIdentical(const PredicateMatcher &B) const override {
2074     if (!InstructionPredicateMatcher::isIdentical(B))
2075       return false;
2076     auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
2077     return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
2078   }
2079 
2080   void emitPredicateOpcodes(MatchTable &Table,
2081                             RuleMatcher &Rule) const override {
2082     Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
2083           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2084           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2085         // Encode number of address spaces to expect.
2086           << MatchTable::Comment("NumAddrSpace")
2087           << MatchTable::IntValue(AddrSpaces.size());
2088     for (unsigned AS : AddrSpaces)
2089       Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
2090 
2091     Table << MatchTable::LineBreak;
2092   }
2093 };
2094 
2095 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
2096 protected:
2097   unsigned MMOIdx;
2098   int MinAlign;
2099 
2100 public:
2101   MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2102                                   int MinAlign)
2103       : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
2104         MMOIdx(MMOIdx), MinAlign(MinAlign) {
2105     assert(MinAlign > 0);
2106   }
2107 
2108   static bool classof(const PredicateMatcher *P) {
2109     return P->getKind() == IPM_MemoryAlignment;
2110   }
2111 
2112   bool isIdentical(const PredicateMatcher &B) const override {
2113     if (!InstructionPredicateMatcher::isIdentical(B))
2114       return false;
2115     auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
2116     return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
2117   }
2118 
2119   void emitPredicateOpcodes(MatchTable &Table,
2120                             RuleMatcher &Rule) const override {
2121     Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
2122           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2123           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2124           << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
2125           << MatchTable::LineBreak;
2126   }
2127 };
2128 
2129 /// Generates code to check that the size of an MMO is less-than, equal-to, or
2130 /// greater than a given LLT.
2131 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
2132 public:
2133   enum RelationKind {
2134     GreaterThan,
2135     EqualTo,
2136     LessThan,
2137   };
2138 
2139 protected:
2140   unsigned MMOIdx;
2141   RelationKind Relation;
2142   unsigned OpIdx;
2143 
2144 public:
2145   MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2146                                   enum RelationKind Relation,
2147                                   unsigned OpIdx)
2148       : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
2149         MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
2150 
2151   static bool classof(const PredicateMatcher *P) {
2152     return P->getKind() == IPM_MemoryVsLLTSize;
2153   }
2154   bool isIdentical(const PredicateMatcher &B) const override {
2155     return InstructionPredicateMatcher::isIdentical(B) &&
2156            MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2157            Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2158            OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2159   }
2160 
2161   void emitPredicateOpcodes(MatchTable &Table,
2162                             RuleMatcher &Rule) const override {
2163     Table << MatchTable::Opcode(Relation == EqualTo
2164                                     ? "GIM_CheckMemorySizeEqualToLLT"
2165                                     : Relation == GreaterThan
2166                                           ? "GIM_CheckMemorySizeGreaterThanLLT"
2167                                           : "GIM_CheckMemorySizeLessThanLLT")
2168           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2169           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2170           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2171           << MatchTable::LineBreak;
2172   }
2173 };
2174 
2175 // Matcher for immAllOnesV/immAllZerosV
2176 class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
2177 public:
2178   enum SplatKind {
2179     AllZeros,
2180     AllOnes
2181   };
2182 
2183 private:
2184   SplatKind Kind;
2185 
2186 public:
2187   VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
2188       : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
2189 
2190   static bool classof(const PredicateMatcher *P) {
2191     return P->getKind() == IPM_VectorSplatImm;
2192   }
2193 
2194   bool isIdentical(const PredicateMatcher &B) const override {
2195     return InstructionPredicateMatcher::isIdentical(B) &&
2196            Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
2197   }
2198 
2199   void emitPredicateOpcodes(MatchTable &Table,
2200                             RuleMatcher &Rule) const override {
2201     if (Kind == AllOnes)
2202       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
2203     else
2204       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
2205 
2206     Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
2207     Table << MatchTable::LineBreak;
2208   }
2209 };
2210 
2211 /// Generates code to check an arbitrary C++ instruction predicate.
2212 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2213 protected:
2214   TreePredicateFn Predicate;
2215 
2216 public:
2217   GenericInstructionPredicateMatcher(unsigned InsnVarID,
2218                                      TreePredicateFn Predicate)
2219       : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2220         Predicate(Predicate) {}
2221 
2222   static bool classof(const InstructionPredicateMatcher *P) {
2223     return P->getKind() == IPM_GenericPredicate;
2224   }
2225   bool isIdentical(const PredicateMatcher &B) const override {
2226     return InstructionPredicateMatcher::isIdentical(B) &&
2227            Predicate ==
2228                static_cast<const GenericInstructionPredicateMatcher &>(B)
2229                    .Predicate;
2230   }
2231   void emitPredicateOpcodes(MatchTable &Table,
2232                             RuleMatcher &Rule) const override {
2233     Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2234           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2235           << MatchTable::Comment("FnId")
2236           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2237           << MatchTable::LineBreak;
2238   }
2239 };
2240 
2241 /// Generates code to check that a set of predicates and operands match for a
2242 /// particular instruction.
2243 ///
2244 /// Typical predicates include:
2245 /// * Has a specific opcode.
2246 /// * Has an nsw/nuw flag or doesn't.
2247 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
2248 protected:
2249   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
2250 
2251   RuleMatcher &Rule;
2252 
2253   /// The operands to match. All rendered operands must be present even if the
2254   /// condition is always true.
2255   OperandVec Operands;
2256   bool NumOperandsCheck = true;
2257 
2258   std::string SymbolicName;
2259   unsigned InsnVarID;
2260 
2261   /// PhysRegInputs - List list has an entry for each explicitly specified
2262   /// physreg input to the pattern.  The first elt is the Register node, the
2263   /// second is the recorded slot number the input pattern match saved it in.
2264   SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2265 
2266 public:
2267   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
2268                      bool NumOpsCheck = true)
2269       : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
2270     // We create a new instruction matcher.
2271     // Get a new ID for that instruction.
2272     InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2273   }
2274 
2275   /// Construct a new instruction predicate and add it to the matcher.
2276   template <class Kind, class... Args>
2277   Optional<Kind *> addPredicate(Args &&... args) {
2278     Predicates.emplace_back(
2279         std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
2280     return static_cast<Kind *>(Predicates.back().get());
2281   }
2282 
2283   RuleMatcher &getRuleMatcher() const { return Rule; }
2284 
2285   unsigned getInsnVarID() const { return InsnVarID; }
2286 
2287   /// Add an operand to the matcher.
2288   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2289                              unsigned AllocatedTemporariesBaseID) {
2290     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2291                                              AllocatedTemporariesBaseID));
2292     if (!SymbolicName.empty())
2293       Rule.defineOperand(SymbolicName, *Operands.back());
2294 
2295     return *Operands.back();
2296   }
2297 
2298   OperandMatcher &getOperand(unsigned OpIdx) {
2299     auto I = llvm::find_if(Operands,
2300                            [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
2301                              return X->getOpIdx() == OpIdx;
2302                            });
2303     if (I != Operands.end())
2304       return **I;
2305     llvm_unreachable("Failed to lookup operand");
2306   }
2307 
2308   OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2309                                   unsigned TempOpIdx) {
2310     assert(SymbolicName.empty());
2311     OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2312     Operands.emplace_back(OM);
2313     Rule.definePhysRegOperand(Reg, *OM);
2314     PhysRegInputs.emplace_back(Reg, OpIdx);
2315     return *OM;
2316   }
2317 
2318   ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2319     return PhysRegInputs;
2320   }
2321 
2322   StringRef getSymbolicName() const { return SymbolicName; }
2323   unsigned getNumOperands() const { return Operands.size(); }
2324   OperandVec::iterator operands_begin() { return Operands.begin(); }
2325   OperandVec::iterator operands_end() { return Operands.end(); }
2326   iterator_range<OperandVec::iterator> operands() {
2327     return make_range(operands_begin(), operands_end());
2328   }
2329   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2330   OperandVec::const_iterator operands_end() const { return Operands.end(); }
2331   iterator_range<OperandVec::const_iterator> operands() const {
2332     return make_range(operands_begin(), operands_end());
2333   }
2334   bool operands_empty() const { return Operands.empty(); }
2335 
2336   void pop_front() { Operands.erase(Operands.begin()); }
2337 
2338   void optimize();
2339 
2340   /// Emit MatchTable opcodes that test whether the instruction named in
2341   /// InsnVarName matches all the predicates and all the operands.
2342   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
2343     if (NumOperandsCheck)
2344       InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2345           .emitPredicateOpcodes(Table, Rule);
2346 
2347     // First emit all instruction level predicates need to be verified before we
2348     // can verify operands.
2349     emitFilteredPredicateListOpcodes(
2350       [](const PredicateMatcher &P) {
2351         return !P.dependsOnOperands();
2352       }, Table, Rule);
2353 
2354     // Emit all operand constraints.
2355     for (const auto &Operand : Operands)
2356       Operand->emitPredicateOpcodes(Table, Rule);
2357 
2358     // All of the tablegen defined predicates should now be matched. Now emit
2359     // any custom predicates that rely on all generated checks.
2360     emitFilteredPredicateListOpcodes(
2361       [](const PredicateMatcher &P) {
2362         return P.dependsOnOperands();
2363       }, Table, Rule);
2364   }
2365 
2366   /// Compare the priority of this object and B.
2367   ///
2368   /// Returns true if this object is more important than B.
2369   bool isHigherPriorityThan(InstructionMatcher &B) {
2370     // Instruction matchers involving more operands have higher priority.
2371     if (Operands.size() > B.Operands.size())
2372       return true;
2373     if (Operands.size() < B.Operands.size())
2374       return false;
2375 
2376     for (auto &&P : zip(predicates(), B.predicates())) {
2377       auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2378       auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2379       if (L->isHigherPriorityThan(*R))
2380         return true;
2381       if (R->isHigherPriorityThan(*L))
2382         return false;
2383     }
2384 
2385     for (auto Operand : zip(Operands, B.Operands)) {
2386       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
2387         return true;
2388       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
2389         return false;
2390     }
2391 
2392     return false;
2393   };
2394 
2395   /// Report the maximum number of temporary operands needed by the instruction
2396   /// matcher.
2397   unsigned countRendererFns() {
2398     return std::accumulate(
2399                predicates().begin(), predicates().end(), 0,
2400                [](unsigned A,
2401                   const std::unique_ptr<PredicateMatcher> &Predicate) {
2402                  return A + Predicate->countRendererFns();
2403                }) +
2404            std::accumulate(
2405                Operands.begin(), Operands.end(), 0,
2406                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
2407                  return A + Operand->countRendererFns();
2408                });
2409   }
2410 
2411   InstructionOpcodeMatcher &getOpcodeMatcher() {
2412     for (auto &P : predicates())
2413       if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2414         return *OpMatcher;
2415     llvm_unreachable("Didn't find an opcode matcher");
2416   }
2417 
2418   bool isConstantInstruction() {
2419     return getOpcodeMatcher().isConstantInstruction();
2420   }
2421 
2422   StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
2423 };
2424 
2425 StringRef RuleMatcher::getOpcode() const {
2426   return Matchers.front()->getOpcode();
2427 }
2428 
2429 unsigned RuleMatcher::getNumOperands() const {
2430   return Matchers.front()->getNumOperands();
2431 }
2432 
2433 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2434   InstructionMatcher &InsnMatcher = *Matchers.front();
2435   if (!InsnMatcher.predicates_empty())
2436     if (const auto *TM =
2437             dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2438       if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2439         return TM->getTy();
2440   return {};
2441 }
2442 
2443 /// Generates code to check that the operand is a register defined by an
2444 /// instruction that matches the given instruction matcher.
2445 ///
2446 /// For example, the pattern:
2447 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2448 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2449 /// the:
2450 ///   (G_ADD $src1, $src2)
2451 /// subpattern.
2452 class InstructionOperandMatcher : public OperandPredicateMatcher {
2453 protected:
2454   std::unique_ptr<InstructionMatcher> InsnMatcher;
2455 
2456 public:
2457   InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2458                             RuleMatcher &Rule, StringRef SymbolicName,
2459                             bool NumOpsCheck = true)
2460       : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
2461         InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
2462 
2463   static bool classof(const PredicateMatcher *P) {
2464     return P->getKind() == OPM_Instruction;
2465   }
2466 
2467   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2468 
2469   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2470     const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2471     Table << MatchTable::Opcode("GIM_RecordInsn")
2472           << MatchTable::Comment("DefineMI")
2473           << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2474           << MatchTable::IntValue(getInsnVarID())
2475           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2476           << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2477           << MatchTable::LineBreak;
2478   }
2479 
2480   void emitPredicateOpcodes(MatchTable &Table,
2481                             RuleMatcher &Rule) const override {
2482     emitCaptureOpcodes(Table, Rule);
2483     InsnMatcher->emitPredicateOpcodes(Table, Rule);
2484   }
2485 
2486   bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2487     if (OperandPredicateMatcher::isHigherPriorityThan(B))
2488       return true;
2489     if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2490       return false;
2491 
2492     if (const InstructionOperandMatcher *BP =
2493             dyn_cast<InstructionOperandMatcher>(&B))
2494       if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2495         return true;
2496     return false;
2497   }
2498 };
2499 
2500 void InstructionMatcher::optimize() {
2501   SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2502   const auto &OpcMatcher = getOpcodeMatcher();
2503 
2504   Stash.push_back(predicates_pop_front());
2505   if (Stash.back().get() == &OpcMatcher) {
2506     if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
2507       Stash.emplace_back(
2508           new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2509     NumOperandsCheck = false;
2510 
2511     for (auto &OM : Operands)
2512       for (auto &OP : OM->predicates())
2513         if (isa<IntrinsicIDOperandMatcher>(OP)) {
2514           Stash.push_back(std::move(OP));
2515           OM->eraseNullPredicates();
2516           break;
2517         }
2518   }
2519 
2520   if (InsnVarID > 0) {
2521     assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2522     for (auto &OP : Operands[0]->predicates())
2523       OP.reset();
2524     Operands[0]->eraseNullPredicates();
2525   }
2526   for (auto &OM : Operands) {
2527     for (auto &OP : OM->predicates())
2528       if (isa<LLTOperandMatcher>(OP))
2529         Stash.push_back(std::move(OP));
2530     OM->eraseNullPredicates();
2531   }
2532   while (!Stash.empty())
2533     prependPredicate(Stash.pop_back_val());
2534 }
2535 
2536 //===- Actions ------------------------------------------------------------===//
2537 class OperandRenderer {
2538 public:
2539   enum RendererKind {
2540     OR_Copy,
2541     OR_CopyOrAddZeroReg,
2542     OR_CopySubReg,
2543     OR_CopyPhysReg,
2544     OR_CopyConstantAsImm,
2545     OR_CopyFConstantAsFPImm,
2546     OR_Imm,
2547     OR_SubRegIndex,
2548     OR_Register,
2549     OR_TempRegister,
2550     OR_ComplexPattern,
2551     OR_Custom,
2552     OR_CustomOperand
2553   };
2554 
2555 protected:
2556   RendererKind Kind;
2557 
2558 public:
2559   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2560   virtual ~OperandRenderer() {}
2561 
2562   RendererKind getKind() const { return Kind; }
2563 
2564   virtual void emitRenderOpcodes(MatchTable &Table,
2565                                  RuleMatcher &Rule) const = 0;
2566 };
2567 
2568 /// A CopyRenderer emits code to copy a single operand from an existing
2569 /// instruction to the one being built.
2570 class CopyRenderer : public OperandRenderer {
2571 protected:
2572   unsigned NewInsnID;
2573   /// The name of the operand.
2574   const StringRef SymbolicName;
2575 
2576 public:
2577   CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2578       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
2579         SymbolicName(SymbolicName) {
2580     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2581   }
2582 
2583   static bool classof(const OperandRenderer *R) {
2584     return R->getKind() == OR_Copy;
2585   }
2586 
2587   StringRef getSymbolicName() const { return SymbolicName; }
2588 
2589   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2590     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2591     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2592     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2593           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2594           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2595           << MatchTable::IntValue(Operand.getOpIdx())
2596           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2597   }
2598 };
2599 
2600 /// A CopyRenderer emits code to copy a virtual register to a specific physical
2601 /// register.
2602 class CopyPhysRegRenderer : public OperandRenderer {
2603 protected:
2604   unsigned NewInsnID;
2605   Record *PhysReg;
2606 
2607 public:
2608   CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2609       : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2610         PhysReg(Reg) {
2611     assert(PhysReg);
2612   }
2613 
2614   static bool classof(const OperandRenderer *R) {
2615     return R->getKind() == OR_CopyPhysReg;
2616   }
2617 
2618   Record *getPhysReg() const { return PhysReg; }
2619 
2620   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2621     const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2622     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2623     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2624           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2625           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2626           << MatchTable::IntValue(Operand.getOpIdx())
2627           << MatchTable::Comment(PhysReg->getName())
2628           << MatchTable::LineBreak;
2629   }
2630 };
2631 
2632 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2633 /// existing instruction to the one being built. If the operand turns out to be
2634 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2635 class CopyOrAddZeroRegRenderer : public OperandRenderer {
2636 protected:
2637   unsigned NewInsnID;
2638   /// The name of the operand.
2639   const StringRef SymbolicName;
2640   const Record *ZeroRegisterDef;
2641 
2642 public:
2643   CopyOrAddZeroRegRenderer(unsigned NewInsnID,
2644                            StringRef SymbolicName, Record *ZeroRegisterDef)
2645       : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2646         SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2647     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2648   }
2649 
2650   static bool classof(const OperandRenderer *R) {
2651     return R->getKind() == OR_CopyOrAddZeroReg;
2652   }
2653 
2654   StringRef getSymbolicName() const { return SymbolicName; }
2655 
2656   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2657     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2658     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2659     Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2660           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2661           << MatchTable::Comment("OldInsnID")
2662           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2663           << MatchTable::IntValue(Operand.getOpIdx())
2664           << MatchTable::NamedValue(
2665                  (ZeroRegisterDef->getValue("Namespace")
2666                       ? ZeroRegisterDef->getValueAsString("Namespace")
2667                       : ""),
2668                  ZeroRegisterDef->getName())
2669           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2670   }
2671 };
2672 
2673 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2674 /// an extended immediate operand.
2675 class CopyConstantAsImmRenderer : public OperandRenderer {
2676 protected:
2677   unsigned NewInsnID;
2678   /// The name of the operand.
2679   const std::string SymbolicName;
2680   bool Signed;
2681 
2682 public:
2683   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2684       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2685         SymbolicName(SymbolicName), Signed(true) {}
2686 
2687   static bool classof(const OperandRenderer *R) {
2688     return R->getKind() == OR_CopyConstantAsImm;
2689   }
2690 
2691   StringRef getSymbolicName() const { return SymbolicName; }
2692 
2693   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2694     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2695     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2696     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2697                                        : "GIR_CopyConstantAsUImm")
2698           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2699           << MatchTable::Comment("OldInsnID")
2700           << MatchTable::IntValue(OldInsnVarID)
2701           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2702   }
2703 };
2704 
2705 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2706 /// instruction to an extended immediate operand.
2707 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2708 protected:
2709   unsigned NewInsnID;
2710   /// The name of the operand.
2711   const std::string SymbolicName;
2712 
2713 public:
2714   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2715       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2716         SymbolicName(SymbolicName) {}
2717 
2718   static bool classof(const OperandRenderer *R) {
2719     return R->getKind() == OR_CopyFConstantAsFPImm;
2720   }
2721 
2722   StringRef getSymbolicName() const { return SymbolicName; }
2723 
2724   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2725     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2726     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2727     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2728           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2729           << MatchTable::Comment("OldInsnID")
2730           << MatchTable::IntValue(OldInsnVarID)
2731           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2732   }
2733 };
2734 
2735 /// A CopySubRegRenderer emits code to copy a single register operand from an
2736 /// existing instruction to the one being built and indicate that only a
2737 /// subregister should be copied.
2738 class CopySubRegRenderer : public OperandRenderer {
2739 protected:
2740   unsigned NewInsnID;
2741   /// The name of the operand.
2742   const StringRef SymbolicName;
2743   /// The subregister to extract.
2744   const CodeGenSubRegIndex *SubReg;
2745 
2746 public:
2747   CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2748                      const CodeGenSubRegIndex *SubReg)
2749       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
2750         SymbolicName(SymbolicName), SubReg(SubReg) {}
2751 
2752   static bool classof(const OperandRenderer *R) {
2753     return R->getKind() == OR_CopySubReg;
2754   }
2755 
2756   StringRef getSymbolicName() const { return SymbolicName; }
2757 
2758   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2759     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2760     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2761     Table << MatchTable::Opcode("GIR_CopySubReg")
2762           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2763           << MatchTable::Comment("OldInsnID")
2764           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2765           << MatchTable::IntValue(Operand.getOpIdx())
2766           << MatchTable::Comment("SubRegIdx")
2767           << MatchTable::IntValue(SubReg->EnumValue)
2768           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2769   }
2770 };
2771 
2772 /// Adds a specific physical register to the instruction being built.
2773 /// This is typically useful for WZR/XZR on AArch64.
2774 class AddRegisterRenderer : public OperandRenderer {
2775 protected:
2776   unsigned InsnID;
2777   const Record *RegisterDef;
2778   bool IsDef;
2779   const CodeGenTarget &Target;
2780 
2781 public:
2782   AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target,
2783                       const Record *RegisterDef, bool IsDef = false)
2784       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2785         IsDef(IsDef), Target(Target) {}
2786 
2787   static bool classof(const OperandRenderer *R) {
2788     return R->getKind() == OR_Register;
2789   }
2790 
2791   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2792     Table << MatchTable::Opcode("GIR_AddRegister")
2793           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID);
2794     if (RegisterDef->getName() != "zero_reg") {
2795       Table << MatchTable::NamedValue(
2796                    (RegisterDef->getValue("Namespace")
2797                         ? RegisterDef->getValueAsString("Namespace")
2798                         : ""),
2799                    RegisterDef->getName());
2800     } else {
2801       Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister");
2802     }
2803     Table << MatchTable::Comment("AddRegisterRegFlags");
2804 
2805     // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2806     // really needed for a physical register reference. We can pack the
2807     // register and flags in a single field.
2808     if (IsDef)
2809       Table << MatchTable::NamedValue("RegState::Define");
2810     else
2811       Table << MatchTable::IntValue(0);
2812     Table << MatchTable::LineBreak;
2813   }
2814 };
2815 
2816 /// Adds a specific temporary virtual register to the instruction being built.
2817 /// This is used to chain instructions together when emitting multiple
2818 /// instructions.
2819 class TempRegRenderer : public OperandRenderer {
2820 protected:
2821   unsigned InsnID;
2822   unsigned TempRegID;
2823   const CodeGenSubRegIndex *SubRegIdx;
2824   bool IsDef;
2825   bool IsDead;
2826 
2827 public:
2828   TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
2829                   const CodeGenSubRegIndex *SubReg = nullptr,
2830                   bool IsDead = false)
2831       : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2832         SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
2833 
2834   static bool classof(const OperandRenderer *R) {
2835     return R->getKind() == OR_TempRegister;
2836   }
2837 
2838   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2839     if (SubRegIdx) {
2840       assert(!IsDef);
2841       Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2842     } else
2843       Table << MatchTable::Opcode("GIR_AddTempRegister");
2844 
2845     Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2846           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2847           << MatchTable::Comment("TempRegFlags");
2848 
2849     if (IsDef) {
2850       SmallString<32> RegFlags;
2851       RegFlags += "RegState::Define";
2852       if (IsDead)
2853         RegFlags += "|RegState::Dead";
2854       Table << MatchTable::NamedValue(RegFlags);
2855     } else
2856       Table << MatchTable::IntValue(0);
2857 
2858     if (SubRegIdx)
2859       Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
2860     Table << MatchTable::LineBreak;
2861   }
2862 };
2863 
2864 /// Adds a specific immediate to the instruction being built.
2865 class ImmRenderer : public OperandRenderer {
2866 protected:
2867   unsigned InsnID;
2868   int64_t Imm;
2869 
2870 public:
2871   ImmRenderer(unsigned InsnID, int64_t Imm)
2872       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
2873 
2874   static bool classof(const OperandRenderer *R) {
2875     return R->getKind() == OR_Imm;
2876   }
2877 
2878   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2879     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2880           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2881           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
2882   }
2883 };
2884 
2885 /// Adds an enum value for a subreg index to the instruction being built.
2886 class SubRegIndexRenderer : public OperandRenderer {
2887 protected:
2888   unsigned InsnID;
2889   const CodeGenSubRegIndex *SubRegIdx;
2890 
2891 public:
2892   SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2893       : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2894 
2895   static bool classof(const OperandRenderer *R) {
2896     return R->getKind() == OR_SubRegIndex;
2897   }
2898 
2899   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2900     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2901           << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2902           << MatchTable::IntValue(SubRegIdx->EnumValue)
2903           << MatchTable::LineBreak;
2904   }
2905 };
2906 
2907 /// Adds operands by calling a renderer function supplied by the ComplexPattern
2908 /// matcher function.
2909 class RenderComplexPatternOperand : public OperandRenderer {
2910 private:
2911   unsigned InsnID;
2912   const Record &TheDef;
2913   /// The name of the operand.
2914   const StringRef SymbolicName;
2915   /// The renderer number. This must be unique within a rule since it's used to
2916   /// identify a temporary variable to hold the renderer function.
2917   unsigned RendererID;
2918   /// When provided, this is the suboperand of the ComplexPattern operand to
2919   /// render. Otherwise all the suboperands will be rendered.
2920   Optional<unsigned> SubOperand;
2921 
2922   unsigned getNumOperands() const {
2923     return TheDef.getValueAsDag("Operands")->getNumArgs();
2924   }
2925 
2926 public:
2927   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
2928                               StringRef SymbolicName, unsigned RendererID,
2929                               Optional<unsigned> SubOperand = None)
2930       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
2931         SymbolicName(SymbolicName), RendererID(RendererID),
2932         SubOperand(SubOperand) {}
2933 
2934   static bool classof(const OperandRenderer *R) {
2935     return R->getKind() == OR_ComplexPattern;
2936   }
2937 
2938   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2939     Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2940                                                       : "GIR_ComplexRenderer")
2941           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2942           << MatchTable::Comment("RendererID")
2943           << MatchTable::IntValue(RendererID);
2944     if (SubOperand.hasValue())
2945       Table << MatchTable::Comment("SubOperand")
2946             << MatchTable::IntValue(SubOperand.getValue());
2947     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2948   }
2949 };
2950 
2951 class CustomRenderer : public OperandRenderer {
2952 protected:
2953   unsigned InsnID;
2954   const Record &Renderer;
2955   /// The name of the operand.
2956   const std::string SymbolicName;
2957 
2958 public:
2959   CustomRenderer(unsigned InsnID, const Record &Renderer,
2960                  StringRef SymbolicName)
2961       : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2962         SymbolicName(SymbolicName) {}
2963 
2964   static bool classof(const OperandRenderer *R) {
2965     return R->getKind() == OR_Custom;
2966   }
2967 
2968   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2969     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2970     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2971     Table << MatchTable::Opcode("GIR_CustomRenderer")
2972           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2973           << MatchTable::Comment("OldInsnID")
2974           << MatchTable::IntValue(OldInsnVarID)
2975           << MatchTable::Comment("Renderer")
2976           << MatchTable::NamedValue(
2977                  "GICR_" + Renderer.getValueAsString("RendererFn").str())
2978           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2979   }
2980 };
2981 
2982 class CustomOperandRenderer : public OperandRenderer {
2983 protected:
2984   unsigned InsnID;
2985   const Record &Renderer;
2986   /// The name of the operand.
2987   const std::string SymbolicName;
2988 
2989 public:
2990   CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2991                         StringRef SymbolicName)
2992       : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2993         SymbolicName(SymbolicName) {}
2994 
2995   static bool classof(const OperandRenderer *R) {
2996     return R->getKind() == OR_CustomOperand;
2997   }
2998 
2999   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3000     const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
3001     Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
3002           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3003           << MatchTable::Comment("OldInsnID")
3004           << MatchTable::IntValue(OpdMatcher.getInsnVarID())
3005           << MatchTable::Comment("OpIdx")
3006           << MatchTable::IntValue(OpdMatcher.getOpIdx())
3007           << MatchTable::Comment("OperandRenderer")
3008           << MatchTable::NamedValue(
3009             "GICR_" + Renderer.getValueAsString("RendererFn").str())
3010           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
3011   }
3012 };
3013 
3014 /// An action taken when all Matcher predicates succeeded for a parent rule.
3015 ///
3016 /// Typical actions include:
3017 /// * Changing the opcode of an instruction.
3018 /// * Adding an operand to an instruction.
3019 class MatchAction {
3020 public:
3021   virtual ~MatchAction() {}
3022 
3023   /// Emit the MatchTable opcodes to implement the action.
3024   virtual void emitActionOpcodes(MatchTable &Table,
3025                                  RuleMatcher &Rule) const = 0;
3026 };
3027 
3028 /// Generates a comment describing the matched rule being acted upon.
3029 class DebugCommentAction : public MatchAction {
3030 private:
3031   std::string S;
3032 
3033 public:
3034   DebugCommentAction(StringRef S) : S(std::string(S)) {}
3035 
3036   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3037     Table << MatchTable::Comment(S) << MatchTable::LineBreak;
3038   }
3039 };
3040 
3041 /// Generates code to build an instruction or mutate an existing instruction
3042 /// into the desired instruction when this is possible.
3043 class BuildMIAction : public MatchAction {
3044 private:
3045   unsigned InsnID;
3046   const CodeGenInstruction *I;
3047   InstructionMatcher *Matched;
3048   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
3049 
3050   /// True if the instruction can be built solely by mutating the opcode.
3051   bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
3052     if (!Insn)
3053       return false;
3054 
3055     if (OperandRenderers.size() != Insn->getNumOperands())
3056       return false;
3057 
3058     for (const auto &Renderer : enumerate(OperandRenderers)) {
3059       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
3060         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
3061         if (Insn != &OM.getInstructionMatcher() ||
3062             OM.getOpIdx() != Renderer.index())
3063           return false;
3064       } else
3065         return false;
3066     }
3067 
3068     return true;
3069   }
3070 
3071 public:
3072   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
3073       : InsnID(InsnID), I(I), Matched(nullptr) {}
3074 
3075   unsigned getInsnID() const { return InsnID; }
3076   const CodeGenInstruction *getCGI() const { return I; }
3077 
3078   void chooseInsnToMutate(RuleMatcher &Rule) {
3079     for (auto *MutateCandidate : Rule.mutatable_insns()) {
3080       if (canMutate(Rule, MutateCandidate)) {
3081         // Take the first one we're offered that we're able to mutate.
3082         Rule.reserveInsnMatcherForMutation(MutateCandidate);
3083         Matched = MutateCandidate;
3084         return;
3085       }
3086     }
3087   }
3088 
3089   template <class Kind, class... Args>
3090   Kind &addRenderer(Args&&... args) {
3091     OperandRenderers.emplace_back(
3092         std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
3093     return *static_cast<Kind *>(OperandRenderers.back().get());
3094   }
3095 
3096   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3097     if (Matched) {
3098       assert(canMutate(Rule, Matched) &&
3099              "Arranged to mutate an insn that isn't mutatable");
3100 
3101       unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
3102       Table << MatchTable::Opcode("GIR_MutateOpcode")
3103             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3104             << MatchTable::Comment("RecycleInsnID")
3105             << MatchTable::IntValue(RecycleInsnID)
3106             << MatchTable::Comment("Opcode")
3107             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3108             << MatchTable::LineBreak;
3109 
3110       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
3111         for (auto Def : I->ImplicitDefs) {
3112           auto Namespace = Def->getValue("Namespace")
3113                                ? Def->getValueAsString("Namespace")
3114                                : "";
3115           Table << MatchTable::Opcode("GIR_AddImplicitDef")
3116                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3117                 << MatchTable::NamedValue(Namespace, Def->getName())
3118                 << MatchTable::LineBreak;
3119         }
3120         for (auto Use : I->ImplicitUses) {
3121           auto Namespace = Use->getValue("Namespace")
3122                                ? Use->getValueAsString("Namespace")
3123                                : "";
3124           Table << MatchTable::Opcode("GIR_AddImplicitUse")
3125                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3126                 << MatchTable::NamedValue(Namespace, Use->getName())
3127                 << MatchTable::LineBreak;
3128         }
3129       }
3130       return;
3131     }
3132 
3133     // TODO: Simple permutation looks like it could be almost as common as
3134     //       mutation due to commutative operations.
3135 
3136     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
3137           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
3138           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3139           << MatchTable::LineBreak;
3140     for (const auto &Renderer : OperandRenderers)
3141       Renderer->emitRenderOpcodes(Table, Rule);
3142 
3143     if (I->mayLoad || I->mayStore) {
3144       Table << MatchTable::Opcode("GIR_MergeMemOperands")
3145             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3146             << MatchTable::Comment("MergeInsnID's");
3147       // Emit the ID's for all the instructions that are matched by this rule.
3148       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
3149       //       some other means of having a memoperand. Also limit this to
3150       //       emitted instructions that expect to have a memoperand too. For
3151       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
3152       //       sign-extend instructions shouldn't put the memoperand on the
3153       //       sign-extend since it has no effect there.
3154       std::vector<unsigned> MergeInsnIDs;
3155       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
3156         MergeInsnIDs.push_back(IDMatcherPair.second);
3157       llvm::sort(MergeInsnIDs);
3158       for (const auto &MergeInsnID : MergeInsnIDs)
3159         Table << MatchTable::IntValue(MergeInsnID);
3160       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
3161             << MatchTable::LineBreak;
3162     }
3163 
3164     // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
3165     //        better for combines. Particularly when there are multiple match
3166     //        roots.
3167     if (InsnID == 0)
3168       Table << MatchTable::Opcode("GIR_EraseFromParent")
3169             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3170             << MatchTable::LineBreak;
3171   }
3172 };
3173 
3174 /// Generates code to constrain the operands of an output instruction to the
3175 /// register classes specified by the definition of that instruction.
3176 class ConstrainOperandsToDefinitionAction : public MatchAction {
3177   unsigned InsnID;
3178 
3179 public:
3180   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
3181 
3182   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3183     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
3184           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3185           << MatchTable::LineBreak;
3186   }
3187 };
3188 
3189 /// Generates code to constrain the specified operand of an output instruction
3190 /// to the specified register class.
3191 class ConstrainOperandToRegClassAction : public MatchAction {
3192   unsigned InsnID;
3193   unsigned OpIdx;
3194   const CodeGenRegisterClass &RC;
3195 
3196 public:
3197   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
3198                                    const CodeGenRegisterClass &RC)
3199       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
3200 
3201   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3202     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3203           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3204           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
3205           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3206           << MatchTable::LineBreak;
3207   }
3208 };
3209 
3210 /// Generates code to create a temporary register which can be used to chain
3211 /// instructions together.
3212 class MakeTempRegisterAction : public MatchAction {
3213 private:
3214   LLTCodeGen Ty;
3215   unsigned TempRegID;
3216 
3217 public:
3218   MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
3219       : Ty(Ty), TempRegID(TempRegID) {
3220     KnownTypes.insert(Ty);
3221   }
3222 
3223   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3224     Table << MatchTable::Opcode("GIR_MakeTempReg")
3225           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3226           << MatchTable::Comment("TypeID")
3227           << MatchTable::NamedValue(Ty.getCxxEnumValue())
3228           << MatchTable::LineBreak;
3229   }
3230 };
3231 
3232 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
3233   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
3234   MutatableInsns.insert(Matchers.back().get());
3235   return *Matchers.back();
3236 }
3237 
3238 void RuleMatcher::addRequiredFeature(Record *Feature) {
3239   RequiredFeatures.push_back(Feature);
3240 }
3241 
3242 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3243   return RequiredFeatures;
3244 }
3245 
3246 // Emplaces an action of the specified Kind at the end of the action list.
3247 //
3248 // Returns a reference to the newly created action.
3249 //
3250 // Like std::vector::emplace_back(), may invalidate all iterators if the new
3251 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
3252 // iterator.
3253 template <class Kind, class... Args>
3254 Kind &RuleMatcher::addAction(Args &&... args) {
3255   Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
3256   return *static_cast<Kind *>(Actions.back().get());
3257 }
3258 
3259 // Emplaces an action of the specified Kind before the given insertion point.
3260 //
3261 // Returns an iterator pointing at the newly created instruction.
3262 //
3263 // Like std::vector::insert(), may invalidate all iterators if the new size
3264 // exceeds the capacity. Otherwise, only invalidates the iterators from the
3265 // insertion point onwards.
3266 template <class Kind, class... Args>
3267 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3268                                           Args &&... args) {
3269   return Actions.emplace(InsertPt,
3270                          std::make_unique<Kind>(std::forward<Args>(args)...));
3271 }
3272 
3273 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
3274   unsigned NewInsnVarID = NextInsnVarID++;
3275   InsnVariableIDs[&Matcher] = NewInsnVarID;
3276   return NewInsnVarID;
3277 }
3278 
3279 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
3280   const auto &I = InsnVariableIDs.find(&InsnMatcher);
3281   if (I != InsnVariableIDs.end())
3282     return I->second;
3283   llvm_unreachable("Matched Insn was not captured in a local variable");
3284 }
3285 
3286 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3287   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3288     DefinedOperands[SymbolicName] = &OM;
3289     return;
3290   }
3291 
3292   // If the operand is already defined, then we must ensure both references in
3293   // the matcher have the exact same node.
3294   OM.addPredicate<SameOperandMatcher>(
3295       OM.getSymbolicName(), getOperandMatcher(OM.getSymbolicName()).getOpIdx());
3296 }
3297 
3298 void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3299   if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3300     PhysRegOperands[Reg] = &OM;
3301     return;
3302   }
3303 }
3304 
3305 InstructionMatcher &
3306 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3307   for (const auto &I : InsnVariableIDs)
3308     if (I.first->getSymbolicName() == SymbolicName)
3309       return *I.first;
3310   llvm_unreachable(
3311       ("Failed to lookup instruction " + SymbolicName).str().c_str());
3312 }
3313 
3314 const OperandMatcher &
3315 RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3316   const auto &I = PhysRegOperands.find(Reg);
3317 
3318   if (I == PhysRegOperands.end()) {
3319     PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3320                     " was not declared in matcher");
3321   }
3322 
3323   return *I->second;
3324 }
3325 
3326 const OperandMatcher &
3327 RuleMatcher::getOperandMatcher(StringRef Name) const {
3328   const auto &I = DefinedOperands.find(Name);
3329 
3330   if (I == DefinedOperands.end())
3331     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3332 
3333   return *I->second;
3334 }
3335 
3336 void RuleMatcher::emit(MatchTable &Table) {
3337   if (Matchers.empty())
3338     llvm_unreachable("Unexpected empty matcher!");
3339 
3340   // The representation supports rules that require multiple roots such as:
3341   //    %ptr(p0) = ...
3342   //    %elt0(s32) = G_LOAD %ptr
3343   //    %1(p0) = G_ADD %ptr, 4
3344   //    %elt1(s32) = G_LOAD p0 %1
3345   // which could be usefully folded into:
3346   //    %ptr(p0) = ...
3347   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3348   // on some targets but we don't need to make use of that yet.
3349   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
3350 
3351   unsigned LabelID = Table.allocateLabelID();
3352   Table << MatchTable::Opcode("GIM_Try", +1)
3353         << MatchTable::Comment("On fail goto")
3354         << MatchTable::JumpTarget(LabelID)
3355         << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
3356         << MatchTable::LineBreak;
3357 
3358   if (!RequiredFeatures.empty()) {
3359     Table << MatchTable::Opcode("GIM_CheckFeatures")
3360           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3361           << MatchTable::LineBreak;
3362   }
3363 
3364   Matchers.front()->emitPredicateOpcodes(Table, *this);
3365 
3366   // We must also check if it's safe to fold the matched instructions.
3367   if (InsnVariableIDs.size() >= 2) {
3368     // Invert the map to create stable ordering (by var names)
3369     SmallVector<unsigned, 2> InsnIDs;
3370     for (const auto &Pair : InsnVariableIDs) {
3371       // Skip the root node since it isn't moving anywhere. Everything else is
3372       // sinking to meet it.
3373       if (Pair.first == Matchers.front().get())
3374         continue;
3375 
3376       InsnIDs.push_back(Pair.second);
3377     }
3378     llvm::sort(InsnIDs);
3379 
3380     for (const auto &InsnID : InsnIDs) {
3381       // Reject the difficult cases until we have a more accurate check.
3382       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3383             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3384             << MatchTable::LineBreak;
3385 
3386       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3387       //        account for unsafe cases.
3388       //
3389       //        Example:
3390       //          MI1--> %0 = ...
3391       //                 %1 = ... %0
3392       //          MI0--> %2 = ... %0
3393       //          It's not safe to erase MI1. We currently handle this by not
3394       //          erasing %0 (even when it's dead).
3395       //
3396       //        Example:
3397       //          MI1--> %0 = load volatile @a
3398       //                 %1 = load volatile @a
3399       //          MI0--> %2 = ... %0
3400       //          It's not safe to sink %0's def past %1. We currently handle
3401       //          this by rejecting all loads.
3402       //
3403       //        Example:
3404       //          MI1--> %0 = load @a
3405       //                 %1 = store @a
3406       //          MI0--> %2 = ... %0
3407       //          It's not safe to sink %0's def past %1. We currently handle
3408       //          this by rejecting all loads.
3409       //
3410       //        Example:
3411       //                   G_CONDBR %cond, @BB1
3412       //                 BB0:
3413       //          MI1-->   %0 = load @a
3414       //                   G_BR @BB1
3415       //                 BB1:
3416       //          MI0-->   %2 = ... %0
3417       //          It's not always safe to sink %0 across control flow. In this
3418       //          case it may introduce a memory fault. We currentl handle this
3419       //          by rejecting all loads.
3420     }
3421   }
3422 
3423   for (const auto &PM : EpilogueMatchers)
3424     PM->emitPredicateOpcodes(Table, *this);
3425 
3426   for (const auto &MA : Actions)
3427     MA->emitActionOpcodes(Table, *this);
3428 
3429   if (Table.isWithCoverage())
3430     Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3431           << MatchTable::LineBreak;
3432   else
3433     Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3434           << MatchTable::LineBreak;
3435 
3436   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
3437         << MatchTable::Label(LabelID);
3438   ++NumPatternEmitted;
3439 }
3440 
3441 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3442   // Rules involving more match roots have higher priority.
3443   if (Matchers.size() > B.Matchers.size())
3444     return true;
3445   if (Matchers.size() < B.Matchers.size())
3446     return false;
3447 
3448   for (auto Matcher : zip(Matchers, B.Matchers)) {
3449     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3450       return true;
3451     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3452       return false;
3453   }
3454 
3455   return false;
3456 }
3457 
3458 unsigned RuleMatcher::countRendererFns() const {
3459   return std::accumulate(
3460       Matchers.begin(), Matchers.end(), 0,
3461       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
3462         return A + Matcher->countRendererFns();
3463       });
3464 }
3465 
3466 bool OperandPredicateMatcher::isHigherPriorityThan(
3467     const OperandPredicateMatcher &B) const {
3468   // Generally speaking, an instruction is more important than an Int or a
3469   // LiteralInt because it can cover more nodes but theres an exception to
3470   // this. G_CONSTANT's are less important than either of those two because they
3471   // are more permissive.
3472 
3473   const InstructionOperandMatcher *AOM =
3474       dyn_cast<InstructionOperandMatcher>(this);
3475   const InstructionOperandMatcher *BOM =
3476       dyn_cast<InstructionOperandMatcher>(&B);
3477   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3478   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3479 
3480   if (AOM && BOM) {
3481     // The relative priorities between a G_CONSTANT and any other instruction
3482     // don't actually matter but this code is needed to ensure a strict weak
3483     // ordering. This is particularly important on Windows where the rules will
3484     // be incorrectly sorted without it.
3485     if (AIsConstantInsn != BIsConstantInsn)
3486       return AIsConstantInsn < BIsConstantInsn;
3487     return false;
3488   }
3489 
3490   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3491     return false;
3492   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3493     return true;
3494 
3495   return Kind < B.Kind;
3496 }
3497 
3498 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
3499                                               RuleMatcher &Rule) const {
3500   const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
3501   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
3502   assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
3503 
3504   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3505         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3506         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3507         << MatchTable::Comment("OtherMI")
3508         << MatchTable::IntValue(OtherInsnVarID)
3509         << MatchTable::Comment("OtherOpIdx")
3510         << MatchTable::IntValue(OtherOM.getOpIdx())
3511         << MatchTable::LineBreak;
3512 }
3513 
3514 //===- GlobalISelEmitter class --------------------------------------------===//
3515 
3516 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3517   ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3518   if (ChildTypes.size() != 1)
3519     return failedImport("Dst pattern child has multiple results");
3520 
3521   Optional<LLTCodeGen> MaybeOpTy;
3522   if (ChildTypes.front().isMachineValueType()) {
3523     MaybeOpTy =
3524       MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3525   }
3526 
3527   if (!MaybeOpTy)
3528     return failedImport("Dst operand has an unsupported type");
3529   return *MaybeOpTy;
3530 }
3531 
3532 class GlobalISelEmitter {
3533 public:
3534   explicit GlobalISelEmitter(RecordKeeper &RK);
3535   void run(raw_ostream &OS);
3536 
3537 private:
3538   const RecordKeeper &RK;
3539   const CodeGenDAGPatterns CGP;
3540   const CodeGenTarget &Target;
3541   CodeGenRegBank &CGRegs;
3542 
3543   /// Keep track of the equivalence between SDNodes and Instruction by mapping
3544   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3545   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
3546   /// This is defined using 'GINodeEquiv' in the target description.
3547   DenseMap<Record *, Record *> NodeEquivs;
3548 
3549   /// Keep track of the equivalence between ComplexPattern's and
3550   /// GIComplexOperandMatcher. Map entries are specified by subclassing
3551   /// GIComplexPatternEquiv.
3552   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3553 
3554   /// Keep track of the equivalence between SDNodeXForm's and
3555   /// GICustomOperandRenderer. Map entries are specified by subclassing
3556   /// GISDNodeXFormEquiv.
3557   DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3558 
3559   /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3560   /// This adds compatibility for RuleMatchers to use this for ordering rules.
3561   DenseMap<uint64_t, int> RuleMatcherScores;
3562 
3563   // Map of predicates to their subtarget features.
3564   SubtargetFeatureInfoMap SubtargetFeatures;
3565 
3566   // Rule coverage information.
3567   Optional<CodeGenCoverage> RuleCoverage;
3568 
3569   /// Variables used to help with collecting of named operands for predicates
3570   /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
3571   /// to the number of named operands that predicate expects. Store locations in
3572   /// StoreIdxForName correspond to the order in which operand names appear in
3573   /// predicate's argument list.
3574   /// When we visit named leaf operand and WaitingForNamedOperands is not zero,
3575   /// add matcher that will record operand and decrease counter.
3576   unsigned WaitingForNamedOperands = 0;
3577   StringMap<unsigned> StoreIdxForName;
3578 
3579   void gatherOpcodeValues();
3580   void gatherTypeIDValues();
3581   void gatherNodeEquivs();
3582 
3583   Record *findNodeEquiv(Record *N) const;
3584   const CodeGenInstruction *getEquivNode(Record &Equiv,
3585                                          const TreePatternNode *N) const;
3586 
3587   Error importRulePredicates(RuleMatcher &M, ArrayRef<Record *> Predicates);
3588   Expected<InstructionMatcher &>
3589   createAndImportSelDAGMatcher(RuleMatcher &Rule,
3590                                InstructionMatcher &InsnMatcher,
3591                                const TreePatternNode *Src, unsigned &TempOpIdx);
3592   Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3593                                            unsigned &TempOpIdx) const;
3594   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3595                            const TreePatternNode *SrcChild,
3596                            bool OperandIsAPointer, bool OperandIsImmArg,
3597                            unsigned OpIdx, unsigned &TempOpIdx);
3598 
3599   Expected<BuildMIAction &> createAndImportInstructionRenderer(
3600       RuleMatcher &M, InstructionMatcher &InsnMatcher,
3601       const TreePatternNode *Src, const TreePatternNode *Dst);
3602   Expected<action_iterator> createAndImportSubInstructionRenderer(
3603       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3604       unsigned TempReg);
3605   Expected<action_iterator>
3606   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
3607                             const TreePatternNode *Dst);
3608 
3609   Expected<action_iterator>
3610   importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3611                              BuildMIAction &DstMIBuilder,
3612                              const TreePatternNode *Dst);
3613 
3614   Expected<action_iterator>
3615   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3616                              BuildMIAction &DstMIBuilder,
3617                              const llvm::TreePatternNode *Dst);
3618   Expected<action_iterator>
3619   importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3620                             BuildMIAction &DstMIBuilder,
3621                             TreePatternNode *DstChild);
3622   Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3623                                       BuildMIAction &DstMIBuilder,
3624                                       DagInit *DefaultOps) const;
3625   Error
3626   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3627                              const std::vector<Record *> &ImplicitDefs) const;
3628 
3629   void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3630                            StringRef TypeIdentifier, StringRef ArgType,
3631                            StringRef ArgName, StringRef AdditionalArgs,
3632                            StringRef AdditionalDeclarations,
3633                            std::function<bool(const Record *R)> Filter);
3634   void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3635                            StringRef ArgType,
3636                            std::function<bool(const Record *R)> Filter);
3637   void emitMIPredicateFns(raw_ostream &OS);
3638 
3639   /// Analyze pattern \p P, returning a matcher for it if possible.
3640   /// Otherwise, return an Error explaining why we don't support it.
3641   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
3642 
3643   void declareSubtargetFeature(Record *Predicate);
3644 
3645   MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3646                              bool WithCoverage);
3647 
3648   /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3649   /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3650   /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3651   /// If no register class is found, return None.
3652   Optional<const CodeGenRegisterClass *>
3653   inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3654                                  TreePatternNode *SuperRegNode,
3655                                  TreePatternNode *SubRegIdxNode);
3656   Optional<CodeGenSubRegIndex *>
3657   inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
3658 
3659   /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3660   /// Return None if no such class exists.
3661   Optional<const CodeGenRegisterClass *>
3662   inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3663                           TreePatternNode *SubRegIdxNode);
3664 
3665   /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3666   Optional<const CodeGenRegisterClass *>
3667   getRegClassFromLeaf(TreePatternNode *Leaf);
3668 
3669   /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3670   /// otherwise.
3671   Optional<const CodeGenRegisterClass *>
3672   inferRegClassFromPattern(TreePatternNode *N);
3673 
3674   /// Return the size of the MemoryVT in this predicate, if possible.
3675   Optional<unsigned>
3676   getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate);
3677 
3678   // Add builtin predicates.
3679   Expected<InstructionMatcher &>
3680   addBuiltinPredicates(const Record *SrcGIEquivOrNull,
3681                        const TreePredicateFn &Predicate,
3682                        InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
3683 
3684 public:
3685   /// Takes a sequence of \p Rules and group them based on the predicates
3686   /// they share. \p MatcherStorage is used as a memory container
3687   /// for the group that are created as part of this process.
3688   ///
3689   /// What this optimization does looks like if GroupT = GroupMatcher:
3690   /// Output without optimization:
3691   /// \verbatim
3692   /// # R1
3693   ///  # predicate A
3694   ///  # predicate B
3695   ///  ...
3696   /// # R2
3697   ///  # predicate A // <-- effectively this is going to be checked twice.
3698   ///                //     Once in R1 and once in R2.
3699   ///  # predicate C
3700   /// \endverbatim
3701   /// Output with optimization:
3702   /// \verbatim
3703   /// # Group1_2
3704   ///  # predicate A // <-- Check is now shared.
3705   ///  # R1
3706   ///   # predicate B
3707   ///  # R2
3708   ///   # predicate C
3709   /// \endverbatim
3710   template <class GroupT>
3711   static std::vector<Matcher *> optimizeRules(
3712       ArrayRef<Matcher *> Rules,
3713       std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
3714 };
3715 
3716 void GlobalISelEmitter::gatherOpcodeValues() {
3717   InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3718 }
3719 
3720 void GlobalISelEmitter::gatherTypeIDValues() {
3721   LLTOperandMatcher::initTypeIDValuesMap();
3722 }
3723 
3724 void GlobalISelEmitter::gatherNodeEquivs() {
3725   assert(NodeEquivs.empty());
3726   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
3727     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
3728 
3729   assert(ComplexPatternEquivs.empty());
3730   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3731     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3732     if (!SelDAGEquiv)
3733       continue;
3734     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3735  }
3736 
3737  assert(SDNodeXFormEquivs.empty());
3738  for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3739    Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3740    if (!SelDAGEquiv)
3741      continue;
3742    SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3743  }
3744 }
3745 
3746 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
3747   return NodeEquivs.lookup(N);
3748 }
3749 
3750 const CodeGenInstruction *
3751 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3752   if (N->getNumChildren() >= 1) {
3753     // setcc operation maps to two different G_* instructions based on the type.
3754     if (!Equiv.isValueUnset("IfFloatingPoint") &&
3755         MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3756       return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3757   }
3758 
3759   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3760     const TreePredicateFn &Predicate = Call.Fn;
3761     if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3762         Predicate.isSignExtLoad())
3763       return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3764     if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3765         Predicate.isZeroExtLoad())
3766       return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3767   }
3768 
3769   return &Target.getInstruction(Equiv.getValueAsDef("I"));
3770 }
3771 
3772 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
3773     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3774       CGRegs(Target.getRegBank()) {}
3775 
3776 //===- Emitter ------------------------------------------------------------===//
3777 
3778 Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
3779                                               ArrayRef<Record *> Predicates) {
3780   for (Record *Pred : Predicates) {
3781     if (Pred->getValueAsString("CondString").empty())
3782       continue;
3783     declareSubtargetFeature(Pred);
3784     M.addRequiredFeature(Pred);
3785   }
3786 
3787   return Error::success();
3788 }
3789 
3790 Optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate) {
3791   Optional<LLTCodeGen> MemTyOrNone =
3792       MVTToLLT(getValueType(Predicate.getMemoryVT()));
3793 
3794   if (!MemTyOrNone)
3795     return None;
3796 
3797   // Align so unusual types like i1 don't get rounded down.
3798   return llvm::alignTo(
3799       static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8);
3800 }
3801 
3802 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
3803     const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
3804     InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
3805   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3806     if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3807       SmallVector<unsigned, 4> ParsedAddrSpaces;
3808 
3809       for (Init *Val : AddrSpaces->getValues()) {
3810         IntInit *IntVal = dyn_cast<IntInit>(Val);
3811         if (!IntVal)
3812           return failedImport("Address space is not an integer");
3813         ParsedAddrSpaces.push_back(IntVal->getValue());
3814       }
3815 
3816       if (!ParsedAddrSpaces.empty()) {
3817         InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3818             0, ParsedAddrSpaces);
3819         return InsnMatcher;
3820       }
3821     }
3822 
3823     int64_t MinAlign = Predicate.getMinAlignment();
3824     if (MinAlign > 0) {
3825       InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3826       return InsnMatcher;
3827     }
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   (void) NumGroups;
5541   assert(CurrentGroup->empty() && "The last group wasn't properly processed");
5542   return OptRules;
5543 }
5544 
5545 MatchTable
5546 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
5547                                    bool Optimize, bool WithCoverage) {
5548   std::vector<Matcher *> InputRules;
5549   for (Matcher &Rule : Rules)
5550     InputRules.push_back(&Rule);
5551 
5552   if (!Optimize)
5553     return MatchTable::buildTable(InputRules, WithCoverage);
5554 
5555   unsigned CurrentOrdering = 0;
5556   StringMap<unsigned> OpcodeOrder;
5557   for (RuleMatcher &Rule : Rules) {
5558     const StringRef Opcode = Rule.getOpcode();
5559     assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5560     if (OpcodeOrder.count(Opcode) == 0)
5561       OpcodeOrder[Opcode] = CurrentOrdering++;
5562   }
5563 
5564   llvm::stable_sort(InputRules, [&OpcodeOrder](const Matcher *A,
5565                                                const Matcher *B) {
5566     auto *L = static_cast<const RuleMatcher *>(A);
5567     auto *R = static_cast<const RuleMatcher *>(B);
5568     return std::make_tuple(OpcodeOrder[L->getOpcode()], L->getNumOperands()) <
5569            std::make_tuple(OpcodeOrder[R->getOpcode()], R->getNumOperands());
5570   });
5571 
5572   for (Matcher *Rule : InputRules)
5573     Rule->optimize();
5574 
5575   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
5576   std::vector<Matcher *> OptRules =
5577       optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5578 
5579   for (Matcher *Rule : OptRules)
5580     Rule->optimize();
5581 
5582   OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5583 
5584   return MatchTable::buildTable(OptRules, WithCoverage);
5585 }
5586 
5587 void GroupMatcher::optimize() {
5588   // Make sure we only sort by a specific predicate within a range of rules that
5589   // all have that predicate checked against a specific value (not a wildcard):
5590   auto F = Matchers.begin();
5591   auto T = F;
5592   auto E = Matchers.end();
5593   while (T != E) {
5594     while (T != E) {
5595       auto *R = static_cast<RuleMatcher *>(*T);
5596       if (!R->getFirstConditionAsRootType().get().isValid())
5597         break;
5598       ++T;
5599     }
5600     std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5601       auto *L = static_cast<RuleMatcher *>(A);
5602       auto *R = static_cast<RuleMatcher *>(B);
5603       return L->getFirstConditionAsRootType() <
5604              R->getFirstConditionAsRootType();
5605     });
5606     if (T != E)
5607       F = ++T;
5608   }
5609   GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5610       .swap(Matchers);
5611   GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5612       .swap(Matchers);
5613 }
5614 
5615 void GlobalISelEmitter::run(raw_ostream &OS) {
5616   if (!UseCoverageFile.empty()) {
5617     RuleCoverage = CodeGenCoverage();
5618     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5619     if (!RuleCoverageBufOrErr) {
5620       PrintWarning(SMLoc(), "Missing rule coverage data");
5621       RuleCoverage = None;
5622     } else {
5623       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5624         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5625         RuleCoverage = None;
5626       }
5627     }
5628   }
5629 
5630   // Track the run-time opcode values
5631   gatherOpcodeValues();
5632   // Track the run-time LLT ID values
5633   gatherTypeIDValues();
5634 
5635   // Track the GINodeEquiv definitions.
5636   gatherNodeEquivs();
5637 
5638   emitSourceFileHeader(("Global Instruction Selector for the " +
5639                        Target.getName() + " target").str(), OS);
5640   std::vector<RuleMatcher> Rules;
5641   // Look through the SelectionDAG patterns we found, possibly emitting some.
5642   for (const PatternToMatch &Pat : CGP.ptms()) {
5643     ++NumPatternTotal;
5644 
5645     auto MatcherOrErr = runOnPattern(Pat);
5646 
5647     // The pattern analysis can fail, indicating an unsupported pattern.
5648     // Report that if we've been asked to do so.
5649     if (auto Err = MatcherOrErr.takeError()) {
5650       if (WarnOnSkippedPatterns) {
5651         PrintWarning(Pat.getSrcRecord()->getLoc(),
5652                      "Skipped pattern: " + toString(std::move(Err)));
5653       } else {
5654         consumeError(std::move(Err));
5655       }
5656       ++NumPatternImportsSkipped;
5657       continue;
5658     }
5659 
5660     if (RuleCoverage) {
5661       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5662         ++NumPatternsTested;
5663       else
5664         PrintWarning(Pat.getSrcRecord()->getLoc(),
5665                      "Pattern is not covered by a test");
5666     }
5667     Rules.push_back(std::move(MatcherOrErr.get()));
5668   }
5669 
5670   // Comparison function to order records by name.
5671   auto orderByName = [](const Record *A, const Record *B) {
5672     return A->getName() < B->getName();
5673   };
5674 
5675   std::vector<Record *> ComplexPredicates =
5676       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
5677   llvm::sort(ComplexPredicates, orderByName);
5678 
5679   std::vector<StringRef> CustomRendererFns;
5680   transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"),
5681             std::back_inserter(CustomRendererFns), [](const auto &Record) {
5682               return Record->getValueAsString("RendererFn");
5683             });
5684   // Sort and remove duplicates to get a list of unique renderer functions, in
5685   // case some were mentioned more than once.
5686   llvm::sort(CustomRendererFns);
5687   CustomRendererFns.erase(
5688       std::unique(CustomRendererFns.begin(), CustomRendererFns.end()),
5689       CustomRendererFns.end());
5690 
5691   unsigned MaxTemporaries = 0;
5692   for (const auto &Rule : Rules)
5693     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
5694 
5695   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5696      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5697      << ";\n"
5698      << "using PredicateBitset = "
5699         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5700      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5701 
5702   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5703      << "  mutable MatcherState State;\n"
5704      << "  typedef "
5705         "ComplexRendererFns("
5706      << Target.getName()
5707      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
5708 
5709      << "  typedef void(" << Target.getName()
5710      << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5711         "MachineInstr &, int) "
5712         "const;\n"
5713      << "  const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5714         "CustomRendererFn> "
5715         "ISelInfo;\n";
5716   OS << "  static " << Target.getName()
5717      << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
5718      << "  static " << Target.getName()
5719      << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
5720      << "  bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
5721         "override;\n"
5722      << "  bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
5723         "const override;\n"
5724      << "  bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
5725         "&Imm) const override;\n"
5726      << "  const int64_t *getMatchTable() const override;\n"
5727      << "  bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI"
5728         ", const std::array<const MachineOperand *, 3> &Operands) "
5729         "const override;\n"
5730      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
5731 
5732   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5733      << ", State(" << MaxTemporaries << "),\n"
5734      << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5735      << ", ComplexPredicateFns, CustomRenderers)\n"
5736      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
5737 
5738   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5739   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5740                                                            OS);
5741 
5742   // Separate subtarget features by how often they must be recomputed.
5743   SubtargetFeatureInfoMap ModuleFeatures;
5744   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5745                std::inserter(ModuleFeatures, ModuleFeatures.end()),
5746                [](const SubtargetFeatureInfoMap::value_type &X) {
5747                  return !X.second.mustRecomputePerFunction();
5748                });
5749   SubtargetFeatureInfoMap FunctionFeatures;
5750   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5751                std::inserter(FunctionFeatures, FunctionFeatures.end()),
5752                [](const SubtargetFeatureInfoMap::value_type &X) {
5753                  return X.second.mustRecomputePerFunction();
5754                });
5755 
5756   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5757     Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5758       ModuleFeatures, OS);
5759 
5760 
5761   OS << "void " << Target.getName() << "InstructionSelector"
5762     "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5763     "  AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5764     "(const " << Target.getName() << "Subtarget *)&MF.getSubtarget(), &MF);\n"
5765     "}\n";
5766 
5767   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5768       Target.getName(), "InstructionSelector",
5769       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5770       "const MachineFunction *MF");
5771 
5772   // Emit a table containing the LLT objects needed by the matcher and an enum
5773   // for the matcher to reference them with.
5774   std::vector<LLTCodeGen> TypeObjects;
5775   append_range(TypeObjects, KnownTypes);
5776   llvm::sort(TypeObjects);
5777   OS << "// LLT Objects.\n"
5778      << "enum {\n";
5779   for (const auto &TypeObject : TypeObjects) {
5780     OS << "  ";
5781     TypeObject.emitCxxEnumValue(OS);
5782     OS << ",\n";
5783   }
5784   OS << "};\n";
5785   OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
5786      << "const static LLT TypeObjects[] = {\n";
5787   for (const auto &TypeObject : TypeObjects) {
5788     OS << "  ";
5789     TypeObject.emitCxxConstructorCall(OS);
5790     OS << ",\n";
5791   }
5792   OS << "};\n\n";
5793 
5794   // Emit a table containing the PredicateBitsets objects needed by the matcher
5795   // and an enum for the matcher to reference them with.
5796   std::vector<std::vector<Record *>> FeatureBitsets;
5797   for (auto &Rule : Rules)
5798     FeatureBitsets.push_back(Rule.getRequiredFeatures());
5799   llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5800                                  const std::vector<Record *> &B) {
5801     if (A.size() < B.size())
5802       return true;
5803     if (A.size() > B.size())
5804       return false;
5805     for (auto Pair : zip(A, B)) {
5806       if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5807         return true;
5808       if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
5809         return false;
5810     }
5811     return false;
5812   });
5813   FeatureBitsets.erase(
5814       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5815       FeatureBitsets.end());
5816   OS << "// Feature bitsets.\n"
5817      << "enum {\n"
5818      << "  GIFBS_Invalid,\n";
5819   for (const auto &FeatureBitset : FeatureBitsets) {
5820     if (FeatureBitset.empty())
5821       continue;
5822     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5823   }
5824   OS << "};\n"
5825      << "const static PredicateBitset FeatureBitsets[] {\n"
5826      << "  {}, // GIFBS_Invalid\n";
5827   for (const auto &FeatureBitset : FeatureBitsets) {
5828     if (FeatureBitset.empty())
5829       continue;
5830     OS << "  {";
5831     for (const auto &Feature : FeatureBitset) {
5832       const auto &I = SubtargetFeatures.find(Feature);
5833       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5834       OS << I->second.getEnumBitName() << ", ";
5835     }
5836     OS << "},\n";
5837   }
5838   OS << "};\n\n";
5839 
5840   // Emit complex predicate table and an enum to reference them with.
5841   OS << "// ComplexPattern predicates.\n"
5842      << "enum {\n"
5843      << "  GICP_Invalid,\n";
5844   for (const auto &Record : ComplexPredicates)
5845     OS << "  GICP_" << Record->getName() << ",\n";
5846   OS << "};\n"
5847      << "// See constructor for table contents\n\n";
5848 
5849   emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
5850     bool Unset;
5851     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5852            !R->getValueAsBit("IsAPInt");
5853   });
5854   emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
5855     bool Unset;
5856     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5857   });
5858   emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
5859     return R->getValueAsBit("IsAPInt");
5860   });
5861   emitMIPredicateFns(OS);
5862   OS << "\n";
5863 
5864   OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5865      << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5866      << "  nullptr, // GICP_Invalid\n";
5867   for (const auto &Record : ComplexPredicates)
5868     OS << "  &" << Target.getName()
5869        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5870        << ", // " << Record->getName() << "\n";
5871   OS << "};\n\n";
5872 
5873   OS << "// Custom renderers.\n"
5874      << "enum {\n"
5875      << "  GICR_Invalid,\n";
5876   for (const auto &Fn : CustomRendererFns)
5877     OS << "  GICR_" << Fn << ",\n";
5878   OS << "};\n";
5879 
5880   OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5881      << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5882      << "  nullptr, // GICR_Invalid\n";
5883   for (const auto &Fn : CustomRendererFns)
5884     OS << "  &" << Target.getName() << "InstructionSelector::" << Fn << ",\n";
5885   OS << "};\n\n";
5886 
5887   llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
5888     int ScoreA = RuleMatcherScores[A.getRuleID()];
5889     int ScoreB = RuleMatcherScores[B.getRuleID()];
5890     if (ScoreA > ScoreB)
5891       return true;
5892     if (ScoreB > ScoreA)
5893       return false;
5894     if (A.isHigherPriorityThan(B)) {
5895       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5896                                            "and less important at "
5897                                            "the same time");
5898       return true;
5899     }
5900     return false;
5901   });
5902 
5903   OS << "bool " << Target.getName()
5904      << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5905         "&CoverageInfo) const {\n"
5906      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
5907      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5908      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5909      << "  NewMIVector OutMIs;\n"
5910      << "  State.MIs.clear();\n"
5911      << "  State.MIs.push_back(&I);\n\n"
5912      << "  if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5913      << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5914      << ", CoverageInfo)) {\n"
5915      << "    return true;\n"
5916      << "  }\n\n"
5917      << "  return false;\n"
5918      << "}\n\n";
5919 
5920   const MatchTable Table =
5921       buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
5922   OS << "const int64_t *" << Target.getName()
5923      << "InstructionSelector::getMatchTable() const {\n";
5924   Table.emitDeclaration(OS);
5925   OS << "  return ";
5926   Table.emitUse(OS);
5927   OS << ";\n}\n";
5928   OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
5929 
5930   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5931      << "PredicateBitset AvailableModuleFeatures;\n"
5932      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5933      << "PredicateBitset getAvailableFeatures() const {\n"
5934      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5935      << "}\n"
5936      << "PredicateBitset\n"
5937      << "computeAvailableModuleFeatures(const " << Target.getName()
5938      << "Subtarget *Subtarget) const;\n"
5939      << "PredicateBitset\n"
5940      << "computeAvailableFunctionFeatures(const " << Target.getName()
5941      << "Subtarget *Subtarget,\n"
5942      << "                                 const MachineFunction *MF) const;\n"
5943      << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
5944      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5945 
5946   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5947      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5948      << "AvailableFunctionFeatures()\n"
5949      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
5950 }
5951 
5952 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5953   if (SubtargetFeatures.count(Predicate) == 0)
5954     SubtargetFeatures.emplace(
5955         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5956 }
5957 
5958 void RuleMatcher::optimize() {
5959   for (auto &Item : InsnVariableIDs) {
5960     InstructionMatcher &InsnMatcher = *Item.first;
5961     for (auto &OM : InsnMatcher.operands()) {
5962       // Complex Patterns are usually expensive and they relatively rarely fail
5963       // on their own: more often we end up throwing away all the work done by a
5964       // matching part of a complex pattern because some other part of the
5965       // enclosing pattern didn't match. All of this makes it beneficial to
5966       // delay complex patterns until the very end of the rule matching,
5967       // especially for targets having lots of complex patterns.
5968       for (auto &OP : OM->predicates())
5969         if (isa<ComplexPatternOperandMatcher>(OP))
5970           EpilogueMatchers.emplace_back(std::move(OP));
5971       OM->eraseNullPredicates();
5972     }
5973     InsnMatcher.optimize();
5974   }
5975   llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5976                                   const std::unique_ptr<PredicateMatcher> &R) {
5977     return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5978            std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5979   });
5980 }
5981 
5982 bool RuleMatcher::hasFirstCondition() const {
5983   if (insnmatchers_empty())
5984     return false;
5985   InstructionMatcher &Matcher = insnmatchers_front();
5986   if (!Matcher.predicates_empty())
5987     return true;
5988   for (auto &OM : Matcher.operands())
5989     for (auto &OP : OM->predicates())
5990       if (!isa<InstructionOperandMatcher>(OP))
5991         return true;
5992   return false;
5993 }
5994 
5995 const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5996   assert(!insnmatchers_empty() &&
5997          "Trying to get a condition from an empty RuleMatcher");
5998 
5999   InstructionMatcher &Matcher = insnmatchers_front();
6000   if (!Matcher.predicates_empty())
6001     return **Matcher.predicates_begin();
6002   // If there is no more predicate on the instruction itself, look at its
6003   // operands.
6004   for (auto &OM : Matcher.operands())
6005     for (auto &OP : OM->predicates())
6006       if (!isa<InstructionOperandMatcher>(OP))
6007         return *OP;
6008 
6009   llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
6010                    "no conditions");
6011 }
6012 
6013 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
6014   assert(!insnmatchers_empty() &&
6015          "Trying to pop a condition from an empty RuleMatcher");
6016 
6017   InstructionMatcher &Matcher = insnmatchers_front();
6018   if (!Matcher.predicates_empty())
6019     return Matcher.predicates_pop_front();
6020   // If there is no more predicate on the instruction itself, look at its
6021   // operands.
6022   for (auto &OM : Matcher.operands())
6023     for (auto &OP : OM->predicates())
6024       if (!isa<InstructionOperandMatcher>(OP)) {
6025         std::unique_ptr<PredicateMatcher> Result = std::move(OP);
6026         OM->eraseNullPredicates();
6027         return Result;
6028       }
6029 
6030   llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
6031                    "no conditions");
6032 }
6033 
6034 bool GroupMatcher::candidateConditionMatches(
6035     const PredicateMatcher &Predicate) const {
6036 
6037   if (empty()) {
6038     // Sharing predicates for nested instructions is not supported yet as we
6039     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
6040     // only work on the original root instruction (InsnVarID == 0):
6041     if (Predicate.getInsnVarID() != 0)
6042       return false;
6043     // ... otherwise an empty group can handle any predicate with no specific
6044     // requirements:
6045     return true;
6046   }
6047 
6048   const Matcher &Representative = **Matchers.begin();
6049   const auto &RepresentativeCondition = Representative.getFirstCondition();
6050   // ... if not empty, the group can only accomodate matchers with the exact
6051   // same first condition:
6052   return Predicate.isIdentical(RepresentativeCondition);
6053 }
6054 
6055 bool GroupMatcher::addMatcher(Matcher &Candidate) {
6056   if (!Candidate.hasFirstCondition())
6057     return false;
6058 
6059   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
6060   if (!candidateConditionMatches(Predicate))
6061     return false;
6062 
6063   Matchers.push_back(&Candidate);
6064   return true;
6065 }
6066 
6067 void GroupMatcher::finalize() {
6068   assert(Conditions.empty() && "Already finalized?");
6069   if (empty())
6070     return;
6071 
6072   Matcher &FirstRule = **Matchers.begin();
6073   for (;;) {
6074     // All the checks are expected to succeed during the first iteration:
6075     for (const auto &Rule : Matchers)
6076       if (!Rule->hasFirstCondition())
6077         return;
6078     const auto &FirstCondition = FirstRule.getFirstCondition();
6079     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6080       if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
6081         return;
6082 
6083     Conditions.push_back(FirstRule.popFirstCondition());
6084     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6085       Matchers[I]->popFirstCondition();
6086   }
6087 }
6088 
6089 void GroupMatcher::emit(MatchTable &Table) {
6090   unsigned LabelID = ~0U;
6091   if (!Conditions.empty()) {
6092     LabelID = Table.allocateLabelID();
6093     Table << MatchTable::Opcode("GIM_Try", +1)
6094           << MatchTable::Comment("On fail goto")
6095           << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
6096   }
6097   for (auto &Condition : Conditions)
6098     Condition->emitPredicateOpcodes(
6099         Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
6100 
6101   for (const auto &M : Matchers)
6102     M->emit(Table);
6103 
6104   // Exit the group
6105   if (!Conditions.empty())
6106     Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
6107           << MatchTable::Label(LabelID);
6108 }
6109 
6110 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
6111   return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
6112 }
6113 
6114 bool SwitchMatcher::candidateConditionMatches(
6115     const PredicateMatcher &Predicate) const {
6116 
6117   if (empty()) {
6118     // Sharing predicates for nested instructions is not supported yet as we
6119     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
6120     // only work on the original root instruction (InsnVarID == 0):
6121     if (Predicate.getInsnVarID() != 0)
6122       return false;
6123     // ... while an attempt to add even a root matcher to an empty SwitchMatcher
6124     // could fail as not all the types of conditions are supported:
6125     if (!isSupportedPredicateType(Predicate))
6126       return false;
6127     // ... or the condition might not have a proper implementation of
6128     // getValue() / isIdenticalDownToValue() yet:
6129     if (!Predicate.hasValue())
6130       return false;
6131     // ... otherwise an empty Switch can accomodate the condition with no
6132     // further requirements:
6133     return true;
6134   }
6135 
6136   const Matcher &CaseRepresentative = **Matchers.begin();
6137   const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
6138   // Switch-cases must share the same kind of condition and path to the value it
6139   // checks:
6140   if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
6141     return false;
6142 
6143   const auto Value = Predicate.getValue();
6144   // ... but be unique with respect to the actual value they check:
6145   return Values.count(Value) == 0;
6146 }
6147 
6148 bool SwitchMatcher::addMatcher(Matcher &Candidate) {
6149   if (!Candidate.hasFirstCondition())
6150     return false;
6151 
6152   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
6153   if (!candidateConditionMatches(Predicate))
6154     return false;
6155   const auto Value = Predicate.getValue();
6156   Values.insert(Value);
6157 
6158   Matchers.push_back(&Candidate);
6159   return true;
6160 }
6161 
6162 void SwitchMatcher::finalize() {
6163   assert(Condition == nullptr && "Already finalized");
6164   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6165   if (empty())
6166     return;
6167 
6168   llvm::stable_sort(Matchers, [](const Matcher *L, const Matcher *R) {
6169     return L->getFirstCondition().getValue() <
6170            R->getFirstCondition().getValue();
6171   });
6172   Condition = Matchers[0]->popFirstCondition();
6173   for (unsigned I = 1, E = Values.size(); I < E; ++I)
6174     Matchers[I]->popFirstCondition();
6175 }
6176 
6177 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
6178                                                  MatchTable &Table) {
6179   assert(isSupportedPredicateType(P) && "Predicate type is not supported");
6180 
6181   if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
6182     Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
6183           << MatchTable::IntValue(Condition->getInsnVarID());
6184     return;
6185   }
6186   if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
6187     Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
6188           << MatchTable::IntValue(Condition->getInsnVarID())
6189           << MatchTable::Comment("Op")
6190           << MatchTable::IntValue(Condition->getOpIdx());
6191     return;
6192   }
6193 
6194   llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
6195                    "predicate type that is claimed to be supported");
6196 }
6197 
6198 void SwitchMatcher::emit(MatchTable &Table) {
6199   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6200   if (empty())
6201     return;
6202   assert(Condition != nullptr &&
6203          "Broken SwitchMatcher, hasn't been finalized?");
6204 
6205   std::vector<unsigned> LabelIDs(Values.size());
6206   std::generate(LabelIDs.begin(), LabelIDs.end(),
6207                 [&Table]() { return Table.allocateLabelID(); });
6208   const unsigned Default = Table.allocateLabelID();
6209 
6210   const int64_t LowerBound = Values.begin()->getRawValue();
6211   const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
6212 
6213   emitPredicateSpecificOpcodes(*Condition, Table);
6214 
6215   Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
6216         << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
6217         << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
6218 
6219   int64_t J = LowerBound;
6220   auto VI = Values.begin();
6221   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6222     auto V = *VI++;
6223     while (J++ < V.getRawValue())
6224       Table << MatchTable::IntValue(0);
6225     V.turnIntoComment();
6226     Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
6227   }
6228   Table << MatchTable::LineBreak;
6229 
6230   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6231     Table << MatchTable::Label(LabelIDs[I]);
6232     Matchers[I]->emit(Table);
6233     Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
6234   }
6235   Table << MatchTable::Label(Default);
6236 }
6237 
6238 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
6239 
6240 } // end anonymous namespace
6241 
6242 //===----------------------------------------------------------------------===//
6243 
6244 namespace llvm {
6245 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
6246   GlobalISelEmitter(RK).run(OS);
6247 }
6248 } // End llvm namespace
6249