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