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