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