1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
23 /// The generated file defines a single method:
24 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
33 #include "CodeGenDAGPatterns.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/CodeGen/MachineValueType.h"
39 #include "llvm/Support/CodeGenCoverage.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/LowLevelTypeImpl.h"
43 #include "llvm/Support/ScopedPrinter.h"
44 #include "llvm/TableGen/Error.h"
45 #include "llvm/TableGen/Record.h"
46 #include "llvm/TableGen/TableGenBackend.h"
47 #include <numeric>
48 #include <string>
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "gisel-emitter"
52 
53 STATISTIC(NumPatternTotal, "Total number of patterns");
54 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
55 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
56 STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
57 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
58 
59 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60 
61 static cl::opt<bool> WarnOnSkippedPatterns(
62     "warn-on-skipped-patterns",
63     cl::desc("Explain why a pattern was skipped for inclusion "
64              "in the GlobalISel selector"),
65     cl::init(false), cl::cat(GlobalISelEmitterCat));
66 
67 static cl::opt<bool> GenerateCoverage(
68     "instrument-gisel-coverage",
69     cl::desc("Generate coverage instrumentation for GlobalISel"),
70     cl::init(false), cl::cat(GlobalISelEmitterCat));
71 
72 static cl::opt<std::string> UseCoverageFile(
73     "gisel-coverage-file", cl::init(""),
74     cl::desc("Specify file to retrieve coverage information from"),
75     cl::cat(GlobalISelEmitterCat));
76 
77 static cl::opt<bool> OptimizeMatchTable(
78     "optimize-match-table",
79     cl::desc("Generate an optimized version of the match table"),
80     cl::init(true), cl::cat(GlobalISelEmitterCat));
81 
82 namespace {
83 //===- Helper functions ---------------------------------------------------===//
84 
85 /// Get the name of the enum value used to number the predicate function.
86 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
87   return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
88          Predicate.getFnName();
89 }
90 
91 /// Get the opcode used to check this predicate.
92 std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
93   return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
94 }
95 
96 /// This class stands in for LLT wherever we want to tablegen-erate an
97 /// equivalent at compiler run-time.
98 class LLTCodeGen {
99 private:
100   LLT Ty;
101 
102 public:
103   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
104 
105   std::string getCxxEnumValue() const {
106     std::string Str;
107     raw_string_ostream OS(Str);
108 
109     emitCxxEnumValue(OS);
110     return OS.str();
111   }
112 
113   void emitCxxEnumValue(raw_ostream &OS) const {
114     if (Ty.isScalar()) {
115       OS << "GILLT_s" << Ty.getSizeInBits();
116       return;
117     }
118     if (Ty.isVector()) {
119       OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
120       return;
121     }
122     if (Ty.isPointer()) {
123       OS << "GILLT_p" << Ty.getAddressSpace();
124       if (Ty.getSizeInBits() > 0)
125         OS << "s" << Ty.getSizeInBits();
126       return;
127     }
128     llvm_unreachable("Unhandled LLT");
129   }
130 
131   void emitCxxConstructorCall(raw_ostream &OS) const {
132     if (Ty.isScalar()) {
133       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
134       return;
135     }
136     if (Ty.isVector()) {
137       OS << "LLT::vector(" << Ty.getNumElements() << ", "
138          << Ty.getScalarSizeInBits() << ")";
139       return;
140     }
141     if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
142       OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
143          << Ty.getSizeInBits() << ")";
144       return;
145     }
146     llvm_unreachable("Unhandled LLT");
147   }
148 
149   const LLT &get() const { return Ty; }
150 
151   /// This ordering is used for std::unique() and std::sort(). There's no
152   /// particular logic behind the order but either A < B or B < A must be
153   /// true if A != B.
154   bool operator<(const LLTCodeGen &Other) const {
155     if (Ty.isValid() != Other.Ty.isValid())
156       return Ty.isValid() < Other.Ty.isValid();
157     if (!Ty.isValid())
158       return false;
159 
160     if (Ty.isVector() != Other.Ty.isVector())
161       return Ty.isVector() < Other.Ty.isVector();
162     if (Ty.isScalar() != Other.Ty.isScalar())
163       return Ty.isScalar() < Other.Ty.isScalar();
164     if (Ty.isPointer() != Other.Ty.isPointer())
165       return Ty.isPointer() < Other.Ty.isPointer();
166 
167     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
168       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
169 
170     if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
171       return Ty.getNumElements() < Other.Ty.getNumElements();
172 
173     return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
174   }
175 
176   bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
177 };
178 
179 class InstructionMatcher;
180 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
181 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
182 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
183   MVT VT(SVT);
184 
185   if (VT.isVector() && VT.getVectorNumElements() != 1)
186     return LLTCodeGen(
187         LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
188 
189   if (VT.isInteger() || VT.isFloatingPoint())
190     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
191   return None;
192 }
193 
194 static std::string explainPredicates(const TreePatternNode *N) {
195   std::string Explanation = "";
196   StringRef Separator = "";
197   for (const auto &P : N->getPredicateFns()) {
198     Explanation +=
199         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
200     Separator = ", ";
201 
202     if (P.isAlwaysTrue())
203       Explanation += " always-true";
204     if (P.isImmediatePattern())
205       Explanation += " immediate";
206 
207     if (P.isUnindexed())
208       Explanation += " unindexed";
209 
210     if (P.isNonExtLoad())
211       Explanation += " non-extload";
212     if (P.isAnyExtLoad())
213       Explanation += " extload";
214     if (P.isSignExtLoad())
215       Explanation += " sextload";
216     if (P.isZeroExtLoad())
217       Explanation += " zextload";
218 
219     if (P.isNonTruncStore())
220       Explanation += " non-truncstore";
221     if (P.isTruncStore())
222       Explanation += " truncstore";
223 
224     if (Record *VT = P.getMemoryVT())
225       Explanation += (" MemVT=" + VT->getName()).str();
226     if (Record *VT = P.getScalarMemoryVT())
227       Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
228 
229     if (P.isAtomicOrderingMonotonic())
230       Explanation += " monotonic";
231     if (P.isAtomicOrderingAcquire())
232       Explanation += " acquire";
233     if (P.isAtomicOrderingRelease())
234       Explanation += " release";
235     if (P.isAtomicOrderingAcquireRelease())
236       Explanation += " acq_rel";
237     if (P.isAtomicOrderingSequentiallyConsistent())
238       Explanation += " seq_cst";
239     if (P.isAtomicOrderingAcquireOrStronger())
240       Explanation += " >=acquire";
241     if (P.isAtomicOrderingWeakerThanAcquire())
242       Explanation += " <acquire";
243     if (P.isAtomicOrderingReleaseOrStronger())
244       Explanation += " >=release";
245     if (P.isAtomicOrderingWeakerThanRelease())
246       Explanation += " <release";
247   }
248   return Explanation;
249 }
250 
251 std::string explainOperator(Record *Operator) {
252   if (Operator->isSubClassOf("SDNode"))
253     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
254 
255   if (Operator->isSubClassOf("Intrinsic"))
256     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
257 
258   if (Operator->isSubClassOf("ComplexPattern"))
259     return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
260             ")")
261         .str();
262 
263   return (" (Operator " + Operator->getName() + " not understood)").str();
264 }
265 
266 /// Helper function to let the emitter report skip reason error messages.
267 static Error failedImport(const Twine &Reason) {
268   return make_error<StringError>(Reason, inconvertibleErrorCode());
269 }
270 
271 static Error isTrivialOperatorNode(const TreePatternNode *N) {
272   std::string Explanation = "";
273   std::string Separator = "";
274 
275   bool HasUnsupportedPredicate = false;
276   for (const auto &Predicate : N->getPredicateFns()) {
277     if (Predicate.isAlwaysTrue())
278       continue;
279 
280     if (Predicate.isImmediatePattern())
281       continue;
282 
283     if (Predicate.isNonExtLoad())
284       continue;
285 
286     if (Predicate.isNonTruncStore())
287       continue;
288 
289     if (Predicate.isLoad() || Predicate.isStore()) {
290       if (Predicate.isUnindexed())
291         continue;
292     }
293 
294     if (Predicate.isAtomic() && Predicate.getMemoryVT())
295       continue;
296 
297     if (Predicate.isAtomic() &&
298         (Predicate.isAtomicOrderingMonotonic() ||
299          Predicate.isAtomicOrderingAcquire() ||
300          Predicate.isAtomicOrderingRelease() ||
301          Predicate.isAtomicOrderingAcquireRelease() ||
302          Predicate.isAtomicOrderingSequentiallyConsistent() ||
303          Predicate.isAtomicOrderingAcquireOrStronger() ||
304          Predicate.isAtomicOrderingWeakerThanAcquire() ||
305          Predicate.isAtomicOrderingReleaseOrStronger() ||
306          Predicate.isAtomicOrderingWeakerThanRelease()))
307       continue;
308 
309     HasUnsupportedPredicate = true;
310     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
311     Separator = ", ";
312     Explanation += (Separator + "first-failing:" +
313                     Predicate.getOrigPatFragRecord()->getRecord()->getName())
314                        .str();
315     break;
316   }
317 
318   if (N->getTransformFn()) {
319     Explanation += Separator + "Has a transform function";
320     Separator = ", ";
321   }
322 
323   if (!HasUnsupportedPredicate && !N->getTransformFn())
324     return Error::success();
325 
326   return failedImport(Explanation);
327 }
328 
329 static Record *getInitValueAsRegClass(Init *V) {
330   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
331     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
332       return VDefInit->getDef()->getValueAsDef("RegClass");
333     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
334       return VDefInit->getDef();
335   }
336   return nullptr;
337 }
338 
339 std::string
340 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
341   std::string Name = "GIFBS";
342   for (const auto &Feature : FeatureBitset)
343     Name += ("_" + Feature->getName()).str();
344   return Name;
345 }
346 
347 //===- MatchTable Helpers -------------------------------------------------===//
348 
349 class MatchTable;
350 
351 /// A record to be stored in a MatchTable.
352 ///
353 /// This class represents any and all output that may be required to emit the
354 /// MatchTable. Instances  are most often configured to represent an opcode or
355 /// value that will be emitted to the table with some formatting but it can also
356 /// represent commas, comments, and other formatting instructions.
357 struct MatchTableRecord {
358   enum RecordFlagsBits {
359     MTRF_None = 0x0,
360     /// Causes EmitStr to be formatted as comment when emitted.
361     MTRF_Comment = 0x1,
362     /// Causes the record value to be followed by a comma when emitted.
363     MTRF_CommaFollows = 0x2,
364     /// Causes the record value to be followed by a line break when emitted.
365     MTRF_LineBreakFollows = 0x4,
366     /// Indicates that the record defines a label and causes an additional
367     /// comment to be emitted containing the index of the label.
368     MTRF_Label = 0x8,
369     /// Causes the record to be emitted as the index of the label specified by
370     /// LabelID along with a comment indicating where that label is.
371     MTRF_JumpTarget = 0x10,
372     /// Causes the formatter to add a level of indentation before emitting the
373     /// record.
374     MTRF_Indent = 0x20,
375     /// Causes the formatter to remove a level of indentation after emitting the
376     /// record.
377     MTRF_Outdent = 0x40,
378   };
379 
380   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
381   /// reference or define.
382   unsigned LabelID;
383   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
384   /// value, a label name.
385   std::string EmitStr;
386 
387 private:
388   /// The number of MatchTable elements described by this record. Comments are 0
389   /// while values are typically 1. Values >1 may occur when we need to emit
390   /// values that exceed the size of a MatchTable element.
391   unsigned NumElements;
392 
393 public:
394   /// A bitfield of RecordFlagsBits flags.
395   unsigned Flags;
396 
397   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
398                    unsigned NumElements, unsigned Flags)
399       : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
400         EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
401     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
402            "This value is reserved for non-labels");
403   }
404 
405   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
406             const MatchTable &Table) const;
407   unsigned size() const { return NumElements; }
408 };
409 
410 /// Holds the contents of a generated MatchTable to enable formatting and the
411 /// necessary index tracking needed to support GIM_Try.
412 class MatchTable {
413   /// An unique identifier for the table. The generated table will be named
414   /// MatchTable${ID}.
415   unsigned ID;
416   /// The records that make up the table. Also includes comments describing the
417   /// values being emitted and line breaks to format it.
418   std::vector<MatchTableRecord> Contents;
419   /// The currently defined labels.
420   DenseMap<unsigned, unsigned> LabelMap;
421   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
422   unsigned CurrentSize;
423 
424   /// A unique identifier for a MatchTable label.
425   static unsigned CurrentLabelID;
426 
427 public:
428   static MatchTableRecord LineBreak;
429   static MatchTableRecord Comment(StringRef Comment) {
430     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
431   }
432   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
433     unsigned ExtraFlags = 0;
434     if (IndentAdjust > 0)
435       ExtraFlags |= MatchTableRecord::MTRF_Indent;
436     if (IndentAdjust < 0)
437       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
438 
439     return MatchTableRecord(None, Opcode, 1,
440                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
441   }
442   static MatchTableRecord NamedValue(StringRef NamedValue) {
443     return MatchTableRecord(None, NamedValue, 1,
444                             MatchTableRecord::MTRF_CommaFollows);
445   }
446   static MatchTableRecord NamedValue(StringRef Namespace,
447                                      StringRef NamedValue) {
448     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
449                             MatchTableRecord::MTRF_CommaFollows);
450   }
451   static MatchTableRecord IntValue(int64_t IntValue) {
452     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
453                             MatchTableRecord::MTRF_CommaFollows);
454   }
455   static MatchTableRecord Label(unsigned LabelID) {
456     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
457                             MatchTableRecord::MTRF_Label |
458                                 MatchTableRecord::MTRF_Comment |
459                                 MatchTableRecord::MTRF_LineBreakFollows);
460   }
461   static MatchTableRecord JumpTarget(unsigned LabelID) {
462     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
463                             MatchTableRecord::MTRF_JumpTarget |
464                                 MatchTableRecord::MTRF_Comment |
465                                 MatchTableRecord::MTRF_CommaFollows);
466   }
467 
468   MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
469 
470   void push_back(const MatchTableRecord &Value) {
471     if (Value.Flags & MatchTableRecord::MTRF_Label)
472       defineLabel(Value.LabelID);
473     Contents.push_back(Value);
474     CurrentSize += Value.size();
475   }
476 
477   unsigned allocateLabelID() const { return CurrentLabelID++; }
478 
479   void defineLabel(unsigned LabelID) {
480     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
481   }
482 
483   unsigned getLabelIndex(unsigned LabelID) const {
484     const auto I = LabelMap.find(LabelID);
485     assert(I != LabelMap.end() && "Use of undeclared label");
486     return I->second;
487   }
488 
489   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
490 
491   void emitDeclaration(raw_ostream &OS) const {
492     unsigned Indentation = 4;
493     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
494     LineBreak.emit(OS, true, *this);
495     OS << std::string(Indentation, ' ');
496 
497     for (auto I = Contents.begin(), E = Contents.end(); I != E;
498          ++I) {
499       bool LineBreakIsNext = false;
500       const auto &NextI = std::next(I);
501 
502       if (NextI != E) {
503         if (NextI->EmitStr == "" &&
504             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
505           LineBreakIsNext = true;
506       }
507 
508       if (I->Flags & MatchTableRecord::MTRF_Indent)
509         Indentation += 2;
510 
511       I->emit(OS, LineBreakIsNext, *this);
512       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
513         OS << std::string(Indentation, ' ');
514 
515       if (I->Flags & MatchTableRecord::MTRF_Outdent)
516         Indentation -= 2;
517     }
518     OS << "};\n";
519   }
520 };
521 
522 unsigned MatchTable::CurrentLabelID = 0;
523 
524 MatchTableRecord MatchTable::LineBreak = {
525     None, "" /* Emit String */, 0 /* Elements */,
526     MatchTableRecord::MTRF_LineBreakFollows};
527 
528 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
529                             const MatchTable &Table) const {
530   bool UseLineComment =
531       LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
532   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
533     UseLineComment = false;
534 
535   if (Flags & MTRF_Comment)
536     OS << (UseLineComment ? "// " : "/*");
537 
538   OS << EmitStr;
539   if (Flags & MTRF_Label)
540     OS << ": @" << Table.getLabelIndex(LabelID);
541 
542   if (Flags & MTRF_Comment && !UseLineComment)
543     OS << "*/";
544 
545   if (Flags & MTRF_JumpTarget) {
546     if (Flags & MTRF_Comment)
547       OS << " ";
548     OS << Table.getLabelIndex(LabelID);
549   }
550 
551   if (Flags & MTRF_CommaFollows) {
552     OS << ",";
553     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
554       OS << " ";
555   }
556 
557   if (Flags & MTRF_LineBreakFollows)
558     OS << "\n";
559 }
560 
561 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
562   Table.push_back(Value);
563   return Table;
564 }
565 
566 //===- Matchers -----------------------------------------------------------===//
567 
568 class OperandMatcher;
569 class MatchAction;
570 class PredicateMatcher;
571 class RuleMatcher;
572 
573 class Matcher {
574 public:
575   virtual ~Matcher() = default;
576   virtual void emit(MatchTable &Table) = 0;
577 };
578 
579 class GroupMatcher : public Matcher {
580   SmallVector<std::unique_ptr<PredicateMatcher>, 8> Conditions;
581   SmallVector<Matcher *, 8> Rules;
582 
583 public:
584   void addCondition(std::unique_ptr<PredicateMatcher> &&Predicate) {
585     Conditions.emplace_back(std::move(Predicate));
586   }
587   void addRule(Matcher &Rule) { Rules.push_back(&Rule); }
588   const std::unique_ptr<PredicateMatcher> &conditions_back() const {
589     return Conditions.back();
590   }
591   bool lastConditionMatches(const PredicateMatcher &Predicate) const;
592   bool conditions_empty() const { return Conditions.empty(); }
593   void clear() {
594     Conditions.clear();
595     Rules.clear();
596   }
597   void emit(MatchTable &Table) override;
598 };
599 
600 /// Generates code to check that a match rule matches.
601 class RuleMatcher : public Matcher {
602 public:
603   using ActionVec = std::vector<std::unique_ptr<MatchAction>>;
604   using action_iterator = ActionVec::iterator;
605 
606 protected:
607   /// A list of matchers that all need to succeed for the current rule to match.
608   /// FIXME: This currently supports a single match position but could be
609   /// extended to support multiple positions to support div/rem fusion or
610   /// load-multiple instructions.
611   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
612 
613   /// A list of actions that need to be taken when all predicates in this rule
614   /// have succeeded.
615   ActionVec Actions;
616 
617   using DefinedInsnVariablesMap =
618       std::map<const InstructionMatcher *, unsigned>;
619 
620   /// A map of instruction matchers to the local variables created by
621   /// emitCaptureOpcodes().
622   DefinedInsnVariablesMap InsnVariableIDs;
623 
624   using MutatableInsnSet = SmallPtrSet<const InstructionMatcher *, 4>;
625 
626   // The set of instruction matchers that have not yet been claimed for mutation
627   // by a BuildMI.
628   MutatableInsnSet MutatableInsns;
629 
630   /// A map of named operands defined by the matchers that may be referenced by
631   /// the renderers.
632   StringMap<OperandMatcher *> DefinedOperands;
633 
634   /// ID for the next instruction variable defined with defineInsnVar()
635   unsigned NextInsnVarID;
636 
637   /// ID for the next output instruction allocated with allocateOutputInsnID()
638   unsigned NextOutputInsnID;
639 
640   /// ID for the next temporary register ID allocated with allocateTempRegID()
641   unsigned NextTempRegID;
642 
643   std::vector<Record *> RequiredFeatures;
644 
645   ArrayRef<SMLoc> SrcLoc;
646 
647   typedef std::tuple<Record *, unsigned, unsigned>
648       DefinedComplexPatternSubOperand;
649   typedef StringMap<DefinedComplexPatternSubOperand>
650       DefinedComplexPatternSubOperandMap;
651   /// A map of Symbolic Names to ComplexPattern sub-operands.
652   DefinedComplexPatternSubOperandMap ComplexSubOperands;
653 
654   uint64_t RuleID;
655   static uint64_t NextRuleID;
656 
657 public:
658   RuleMatcher(ArrayRef<SMLoc> SrcLoc)
659       : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
660         DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
661         NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
662         RuleID(NextRuleID++) {}
663   RuleMatcher(RuleMatcher &&Other) = default;
664   RuleMatcher &operator=(RuleMatcher &&Other) = default;
665 
666   uint64_t getRuleID() const { return RuleID; }
667 
668   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
669   void addRequiredFeature(Record *Feature);
670   const std::vector<Record *> &getRequiredFeatures() const;
671 
672   template <class Kind, class... Args> Kind &addAction(Args &&... args);
673   template <class Kind, class... Args>
674   action_iterator insertAction(action_iterator InsertPt, Args &&... args);
675 
676   /// Define an instruction without emitting any code to do so.
677   /// This is used for the root of the match.
678   unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
679   void clearImplicitMap() {
680     NextInsnVarID = 0;
681     InsnVariableIDs.clear();
682   };
683   /// Define an instruction and emit corresponding state-machine opcodes.
684   unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
685                          unsigned InsnVarID, unsigned OpIdx);
686   unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
687   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
688     return InsnVariableIDs.begin();
689   }
690   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
691     return InsnVariableIDs.end();
692   }
693   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
694   defined_insn_vars() const {
695     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
696   }
697 
698   MutatableInsnSet::const_iterator mutatable_insns_begin() const {
699     return MutatableInsns.begin();
700   }
701   MutatableInsnSet::const_iterator mutatable_insns_end() const {
702     return MutatableInsns.end();
703   }
704   iterator_range<typename MutatableInsnSet::const_iterator>
705   mutatable_insns() const {
706     return make_range(mutatable_insns_begin(), mutatable_insns_end());
707   }
708   void reserveInsnMatcherForMutation(const InstructionMatcher *InsnMatcher) {
709     bool R = MutatableInsns.erase(InsnMatcher);
710     assert(R && "Reserving a mutatable insn that isn't available");
711     (void)R;
712   }
713 
714   action_iterator actions_begin() { return Actions.begin(); }
715   action_iterator actions_end() { return Actions.end(); }
716   iterator_range<action_iterator> actions() {
717     return make_range(actions_begin(), actions_end());
718   }
719 
720   void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
721 
722   void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
723                                unsigned RendererID, unsigned SubOperandID) {
724     assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
725     ComplexSubOperands[SymbolicName] =
726         std::make_tuple(ComplexPattern, RendererID, SubOperandID);
727   }
728   Optional<DefinedComplexPatternSubOperand>
729   getComplexSubOperand(StringRef SymbolicName) const {
730     const auto &I = ComplexSubOperands.find(SymbolicName);
731     if (I == ComplexSubOperands.end())
732       return None;
733     return I->second;
734   }
735 
736   const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
737   const OperandMatcher &getOperandMatcher(StringRef Name) const;
738 
739   void emitCaptureOpcodes(MatchTable &Table);
740 
741   void emit(MatchTable &Table) override;
742 
743   /// Compare the priority of this object and B.
744   ///
745   /// Returns true if this object is more important than B.
746   bool isHigherPriorityThan(const RuleMatcher &B) const;
747 
748   /// Report the maximum number of temporary operands needed by the rule
749   /// matcher.
750   unsigned countRendererFns() const;
751 
752   std::unique_ptr<PredicateMatcher> forgetFirstCondition();
753 
754   // FIXME: Remove this as soon as possible
755   InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
756 
757   unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
758   unsigned allocateTempRegID() { return NextTempRegID++; }
759 
760   bool insnmatchers_empty() const { return Matchers.empty(); }
761   void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
762 };
763 
764 uint64_t RuleMatcher::NextRuleID = 0;
765 
766 using action_iterator = RuleMatcher::action_iterator;
767 
768 template <class PredicateTy> class PredicateListMatcher {
769 private:
770   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
771   PredicateVec Predicates;
772 
773   /// Template instantiations should specialize this to return a string to use
774   /// for the comment emitted when there are no predicates.
775   std::string getNoPredicateComment() const;
776 
777 public:
778   /// Construct a new operand predicate and add it to the matcher.
779   template <class Kind, class... Args>
780   Optional<Kind *> addPredicate(Args&&... args) {
781     Predicates.emplace_back(
782         llvm::make_unique<Kind>(std::forward<Args>(args)...));
783     return static_cast<Kind *>(Predicates.back().get());
784   }
785 
786   typename PredicateVec::const_iterator predicates_begin() const {
787     return Predicates.begin();
788   }
789   typename PredicateVec::const_iterator predicates_end() const {
790     return Predicates.end();
791   }
792   iterator_range<typename PredicateVec::const_iterator> predicates() const {
793     return make_range(predicates_begin(), predicates_end());
794   }
795   typename PredicateVec::size_type predicates_size() const {
796     return Predicates.size();
797   }
798   bool predicates_empty() const { return Predicates.empty(); }
799 
800   std::unique_ptr<PredicateTy> predicates_pop_front() {
801     std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
802     Predicates.erase(Predicates.begin());
803     return Front;
804   }
805 
806   /// Emit MatchTable opcodes that tests whether all the predicates are met.
807   template <class... Args>
808   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
809     if (Predicates.empty()) {
810       Table << MatchTable::Comment(getNoPredicateComment())
811             << MatchTable::LineBreak;
812       return;
813     }
814 
815     unsigned OpIdx = (*predicates_begin())->getOpIdx();
816     (void)OpIdx;
817     for (const auto &Predicate : predicates()) {
818       assert(Predicate->getOpIdx() == OpIdx &&
819              "Checks touch different operands?");
820       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
821     }
822   }
823 };
824 
825 class PredicateMatcher {
826 public:
827   /// This enum is used for RTTI and also defines the priority that is given to
828   /// the predicate when generating the matcher code. Kinds with higher priority
829   /// must be tested first.
830   ///
831   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
832   /// but OPM_Int must have priority over OPM_RegBank since constant integers
833   /// are represented by a virtual register defined by a G_CONSTANT instruction.
834   ///
835   /// Note: The relative priority between IPM_ and OPM_ does not matter, they
836   /// are currently not compared between each other.
837   enum PredicateKind {
838     IPM_Opcode,
839     IPM_ImmPredicate,
840     IPM_AtomicOrderingMMO,
841     OPM_SameOperand,
842     OPM_ComplexPattern,
843     OPM_IntrinsicID,
844     OPM_Instruction,
845     OPM_Int,
846     OPM_LiteralInt,
847     OPM_LLT,
848     OPM_PointerToAny,
849     OPM_RegBank,
850     OPM_MBB,
851   };
852 
853 protected:
854   PredicateKind Kind;
855   unsigned InsnVarID;
856   unsigned OpIdx;
857 
858 public:
859   PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
860       : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
861 
862   unsigned getOpIdx() const { return OpIdx; }
863   virtual ~PredicateMatcher() = default;
864   /// Emit MatchTable opcodes that check the predicate for the given operand.
865   virtual void emitPredicateOpcodes(MatchTable &Table,
866                                     RuleMatcher &Rule) const = 0;
867 
868   PredicateKind getKind() const { return Kind; }
869 
870   virtual bool isIdentical(const PredicateMatcher &B) const {
871     if (InsnVarID != 0 || OpIdx != (unsigned)~0) {
872       // We currently don't hoist the record of instruction properly.
873       // Therefore we can only work on the orig instruction (InsnVarID
874       // == 0).
875       DEBUG(dbgs() << "Non-zero instr ID not supported yet\n");
876       return false;
877     }
878     return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
879            OpIdx == B.OpIdx;
880   }
881 };
882 
883 /// Generates code to check a predicate of an operand.
884 ///
885 /// Typical predicates include:
886 /// * Operand is a particular register.
887 /// * Operand is assigned a particular register bank.
888 /// * Operand is an MBB.
889 class OperandPredicateMatcher : public PredicateMatcher {
890 public:
891   OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
892                           unsigned OpIdx)
893       : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
894   virtual ~OperandPredicateMatcher() {}
895 
896   /// Emit MatchTable opcodes to capture instructions into the MIs table.
897   ///
898   /// Only InstructionOperandMatcher needs to do anything for this method the
899   /// rest just walk the tree.
900   virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {}
901 
902   /// Compare the priority of this object and B.
903   ///
904   /// Returns true if this object is more important than B.
905   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
906 
907   /// Report the maximum number of temporary operands needed by the predicate
908   /// matcher.
909   virtual unsigned countRendererFns() const { return 0; }
910 };
911 
912 template <>
913 std::string
914 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
915   return "No operand predicates";
916 }
917 
918 /// Generates code to check that a register operand is defined by the same exact
919 /// one as another.
920 class SameOperandMatcher : public OperandPredicateMatcher {
921   std::string MatchingName;
922 
923 public:
924   SameOperandMatcher(StringRef MatchingName, unsigned InsnVarID, unsigned OpIdx)
925       : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
926         MatchingName(MatchingName) {}
927 
928   static bool classof(const OperandPredicateMatcher *P) {
929     return P->getKind() == OPM_SameOperand;
930   }
931 
932   void emitPredicateOpcodes(MatchTable &Table,
933                             RuleMatcher &Rule) const override;
934 };
935 
936 /// Generates code to check that an operand is a particular LLT.
937 class LLTOperandMatcher : public OperandPredicateMatcher {
938 protected:
939   LLTCodeGen Ty;
940 
941 public:
942   static std::set<LLTCodeGen> KnownTypes;
943 
944   LLTOperandMatcher(const LLTCodeGen &Ty, unsigned InsnVarID, unsigned OpIdx)
945       : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
946     KnownTypes.insert(Ty);
947   }
948 
949   static bool classof(const PredicateMatcher *P) {
950     return P->getKind() == OPM_LLT;
951   }
952   bool isIdentical(const PredicateMatcher &B) const override {
953     return OperandPredicateMatcher::isIdentical(B) &&
954            Ty == cast<LLTOperandMatcher>(&B)->Ty;
955   }
956 
957   void emitPredicateOpcodes(MatchTable &Table,
958                             RuleMatcher &Rule) const override {
959     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
960           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
961           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
962           << MatchTable::NamedValue(Ty.getCxxEnumValue())
963           << MatchTable::LineBreak;
964   }
965 };
966 
967 std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
968 
969 /// Generates code to check that an operand is a pointer to any address space.
970 ///
971 /// In SelectionDAG, the types did not describe pointers or address spaces. As a
972 /// result, iN is used to describe a pointer of N bits to any address space and
973 /// PatFrag predicates are typically used to constrain the address space. There's
974 /// no reliable means to derive the missing type information from the pattern so
975 /// imported rules must test the components of a pointer separately.
976 ///
977 /// If SizeInBits is zero, then the pointer size will be obtained from the
978 /// subtarget.
979 class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
980 protected:
981   unsigned SizeInBits;
982 
983 public:
984   PointerToAnyOperandMatcher(unsigned SizeInBits, unsigned InsnVarID,
985                              unsigned OpIdx)
986       : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
987         SizeInBits(SizeInBits) {}
988 
989   static bool classof(const OperandPredicateMatcher *P) {
990     return P->getKind() == OPM_PointerToAny;
991   }
992 
993   void emitPredicateOpcodes(MatchTable &Table,
994                             RuleMatcher &Rule) const override {
995     Table << MatchTable::Opcode("GIM_CheckPointerToAny")
996           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
997           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
998           << MatchTable::Comment("SizeInBits")
999           << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1000   }
1001 };
1002 
1003 /// Generates code to check that an operand is a particular target constant.
1004 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1005 protected:
1006   const OperandMatcher &Operand;
1007   const Record &TheDef;
1008 
1009   unsigned getAllocatedTemporariesBaseID() const;
1010 
1011 public:
1012   bool isIdentical(const PredicateMatcher &B) const override { return false; }
1013 
1014   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
1015                                const Record &TheDef, unsigned InsnVarID,
1016                                unsigned OpIdx)
1017       : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1018         Operand(Operand), TheDef(TheDef) {}
1019 
1020   static bool classof(const PredicateMatcher *P) {
1021     return P->getKind() == OPM_ComplexPattern;
1022   }
1023 
1024   void emitPredicateOpcodes(MatchTable &Table,
1025                             RuleMatcher &Rule) const override {
1026     unsigned ID = getAllocatedTemporariesBaseID();
1027     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1028           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1029           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1030           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1031           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1032           << MatchTable::LineBreak;
1033   }
1034 
1035   unsigned countRendererFns() const override {
1036     return 1;
1037   }
1038 };
1039 
1040 /// Generates code to check that an operand is in a particular register bank.
1041 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1042 protected:
1043   const CodeGenRegisterClass &RC;
1044 
1045 public:
1046   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC, unsigned InsnVarID,
1047                              unsigned OpIdx)
1048       : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
1049 
1050   bool isIdentical(const PredicateMatcher &B) const override {
1051     return OperandPredicateMatcher::isIdentical(B) &&
1052            RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1053   }
1054 
1055   static bool classof(const PredicateMatcher *P) {
1056     return P->getKind() == OPM_RegBank;
1057   }
1058 
1059   void emitPredicateOpcodes(MatchTable &Table,
1060                             RuleMatcher &Rule) const override {
1061     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1062           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1063           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1064           << MatchTable::Comment("RC")
1065           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1066           << MatchTable::LineBreak;
1067   }
1068 };
1069 
1070 /// Generates code to check that an operand is a basic block.
1071 class MBBOperandMatcher : public OperandPredicateMatcher {
1072 public:
1073   MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1074       : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
1075 
1076   static bool classof(const PredicateMatcher *P) {
1077     return P->getKind() == OPM_MBB;
1078   }
1079 
1080   void emitPredicateOpcodes(MatchTable &Table,
1081                             RuleMatcher &Rule) const override {
1082     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1083           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1084           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1085   }
1086 };
1087 
1088 /// Generates code to check that an operand is a G_CONSTANT with a particular
1089 /// int.
1090 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
1091 protected:
1092   int64_t Value;
1093 
1094 public:
1095   ConstantIntOperandMatcher(int64_t Value, unsigned InsnVarID, unsigned OpIdx)
1096       : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
1097 
1098   bool isIdentical(const PredicateMatcher &B) const override {
1099     return OperandPredicateMatcher::isIdentical(B) &&
1100            Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1101   }
1102 
1103   static bool classof(const PredicateMatcher *P) {
1104     return P->getKind() == OPM_Int;
1105   }
1106 
1107   void emitPredicateOpcodes(MatchTable &Table,
1108                             RuleMatcher &Rule) const override {
1109     Table << MatchTable::Opcode("GIM_CheckConstantInt")
1110           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1111           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1112           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1113   }
1114 };
1115 
1116 /// Generates code to check that an operand is a raw int (where MO.isImm() or
1117 /// MO.isCImm() is true).
1118 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1119 protected:
1120   int64_t Value;
1121 
1122 public:
1123   LiteralIntOperandMatcher(int64_t Value, unsigned InsnVarID, unsigned OpIdx)
1124       : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1125         Value(Value) {}
1126 
1127   bool isIdentical(const PredicateMatcher &B) const override {
1128     return OperandPredicateMatcher::isIdentical(B) &&
1129            Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1130   }
1131 
1132   static bool classof(const PredicateMatcher *P) {
1133     return P->getKind() == OPM_LiteralInt;
1134   }
1135 
1136   void emitPredicateOpcodes(MatchTable &Table,
1137                             RuleMatcher &Rule) const override {
1138     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1139           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1140           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1141           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1142   }
1143 };
1144 
1145 /// Generates code to check that an operand is an intrinsic ID.
1146 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1147 protected:
1148   const CodeGenIntrinsic *II;
1149 
1150 public:
1151   IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II, unsigned InsnVarID,
1152                             unsigned OpIdx)
1153       : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
1154 
1155   bool isIdentical(const PredicateMatcher &B) const override {
1156     return OperandPredicateMatcher::isIdentical(B) &&
1157            II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1158   }
1159 
1160   static bool classof(const PredicateMatcher *P) {
1161     return P->getKind() == OPM_IntrinsicID;
1162   }
1163 
1164   void emitPredicateOpcodes(MatchTable &Table,
1165                             RuleMatcher &Rule) const override {
1166     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1167           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1168           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1169           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1170           << MatchTable::LineBreak;
1171   }
1172 };
1173 
1174 /// Generates code to check that a set of predicates match for a particular
1175 /// operand.
1176 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1177 protected:
1178   InstructionMatcher &Insn;
1179   unsigned OpIdx;
1180   std::string SymbolicName;
1181 
1182   /// The index of the first temporary variable allocated to this operand. The
1183   /// number of allocated temporaries can be found with
1184   /// countRendererFns().
1185   unsigned AllocatedTemporariesBaseID;
1186 
1187 public:
1188   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
1189                  const std::string &SymbolicName,
1190                  unsigned AllocatedTemporariesBaseID)
1191       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1192         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
1193 
1194   bool hasSymbolicName() const { return !SymbolicName.empty(); }
1195   const StringRef getSymbolicName() const { return SymbolicName; }
1196   void setSymbolicName(StringRef Name) {
1197     assert(SymbolicName.empty() && "Operand already has a symbolic name");
1198     SymbolicName = Name;
1199   }
1200   unsigned getOperandIndex() const { return OpIdx; }
1201   unsigned getInsnVarID() const;
1202 
1203   std::string getOperandExpr(unsigned InsnVarID) const {
1204     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1205            llvm::to_string(OpIdx) + ")";
1206   }
1207 
1208   InstructionMatcher &getInstructionMatcher() const { return Insn; }
1209 
1210   Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1211                               bool OperandIsAPointer);
1212 
1213   /// Emit MatchTable opcodes to capture instructions into the MIs table.
1214   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
1215     for (const auto &Predicate : predicates())
1216       Predicate->emitCaptureOpcodes(Table, Rule);
1217   }
1218 
1219   /// Emit MatchTable opcodes that test whether the instruction named in
1220   /// InsnVarID matches all the predicates and all the operands.
1221   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
1222     std::string Comment;
1223     raw_string_ostream CommentOS(Comment);
1224     CommentOS << "MIs[" << getInsnVarID() << "] ";
1225     if (SymbolicName.empty())
1226       CommentOS << "Operand " << OpIdx;
1227     else
1228       CommentOS << SymbolicName;
1229     Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1230 
1231     emitPredicateListOpcodes(Table, Rule);
1232   }
1233 
1234   /// Compare the priority of this object and B.
1235   ///
1236   /// Returns true if this object is more important than B.
1237   bool isHigherPriorityThan(const OperandMatcher &B) const {
1238     // Operand matchers involving more predicates have higher priority.
1239     if (predicates_size() > B.predicates_size())
1240       return true;
1241     if (predicates_size() < B.predicates_size())
1242       return false;
1243 
1244     // This assumes that predicates are added in a consistent order.
1245     for (const auto &Predicate : zip(predicates(), B.predicates())) {
1246       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1247         return true;
1248       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1249         return false;
1250     }
1251 
1252     return false;
1253   };
1254 
1255   /// Report the maximum number of temporary operands needed by the operand
1256   /// matcher.
1257   unsigned countRendererFns() const {
1258     return std::accumulate(
1259         predicates().begin(), predicates().end(), 0,
1260         [](unsigned A,
1261            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
1262           return A + Predicate->countRendererFns();
1263         });
1264   }
1265 
1266   unsigned getAllocatedTemporariesBaseID() const {
1267     return AllocatedTemporariesBaseID;
1268   }
1269 
1270   bool isSameAsAnotherOperand() const {
1271     for (const auto &Predicate : predicates())
1272       if (isa<SameOperandMatcher>(Predicate))
1273         return true;
1274     return false;
1275   }
1276 };
1277 
1278 // Specialize OperandMatcher::addPredicate() to refrain from adding redundant
1279 // predicates.
1280 template <>
1281 template <class Kind, class... Args>
1282 Optional<Kind *>
1283 PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
1284   auto *OpMatcher = static_cast<OperandMatcher *>(this);
1285   if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
1286     return None;
1287   Predicates.emplace_back(llvm::make_unique<Kind>(
1288       std::forward<Args>(args)..., OpMatcher->getInsnVarID(),
1289       OpMatcher->getOperandIndex()));
1290   return static_cast<Kind *>(Predicates.back().get());
1291 }
1292 
1293 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1294                                             bool OperandIsAPointer) {
1295   if (!VTy.isMachineValueType())
1296     return failedImport("unsupported typeset");
1297 
1298   if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1299     addPredicate<PointerToAnyOperandMatcher>(0);
1300     return Error::success();
1301   }
1302 
1303   auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1304   if (!OpTyOrNone)
1305     return failedImport("unsupported type");
1306 
1307   if (OperandIsAPointer)
1308     addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1309   else
1310     addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1311   return Error::success();
1312 }
1313 
1314 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1315   return Operand.getAllocatedTemporariesBaseID();
1316 }
1317 
1318 /// Generates code to check a predicate on an instruction.
1319 ///
1320 /// Typical predicates include:
1321 /// * The opcode of the instruction is a particular value.
1322 /// * The nsw/nuw flag is/isn't set.
1323 class InstructionPredicateMatcher : public PredicateMatcher {
1324 public:
1325   InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1326       : PredicateMatcher(Kind, InsnVarID) {}
1327   virtual ~InstructionPredicateMatcher() {}
1328 
1329   /// Compare the priority of this object and B.
1330   ///
1331   /// Returns true if this object is more important than B.
1332   virtual bool
1333   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
1334     return Kind < B.Kind;
1335   };
1336 
1337   /// Report the maximum number of temporary operands needed by the predicate
1338   /// matcher.
1339   virtual unsigned countRendererFns() const { return 0; }
1340 };
1341 
1342 template <>
1343 std::string
1344 PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1345   return "No instruction predicates";
1346 }
1347 
1348 /// Generates code to check the opcode of an instruction.
1349 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1350 protected:
1351   const CodeGenInstruction *I;
1352 
1353 public:
1354   InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1355       : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
1356 
1357   static bool classof(const PredicateMatcher *P) {
1358     return P->getKind() == IPM_Opcode;
1359   }
1360 
1361   bool isIdentical(const PredicateMatcher &B) const override {
1362     return InstructionPredicateMatcher::isIdentical(B) &&
1363            I == cast<InstructionOpcodeMatcher>(&B)->I;
1364   }
1365 
1366   void emitPredicateOpcodes(MatchTable &Table,
1367                             RuleMatcher &Rule) const override {
1368     Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1369           << MatchTable::IntValue(InsnVarID)
1370           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1371           << MatchTable::LineBreak;
1372   }
1373 
1374   /// Compare the priority of this object and B.
1375   ///
1376   /// Returns true if this object is more important than B.
1377   bool
1378   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1379     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1380       return true;
1381     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1382       return false;
1383 
1384     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1385     // this is cosmetic at the moment, we may want to drive a similar ordering
1386     // using instruction frequency information to improve compile time.
1387     if (const InstructionOpcodeMatcher *BO =
1388             dyn_cast<InstructionOpcodeMatcher>(&B))
1389       return I->TheDef->getName() < BO->I->TheDef->getName();
1390 
1391     return false;
1392   };
1393 
1394   bool isConstantInstruction() const {
1395     return I->TheDef->getName() == "G_CONSTANT";
1396   }
1397 };
1398 
1399 /// Generates code to check that this instruction is a constant whose value
1400 /// meets an immediate predicate.
1401 ///
1402 /// Immediates are slightly odd since they are typically used like an operand
1403 /// but are represented as an operator internally. We typically write simm8:$src
1404 /// in a tablegen pattern, but this is just syntactic sugar for
1405 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1406 /// that will be matched and the predicate (which is attached to the imm
1407 /// operator) that will be tested. In SelectionDAG this describes a
1408 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1409 ///
1410 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1411 /// this representation, the immediate could be tested with an
1412 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1413 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1414 /// there are two implementation issues with producing that matcher
1415 /// configuration from the SelectionDAG pattern:
1416 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1417 ///   were we to sink the immediate predicate to the operand we would have to
1418 ///   have two partial implementations of PatFrag support, one for immediates
1419 ///   and one for non-immediates.
1420 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1421 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1422 ///   would also have to complicate (or duplicate) the code that descends and
1423 ///   creates matchers for the subtree.
1424 /// Overall, it's simpler to handle it in the place it was found.
1425 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1426 protected:
1427   TreePredicateFn Predicate;
1428 
1429 public:
1430   InstructionImmPredicateMatcher(unsigned InsnVarID,
1431                                  const TreePredicateFn &Predicate)
1432       : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1433         Predicate(Predicate) {}
1434 
1435   bool isIdentical(const PredicateMatcher &B) const override {
1436     return InstructionPredicateMatcher::isIdentical(B) &&
1437            Predicate.getOrigPatFragRecord() ==
1438                cast<InstructionImmPredicateMatcher>(&B)
1439                    ->Predicate.getOrigPatFragRecord();
1440   }
1441 
1442   static bool classof(const PredicateMatcher *P) {
1443     return P->getKind() == IPM_ImmPredicate;
1444   }
1445 
1446   void emitPredicateOpcodes(MatchTable &Table,
1447                             RuleMatcher &Rule) const override {
1448     Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
1449           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1450           << MatchTable::Comment("Predicate")
1451           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1452           << MatchTable::LineBreak;
1453   }
1454 };
1455 
1456 /// Generates code to check that a memory instruction has a atomic ordering
1457 /// MachineMemoryOperand.
1458 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1459 public:
1460   enum AOComparator {
1461     AO_Exactly,
1462     AO_OrStronger,
1463     AO_WeakerThan,
1464   };
1465 
1466 protected:
1467   StringRef Order;
1468   AOComparator Comparator;
1469 
1470 public:
1471   AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
1472                                     AOComparator Comparator = AO_Exactly)
1473       : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1474         Order(Order), Comparator(Comparator) {}
1475 
1476   static bool classof(const InstructionPredicateMatcher *P) {
1477     return P->getKind() == IPM_AtomicOrderingMMO;
1478   }
1479 
1480   void emitPredicateOpcodes(MatchTable &Table,
1481                             RuleMatcher &Rule) const override {
1482     StringRef Opcode = "GIM_CheckAtomicOrdering";
1483 
1484     if (Comparator == AO_OrStronger)
1485       Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1486     if (Comparator == AO_WeakerThan)
1487       Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1488 
1489     Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1490           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
1491           << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
1492           << MatchTable::LineBreak;
1493   }
1494 };
1495 
1496 /// Generates code to check that a set of predicates and operands match for a
1497 /// particular instruction.
1498 ///
1499 /// Typical predicates include:
1500 /// * Has a specific opcode.
1501 /// * Has an nsw/nuw flag or doesn't.
1502 class InstructionMatcher
1503     : public PredicateListMatcher<InstructionPredicateMatcher> {
1504 protected:
1505   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
1506 
1507   RuleMatcher &Rule;
1508 
1509   /// The operands to match. All rendered operands must be present even if the
1510   /// condition is always true.
1511   OperandVec Operands;
1512 
1513   std::string SymbolicName;
1514   unsigned InsnVarID;
1515 
1516 public:
1517   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1518       : Rule(Rule), SymbolicName(SymbolicName) {
1519     // We create a new instruction matcher.
1520     // Get a new ID for that instruction.
1521     InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1522   }
1523 
1524   RuleMatcher &getRuleMatcher() const { return Rule; }
1525 
1526   unsigned getVarID() const { return InsnVarID; }
1527 
1528   /// Add an operand to the matcher.
1529   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1530                              unsigned AllocatedTemporariesBaseID) {
1531     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1532                                              AllocatedTemporariesBaseID));
1533     if (!SymbolicName.empty())
1534       Rule.defineOperand(SymbolicName, *Operands.back());
1535 
1536     return *Operands.back();
1537   }
1538 
1539   OperandMatcher &getOperand(unsigned OpIdx) {
1540     auto I = std::find_if(Operands.begin(), Operands.end(),
1541                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1542                             return X->getOperandIndex() == OpIdx;
1543                           });
1544     if (I != Operands.end())
1545       return **I;
1546     llvm_unreachable("Failed to lookup operand");
1547   }
1548 
1549   StringRef getSymbolicName() const { return SymbolicName; }
1550   unsigned getNumOperands() const { return Operands.size(); }
1551   OperandVec::iterator operands_begin() { return Operands.begin(); }
1552   OperandVec::iterator operands_end() { return Operands.end(); }
1553   iterator_range<OperandVec::iterator> operands() {
1554     return make_range(operands_begin(), operands_end());
1555   }
1556   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1557   OperandVec::const_iterator operands_end() const { return Operands.end(); }
1558   iterator_range<OperandVec::const_iterator> operands() const {
1559     return make_range(operands_begin(), operands_end());
1560   }
1561   bool operands_empty() const { return Operands.empty(); }
1562 
1563   void pop_front() { Operands.erase(Operands.begin()); }
1564 
1565   /// Emit MatchTable opcodes to check the shape of the match and capture
1566   /// instructions into the MIs table.
1567   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1568     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1569           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1570           << MatchTable::Comment("Expected")
1571           << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
1572     for (const auto &Operand : Operands)
1573       Operand->emitCaptureOpcodes(Table, Rule);
1574   }
1575 
1576   /// Emit MatchTable opcodes that test whether the instruction named in
1577   /// InsnVarName matches all the predicates and all the operands.
1578   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
1579     emitPredicateListOpcodes(Table, Rule);
1580     for (const auto &Operand : Operands)
1581       Operand->emitPredicateOpcodes(Table, Rule);
1582   }
1583 
1584   /// Compare the priority of this object and B.
1585   ///
1586   /// Returns true if this object is more important than B.
1587   bool isHigherPriorityThan(const InstructionMatcher &B) const {
1588     // Instruction matchers involving more operands have higher priority.
1589     if (Operands.size() > B.Operands.size())
1590       return true;
1591     if (Operands.size() < B.Operands.size())
1592       return false;
1593 
1594     for (const auto &Predicate : zip(predicates(), B.predicates())) {
1595       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1596         return true;
1597       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1598         return false;
1599     }
1600 
1601     for (const auto &Operand : zip(Operands, B.Operands)) {
1602       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
1603         return true;
1604       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
1605         return false;
1606     }
1607 
1608     return false;
1609   };
1610 
1611   /// Report the maximum number of temporary operands needed by the instruction
1612   /// matcher.
1613   unsigned countRendererFns() const {
1614     return std::accumulate(predicates().begin(), predicates().end(), 0,
1615                            [](unsigned A,
1616                               const std::unique_ptr<InstructionPredicateMatcher>
1617                                   &Predicate) {
1618                              return A + Predicate->countRendererFns();
1619                            }) +
1620            std::accumulate(
1621                Operands.begin(), Operands.end(), 0,
1622                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
1623                  return A + Operand->countRendererFns();
1624                });
1625   }
1626 
1627   bool isConstantInstruction() const {
1628     for (const auto &P : predicates())
1629       if (const InstructionOpcodeMatcher *Opcode =
1630               dyn_cast<InstructionOpcodeMatcher>(P.get()))
1631         return Opcode->isConstantInstruction();
1632     return false;
1633   }
1634 };
1635 
1636 template <>
1637 template <class Kind, class... Args>
1638 Optional<Kind *>
1639 PredicateListMatcher<InstructionPredicateMatcher>::addPredicate(
1640     Args &&... args) {
1641   InstructionMatcher *InstMatcher = static_cast<InstructionMatcher *>(this);
1642   Predicates.emplace_back(llvm::make_unique<Kind>(InstMatcher->getVarID(),
1643                                                   std::forward<Args>(args)...));
1644   return static_cast<Kind *>(Predicates.back().get());
1645 }
1646 
1647 /// Generates code to check that the operand is a register defined by an
1648 /// instruction that matches the given instruction matcher.
1649 ///
1650 /// For example, the pattern:
1651 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1652 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1653 /// the:
1654 ///   (G_ADD $src1, $src2)
1655 /// subpattern.
1656 class InstructionOperandMatcher : public OperandPredicateMatcher {
1657 protected:
1658   std::unique_ptr<InstructionMatcher> InsnMatcher;
1659 
1660 public:
1661   InstructionOperandMatcher(RuleMatcher &Rule, StringRef SymbolicName,
1662                             unsigned InsnVarID, unsigned OpIdx)
1663       : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
1664         InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
1665 
1666   static bool classof(const PredicateMatcher *P) {
1667     return P->getKind() == OPM_Instruction;
1668   }
1669 
1670   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1671 
1672   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1673     unsigned InsnID =
1674         Rule.defineInsnVar(Table, *InsnMatcher, InsnVarID, getOpIdx());
1675     (void)InsnID;
1676     assert(InsnMatcher->getVarID() == InsnID &&
1677            "Mismatch between build and emit");
1678     InsnMatcher->emitCaptureOpcodes(Table, Rule);
1679   }
1680 
1681   void emitPredicateOpcodes(MatchTable &Table,
1682                             RuleMatcher &Rule) const override {
1683     InsnMatcher->emitPredicateOpcodes(Table, Rule);
1684   }
1685 };
1686 
1687 //===- Actions ------------------------------------------------------------===//
1688 class OperandRenderer {
1689 public:
1690   enum RendererKind {
1691     OR_Copy,
1692     OR_CopyOrAddZeroReg,
1693     OR_CopySubReg,
1694     OR_CopyConstantAsImm,
1695     OR_CopyFConstantAsFPImm,
1696     OR_Imm,
1697     OR_Register,
1698     OR_TempRegister,
1699     OR_ComplexPattern
1700   };
1701 
1702 protected:
1703   RendererKind Kind;
1704 
1705 public:
1706   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1707   virtual ~OperandRenderer() {}
1708 
1709   RendererKind getKind() const { return Kind; }
1710 
1711   virtual void emitRenderOpcodes(MatchTable &Table,
1712                                  RuleMatcher &Rule) const = 0;
1713 };
1714 
1715 /// A CopyRenderer emits code to copy a single operand from an existing
1716 /// instruction to the one being built.
1717 class CopyRenderer : public OperandRenderer {
1718 protected:
1719   unsigned NewInsnID;
1720   /// The name of the operand.
1721   const StringRef SymbolicName;
1722 
1723 public:
1724   CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
1725       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
1726         SymbolicName(SymbolicName) {
1727     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1728   }
1729 
1730   static bool classof(const OperandRenderer *R) {
1731     return R->getKind() == OR_Copy;
1732   }
1733 
1734   const StringRef getSymbolicName() const { return SymbolicName; }
1735 
1736   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1737     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1738     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1739     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1740           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1741           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1742           << MatchTable::IntValue(Operand.getOperandIndex())
1743           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1744   }
1745 };
1746 
1747 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1748 /// existing instruction to the one being built. If the operand turns out to be
1749 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1750 class CopyOrAddZeroRegRenderer : public OperandRenderer {
1751 protected:
1752   unsigned NewInsnID;
1753   /// The name of the operand.
1754   const StringRef SymbolicName;
1755   const Record *ZeroRegisterDef;
1756 
1757 public:
1758   CopyOrAddZeroRegRenderer(unsigned NewInsnID,
1759                            StringRef SymbolicName, Record *ZeroRegisterDef)
1760       : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1761         SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1762     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1763   }
1764 
1765   static bool classof(const OperandRenderer *R) {
1766     return R->getKind() == OR_CopyOrAddZeroReg;
1767   }
1768 
1769   const StringRef getSymbolicName() const { return SymbolicName; }
1770 
1771   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1772     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1773     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1774     Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1775           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1776           << MatchTable::Comment("OldInsnID")
1777           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1778           << MatchTable::IntValue(Operand.getOperandIndex())
1779           << MatchTable::NamedValue(
1780                  (ZeroRegisterDef->getValue("Namespace")
1781                       ? ZeroRegisterDef->getValueAsString("Namespace")
1782                       : ""),
1783                  ZeroRegisterDef->getName())
1784           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1785   }
1786 };
1787 
1788 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1789 /// an extended immediate operand.
1790 class CopyConstantAsImmRenderer : public OperandRenderer {
1791 protected:
1792   unsigned NewInsnID;
1793   /// The name of the operand.
1794   const std::string SymbolicName;
1795   bool Signed;
1796 
1797 public:
1798   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1799       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1800         SymbolicName(SymbolicName), Signed(true) {}
1801 
1802   static bool classof(const OperandRenderer *R) {
1803     return R->getKind() == OR_CopyConstantAsImm;
1804   }
1805 
1806   const StringRef getSymbolicName() const { return SymbolicName; }
1807 
1808   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1809     const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1810     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1811     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1812                                        : "GIR_CopyConstantAsUImm")
1813           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1814           << MatchTable::Comment("OldInsnID")
1815           << MatchTable::IntValue(OldInsnVarID)
1816           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1817   }
1818 };
1819 
1820 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1821 /// instruction to an extended immediate operand.
1822 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1823 protected:
1824   unsigned NewInsnID;
1825   /// The name of the operand.
1826   const std::string SymbolicName;
1827 
1828 public:
1829   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1830       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1831         SymbolicName(SymbolicName) {}
1832 
1833   static bool classof(const OperandRenderer *R) {
1834     return R->getKind() == OR_CopyFConstantAsFPImm;
1835   }
1836 
1837   const StringRef getSymbolicName() const { return SymbolicName; }
1838 
1839   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1840     const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1841     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1842     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1843           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1844           << MatchTable::Comment("OldInsnID")
1845           << MatchTable::IntValue(OldInsnVarID)
1846           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1847   }
1848 };
1849 
1850 /// A CopySubRegRenderer emits code to copy a single register operand from an
1851 /// existing instruction to the one being built and indicate that only a
1852 /// subregister should be copied.
1853 class CopySubRegRenderer : public OperandRenderer {
1854 protected:
1855   unsigned NewInsnID;
1856   /// The name of the operand.
1857   const StringRef SymbolicName;
1858   /// The subregister to extract.
1859   const CodeGenSubRegIndex *SubReg;
1860 
1861 public:
1862   CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
1863                      const CodeGenSubRegIndex *SubReg)
1864       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
1865         SymbolicName(SymbolicName), SubReg(SubReg) {}
1866 
1867   static bool classof(const OperandRenderer *R) {
1868     return R->getKind() == OR_CopySubReg;
1869   }
1870 
1871   const StringRef getSymbolicName() const { return SymbolicName; }
1872 
1873   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1874     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1875     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1876     Table << MatchTable::Opcode("GIR_CopySubReg")
1877           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1878           << MatchTable::Comment("OldInsnID")
1879           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1880           << MatchTable::IntValue(Operand.getOperandIndex())
1881           << MatchTable::Comment("SubRegIdx")
1882           << MatchTable::IntValue(SubReg->EnumValue)
1883           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1884   }
1885 };
1886 
1887 /// Adds a specific physical register to the instruction being built.
1888 /// This is typically useful for WZR/XZR on AArch64.
1889 class AddRegisterRenderer : public OperandRenderer {
1890 protected:
1891   unsigned InsnID;
1892   const Record *RegisterDef;
1893 
1894 public:
1895   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1896       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1897   }
1898 
1899   static bool classof(const OperandRenderer *R) {
1900     return R->getKind() == OR_Register;
1901   }
1902 
1903   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1904     Table << MatchTable::Opcode("GIR_AddRegister")
1905           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1906           << MatchTable::NamedValue(
1907                  (RegisterDef->getValue("Namespace")
1908                       ? RegisterDef->getValueAsString("Namespace")
1909                       : ""),
1910                  RegisterDef->getName())
1911           << MatchTable::LineBreak;
1912   }
1913 };
1914 
1915 /// Adds a specific temporary virtual register to the instruction being built.
1916 /// This is used to chain instructions together when emitting multiple
1917 /// instructions.
1918 class TempRegRenderer : public OperandRenderer {
1919 protected:
1920   unsigned InsnID;
1921   unsigned TempRegID;
1922   bool IsDef;
1923 
1924 public:
1925   TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
1926       : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
1927         IsDef(IsDef) {}
1928 
1929   static bool classof(const OperandRenderer *R) {
1930     return R->getKind() == OR_TempRegister;
1931   }
1932 
1933   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1934     Table << MatchTable::Opcode("GIR_AddTempRegister")
1935           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1936           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
1937           << MatchTable::Comment("TempRegFlags");
1938     if (IsDef)
1939       Table << MatchTable::NamedValue("RegState::Define");
1940     else
1941       Table << MatchTable::IntValue(0);
1942     Table << MatchTable::LineBreak;
1943   }
1944 };
1945 
1946 /// Adds a specific immediate to the instruction being built.
1947 class ImmRenderer : public OperandRenderer {
1948 protected:
1949   unsigned InsnID;
1950   int64_t Imm;
1951 
1952 public:
1953   ImmRenderer(unsigned InsnID, int64_t Imm)
1954       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
1955 
1956   static bool classof(const OperandRenderer *R) {
1957     return R->getKind() == OR_Imm;
1958   }
1959 
1960   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1961     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1962           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1963           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
1964   }
1965 };
1966 
1967 /// Adds operands by calling a renderer function supplied by the ComplexPattern
1968 /// matcher function.
1969 class RenderComplexPatternOperand : public OperandRenderer {
1970 private:
1971   unsigned InsnID;
1972   const Record &TheDef;
1973   /// The name of the operand.
1974   const StringRef SymbolicName;
1975   /// The renderer number. This must be unique within a rule since it's used to
1976   /// identify a temporary variable to hold the renderer function.
1977   unsigned RendererID;
1978   /// When provided, this is the suboperand of the ComplexPattern operand to
1979   /// render. Otherwise all the suboperands will be rendered.
1980   Optional<unsigned> SubOperand;
1981 
1982   unsigned getNumOperands() const {
1983     return TheDef.getValueAsDag("Operands")->getNumArgs();
1984   }
1985 
1986 public:
1987   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1988                               StringRef SymbolicName, unsigned RendererID,
1989                               Optional<unsigned> SubOperand = None)
1990       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
1991         SymbolicName(SymbolicName), RendererID(RendererID),
1992         SubOperand(SubOperand) {}
1993 
1994   static bool classof(const OperandRenderer *R) {
1995     return R->getKind() == OR_ComplexPattern;
1996   }
1997 
1998   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1999     Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2000                                                       : "GIR_ComplexRenderer")
2001           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2002           << MatchTable::Comment("RendererID")
2003           << MatchTable::IntValue(RendererID);
2004     if (SubOperand.hasValue())
2005       Table << MatchTable::Comment("SubOperand")
2006             << MatchTable::IntValue(SubOperand.getValue());
2007     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2008   }
2009 };
2010 
2011 /// An action taken when all Matcher predicates succeeded for a parent rule.
2012 ///
2013 /// Typical actions include:
2014 /// * Changing the opcode of an instruction.
2015 /// * Adding an operand to an instruction.
2016 class MatchAction {
2017 public:
2018   virtual ~MatchAction() {}
2019 
2020   /// Emit the MatchTable opcodes to implement the action.
2021   virtual void emitActionOpcodes(MatchTable &Table,
2022                                  RuleMatcher &Rule) const = 0;
2023 };
2024 
2025 /// Generates a comment describing the matched rule being acted upon.
2026 class DebugCommentAction : public MatchAction {
2027 private:
2028   std::string S;
2029 
2030 public:
2031   DebugCommentAction(StringRef S) : S(S) {}
2032 
2033   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2034     Table << MatchTable::Comment(S) << MatchTable::LineBreak;
2035   }
2036 };
2037 
2038 /// Generates code to build an instruction or mutate an existing instruction
2039 /// into the desired instruction when this is possible.
2040 class BuildMIAction : public MatchAction {
2041 private:
2042   unsigned InsnID;
2043   const CodeGenInstruction *I;
2044   const InstructionMatcher *Matched;
2045   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2046 
2047   /// True if the instruction can be built solely by mutating the opcode.
2048   bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2049     if (!Insn)
2050       return false;
2051 
2052     if (OperandRenderers.size() != Insn->getNumOperands())
2053       return false;
2054 
2055     for (const auto &Renderer : enumerate(OperandRenderers)) {
2056       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
2057         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
2058         if (Insn != &OM.getInstructionMatcher() ||
2059             OM.getOperandIndex() != Renderer.index())
2060           return false;
2061       } else
2062         return false;
2063     }
2064 
2065     return true;
2066   }
2067 
2068 public:
2069   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2070       : InsnID(InsnID), I(I), Matched(nullptr) {}
2071 
2072   const CodeGenInstruction *getCGI() const { return I; }
2073 
2074   void chooseInsnToMutate(RuleMatcher &Rule) {
2075     for (const auto *MutateCandidate : Rule.mutatable_insns()) {
2076       if (canMutate(Rule, MutateCandidate)) {
2077         // Take the first one we're offered that we're able to mutate.
2078         Rule.reserveInsnMatcherForMutation(MutateCandidate);
2079         Matched = MutateCandidate;
2080         return;
2081       }
2082     }
2083   }
2084 
2085   template <class Kind, class... Args>
2086   Kind &addRenderer(Args&&... args) {
2087     OperandRenderers.emplace_back(
2088         llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
2089     return *static_cast<Kind *>(OperandRenderers.back().get());
2090   }
2091 
2092   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2093     if (Matched) {
2094       assert(canMutate(Rule, Matched) &&
2095              "Arranged to mutate an insn that isn't mutatable");
2096 
2097       unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
2098       Table << MatchTable::Opcode("GIR_MutateOpcode")
2099             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2100             << MatchTable::Comment("RecycleInsnID")
2101             << MatchTable::IntValue(RecycleInsnID)
2102             << MatchTable::Comment("Opcode")
2103             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2104             << MatchTable::LineBreak;
2105 
2106       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
2107         for (auto Def : I->ImplicitDefs) {
2108           auto Namespace = Def->getValue("Namespace")
2109                                ? Def->getValueAsString("Namespace")
2110                                : "";
2111           Table << MatchTable::Opcode("GIR_AddImplicitDef")
2112                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2113                 << MatchTable::NamedValue(Namespace, Def->getName())
2114                 << MatchTable::LineBreak;
2115         }
2116         for (auto Use : I->ImplicitUses) {
2117           auto Namespace = Use->getValue("Namespace")
2118                                ? Use->getValueAsString("Namespace")
2119                                : "";
2120           Table << MatchTable::Opcode("GIR_AddImplicitUse")
2121                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2122                 << MatchTable::NamedValue(Namespace, Use->getName())
2123                 << MatchTable::LineBreak;
2124         }
2125       }
2126       return;
2127     }
2128 
2129     // TODO: Simple permutation looks like it could be almost as common as
2130     //       mutation due to commutative operations.
2131 
2132     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2133           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2134           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2135           << MatchTable::LineBreak;
2136     for (const auto &Renderer : OperandRenderers)
2137       Renderer->emitRenderOpcodes(Table, Rule);
2138 
2139     if (I->mayLoad || I->mayStore) {
2140       Table << MatchTable::Opcode("GIR_MergeMemOperands")
2141             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2142             << MatchTable::Comment("MergeInsnID's");
2143       // Emit the ID's for all the instructions that are matched by this rule.
2144       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2145       //       some other means of having a memoperand. Also limit this to
2146       //       emitted instructions that expect to have a memoperand too. For
2147       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
2148       //       sign-extend instructions shouldn't put the memoperand on the
2149       //       sign-extend since it has no effect there.
2150       std::vector<unsigned> MergeInsnIDs;
2151       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2152         MergeInsnIDs.push_back(IDMatcherPair.second);
2153       std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
2154       for (const auto &MergeInsnID : MergeInsnIDs)
2155         Table << MatchTable::IntValue(MergeInsnID);
2156       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2157             << MatchTable::LineBreak;
2158     }
2159 
2160     // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2161     //        better for combines. Particularly when there are multiple match
2162     //        roots.
2163     if (InsnID == 0)
2164       Table << MatchTable::Opcode("GIR_EraseFromParent")
2165             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2166             << MatchTable::LineBreak;
2167   }
2168 };
2169 
2170 /// Generates code to constrain the operands of an output instruction to the
2171 /// register classes specified by the definition of that instruction.
2172 class ConstrainOperandsToDefinitionAction : public MatchAction {
2173   unsigned InsnID;
2174 
2175 public:
2176   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
2177 
2178   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2179     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2180           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2181           << MatchTable::LineBreak;
2182   }
2183 };
2184 
2185 /// Generates code to constrain the specified operand of an output instruction
2186 /// to the specified register class.
2187 class ConstrainOperandToRegClassAction : public MatchAction {
2188   unsigned InsnID;
2189   unsigned OpIdx;
2190   const CodeGenRegisterClass &RC;
2191 
2192 public:
2193   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
2194                                    const CodeGenRegisterClass &RC)
2195       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
2196 
2197   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2198     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2199           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2200           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2201           << MatchTable::Comment("RC " + RC.getName())
2202           << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
2203   }
2204 };
2205 
2206 /// Generates code to create a temporary register which can be used to chain
2207 /// instructions together.
2208 class MakeTempRegisterAction : public MatchAction {
2209 private:
2210   LLTCodeGen Ty;
2211   unsigned TempRegID;
2212 
2213 public:
2214   MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2215       : Ty(Ty), TempRegID(TempRegID) {}
2216 
2217   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2218     Table << MatchTable::Opcode("GIR_MakeTempReg")
2219           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2220           << MatchTable::Comment("TypeID")
2221           << MatchTable::NamedValue(Ty.getCxxEnumValue())
2222           << MatchTable::LineBreak;
2223   }
2224 };
2225 
2226 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
2227   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
2228   MutatableInsns.insert(Matchers.back().get());
2229   return *Matchers.back();
2230 }
2231 
2232 void RuleMatcher::addRequiredFeature(Record *Feature) {
2233   RequiredFeatures.push_back(Feature);
2234 }
2235 
2236 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2237   return RequiredFeatures;
2238 }
2239 
2240 // Emplaces an action of the specified Kind at the end of the action list.
2241 //
2242 // Returns a reference to the newly created action.
2243 //
2244 // Like std::vector::emplace_back(), may invalidate all iterators if the new
2245 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
2246 // iterator.
2247 template <class Kind, class... Args>
2248 Kind &RuleMatcher::addAction(Args &&... args) {
2249   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2250   return *static_cast<Kind *>(Actions.back().get());
2251 }
2252 
2253 // Emplaces an action of the specified Kind before the given insertion point.
2254 //
2255 // Returns an iterator pointing at the newly created instruction.
2256 //
2257 // Like std::vector::insert(), may invalidate all iterators if the new size
2258 // exceeds the capacity. Otherwise, only invalidates the iterators from the
2259 // insertion point onwards.
2260 template <class Kind, class... Args>
2261 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2262                                           Args &&... args) {
2263   return Actions.emplace(InsertPt,
2264                          llvm::make_unique<Kind>(std::forward<Args>(args)...));
2265 }
2266 
2267 unsigned
2268 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
2269   unsigned NewInsnVarID = NextInsnVarID++;
2270   InsnVariableIDs[&Matcher] = NewInsnVarID;
2271   return NewInsnVarID;
2272 }
2273 
2274 unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
2275                                     const InstructionMatcher &Matcher,
2276                                     unsigned InsnID, unsigned OpIdx) {
2277   unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
2278   Table << MatchTable::Opcode("GIM_RecordInsn")
2279         << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
2280         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
2281         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2282         << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2283         << MatchTable::LineBreak;
2284   return NewInsnVarID;
2285 }
2286 
2287 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
2288   const auto &I = InsnVariableIDs.find(&InsnMatcher);
2289   if (I != InsnVariableIDs.end())
2290     return I->second;
2291   llvm_unreachable("Matched Insn was not captured in a local variable");
2292 }
2293 
2294 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2295   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2296     DefinedOperands[SymbolicName] = &OM;
2297     return;
2298   }
2299 
2300   // If the operand is already defined, then we must ensure both references in
2301   // the matcher have the exact same node.
2302   OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2303 }
2304 
2305 const InstructionMatcher &
2306 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2307   for (const auto &I : InsnVariableIDs)
2308     if (I.first->getSymbolicName() == SymbolicName)
2309       return *I.first;
2310   llvm_unreachable(
2311       ("Failed to lookup instruction " + SymbolicName).str().c_str());
2312 }
2313 
2314 const OperandMatcher &
2315 RuleMatcher::getOperandMatcher(StringRef Name) const {
2316   const auto &I = DefinedOperands.find(Name);
2317 
2318   if (I == DefinedOperands.end())
2319     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2320 
2321   return *I->second;
2322 }
2323 
2324 /// Emit MatchTable opcodes to check the shape of the match and capture
2325 /// instructions into local variables.
2326 void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
2327   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
2328   unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
2329   (void)InsnVarID;
2330   assert(Matchers.front()->getVarID() == InsnVarID &&
2331          "IDs differ between build and emit");
2332   Matchers.front()->emitCaptureOpcodes(Table, *this);
2333 }
2334 
2335 void RuleMatcher::emit(MatchTable &Table) {
2336   if (Matchers.empty())
2337     llvm_unreachable("Unexpected empty matcher!");
2338 
2339   // The representation supports rules that require multiple roots such as:
2340   //    %ptr(p0) = ...
2341   //    %elt0(s32) = G_LOAD %ptr
2342   //    %1(p0) = G_ADD %ptr, 4
2343   //    %elt1(s32) = G_LOAD p0 %1
2344   // which could be usefully folded into:
2345   //    %ptr(p0) = ...
2346   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2347   // on some targets but we don't need to make use of that yet.
2348   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
2349 
2350   unsigned LabelID = Table.allocateLabelID();
2351   Table << MatchTable::Opcode("GIM_Try", +1)
2352         << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
2353         << MatchTable::LineBreak;
2354 
2355   if (!RequiredFeatures.empty()) {
2356     Table << MatchTable::Opcode("GIM_CheckFeatures")
2357           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2358           << MatchTable::LineBreak;
2359   }
2360 
2361   emitCaptureOpcodes(Table);
2362 
2363   Matchers.front()->emitPredicateOpcodes(Table, *this);
2364 
2365   // We must also check if it's safe to fold the matched instructions.
2366   if (InsnVariableIDs.size() >= 2) {
2367     // Invert the map to create stable ordering (by var names)
2368     SmallVector<unsigned, 2> InsnIDs;
2369     for (const auto &Pair : InsnVariableIDs) {
2370       // Skip the root node since it isn't moving anywhere. Everything else is
2371       // sinking to meet it.
2372       if (Pair.first == Matchers.front().get())
2373         continue;
2374 
2375       InsnIDs.push_back(Pair.second);
2376     }
2377     std::sort(InsnIDs.begin(), InsnIDs.end());
2378 
2379     for (const auto &InsnID : InsnIDs) {
2380       // Reject the difficult cases until we have a more accurate check.
2381       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2382             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2383             << MatchTable::LineBreak;
2384 
2385       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2386       //        account for unsafe cases.
2387       //
2388       //        Example:
2389       //          MI1--> %0 = ...
2390       //                 %1 = ... %0
2391       //          MI0--> %2 = ... %0
2392       //          It's not safe to erase MI1. We currently handle this by not
2393       //          erasing %0 (even when it's dead).
2394       //
2395       //        Example:
2396       //          MI1--> %0 = load volatile @a
2397       //                 %1 = load volatile @a
2398       //          MI0--> %2 = ... %0
2399       //          It's not safe to sink %0's def past %1. We currently handle
2400       //          this by rejecting all loads.
2401       //
2402       //        Example:
2403       //          MI1--> %0 = load @a
2404       //                 %1 = store @a
2405       //          MI0--> %2 = ... %0
2406       //          It's not safe to sink %0's def past %1. We currently handle
2407       //          this by rejecting all loads.
2408       //
2409       //        Example:
2410       //                   G_CONDBR %cond, @BB1
2411       //                 BB0:
2412       //          MI1-->   %0 = load @a
2413       //                   G_BR @BB1
2414       //                 BB1:
2415       //          MI0-->   %2 = ... %0
2416       //          It's not always safe to sink %0 across control flow. In this
2417       //          case it may introduce a memory fault. We currentl handle this
2418       //          by rejecting all loads.
2419     }
2420   }
2421 
2422   for (const auto &MA : Actions)
2423     MA->emitActionOpcodes(Table, *this);
2424 
2425   if (GenerateCoverage)
2426     Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2427           << MatchTable::LineBreak;
2428 
2429   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
2430         << MatchTable::Label(LabelID);
2431 }
2432 
2433 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2434   // Rules involving more match roots have higher priority.
2435   if (Matchers.size() > B.Matchers.size())
2436     return true;
2437   if (Matchers.size() < B.Matchers.size())
2438     return false;
2439 
2440   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2441     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2442       return true;
2443     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2444       return false;
2445   }
2446 
2447   return false;
2448 }
2449 
2450 unsigned RuleMatcher::countRendererFns() const {
2451   return std::accumulate(
2452       Matchers.begin(), Matchers.end(), 0,
2453       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
2454         return A + Matcher->countRendererFns();
2455       });
2456 }
2457 
2458 bool OperandPredicateMatcher::isHigherPriorityThan(
2459     const OperandPredicateMatcher &B) const {
2460   // Generally speaking, an instruction is more important than an Int or a
2461   // LiteralInt because it can cover more nodes but theres an exception to
2462   // this. G_CONSTANT's are less important than either of those two because they
2463   // are more permissive.
2464 
2465   const InstructionOperandMatcher *AOM =
2466       dyn_cast<InstructionOperandMatcher>(this);
2467   const InstructionOperandMatcher *BOM =
2468       dyn_cast<InstructionOperandMatcher>(&B);
2469   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2470   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2471 
2472   if (AOM && BOM) {
2473     // The relative priorities between a G_CONSTANT and any other instruction
2474     // don't actually matter but this code is needed to ensure a strict weak
2475     // ordering. This is particularly important on Windows where the rules will
2476     // be incorrectly sorted without it.
2477     if (AIsConstantInsn != BIsConstantInsn)
2478       return AIsConstantInsn < BIsConstantInsn;
2479     return false;
2480   }
2481 
2482   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2483     return false;
2484   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2485     return true;
2486 
2487   return Kind < B.Kind;
2488 }
2489 
2490 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
2491                                               RuleMatcher &Rule) const {
2492   const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
2493   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
2494   assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getVarID());
2495 
2496   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2497         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2498         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2499         << MatchTable::Comment("OtherMI")
2500         << MatchTable::IntValue(OtherInsnVarID)
2501         << MatchTable::Comment("OtherOpIdx")
2502         << MatchTable::IntValue(OtherOM.getOperandIndex())
2503         << MatchTable::LineBreak;
2504 }
2505 
2506 //===- GlobalISelEmitter class --------------------------------------------===//
2507 
2508 class GlobalISelEmitter {
2509 public:
2510   explicit GlobalISelEmitter(RecordKeeper &RK);
2511   void run(raw_ostream &OS);
2512 
2513 private:
2514   const RecordKeeper &RK;
2515   const CodeGenDAGPatterns CGP;
2516   const CodeGenTarget &Target;
2517   CodeGenRegBank CGRegs;
2518 
2519   /// Keep track of the equivalence between SDNodes and Instruction by mapping
2520   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2521   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
2522   /// This is defined using 'GINodeEquiv' in the target description.
2523   DenseMap<Record *, Record *> NodeEquivs;
2524 
2525   /// Keep track of the equivalence between ComplexPattern's and
2526   /// GIComplexOperandMatcher. Map entries are specified by subclassing
2527   /// GIComplexPatternEquiv.
2528   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2529 
2530   // Map of predicates to their subtarget features.
2531   SubtargetFeatureInfoMap SubtargetFeatures;
2532 
2533   // Rule coverage information.
2534   Optional<CodeGenCoverage> RuleCoverage;
2535 
2536   void gatherNodeEquivs();
2537   Record *findNodeEquiv(Record *N) const;
2538 
2539   Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
2540   Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2541       RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2542       const TreePatternNode *Src, unsigned &TempOpIdx) const;
2543   Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2544                                            unsigned &TempOpIdx) const;
2545   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2546                            const TreePatternNode *SrcChild,
2547                            bool OperandIsAPointer, unsigned OpIdx,
2548                            unsigned &TempOpIdx) const;
2549 
2550   Expected<BuildMIAction &>
2551   createAndImportInstructionRenderer(RuleMatcher &M,
2552                                      const TreePatternNode *Dst);
2553   Expected<action_iterator> createAndImportSubInstructionRenderer(
2554       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
2555       unsigned TempReg);
2556   Expected<action_iterator>
2557   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
2558                             const TreePatternNode *Dst);
2559   void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
2560   Expected<action_iterator>
2561   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
2562                              BuildMIAction &DstMIBuilder,
2563                              const llvm::TreePatternNode *Dst);
2564   Expected<action_iterator>
2565   importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
2566                             BuildMIAction &DstMIBuilder,
2567                             TreePatternNode *DstChild);
2568   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2569                                       DagInit *DefaultOps) const;
2570   Error
2571   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2572                              const std::vector<Record *> &ImplicitDefs) const;
2573 
2574   void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2575                          StringRef Type,
2576                          std::function<bool(const Record *R)> Filter);
2577 
2578   /// Analyze pattern \p P, returning a matcher for it if possible.
2579   /// Otherwise, return an Error explaining why we don't support it.
2580   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
2581 
2582   void declareSubtargetFeature(Record *Predicate);
2583 
2584   TreePatternNode *fixupPatternNode(TreePatternNode *N);
2585   void fixupPatternTrees(TreePattern *P);
2586 
2587   /// Takes a sequence of \p Rules and group them based on the predicates
2588   /// they share. \p StorageGroupMatcher is used as a memory container
2589   /// for the the group that are created as part of this process.
2590   /// The optimization process does not change the relative order of
2591   /// the rules. In particular, we don't try to share predicates if
2592   /// that means reordering the rules (e.g., we won't group R1 and R3
2593   /// in the following example as it would imply reordering R2 and R3
2594   /// => R1 p1, R2 p2, R3 p1).
2595   ///
2596   /// What this optimization does looks like:
2597   /// Output without optimization:
2598   /// \verbatim
2599   /// # R1
2600   ///  # predicate A
2601   ///  # predicate B
2602   ///  ...
2603   /// # R2
2604   ///  # predicate A // <-- effectively this is going to be checked twice.
2605   ///                //     Once in R1 and once in R2.
2606   ///  # predicate C
2607   /// \endverbatim
2608   /// Output with optimization:
2609   /// \verbatim
2610   /// # Group1_2
2611   ///  # predicate A // <-- Check is now shared.
2612   ///  # R1
2613   ///   # predicate B
2614   ///  # R2
2615   ///   # predicate C
2616   /// \endverbatim
2617   std::vector<Matcher *> optimizeRules(
2618       std::vector<RuleMatcher> &Rules,
2619       std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher);
2620 };
2621 
2622 void GlobalISelEmitter::gatherNodeEquivs() {
2623   assert(NodeEquivs.empty());
2624   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
2625     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
2626 
2627   assert(ComplexPatternEquivs.empty());
2628   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2629     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2630     if (!SelDAGEquiv)
2631       continue;
2632     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2633  }
2634 }
2635 
2636 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
2637   return NodeEquivs.lookup(N);
2638 }
2639 
2640 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
2641     : RK(RK), CGP(RK, [&](TreePattern *P) { fixupPatternTrees(P); }),
2642       Target(CGP.getTargetInfo()), CGRegs(RK, Target.getHwModes()) {}
2643 
2644 //===- Emitter ------------------------------------------------------------===//
2645 
2646 Error
2647 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
2648                                         ArrayRef<Predicate> Predicates) {
2649   for (const Predicate &P : Predicates) {
2650     if (!P.Def)
2651       continue;
2652     declareSubtargetFeature(P.Def);
2653     M.addRequiredFeature(P.Def);
2654   }
2655 
2656   return Error::success();
2657 }
2658 
2659 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2660     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2661     const TreePatternNode *Src, unsigned &TempOpIdx) const {
2662   Record *SrcGIEquivOrNull = nullptr;
2663   const CodeGenInstruction *SrcGIOrNull = nullptr;
2664 
2665   // Start with the defined operands (i.e., the results of the root operator).
2666   if (Src->getExtTypes().size() > 1)
2667     return failedImport("Src pattern has multiple results");
2668 
2669   if (Src->isLeaf()) {
2670     Init *SrcInit = Src->getLeafValue();
2671     if (isa<IntInit>(SrcInit)) {
2672       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2673           &Target.getInstruction(RK.getDef("G_CONSTANT")));
2674     } else
2675       return failedImport(
2676           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2677   } else {
2678     SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2679     if (!SrcGIEquivOrNull)
2680       return failedImport("Pattern operator lacks an equivalent Instruction" +
2681                           explainOperator(Src->getOperator()));
2682     SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
2683 
2684     // The operators look good: match the opcode
2685     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
2686   }
2687 
2688   unsigned OpIdx = 0;
2689   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2690     // Results don't have a name unless they are the root node. The caller will
2691     // set the name if appropriate.
2692     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2693     if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2694       return failedImport(toString(std::move(Error)) +
2695                           " for result of Src pattern operator");
2696   }
2697 
2698   for (const auto &Predicate : Src->getPredicateFns()) {
2699     if (Predicate.isAlwaysTrue())
2700       continue;
2701 
2702     if (Predicate.isImmediatePattern()) {
2703       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2704       continue;
2705     }
2706 
2707     // No check required. G_LOAD by itself is a non-extending load.
2708     if (Predicate.isNonExtLoad())
2709       continue;
2710 
2711     // No check required. G_STORE by itself is a non-extending store.
2712     if (Predicate.isNonTruncStore())
2713       continue;
2714 
2715     if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
2716       if (Predicate.getMemoryVT() != nullptr) {
2717         Optional<LLTCodeGen> MemTyOrNone =
2718             MVTToLLT(getValueType(Predicate.getMemoryVT()));
2719 
2720         if (!MemTyOrNone)
2721           return failedImport("MemVT could not be converted to LLT");
2722 
2723         OperandMatcher &OM = InsnMatcher.getOperand(0);
2724         OM.addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2725         continue;
2726       }
2727     }
2728 
2729     if (Predicate.isLoad() || Predicate.isStore()) {
2730       // No check required. A G_LOAD/G_STORE is an unindexed load.
2731       if (Predicate.isUnindexed())
2732         continue;
2733     }
2734 
2735     if (Predicate.isAtomic()) {
2736       if (Predicate.isAtomicOrderingMonotonic()) {
2737         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2738             "Monotonic");
2739         continue;
2740       }
2741       if (Predicate.isAtomicOrderingAcquire()) {
2742         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
2743         continue;
2744       }
2745       if (Predicate.isAtomicOrderingRelease()) {
2746         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
2747         continue;
2748       }
2749       if (Predicate.isAtomicOrderingAcquireRelease()) {
2750         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2751             "AcquireRelease");
2752         continue;
2753       }
2754       if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
2755         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2756             "SequentiallyConsistent");
2757         continue;
2758       }
2759 
2760       if (Predicate.isAtomicOrderingAcquireOrStronger()) {
2761         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2762             "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2763         continue;
2764       }
2765       if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
2766         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2767             "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2768         continue;
2769       }
2770 
2771       if (Predicate.isAtomicOrderingReleaseOrStronger()) {
2772         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2773             "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2774         continue;
2775       }
2776       if (Predicate.isAtomicOrderingWeakerThanRelease()) {
2777         InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2778             "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2779         continue;
2780       }
2781     }
2782 
2783     return failedImport("Src pattern child has predicate (" +
2784                         explainPredicates(Src) + ")");
2785   }
2786   if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2787     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
2788 
2789   if (Src->isLeaf()) {
2790     Init *SrcInit = Src->getLeafValue();
2791     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
2792       OperandMatcher &OM =
2793           InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
2794       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2795     } else
2796       return failedImport(
2797           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2798   } else {
2799     assert(SrcGIOrNull &&
2800            "Expected to have already found an equivalent Instruction");
2801     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2802         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2803       // imm/fpimm still have operands but we don't need to do anything with it
2804       // here since we don't support ImmLeaf predicates yet. However, we still
2805       // need to note the hidden operand to get GIM_CheckNumOperands correct.
2806       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2807       return InsnMatcher;
2808     }
2809 
2810     // Match the used operands (i.e. the children of the operator).
2811     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
2812       TreePatternNode *SrcChild = Src->getChild(i);
2813 
2814       // SelectionDAG allows pointers to be represented with iN since it doesn't
2815       // distinguish between pointers and integers but they are different types in GlobalISel.
2816       // Coerce integers to pointers to address space 0 if the context indicates a pointer.
2817       bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
2818 
2819       // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2820       // following the defs is an intrinsic ID.
2821       if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2822            SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2823           i == 0) {
2824         if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
2825           OperandMatcher &OM =
2826               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
2827           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
2828           continue;
2829         }
2830 
2831         return failedImport("Expected IntInit containing instrinsic ID)");
2832       }
2833 
2834       if (auto Error =
2835               importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2836                                  OpIdx++, TempOpIdx))
2837         return std::move(Error);
2838     }
2839   }
2840 
2841   return InsnMatcher;
2842 }
2843 
2844 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2845     OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2846   const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2847   if (ComplexPattern == ComplexPatternEquivs.end())
2848     return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2849                         ") not mapped to GlobalISel");
2850 
2851   OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2852   TempOpIdx++;
2853   return Error::success();
2854 }
2855 
2856 Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2857                                             InstructionMatcher &InsnMatcher,
2858                                             const TreePatternNode *SrcChild,
2859                                             bool OperandIsAPointer,
2860                                             unsigned OpIdx,
2861                                             unsigned &TempOpIdx) const {
2862   OperandMatcher &OM =
2863       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
2864   if (OM.isSameAsAnotherOperand())
2865     return Error::success();
2866 
2867   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
2868   if (ChildTypes.size() != 1)
2869     return failedImport("Src pattern child has multiple results");
2870 
2871   // Check MBB's before the type check since they are not a known type.
2872   if (!SrcChild->isLeaf()) {
2873     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2874       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2875       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2876         OM.addPredicate<MBBOperandMatcher>();
2877         return Error::success();
2878       }
2879     }
2880   }
2881 
2882   if (auto Error =
2883           OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2884     return failedImport(toString(std::move(Error)) + " for Src operand (" +
2885                         to_string(*SrcChild) + ")");
2886 
2887   // Check for nested instructions.
2888   if (!SrcChild->isLeaf()) {
2889     if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2890       // When a ComplexPattern is used as an operator, it should do the same
2891       // thing as when used as a leaf. However, the children of the operator
2892       // name the sub-operands that make up the complex operand and we must
2893       // prepare to reference them in the renderer too.
2894       unsigned RendererID = TempOpIdx;
2895       if (auto Error = importComplexPatternOperandMatcher(
2896               OM, SrcChild->getOperator(), TempOpIdx))
2897         return Error;
2898 
2899       for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2900         auto *SubOperand = SrcChild->getChild(i);
2901         if (!SubOperand->getName().empty())
2902           Rule.defineComplexSubOperand(SubOperand->getName(),
2903                                        SrcChild->getOperator(), RendererID, i);
2904       }
2905 
2906       return Error::success();
2907     }
2908 
2909     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2910         InsnMatcher.getRuleMatcher(), SrcChild->getName());
2911     if (!MaybeInsnOperand.hasValue()) {
2912       // This isn't strictly true. If the user were to provide exactly the same
2913       // matchers as the original operand then we could allow it. However, it's
2914       // simpler to not permit the redundant specification.
2915       return failedImport("Nested instruction cannot be the same as another operand");
2916     }
2917 
2918     // Map the node to a gMIR instruction.
2919     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
2920     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
2921         Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
2922     if (auto Error = InsnMatcherOrError.takeError())
2923       return Error;
2924 
2925     return Error::success();
2926   }
2927 
2928   if (SrcChild->hasAnyPredicate())
2929     return failedImport("Src pattern child has unsupported predicate");
2930 
2931   // Check for constant immediates.
2932   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
2933     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
2934     return Error::success();
2935   }
2936 
2937   // Check for def's like register classes or ComplexPattern's.
2938   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2939     auto *ChildRec = ChildDefInit->getDef();
2940 
2941     // Check for register classes.
2942     if (ChildRec->isSubClassOf("RegisterClass") ||
2943         ChildRec->isSubClassOf("RegisterOperand")) {
2944       OM.addPredicate<RegisterBankOperandMatcher>(
2945           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
2946       return Error::success();
2947     }
2948 
2949     // Check for ValueType.
2950     if (ChildRec->isSubClassOf("ValueType")) {
2951       // We already added a type check as standard practice so this doesn't need
2952       // to do anything.
2953       return Error::success();
2954     }
2955 
2956     // Check for ComplexPattern's.
2957     if (ChildRec->isSubClassOf("ComplexPattern"))
2958       return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
2959 
2960     if (ChildRec->isSubClassOf("ImmLeaf")) {
2961       return failedImport(
2962           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2963     }
2964 
2965     return failedImport(
2966         "Src pattern child def is an unsupported tablegen class");
2967   }
2968 
2969   return failedImport("Src pattern child is an unsupported kind");
2970 }
2971 
2972 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
2973     action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
2974     TreePatternNode *DstChild) {
2975   if (DstChild->getTransformFn() != nullptr) {
2976     return failedImport("Dst pattern child has transform fn " +
2977                         DstChild->getTransformFn()->getName());
2978   }
2979 
2980   const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
2981   if (SubOperand.hasValue()) {
2982     DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2983         *std::get<0>(*SubOperand), DstChild->getName(),
2984         std::get<1>(*SubOperand), std::get<2>(*SubOperand));
2985     return InsertPt;
2986   }
2987 
2988   if (!DstChild->isLeaf()) {
2989     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2990     // inline, but in MI it's just another operand.
2991     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2992       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2993       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2994         DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
2995         return InsertPt;
2996       }
2997     }
2998 
2999     // Similarly, imm is an operator in TreePatternNode's view but must be
3000     // rendered as operands.
3001     // FIXME: The target should be able to choose sign-extended when appropriate
3002     //        (e.g. on Mips).
3003     if (DstChild->getOperator()->getName() == "imm") {
3004       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
3005       return InsertPt;
3006     } else if (DstChild->getOperator()->getName() == "fpimm") {
3007       DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
3008           DstChild->getName());
3009       return InsertPt;
3010     }
3011 
3012     if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3013       ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3014       if (ChildTypes.size() != 1)
3015         return failedImport("Dst pattern child has multiple results");
3016 
3017       Optional<LLTCodeGen> OpTyOrNone = None;
3018       if (ChildTypes.front().isMachineValueType())
3019         OpTyOrNone =
3020             MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3021       if (!OpTyOrNone)
3022         return failedImport("Dst operand has an unsupported type");
3023 
3024       unsigned TempRegID = Rule.allocateTempRegID();
3025       InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3026           InsertPt, OpTyOrNone.getValue(), TempRegID);
3027       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3028 
3029       auto InsertPtOrError = createAndImportSubInstructionRenderer(
3030           ++InsertPt, Rule, DstChild, TempRegID);
3031       if (auto Error = InsertPtOrError.takeError())
3032         return std::move(Error);
3033       return InsertPtOrError.get();
3034     }
3035 
3036     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
3037   }
3038 
3039   // It could be a specific immediate in which case we should just check for
3040   // that immediate.
3041   if (const IntInit *ChildIntInit =
3042           dyn_cast<IntInit>(DstChild->getLeafValue())) {
3043     DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3044     return InsertPt;
3045   }
3046 
3047   // Otherwise, we're looking for a bog-standard RegisterClass operand.
3048   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
3049     auto *ChildRec = ChildDefInit->getDef();
3050 
3051     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3052     if (ChildTypes.size() != 1)
3053       return failedImport("Dst pattern child has multiple results");
3054 
3055     Optional<LLTCodeGen> OpTyOrNone = None;
3056     if (ChildTypes.front().isMachineValueType())
3057       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3058     if (!OpTyOrNone)
3059       return failedImport("Dst operand has an unsupported type");
3060 
3061     if (ChildRec->isSubClassOf("Register")) {
3062       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
3063       return InsertPt;
3064     }
3065 
3066     if (ChildRec->isSubClassOf("RegisterClass") ||
3067         ChildRec->isSubClassOf("RegisterOperand") ||
3068         ChildRec->isSubClassOf("ValueType")) {
3069       if (ChildRec->isSubClassOf("RegisterOperand") &&
3070           !ChildRec->isValueUnset("GIZeroRegister")) {
3071         DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
3072             DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
3073         return InsertPt;
3074       }
3075 
3076       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
3077       return InsertPt;
3078     }
3079 
3080     if (ChildRec->isSubClassOf("ComplexPattern")) {
3081       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3082       if (ComplexPattern == ComplexPatternEquivs.end())
3083         return failedImport(
3084             "SelectionDAG ComplexPattern not mapped to GlobalISel");
3085 
3086       const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
3087       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
3088           *ComplexPattern->second, DstChild->getName(),
3089           OM.getAllocatedTemporariesBaseID());
3090       return InsertPt;
3091     }
3092 
3093     if (ChildRec->isSubClassOf("SDNodeXForm"))
3094       return failedImport("Dst pattern child def is an unsupported tablegen "
3095                           "class (SDNodeXForm)");
3096 
3097     return failedImport(
3098         "Dst pattern child def is an unsupported tablegen class");
3099   }
3100 
3101   return failedImport("Dst pattern child is an unsupported kind");
3102 }
3103 
3104 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
3105     RuleMatcher &M, const TreePatternNode *Dst) {
3106   auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3107   if (auto Error = InsertPtOrError.takeError())
3108     return std::move(Error);
3109 
3110   action_iterator InsertPt = InsertPtOrError.get();
3111   BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
3112 
3113   importExplicitDefRenderers(DstMIBuilder);
3114 
3115   if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3116                        .takeError())
3117     return std::move(Error);
3118 
3119   return DstMIBuilder;
3120 }
3121 
3122 Expected<action_iterator>
3123 GlobalISelEmitter::createAndImportSubInstructionRenderer(
3124     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3125     unsigned TempRegID) {
3126   auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3127 
3128   // TODO: Assert there's exactly one result.
3129 
3130   if (auto Error = InsertPtOrError.takeError())
3131     return std::move(Error);
3132   InsertPt = InsertPtOrError.get();
3133 
3134   BuildMIAction &DstMIBuilder =
3135       *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3136 
3137   // Assign the result to TempReg.
3138   DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3139 
3140   InsertPtOrError = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst);
3141   if (auto Error = InsertPtOrError.takeError())
3142     return std::move(Error);
3143 
3144   return InsertPtOrError.get();
3145 }
3146 
3147 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
3148     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
3149   Record *DstOp = Dst->getOperator();
3150   if (!DstOp->isSubClassOf("Instruction")) {
3151     if (DstOp->isSubClassOf("ValueType"))
3152       return failedImport(
3153           "Pattern operator isn't an instruction (it's a ValueType)");
3154     return failedImport("Pattern operator isn't an instruction");
3155   }
3156   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
3157 
3158   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
3159   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
3160   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
3161     DstI = &Target.getInstruction(RK.getDef("COPY"));
3162   else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
3163     DstI = &Target.getInstruction(RK.getDef("COPY"));
3164   else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3165     return failedImport("Unable to emit REG_SEQUENCE");
3166 
3167   return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3168                                        DstI);
3169 }
3170 
3171 void GlobalISelEmitter::importExplicitDefRenderers(
3172     BuildMIAction &DstMIBuilder) {
3173   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3174   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3175     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
3176     DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3177   }
3178 }
3179 
3180 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3181     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
3182     const llvm::TreePatternNode *Dst) {
3183   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3184   CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
3185 
3186   // EXTRACT_SUBREG needs to use a subregister COPY.
3187   if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
3188     if (!Dst->getChild(0)->isLeaf())
3189       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3190 
3191     if (DefInit *SubRegInit =
3192             dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
3193       Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3194       if (!RCDef)
3195         return failedImport("EXTRACT_SUBREG child #0 could not "
3196                             "be coerced to a register class");
3197 
3198       CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
3199       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3200 
3201       const auto &SrcRCDstRCPair =
3202           RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3203       if (SrcRCDstRCPair.hasValue()) {
3204         assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3205         if (SrcRCDstRCPair->first != RC)
3206           return failedImport("EXTRACT_SUBREG requires an additional COPY");
3207       }
3208 
3209       DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
3210                                                    SubIdx);
3211       return InsertPt;
3212     }
3213 
3214     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3215   }
3216 
3217   // Render the explicit uses.
3218   unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
3219   unsigned ExpectedDstINumUses = Dst->getNumChildren();
3220   if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3221     DstINumUses--; // Ignore the class constraint.
3222     ExpectedDstINumUses--;
3223   }
3224 
3225   unsigned Child = 0;
3226   unsigned NumDefaultOps = 0;
3227   for (unsigned I = 0; I != DstINumUses; ++I) {
3228     const CGIOperandList::OperandInfo &DstIOperand =
3229         DstI->Operands[DstI->Operands.NumDefs + I];
3230 
3231     // If the operand has default values, introduce them now.
3232     // FIXME: Until we have a decent test case that dictates we should do
3233     // otherwise, we're going to assume that operands with default values cannot
3234     // be specified in the patterns. Therefore, adding them will not cause us to
3235     // end up with too many rendered operands.
3236     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
3237       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
3238       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3239         return std::move(Error);
3240       ++NumDefaultOps;
3241       continue;
3242     }
3243 
3244     auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
3245                                                      Dst->getChild(Child));
3246     if (auto Error = InsertPtOrError.takeError())
3247       return std::move(Error);
3248     InsertPt = InsertPtOrError.get();
3249     ++Child;
3250   }
3251 
3252   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
3253     return failedImport("Expected " + llvm::to_string(DstINumUses) +
3254                         " used operands but found " +
3255                         llvm::to_string(ExpectedDstINumUses) +
3256                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
3257                         " default ones");
3258 
3259   return InsertPt;
3260 }
3261 
3262 Error GlobalISelEmitter::importDefaultOperandRenderers(
3263     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
3264   for (const auto *DefaultOp : DefaultOps->getArgs()) {
3265     // Look through ValueType operators.
3266     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3267       if (const DefInit *DefaultDagOperator =
3268               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3269         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3270           DefaultOp = DefaultDagOp->getArg(0);
3271       }
3272     }
3273 
3274     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
3275       DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
3276       continue;
3277     }
3278 
3279     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
3280       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
3281       continue;
3282     }
3283 
3284     return failedImport("Could not add default op");
3285   }
3286 
3287   return Error::success();
3288 }
3289 
3290 Error GlobalISelEmitter::importImplicitDefRenderers(
3291     BuildMIAction &DstMIBuilder,
3292     const std::vector<Record *> &ImplicitDefs) const {
3293   if (!ImplicitDefs.empty())
3294     return failedImport("Pattern defines a physical register");
3295   return Error::success();
3296 }
3297 
3298 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
3299   // Keep track of the matchers and actions to emit.
3300   RuleMatcher M(P.getSrcRecord()->getLoc());
3301   M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3302                                   "  =>  " +
3303                                   llvm::to_string(*P.getDstPattern()));
3304 
3305   if (auto Error = importRulePredicates(M, P.getPredicates()))
3306     return std::move(Error);
3307 
3308   // Next, analyze the pattern operators.
3309   TreePatternNode *Src = P.getSrcPattern();
3310   TreePatternNode *Dst = P.getDstPattern();
3311 
3312   // If the root of either pattern isn't a simple operator, ignore it.
3313   if (auto Err = isTrivialOperatorNode(Dst))
3314     return failedImport("Dst pattern root isn't a trivial operator (" +
3315                         toString(std::move(Err)) + ")");
3316   if (auto Err = isTrivialOperatorNode(Src))
3317     return failedImport("Src pattern root isn't a trivial operator (" +
3318                         toString(std::move(Err)) + ")");
3319 
3320   // The different predicates and matchers created during
3321   // addInstructionMatcher use the RuleMatcher M to set up their
3322   // instruction ID (InsnVarID) that are going to be used when
3323   // M is going to be emitted.
3324   // However, the code doing the emission still relies on the IDs
3325   // returned during that process by the RuleMatcher when issuing
3326   // the recordInsn opcodes.
3327   // Because of that:
3328   // 1. The order in which we created the predicates
3329   //    and such must be the same as the order in which we emit them,
3330   //    and
3331   // 2. We need to reset the generation of the IDs in M somewhere between
3332   //    addInstructionMatcher and emit
3333   //
3334   // FIXME: Long term, we don't want to have to rely on this implicit
3335   // naming being the same. One possible solution would be to have
3336   // explicit operator for operation capture and reference those.
3337   // The plus side is that it would expose opportunities to share
3338   // the capture accross rules. The downside is that it would
3339   // introduce a dependency between predicates (captures must happen
3340   // before their first use.)
3341   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
3342   unsigned TempOpIdx = 0;
3343   auto InsnMatcherOrError =
3344       createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
3345   // Reset the ID generation so that the emitted IDs match the ones
3346   // in the InstructionMatcher and such.
3347   M.clearImplicitMap();
3348   if (auto Error = InsnMatcherOrError.takeError())
3349     return std::move(Error);
3350   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3351 
3352   if (Dst->isLeaf()) {
3353     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
3354 
3355     const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3356     if (RCDef) {
3357       // We need to replace the def and all its uses with the specified
3358       // operand. However, we must also insert COPY's wherever needed.
3359       // For now, emit a copy and let the register allocator clean up.
3360       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3361       const auto &DstIOperand = DstI.Operands[0];
3362 
3363       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3364       OM0.setSymbolicName(DstIOperand.Name);
3365       M.defineOperand(OM0.getSymbolicName(), OM0);
3366       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3367 
3368       auto &DstMIBuilder =
3369           M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3370       DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3371       DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
3372       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3373 
3374       // We're done with this pattern!  It's eligible for GISel emission; return
3375       // it.
3376       ++NumPatternImported;
3377       return std::move(M);
3378     }
3379 
3380     return failedImport("Dst pattern root isn't a known leaf");
3381   }
3382 
3383   // Start with the defined operands (i.e., the results of the root operator).
3384   Record *DstOp = Dst->getOperator();
3385   if (!DstOp->isSubClassOf("Instruction"))
3386     return failedImport("Pattern operator isn't an instruction");
3387 
3388   auto &DstI = Target.getInstruction(DstOp);
3389   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
3390     return failedImport("Src pattern results and dst MI defs are different (" +
3391                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
3392                         to_string(DstI.Operands.NumDefs) + " def(s))");
3393 
3394   // The root of the match also has constraints on the register bank so that it
3395   // matches the result instruction.
3396   unsigned OpIdx = 0;
3397   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3398     (void)VTy;
3399 
3400     const auto &DstIOperand = DstI.Operands[OpIdx];
3401     Record *DstIOpRec = DstIOperand.Rec;
3402     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3403       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3404 
3405       if (DstIOpRec == nullptr)
3406         return failedImport(
3407             "COPY_TO_REGCLASS operand #1 isn't a register class");
3408     } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3409       if (!Dst->getChild(0)->isLeaf())
3410         return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3411 
3412       // We can assume that a subregister is in the same bank as it's super
3413       // register.
3414       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3415 
3416       if (DstIOpRec == nullptr)
3417         return failedImport(
3418             "EXTRACT_SUBREG operand #0 isn't a register class");
3419     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
3420       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
3421     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
3422       return failedImport("Dst MI def isn't a register class" +
3423                           to_string(*Dst));
3424 
3425     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3426     OM.setSymbolicName(DstIOperand.Name);
3427     M.defineOperand(OM.getSymbolicName(), OM);
3428     OM.addPredicate<RegisterBankOperandMatcher>(
3429         Target.getRegisterClass(DstIOpRec));
3430     ++OpIdx;
3431   }
3432 
3433   auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
3434   if (auto Error = DstMIBuilderOrError.takeError())
3435     return std::move(Error);
3436   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
3437 
3438   // Render the implicit defs.
3439   // These are only added to the root of the result.
3440   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
3441     return std::move(Error);
3442 
3443   DstMIBuilder.chooseInsnToMutate(M);
3444 
3445   // Constrain the registers to classes. This is normally derived from the
3446   // emitted instruction but a few instructions require special handling.
3447   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3448     // COPY_TO_REGCLASS does not provide operand constraints itself but the
3449     // result is constrained to the class given by the second child.
3450     Record *DstIOpRec =
3451         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3452 
3453     if (DstIOpRec == nullptr)
3454       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3455 
3456     M.addAction<ConstrainOperandToRegClassAction>(
3457         0, 0, Target.getRegisterClass(DstIOpRec));
3458 
3459     // We're done with this pattern!  It's eligible for GISel emission; return
3460     // it.
3461     ++NumPatternImported;
3462     return std::move(M);
3463   }
3464 
3465   if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3466     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
3467     // instructions, the result register class is controlled by the
3468     // subregisters of the operand. As a result, we must constrain the result
3469     // class rather than check that it's already the right one.
3470     if (!Dst->getChild(0)->isLeaf())
3471       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3472 
3473     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
3474     if (!SubRegInit)
3475       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3476 
3477     // Constrain the result to the same register bank as the operand.
3478     Record *DstIOpRec =
3479         getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3480 
3481     if (DstIOpRec == nullptr)
3482       return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
3483 
3484     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3485     CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
3486 
3487     // It would be nice to leave this constraint implicit but we're required
3488     // to pick a register class so constrain the result to a register class
3489     // that can hold the correct MVT.
3490     //
3491     // FIXME: This may introduce an extra copy if the chosen class doesn't
3492     //        actually contain the subregisters.
3493     assert(Src->getExtTypes().size() == 1 &&
3494              "Expected Src of EXTRACT_SUBREG to have one result type");
3495 
3496     const auto &SrcRCDstRCPair =
3497         SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3498     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3499     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
3500     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
3501 
3502     // We're done with this pattern!  It's eligible for GISel emission; return
3503     // it.
3504     ++NumPatternImported;
3505     return std::move(M);
3506   }
3507 
3508   M.addAction<ConstrainOperandsToDefinitionAction>(0);
3509 
3510   // We're done with this pattern!  It's eligible for GISel emission; return it.
3511   ++NumPatternImported;
3512   return std::move(M);
3513 }
3514 
3515 // Emit imm predicate table and an enum to reference them with.
3516 // The 'Predicate_' part of the name is redundant but eliminating it is more
3517 // trouble than it's worth.
3518 void GlobalISelEmitter::emitImmPredicates(
3519     raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
3520     std::function<bool(const Record *R)> Filter) {
3521   std::vector<const Record *> MatchedRecords;
3522   const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
3523   std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
3524                [&](Record *Record) {
3525                  return !Record->getValueAsString("ImmediateCode").empty() &&
3526                         Filter(Record);
3527                });
3528 
3529   if (!MatchedRecords.empty()) {
3530     OS << "// PatFrag predicates.\n"
3531        << "enum {\n";
3532     std::string EnumeratorSeparator =
3533         (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
3534     for (const auto *Record : MatchedRecords) {
3535       OS << "  GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
3536          << EnumeratorSeparator;
3537       EnumeratorSeparator = ",\n";
3538     }
3539     OS << "};\n";
3540   }
3541 
3542   for (const auto *Record : MatchedRecords)
3543     OS << "static bool Predicate_" << Record->getName() << "(" << Type
3544        << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
3545 
3546   OS << "static InstructionSelector::" << TypeIdentifier
3547      << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
3548      << "  nullptr,\n";
3549   for (const auto *Record : MatchedRecords)
3550     OS << "  Predicate_" << Record->getName() << ",\n";
3551   OS << "};\n";
3552 }
3553 
3554 std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
3555     std::vector<RuleMatcher> &Rules,
3556     std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher) {
3557   std::vector<Matcher *> OptRules;
3558   // Start with a stupid grouping for now.
3559   std::unique_ptr<GroupMatcher> CurrentGroup = make_unique<GroupMatcher>();
3560   assert(CurrentGroup->conditions_empty());
3561   unsigned NbGroup = 0;
3562   for (RuleMatcher &Rule : Rules) {
3563     std::unique_ptr<PredicateMatcher> Predicate = Rule.forgetFirstCondition();
3564     if (!CurrentGroup->conditions_empty() &&
3565         !CurrentGroup->lastConditionMatches(*Predicate)) {
3566       // Start a new group.
3567       ++NbGroup;
3568       OptRules.push_back(CurrentGroup.get());
3569       StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3570       CurrentGroup = make_unique<GroupMatcher>();
3571       assert(CurrentGroup->conditions_empty());
3572     }
3573     if (CurrentGroup->conditions_empty())
3574       CurrentGroup->addCondition(std::move(Predicate));
3575     CurrentGroup->addRule(Rule);
3576   }
3577   if (!CurrentGroup->conditions_empty()) {
3578     ++NbGroup;
3579     OptRules.push_back(CurrentGroup.get());
3580     StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3581   }
3582   DEBUG(dbgs() << "NbGroup: " << NbGroup << "\n");
3583   return OptRules;
3584 }
3585 
3586 void GlobalISelEmitter::run(raw_ostream &OS) {
3587   if (!UseCoverageFile.empty()) {
3588     RuleCoverage = CodeGenCoverage();
3589     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
3590     if (!RuleCoverageBufOrErr) {
3591       PrintWarning(SMLoc(), "Missing rule coverage data");
3592       RuleCoverage = None;
3593     } else {
3594       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
3595         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
3596         RuleCoverage = None;
3597       }
3598     }
3599   }
3600 
3601   // Track the GINodeEquiv definitions.
3602   gatherNodeEquivs();
3603 
3604   emitSourceFileHeader(("Global Instruction Selector for the " +
3605                        Target.getName() + " target").str(), OS);
3606   std::vector<RuleMatcher> Rules;
3607   // Look through the SelectionDAG patterns we found, possibly emitting some.
3608   for (const PatternToMatch &Pat : CGP.ptms()) {
3609     ++NumPatternTotal;
3610 
3611     auto MatcherOrErr = runOnPattern(Pat);
3612 
3613     // The pattern analysis can fail, indicating an unsupported pattern.
3614     // Report that if we've been asked to do so.
3615     if (auto Err = MatcherOrErr.takeError()) {
3616       if (WarnOnSkippedPatterns) {
3617         PrintWarning(Pat.getSrcRecord()->getLoc(),
3618                      "Skipped pattern: " + toString(std::move(Err)));
3619       } else {
3620         consumeError(std::move(Err));
3621       }
3622       ++NumPatternImportsSkipped;
3623       continue;
3624     }
3625 
3626     if (RuleCoverage) {
3627       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
3628         ++NumPatternsTested;
3629       else
3630         PrintWarning(Pat.getSrcRecord()->getLoc(),
3631                      "Pattern is not covered by a test");
3632     }
3633     Rules.push_back(std::move(MatcherOrErr.get()));
3634   }
3635 
3636   std::vector<Record *> ComplexPredicates =
3637       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
3638   std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
3639             [](const Record *A, const Record *B) {
3640               if (A->getName() < B->getName())
3641                 return true;
3642               return false;
3643             });
3644   unsigned MaxTemporaries = 0;
3645   for (const auto &Rule : Rules)
3646     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
3647 
3648   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3649      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3650      << ";\n"
3651      << "using PredicateBitset = "
3652         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3653      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3654 
3655   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3656      << "  mutable MatcherState State;\n"
3657      << "  typedef "
3658         "ComplexRendererFns("
3659      << Target.getName()
3660      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
3661      << "  const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
3662         "MatcherInfo;\n"
3663      << "  static " << Target.getName()
3664      << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
3665      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
3666 
3667   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3668      << ", State(" << MaxTemporaries << "),\n"
3669      << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
3670         "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n"
3671      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
3672 
3673   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3674   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3675                                                            OS);
3676 
3677   // Separate subtarget features by how often they must be recomputed.
3678   SubtargetFeatureInfoMap ModuleFeatures;
3679   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3680                std::inserter(ModuleFeatures, ModuleFeatures.end()),
3681                [](const SubtargetFeatureInfoMap::value_type &X) {
3682                  return !X.second.mustRecomputePerFunction();
3683                });
3684   SubtargetFeatureInfoMap FunctionFeatures;
3685   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3686                std::inserter(FunctionFeatures, FunctionFeatures.end()),
3687                [](const SubtargetFeatureInfoMap::value_type &X) {
3688                  return X.second.mustRecomputePerFunction();
3689                });
3690 
3691   SubtargetFeatureInfo::emitComputeAvailableFeatures(
3692       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3693       ModuleFeatures, OS);
3694   SubtargetFeatureInfo::emitComputeAvailableFeatures(
3695       Target.getName(), "InstructionSelector",
3696       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3697       "const MachineFunction *MF");
3698 
3699   // Emit a table containing the LLT objects needed by the matcher and an enum
3700   // for the matcher to reference them with.
3701   std::vector<LLTCodeGen> TypeObjects;
3702   for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3703     TypeObjects.push_back(Ty);
3704   std::sort(TypeObjects.begin(), TypeObjects.end());
3705   OS << "// LLT Objects.\n"
3706      << "enum {\n";
3707   for (const auto &TypeObject : TypeObjects) {
3708     OS << "  ";
3709     TypeObject.emitCxxEnumValue(OS);
3710     OS << ",\n";
3711   }
3712   OS << "};\n"
3713      << "const static LLT TypeObjects[] = {\n";
3714   for (const auto &TypeObject : TypeObjects) {
3715     OS << "  ";
3716     TypeObject.emitCxxConstructorCall(OS);
3717     OS << ",\n";
3718   }
3719   OS << "};\n\n";
3720 
3721   // Emit a table containing the PredicateBitsets objects needed by the matcher
3722   // and an enum for the matcher to reference them with.
3723   std::vector<std::vector<Record *>> FeatureBitsets;
3724   for (auto &Rule : Rules)
3725     FeatureBitsets.push_back(Rule.getRequiredFeatures());
3726   std::sort(
3727       FeatureBitsets.begin(), FeatureBitsets.end(),
3728       [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3729         if (A.size() < B.size())
3730           return true;
3731         if (A.size() > B.size())
3732           return false;
3733         for (const auto &Pair : zip(A, B)) {
3734           if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3735             return true;
3736           if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3737             return false;
3738         }
3739         return false;
3740       });
3741   FeatureBitsets.erase(
3742       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3743       FeatureBitsets.end());
3744   OS << "// Feature bitsets.\n"
3745      << "enum {\n"
3746      << "  GIFBS_Invalid,\n";
3747   for (const auto &FeatureBitset : FeatureBitsets) {
3748     if (FeatureBitset.empty())
3749       continue;
3750     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3751   }
3752   OS << "};\n"
3753      << "const static PredicateBitset FeatureBitsets[] {\n"
3754      << "  {}, // GIFBS_Invalid\n";
3755   for (const auto &FeatureBitset : FeatureBitsets) {
3756     if (FeatureBitset.empty())
3757       continue;
3758     OS << "  {";
3759     for (const auto &Feature : FeatureBitset) {
3760       const auto &I = SubtargetFeatures.find(Feature);
3761       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3762       OS << I->second.getEnumBitName() << ", ";
3763     }
3764     OS << "},\n";
3765   }
3766   OS << "};\n\n";
3767 
3768   // Emit complex predicate table and an enum to reference them with.
3769   OS << "// ComplexPattern predicates.\n"
3770      << "enum {\n"
3771      << "  GICP_Invalid,\n";
3772   for (const auto &Record : ComplexPredicates)
3773     OS << "  GICP_" << Record->getName() << ",\n";
3774   OS << "};\n"
3775      << "// See constructor for table contents\n\n";
3776 
3777   emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
3778     bool Unset;
3779     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3780            !R->getValueAsBit("IsAPInt");
3781   });
3782   emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3783     bool Unset;
3784     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3785   });
3786   emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3787     return R->getValueAsBit("IsAPInt");
3788   });
3789   OS << "\n";
3790 
3791   OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3792      << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3793      << "  nullptr, // GICP_Invalid\n";
3794   for (const auto &Record : ComplexPredicates)
3795     OS << "  &" << Target.getName()
3796        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3797        << ", // " << Record->getName() << "\n";
3798   OS << "};\n\n";
3799 
3800   OS << "bool " << Target.getName()
3801      << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
3802         "&CoverageInfo) const {\n"
3803      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
3804      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
3805      << "  // FIXME: This should be computed on a per-function basis rather "
3806         "than per-insn.\n"
3807      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3808         "&MF);\n"
3809      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3810      << "  NewMIVector OutMIs;\n"
3811      << "  State.MIs.clear();\n"
3812      << "  State.MIs.push_back(&I);\n\n";
3813 
3814   std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
3815                                                    const RuleMatcher &B) {
3816     if (A.isHigherPriorityThan(B)) {
3817       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3818                                            "and less important at "
3819                                            "the same time");
3820       return true;
3821     }
3822     return false;
3823   });
3824   std::vector<std::unique_ptr<GroupMatcher>> StorageGroupMatcher;
3825 
3826   std::vector<Matcher *> OptRules;
3827   if (OptimizeMatchTable)
3828     OptRules = optimizeRules(Rules, StorageGroupMatcher);
3829   else
3830     for (Matcher &Rule : Rules)
3831       OptRules.push_back(&Rule);
3832 
3833   MatchTable Table(0);
3834   for (Matcher *Rule : OptRules) {
3835     Rule->emit(Table);
3836     ++NumPatternEmitted;
3837   }
3838   Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3839   Table.emitDeclaration(OS);
3840   OS << "  if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
3841   Table.emitUse(OS);
3842   OS << ", TII, MRI, TRI, RBI, AvailableFeatures, CoverageInfo)) {\n"
3843      << "    return true;\n"
3844      << "  }\n\n";
3845 
3846   OS << "  return false;\n"
3847      << "}\n"
3848      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
3849 
3850   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3851      << "PredicateBitset AvailableModuleFeatures;\n"
3852      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3853      << "PredicateBitset getAvailableFeatures() const {\n"
3854      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3855      << "}\n"
3856      << "PredicateBitset\n"
3857      << "computeAvailableModuleFeatures(const " << Target.getName()
3858      << "Subtarget *Subtarget) const;\n"
3859      << "PredicateBitset\n"
3860      << "computeAvailableFunctionFeatures(const " << Target.getName()
3861      << "Subtarget *Subtarget,\n"
3862      << "                                 const MachineFunction *MF) const;\n"
3863      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3864 
3865   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3866      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
3867      << "AvailableFunctionFeatures()\n"
3868      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
3869 }
3870 
3871 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
3872   if (SubtargetFeatures.count(Predicate) == 0)
3873     SubtargetFeatures.emplace(
3874         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
3875 }
3876 
3877 TreePatternNode *GlobalISelEmitter::fixupPatternNode(TreePatternNode *N) {
3878   if (!N->isLeaf()) {
3879     for (unsigned I = 0, E = N->getNumChildren(); I < E; ++I) {
3880       TreePatternNode *OrigChild = N->getChild(I);
3881       TreePatternNode *NewChild = fixupPatternNode(OrigChild);
3882       if (OrigChild != NewChild)
3883         N->setChild(I, NewChild);
3884     }
3885 
3886     if (N->getOperator()->getName() == "ld") {
3887       // If it's a signext-load we need to adapt the pattern slightly. We need
3888       // to split the node into (sext (ld ...)), remove the <<signext>> predicate,
3889       // and then apply the <<signextTY>> predicate by updating the result type
3890       // of the load.
3891       //
3892       // For example:
3893       //   (ld:[i32] [iPTR])<<unindexed>><<signext>><<signexti16>>
3894       // must be transformed into:
3895       //   (sext:[i32] (ld:[i16] [iPTR])<<unindexed>>)
3896       //
3897       // Likewise for zeroext-load and anyext-load.
3898 
3899       std::vector<TreePredicateFn> Predicates;
3900       bool IsSignExtLoad = false;
3901       bool IsZeroExtLoad = false;
3902       bool IsAnyExtLoad = false;
3903       Record *MemVT = nullptr;
3904       for (const auto &P : N->getPredicateFns()) {
3905         if (P.isLoad() && P.isSignExtLoad()) {
3906           IsSignExtLoad = true;
3907           continue;
3908         }
3909         if (P.isLoad() && P.isZeroExtLoad()) {
3910           IsZeroExtLoad = true;
3911           continue;
3912         }
3913         if (P.isLoad() && P.isAnyExtLoad()) {
3914           IsAnyExtLoad = true;
3915           continue;
3916         }
3917         if (P.isLoad() && P.getMemoryVT()) {
3918           MemVT = P.getMemoryVT();
3919           continue;
3920         }
3921         Predicates.push_back(P);
3922       }
3923 
3924       if ((IsSignExtLoad || IsZeroExtLoad || IsAnyExtLoad) && MemVT) {
3925         assert((IsSignExtLoad + IsZeroExtLoad + IsAnyExtLoad) == 1 &&
3926                "IsSignExtLoad, IsZeroExtLoad, IsAnyExtLoad are mutually exclusive");
3927         TreePatternNode *Ext = new TreePatternNode(
3928             RK.getDef(IsSignExtLoad ? "sext"
3929                                     : IsZeroExtLoad ? "zext" : "anyext"),
3930             {N}, 1);
3931         Ext->setType(0, N->getType(0));
3932         N->clearPredicateFns();
3933         N->setPredicateFns(Predicates);
3934         N->setType(0, getValueType(MemVT));
3935         return Ext;
3936       }
3937     }
3938   }
3939 
3940   return N;
3941 }
3942 
3943 void GlobalISelEmitter::fixupPatternTrees(TreePattern *P) {
3944   for (unsigned I = 0, E = P->getNumTrees(); I < E; ++I) {
3945     TreePatternNode *OrigTree = P->getTree(I);
3946     TreePatternNode *NewTree = fixupPatternNode(OrigTree);
3947     if (OrigTree != NewTree)
3948       P->setTree(I, NewTree);
3949   }
3950 }
3951 
3952 std::unique_ptr<PredicateMatcher> RuleMatcher::forgetFirstCondition() {
3953   assert(!insnmatchers_empty() &&
3954          "Trying to forget something that does not exist");
3955 
3956   InstructionMatcher &Matcher = insnmatchers_front();
3957   std::unique_ptr<PredicateMatcher> Condition;
3958   if (!Matcher.predicates_empty())
3959     Condition = Matcher.predicates_pop_front();
3960   if (!Condition) {
3961     // If there is no more predicate on the instruction itself, look at its
3962     // operands.
3963     assert(!Matcher.operands_empty() &&
3964            "Empty instruction should have been discarded");
3965     OperandMatcher &OpMatcher = **Matcher.operands_begin();
3966     assert(!OpMatcher.predicates_empty() && "no operand constraint");
3967     Condition = OpMatcher.predicates_pop_front();
3968     // If this operand is free of constraints, rip it off.
3969     if (OpMatcher.predicates_empty())
3970       Matcher.pop_front();
3971   }
3972   // Rip the instruction off when it is empty.
3973   if (Matcher.operands_empty() && Matcher.predicates_empty())
3974     insnmatchers_pop_front();
3975   return Condition;
3976 }
3977 
3978 bool GroupMatcher::lastConditionMatches(
3979     const PredicateMatcher &Predicate) const {
3980   const auto &LastCondition = conditions_back();
3981   return Predicate.isIdentical(*LastCondition);
3982 }
3983 
3984 void GroupMatcher::emit(MatchTable &Table) {
3985   unsigned LabelID = Table.allocateLabelID();
3986   if (!conditions_empty()) {
3987     Table << MatchTable::Opcode("GIM_Try", +1)
3988           << MatchTable::Comment("On fail goto")
3989           << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
3990     for (auto &Condition : Conditions)
3991       Condition->emitPredicateOpcodes(
3992           Table, *static_cast<RuleMatcher *>(*Rules.begin()));
3993   }
3994   // Emit the conditions.
3995   // Then checks apply the rules.
3996   for (const auto &Rule : Rules)
3997     Rule->emit(Table);
3998   // If we don't succeeded for that block, that means we are not going to select
3999   // this instruction.
4000   if (!conditions_empty()) {
4001     Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4002     Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
4003           << MatchTable::Label(LabelID);
4004   }
4005 }
4006 
4007 unsigned OperandMatcher::getInsnVarID() const { return Insn.getVarID(); }
4008 
4009 } // end anonymous namespace
4010 
4011 //===----------------------------------------------------------------------===//
4012 
4013 namespace llvm {
4014 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4015   GlobalISelEmitter(RK).run(OS);
4016 }
4017 } // End llvm namespace
4018