xref: /llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp (revision 5a81a559d69fb84e1e8ef623ac4b642081c14c51)
1 
2 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/Target/GlobalISel/Target.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 "Basic/CodeGenIntrinsics.h"
34 #include "Common/CodeGenDAGPatterns.h"
35 #include "Common/CodeGenInstruction.h"
36 #include "Common/CodeGenRegisters.h"
37 #include "Common/CodeGenTarget.h"
38 #include "Common/GlobalISel/GlobalISelMatchTable.h"
39 #include "Common/GlobalISel/GlobalISelMatchTableExecutorEmitter.h"
40 #include "Common/InfoByHwMode.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/CodeGenTypes/LowLevelType.h"
43 #include "llvm/CodeGenTypes/MachineValueType.h"
44 #include "llvm/Support/CodeGenCoverage.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Error.h"
47 #include "llvm/Support/ScopedPrinter.h"
48 #include "llvm/TableGen/Error.h"
49 #include "llvm/TableGen/Record.h"
50 #include "llvm/TableGen/TableGenBackend.h"
51 #include <string>
52 
53 using namespace llvm;
54 using namespace llvm::gi;
55 
56 using action_iterator = RuleMatcher::action_iterator;
57 
58 #define DEBUG_TYPE "gisel-emitter"
59 
60 STATISTIC(NumPatternTotal, "Total number of patterns");
61 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
62 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
63 STATISTIC(NumPatternsTested,
64           "Number of patterns executed according to coverage information");
65 
66 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
67 
68 static cl::opt<bool> WarnOnSkippedPatterns(
69     "warn-on-skipped-patterns",
70     cl::desc("Explain why a pattern was skipped for inclusion "
71              "in the GlobalISel selector"),
72     cl::init(false), cl::cat(GlobalISelEmitterCat));
73 
74 static cl::opt<bool> GenerateCoverage(
75     "instrument-gisel-coverage",
76     cl::desc("Generate coverage instrumentation for GlobalISel"),
77     cl::init(false), cl::cat(GlobalISelEmitterCat));
78 
79 static cl::opt<std::string> UseCoverageFile(
80     "gisel-coverage-file", cl::init(""),
81     cl::desc("Specify file to retrieve coverage information from"),
82     cl::cat(GlobalISelEmitterCat));
83 
84 static cl::opt<bool> OptimizeMatchTable(
85     "optimize-match-table",
86     cl::desc("Generate an optimized version of the match table"),
87     cl::init(true), cl::cat(GlobalISelEmitterCat));
88 
89 namespace {
90 
91 static std::string explainPredicates(const TreePatternNode &N) {
92   std::string Explanation;
93   StringRef Separator = "";
94   for (const TreePredicateCall &Call : N.getPredicateCalls()) {
95     const TreePredicateFn &P = Call.Fn;
96     Explanation +=
97         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
98     Separator = ", ";
99 
100     if (P.isAlwaysTrue())
101       Explanation += " always-true";
102     if (P.isImmediatePattern())
103       Explanation += " immediate";
104 
105     if (P.isUnindexed())
106       Explanation += " unindexed";
107 
108     if (P.isNonExtLoad())
109       Explanation += " non-extload";
110     if (P.isAnyExtLoad())
111       Explanation += " extload";
112     if (P.isSignExtLoad())
113       Explanation += " sextload";
114     if (P.isZeroExtLoad())
115       Explanation += " zextload";
116 
117     if (P.isNonTruncStore())
118       Explanation += " non-truncstore";
119     if (P.isTruncStore())
120       Explanation += " truncstore";
121 
122     if (const Record *VT = P.getMemoryVT())
123       Explanation += (" MemVT=" + VT->getName()).str();
124     if (const Record *VT = P.getScalarMemoryVT())
125       Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
126 
127     if (const ListInit *AddrSpaces = P.getAddressSpaces()) {
128       raw_string_ostream OS(Explanation);
129       OS << " AddressSpaces=[";
130 
131       StringRef AddrSpaceSeparator;
132       for (const Init *Val : AddrSpaces->getValues()) {
133         const IntInit *IntVal = dyn_cast<IntInit>(Val);
134         if (!IntVal)
135           continue;
136 
137         OS << AddrSpaceSeparator << IntVal->getValue();
138         AddrSpaceSeparator = ", ";
139       }
140 
141       OS << ']';
142     }
143 
144     int64_t MinAlign = P.getMinAlignment();
145     if (MinAlign > 0)
146       Explanation += " MinAlign=" + utostr(MinAlign);
147 
148     if (P.isAtomicOrderingMonotonic())
149       Explanation += " monotonic";
150     if (P.isAtomicOrderingAcquire())
151       Explanation += " acquire";
152     if (P.isAtomicOrderingRelease())
153       Explanation += " release";
154     if (P.isAtomicOrderingAcquireRelease())
155       Explanation += " acq_rel";
156     if (P.isAtomicOrderingSequentiallyConsistent())
157       Explanation += " seq_cst";
158     if (P.isAtomicOrderingAcquireOrStronger())
159       Explanation += " >=acquire";
160     if (P.isAtomicOrderingWeakerThanAcquire())
161       Explanation += " <acquire";
162     if (P.isAtomicOrderingReleaseOrStronger())
163       Explanation += " >=release";
164     if (P.isAtomicOrderingWeakerThanRelease())
165       Explanation += " <release";
166   }
167   return Explanation;
168 }
169 
170 std::string explainOperator(const Record *Operator) {
171   if (Operator->isSubClassOf("SDNode"))
172     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
173 
174   if (Operator->isSubClassOf("Intrinsic"))
175     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
176 
177   if (Operator->isSubClassOf("ComplexPattern"))
178     return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
179             ")")
180         .str();
181 
182   if (Operator->isSubClassOf("SDNodeXForm"))
183     return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
184             ")")
185         .str();
186 
187   return (" (Operator " + Operator->getName() + " not understood)").str();
188 }
189 
190 /// Helper function to let the emitter report skip reason error messages.
191 static Error failedImport(const Twine &Reason) {
192   return make_error<StringError>(Reason, inconvertibleErrorCode());
193 }
194 
195 static Error isTrivialOperatorNode(const TreePatternNode &N) {
196   std::string Explanation;
197   std::string Separator;
198 
199   bool HasUnsupportedPredicate = false;
200   for (const TreePredicateCall &Call : N.getPredicateCalls()) {
201     const TreePredicateFn &Predicate = Call.Fn;
202 
203     if (Predicate.isAlwaysTrue())
204       continue;
205 
206     if (Predicate.isImmediatePattern())
207       continue;
208 
209     if (Predicate.hasNoUse() || Predicate.hasOneUse())
210       continue;
211 
212     if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
213         Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
214       continue;
215 
216     if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
217       continue;
218 
219     if (Predicate.isLoad() && Predicate.getMemoryVT())
220       continue;
221 
222     if (Predicate.isLoad() || Predicate.isStore()) {
223       if (Predicate.isUnindexed())
224         continue;
225     }
226 
227     if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
228       const ListInit *AddrSpaces = Predicate.getAddressSpaces();
229       if (AddrSpaces && !AddrSpaces->empty())
230         continue;
231 
232       if (Predicate.getMinAlignment() > 0)
233         continue;
234     }
235 
236     if (Predicate.isAtomic() && Predicate.getMemoryVT())
237       continue;
238 
239     if (Predicate.isAtomic() &&
240         (Predicate.isAtomicOrderingMonotonic() ||
241          Predicate.isAtomicOrderingAcquire() ||
242          Predicate.isAtomicOrderingRelease() ||
243          Predicate.isAtomicOrderingAcquireRelease() ||
244          Predicate.isAtomicOrderingSequentiallyConsistent() ||
245          Predicate.isAtomicOrderingAcquireOrStronger() ||
246          Predicate.isAtomicOrderingWeakerThanAcquire() ||
247          Predicate.isAtomicOrderingReleaseOrStronger() ||
248          Predicate.isAtomicOrderingWeakerThanRelease()))
249       continue;
250 
251     if (Predicate.hasGISelPredicateCode())
252       continue;
253 
254     HasUnsupportedPredicate = true;
255     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
256     Separator = ", ";
257     Explanation += (Separator + "first-failing:" +
258                     Predicate.getOrigPatFragRecord()->getRecord()->getName())
259                        .str();
260     break;
261   }
262 
263   if (!HasUnsupportedPredicate)
264     return Error::success();
265 
266   return failedImport(Explanation);
267 }
268 
269 static const Record *getInitValueAsRegClass(const Init *V) {
270   if (const DefInit *VDefInit = dyn_cast<DefInit>(V)) {
271     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
272       return VDefInit->getDef()->getValueAsDef("RegClass");
273     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
274       return VDefInit->getDef();
275   }
276   return nullptr;
277 }
278 
279 static std::string getScopedName(unsigned Scope, const std::string &Name) {
280   return ("pred:" + Twine(Scope) + ":" + Name).str();
281 }
282 
283 static std::string getMangledRootDefName(StringRef DefOperandName) {
284   return ("DstI[" + DefOperandName + "]").str();
285 }
286 
287 //===- GlobalISelEmitter class --------------------------------------------===//
288 
289 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode &Dst,
290                                               const CodeGenTarget &Target) {
291   // While we allow more than one output (both implicit and explicit defs)
292   // below, we only expect one explicit def here.
293   assert(Dst.getOperator()->isSubClassOf("Instruction"));
294   CodeGenInstruction &InstInfo = Target.getInstruction(Dst.getOperator());
295   if (!InstInfo.Operands.NumDefs)
296     return failedImport("Dst pattern child needs a def");
297 
298   ArrayRef<TypeSetByHwMode> ChildTypes = Dst.getExtTypes();
299   if (ChildTypes.size() < 1)
300     return failedImport("Dst pattern child has no result");
301 
302   // If there are multiple results, just take the first one (this is how
303   // SelectionDAG does it).
304   std::optional<LLTCodeGen> MaybeOpTy;
305   if (ChildTypes.front().isMachineValueType()) {
306     MaybeOpTy = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
307   }
308 
309   if (!MaybeOpTy)
310     return failedImport("Dst operand has an unsupported type");
311   return *MaybeOpTy;
312 }
313 
314 class GlobalISelEmitter final : public GlobalISelMatchTableExecutorEmitter {
315 public:
316   explicit GlobalISelEmitter(const RecordKeeper &RK);
317 
318   void emitAdditionalImpl(raw_ostream &OS) override;
319 
320   void emitMIPredicateFns(raw_ostream &OS) override;
321   void emitI64ImmPredicateFns(raw_ostream &OS) override;
322   void emitAPFloatImmPredicateFns(raw_ostream &OS) override;
323   void emitAPIntImmPredicateFns(raw_ostream &OS) override;
324   void emitTestSimplePredicate(raw_ostream &OS) override;
325   void emitRunCustomAction(raw_ostream &OS) override;
326 
327   const CodeGenTarget &getTarget() const override { return Target; }
328   StringRef getClassName() const override { return ClassName; }
329 
330   void run(raw_ostream &OS);
331 
332 private:
333   std::string ClassName;
334 
335   const RecordKeeper &RK;
336   const CodeGenDAGPatterns CGP;
337   const CodeGenTarget &Target;
338   CodeGenRegBank &CGRegs;
339 
340   ArrayRef<const Record *> AllPatFrags;
341 
342   /// Keep track of the equivalence between SDNodes and Instruction by mapping
343   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
344   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
345   /// This is defined using 'GINodeEquiv' in the target description.
346   DenseMap<const Record *, const Record *> NodeEquivs;
347 
348   /// Keep track of the equivalence between ComplexPattern's and
349   /// GIComplexOperandMatcher. Map entries are specified by subclassing
350   /// GIComplexPatternEquiv.
351   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
352 
353   /// Keep track of the equivalence between SDNodeXForm's and
354   /// GICustomOperandRenderer. Map entries are specified by subclassing
355   /// GISDNodeXFormEquiv.
356   DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
357 
358   /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
359   /// This adds compatibility for RuleMatchers to use this for ordering rules.
360   DenseMap<uint64_t, int> RuleMatcherScores;
361 
362   // Rule coverage information.
363   std::optional<CodeGenCoverage> RuleCoverage;
364 
365   /// Variables used to help with collecting of named operands for predicates
366   /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
367   /// to the number of named operands that predicate expects. Store locations in
368   /// StoreIdxForName correspond to the order in which operand names appear in
369   /// predicate's argument list.
370   /// When we visit named operand and WaitingForNamedOperands is not zero, add
371   /// matcher that will record operand and decrease counter.
372   unsigned WaitingForNamedOperands = 0;
373   StringMap<unsigned> StoreIdxForName;
374 
375   void gatherOpcodeValues();
376   void gatherTypeIDValues();
377   void gatherNodeEquivs();
378 
379   const Record *findNodeEquiv(const Record *N) const;
380   const CodeGenInstruction *getEquivNode(const Record &Equiv,
381                                          const TreePatternNode &N) const;
382 
383   Error importRulePredicates(RuleMatcher &M,
384                              ArrayRef<const Record *> Predicates);
385   Expected<InstructionMatcher &>
386   createAndImportSelDAGMatcher(RuleMatcher &Rule,
387                                InstructionMatcher &InsnMatcher,
388                                const TreePatternNode &Src, unsigned &TempOpIdx);
389   Error importComplexPatternOperandMatcher(OperandMatcher &OM, const Record *R,
390                                            unsigned &TempOpIdx) const;
391   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
392                            const TreePatternNode &SrcChild,
393                            bool OperandIsAPointer, bool OperandIsImmArg,
394                            unsigned OpIdx, unsigned &TempOpIdx);
395 
396   Expected<BuildMIAction &>
397   createAndImportInstructionRenderer(RuleMatcher &M,
398                                      InstructionMatcher &InsnMatcher,
399                                      const TreePatternNode &Dst) const;
400   Expected<action_iterator> createAndImportSubInstructionRenderer(
401       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode &Dst,
402       unsigned TempReg) const;
403   Expected<action_iterator>
404   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
405                             const TreePatternNode &Dst) const;
406 
407   Expected<action_iterator>
408   importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
409                              BuildMIAction &DstMIBuilder,
410                              const TreePatternNode &Dst, bool IsRoot) const;
411 
412   Expected<action_iterator>
413   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
414                              BuildMIAction &DstMIBuilder,
415                              const TreePatternNode &Dst) const;
416 
417   Error importNamedNodeRenderer(RuleMatcher &M, BuildMIAction &MIBuilder,
418                                 const TreePatternNode &N) const;
419 
420   Error importLeafNodeRenderer(RuleMatcher &M, BuildMIAction &MIBuilder,
421                                const TreePatternNode &N,
422                                action_iterator InsertPt) const;
423 
424   Error importXFormNodeRenderer(RuleMatcher &M, BuildMIAction &MIBuilder,
425                                 const TreePatternNode &N) const;
426 
427   Error importInstructionNodeRenderer(RuleMatcher &M, BuildMIAction &MIBuilder,
428                                       const TreePatternNode &N,
429                                       action_iterator &InsertPt) const;
430 
431   Error importNodeRenderer(RuleMatcher &M, BuildMIAction &MIBuilder,
432                            const TreePatternNode &N,
433                            action_iterator &InsertPt) const;
434 
435   Error importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
436                                    ArrayRef<const Record *> ImplicitDefs) const;
437 
438   /// Analyze pattern \p P, returning a matcher for it if possible.
439   /// Otherwise, return an Error explaining why we don't support it.
440   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
441 
442   void declareSubtargetFeature(const Record *Predicate);
443 
444   unsigned declareHwModeCheck(StringRef HwModeFeatures);
445 
446   MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
447                              bool WithCoverage);
448 
449   /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
450   /// CodeGenRegisterClass will support the CodeGenRegisterClass of
451   /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
452   /// If no register class is found, return nullptr.
453   const CodeGenRegisterClass *
454   inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
455                                  const TreePatternNode &SuperRegNode,
456                                  const TreePatternNode &SubRegIdxNode) const;
457   const CodeGenSubRegIndex *
458   inferSubRegIndexForNode(const TreePatternNode &SubRegIdxNode) const;
459 
460   /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
461   /// Return nullptr if no such class exists.
462   const CodeGenRegisterClass *
463   inferSuperRegisterClass(const TypeSetByHwMode &Ty,
464                           const TreePatternNode &SubRegIdxNode) const;
465 
466   /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
467   const CodeGenRegisterClass *
468   getRegClassFromLeaf(const TreePatternNode &Leaf) const;
469 
470   /// Return a CodeGenRegisterClass for \p N if one can be found. Return
471   /// nullptr otherwise.
472   const CodeGenRegisterClass *
473   inferRegClassFromPattern(const TreePatternNode &N) const;
474 
475   const CodeGenRegisterClass *
476   inferRegClassFromInstructionPattern(const TreePatternNode &N,
477                                       unsigned ResIdx) const;
478 
479   Error constrainOperands(action_iterator InsertPt, RuleMatcher &M,
480                           unsigned InsnID, const TreePatternNode &Dst) const;
481 
482   /// Return the size of the MemoryVT in this predicate, if possible.
483   std::optional<unsigned>
484   getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate);
485 
486   // Add builtin predicates.
487   Expected<InstructionMatcher &>
488   addBuiltinPredicates(const Record *SrcGIEquivOrNull,
489                        const TreePredicateFn &Predicate,
490                        InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
491 };
492 
493 StringRef getPatFragPredicateEnumName(const Record *R) { return R->getName(); }
494 
495 void GlobalISelEmitter::gatherOpcodeValues() {
496   InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
497 }
498 
499 void GlobalISelEmitter::gatherTypeIDValues() {
500   LLTOperandMatcher::initTypeIDValuesMap();
501 }
502 
503 void GlobalISelEmitter::gatherNodeEquivs() {
504   assert(NodeEquivs.empty());
505   for (const Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
506     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
507 
508   assert(ComplexPatternEquivs.empty());
509   for (const Record *Equiv :
510        RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
511     const Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
512     if (!SelDAGEquiv)
513       continue;
514     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
515   }
516 
517   assert(SDNodeXFormEquivs.empty());
518   for (const Record *Equiv :
519        RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
520     const Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
521     if (!SelDAGEquiv)
522       continue;
523     SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
524   }
525 }
526 
527 const Record *GlobalISelEmitter::findNodeEquiv(const Record *N) const {
528   return NodeEquivs.lookup(N);
529 }
530 
531 const CodeGenInstruction *
532 GlobalISelEmitter::getEquivNode(const Record &Equiv,
533                                 const TreePatternNode &N) const {
534   if (N.getNumChildren() >= 1) {
535     // setcc operation maps to two different G_* instructions based on the type.
536     if (!Equiv.isValueUnset("IfFloatingPoint") &&
537         MVT(N.getChild(0).getSimpleType(0)).isFloatingPoint())
538       return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
539   }
540 
541   if (!Equiv.isValueUnset("IfConvergent") &&
542       N.getIntrinsicInfo(CGP)->isConvergent)
543     return &Target.getInstruction(Equiv.getValueAsDef("IfConvergent"));
544 
545   for (const TreePredicateCall &Call : N.getPredicateCalls()) {
546     const TreePredicateFn &Predicate = Call.Fn;
547     if (!Equiv.isValueUnset("IfSignExtend") &&
548         (Predicate.isLoad() || Predicate.isAtomic()) &&
549         Predicate.isSignExtLoad())
550       return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
551     if (!Equiv.isValueUnset("IfZeroExtend") &&
552         (Predicate.isLoad() || Predicate.isAtomic()) &&
553         Predicate.isZeroExtLoad())
554       return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
555   }
556 
557   return &Target.getInstruction(Equiv.getValueAsDef("I"));
558 }
559 
560 GlobalISelEmitter::GlobalISelEmitter(const RecordKeeper &RK)
561     : GlobalISelMatchTableExecutorEmitter(), RK(RK), CGP(RK),
562       Target(CGP.getTargetInfo()), CGRegs(Target.getRegBank()) {
563   ClassName = Target.getName().str() + "InstructionSelector";
564 }
565 
566 //===- Emitter ------------------------------------------------------------===//
567 
568 Error GlobalISelEmitter::importRulePredicates(
569     RuleMatcher &M, ArrayRef<const Record *> Predicates) {
570   for (const Record *Pred : Predicates) {
571     if (Pred->getValueAsString("CondString").empty())
572       continue;
573     declareSubtargetFeature(Pred);
574     M.addRequiredFeature(Pred);
575   }
576 
577   return Error::success();
578 }
579 
580 std::optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(
581     const TreePredicateFn &Predicate) {
582   std::optional<LLTCodeGen> MemTyOrNone =
583       MVTToLLT(getValueType(Predicate.getMemoryVT()));
584 
585   if (!MemTyOrNone)
586     return std::nullopt;
587 
588   // Align so unusual types like i1 don't get rounded down.
589   return llvm::alignTo(
590       static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8);
591 }
592 
593 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
594     const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
595     InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
596   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
597     if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
598       SmallVector<unsigned, 4> ParsedAddrSpaces;
599 
600       for (const Init *Val : AddrSpaces->getValues()) {
601         const IntInit *IntVal = dyn_cast<IntInit>(Val);
602         if (!IntVal)
603           return failedImport("Address space is not an integer");
604         ParsedAddrSpaces.push_back(IntVal->getValue());
605       }
606 
607       if (!ParsedAddrSpaces.empty()) {
608         InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
609             0, ParsedAddrSpaces);
610         return InsnMatcher;
611       }
612     }
613 
614     int64_t MinAlign = Predicate.getMinAlignment();
615     if (MinAlign > 0) {
616       InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
617       return InsnMatcher;
618     }
619   }
620 
621   // G_LOAD is used for both non-extending and any-extending loads.
622   if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
623     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
624         0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
625     return InsnMatcher;
626   }
627   if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
628     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
629         0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
630     return InsnMatcher;
631   }
632 
633   if (Predicate.isStore()) {
634     if (Predicate.isTruncStore()) {
635       if (Predicate.getMemoryVT() != nullptr) {
636         // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
637         auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
638         if (!MemSizeInBits)
639           return failedImport("MemVT could not be converted to LLT");
640 
641         InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, *MemSizeInBits /
642                                                                     8);
643       } else {
644         InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
645             0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
646       }
647       return InsnMatcher;
648     }
649     if (Predicate.isNonTruncStore()) {
650       // We need to check the sizes match here otherwise we could incorrectly
651       // match truncating stores with non-truncating ones.
652       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
653           0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
654     }
655   }
656 
657   assert(SrcGIEquivOrNull != nullptr && "Invalid SrcGIEquivOrNull value");
658   // No check required. We already did it by swapping the opcode.
659   if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
660       Predicate.isSignExtLoad())
661     return InsnMatcher;
662 
663   // No check required. We already did it by swapping the opcode.
664   if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
665       Predicate.isZeroExtLoad())
666     return InsnMatcher;
667 
668   // No check required. G_STORE by itself is a non-extending store.
669   if (Predicate.isNonTruncStore())
670     return InsnMatcher;
671 
672   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
673     if (Predicate.getMemoryVT() != nullptr) {
674       auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
675       if (!MemSizeInBits)
676         return failedImport("MemVT could not be converted to LLT");
677 
678       InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
679                                                            *MemSizeInBits / 8);
680       return InsnMatcher;
681     }
682   }
683 
684   if (Predicate.isLoad() || Predicate.isStore()) {
685     // No check required. A G_LOAD/G_STORE is an unindexed load.
686     if (Predicate.isUnindexed())
687       return InsnMatcher;
688   }
689 
690   if (Predicate.isAtomic()) {
691     if (Predicate.isAtomicOrderingMonotonic()) {
692       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
693       return InsnMatcher;
694     }
695     if (Predicate.isAtomicOrderingAcquire()) {
696       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
697       return InsnMatcher;
698     }
699     if (Predicate.isAtomicOrderingRelease()) {
700       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
701       return InsnMatcher;
702     }
703     if (Predicate.isAtomicOrderingAcquireRelease()) {
704       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
705           "AcquireRelease");
706       return InsnMatcher;
707     }
708     if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
709       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
710           "SequentiallyConsistent");
711       return InsnMatcher;
712     }
713   }
714 
715   if (Predicate.isAtomicOrderingAcquireOrStronger()) {
716     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
717         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
718     return InsnMatcher;
719   }
720   if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
721     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
722         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
723     return InsnMatcher;
724   }
725 
726   if (Predicate.isAtomicOrderingReleaseOrStronger()) {
727     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
728         "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
729     return InsnMatcher;
730   }
731   if (Predicate.isAtomicOrderingWeakerThanRelease()) {
732     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
733         "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
734     return InsnMatcher;
735   }
736   HasAddedMatcher = false;
737   return InsnMatcher;
738 }
739 
740 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
741     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
742     const TreePatternNode &Src, unsigned &TempOpIdx) {
743   const auto SavedFlags = Rule.setGISelFlags(Src.getGISelFlagsRecord());
744 
745   const Record *SrcGIEquivOrNull = nullptr;
746   const CodeGenInstruction *SrcGIOrNull = nullptr;
747 
748   // Start with the defined operands (i.e., the results of the root operator).
749   if (Src.isLeaf()) {
750     const Init *SrcInit = Src.getLeafValue();
751     if (isa<IntInit>(SrcInit)) {
752       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
753           &Target.getInstruction(RK.getDef("G_CONSTANT")));
754     } else
755       return failedImport(
756           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
757   } else {
758     SrcGIEquivOrNull = findNodeEquiv(Src.getOperator());
759     if (!SrcGIEquivOrNull)
760       return failedImport("Pattern operator lacks an equivalent Instruction" +
761                           explainOperator(Src.getOperator()));
762     SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
763 
764     // The operators look good: match the opcode
765     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
766   }
767 
768   // Since there are no opcodes for atomic loads and stores comparing to
769   // SelectionDAG, we add CheckMMOIsNonAtomic predicate immediately after the
770   // opcode predicate to make a logical combination of them.
771   if (SrcGIEquivOrNull &&
772       SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
773     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
774   else if (SrcGIEquivOrNull &&
775            SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
776     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
777         "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
778   }
779 
780   unsigned OpIdx = 0;
781   for (const TypeSetByHwMode &VTy : Src.getExtTypes()) {
782     // Results don't have a name unless they are the root node. The caller will
783     // set the name if appropriate.
784     const bool OperandIsAPointer =
785         SrcGIOrNull && SrcGIOrNull->isOutOperandAPointer(OpIdx);
786     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
787     if (auto Error = OM.addTypeCheckPredicate(VTy, OperandIsAPointer))
788       return failedImport(toString(std::move(Error)) +
789                           " for result of Src pattern operator");
790   }
791 
792   for (const TreePredicateCall &Call : Src.getPredicateCalls()) {
793     const TreePredicateFn &Predicate = Call.Fn;
794     bool HasAddedBuiltinMatcher = true;
795     if (Predicate.isAlwaysTrue())
796       continue;
797 
798     if (Predicate.isImmediatePattern()) {
799       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
800       continue;
801     }
802 
803     auto InsnMatcherOrError = addBuiltinPredicates(
804         SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
805     if (auto Error = InsnMatcherOrError.takeError())
806       return std::move(Error);
807 
808     // FIXME: This should be part of addBuiltinPredicates(). If we add this at
809     // the start of addBuiltinPredicates() without returning, then there might
810     // be cases where we hit the last return before which the
811     // HasAddedBuiltinMatcher will be set to false. The predicate could be
812     // missed if we add it in the middle or at the end due to return statements
813     // after the addPredicate<>() calls.
814     if (Predicate.hasNoUse()) {
815       InsnMatcher.addPredicate<NoUsePredicateMatcher>();
816       HasAddedBuiltinMatcher = true;
817     }
818     if (Predicate.hasOneUse()) {
819       InsnMatcher.addPredicate<OneUsePredicateMatcher>();
820       HasAddedBuiltinMatcher = true;
821     }
822 
823     if (Predicate.hasGISelPredicateCode()) {
824       if (Predicate.usesOperands()) {
825         assert(WaitingForNamedOperands == 0 &&
826                "previous predicate didn't find all operands or "
827                "nested predicate that uses operands");
828         TreePattern *TP = Predicate.getOrigPatFragRecord();
829         WaitingForNamedOperands = TP->getNumArgs();
830         for (unsigned I = 0; I < WaitingForNamedOperands; ++I)
831           StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(I))] = I;
832       }
833       InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
834       continue;
835     }
836     if (!HasAddedBuiltinMatcher) {
837       return failedImport("Src pattern child has predicate (" +
838                           explainPredicates(Src) + ")");
839     }
840   }
841 
842   if (Src.isLeaf()) {
843     const Init *SrcInit = Src.getLeafValue();
844     if (const IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
845       OperandMatcher &OM =
846           InsnMatcher.addOperand(OpIdx++, Src.getName(), TempOpIdx);
847       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
848     } else
849       return failedImport(
850           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
851   } else {
852     assert(SrcGIOrNull &&
853            "Expected to have already found an equivalent Instruction");
854     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
855         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT" ||
856         SrcGIOrNull->TheDef->getName() == "G_FRAME_INDEX") {
857       // imm/fpimm still have operands but we don't need to do anything with it
858       // here since we don't support ImmLeaf predicates yet. However, we still
859       // need to note the hidden operand to get GIM_CheckNumOperands correct.
860       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
861       return InsnMatcher;
862     }
863 
864     // Special case because the operand order is changed from setcc. The
865     // predicate operand needs to be swapped from the last operand to the first
866     // source.
867 
868     unsigned NumChildren = Src.getNumChildren();
869     bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
870 
871     if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
872       const TreePatternNode &SrcChild = Src.getChild(NumChildren - 1);
873       if (SrcChild.isLeaf()) {
874         const DefInit *DI = dyn_cast<DefInit>(SrcChild.getLeafValue());
875         const Record *CCDef = DI ? DI->getDef() : nullptr;
876         if (!CCDef || !CCDef->isSubClassOf("CondCode"))
877           return failedImport("Unable to handle CondCode");
878 
879         OperandMatcher &OM =
880             InsnMatcher.addOperand(OpIdx++, SrcChild.getName(), TempOpIdx);
881         StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate")
882                                     : CCDef->getValueAsString("ICmpPredicate");
883 
884         if (!PredType.empty()) {
885           OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
886           // Process the other 2 operands normally.
887           --NumChildren;
888         }
889       }
890     }
891 
892     // Match the used operands (i.e. the children of the operator).
893     bool IsIntrinsic =
894         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
895         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS" ||
896         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_CONVERGENT" ||
897         SrcGIOrNull->TheDef->getName() ==
898             "G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS";
899     const CodeGenIntrinsic *II = Src.getIntrinsicInfo(CGP);
900     if (IsIntrinsic && !II)
901       return failedImport("Expected IntInit containing intrinsic ID)");
902 
903     for (unsigned I = 0; I != NumChildren; ++I) {
904       const TreePatternNode &SrcChild = Src.getChild(I);
905 
906       // We need to determine the meaning of a literal integer based on the
907       // context. If this is a field required to be an immediate (such as an
908       // immarg intrinsic argument), the required predicates are different than
909       // a constant which may be materialized in a register. If we have an
910       // argument that is required to be an immediate, we should not emit an LLT
911       // type check, and should not be looking for a G_CONSTANT defined
912       // register.
913       bool OperandIsImmArg = SrcGIOrNull->isInOperandImmArg(I);
914 
915       // SelectionDAG allows pointers to be represented with iN since it doesn't
916       // distinguish between pointers and integers but they are different types
917       // in GlobalISel. Coerce integers to pointers to address space 0 if the
918       // context indicates a pointer.
919       //
920       bool OperandIsAPointer = SrcGIOrNull->isInOperandAPointer(I);
921 
922       if (IsIntrinsic) {
923         // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
924         // following the defs is an intrinsic ID.
925         if (I == 0) {
926           OperandMatcher &OM =
927               InsnMatcher.addOperand(OpIdx++, SrcChild.getName(), TempOpIdx);
928           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
929           continue;
930         }
931 
932         // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
933         //
934         // Note that we have to look at the i-1th parameter, because we don't
935         // have the intrinsic ID in the intrinsic's parameter list.
936         OperandIsAPointer |= II->isParamAPointer(I - 1);
937         OperandIsImmArg |= II->isParamImmArg(I - 1);
938       }
939 
940       if (auto Error =
941               importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
942                                  OperandIsImmArg, OpIdx++, TempOpIdx))
943         return std::move(Error);
944     }
945   }
946 
947   return InsnMatcher;
948 }
949 
950 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
951     OperandMatcher &OM, const Record *R, unsigned &TempOpIdx) const {
952   const auto &ComplexPattern = ComplexPatternEquivs.find(R);
953   if (ComplexPattern == ComplexPatternEquivs.end())
954     return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
955                         ") not mapped to GlobalISel");
956 
957   OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
958   TempOpIdx++;
959   return Error::success();
960 }
961 
962 // Get the name to use for a pattern operand. For an anonymous physical register
963 // input, this should use the register name.
964 static StringRef getSrcChildName(const TreePatternNode &SrcChild,
965                                  const Record *&PhysReg) {
966   StringRef SrcChildName = SrcChild.getName();
967   if (SrcChildName.empty() && SrcChild.isLeaf()) {
968     if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild.getLeafValue())) {
969       auto *ChildRec = ChildDefInit->getDef();
970       if (ChildRec->isSubClassOf("Register")) {
971         SrcChildName = ChildRec->getName();
972         PhysReg = ChildRec;
973       }
974     }
975   }
976 
977   return SrcChildName;
978 }
979 
980 Error GlobalISelEmitter::importChildMatcher(
981     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
982     const TreePatternNode &SrcChild, bool OperandIsAPointer,
983     bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
984 
985   const Record *PhysReg = nullptr;
986   std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg));
987   if (!SrcChild.isLeaf() &&
988       SrcChild.getOperator()->isSubClassOf("ComplexPattern")) {
989     // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
990     // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
991     std::string PatternName = std::string(SrcChild.getOperator()->getName());
992     for (const TreePatternNode &Child : SrcChild.children()) {
993       PatternName += ":";
994       PatternName += Child.getName();
995     }
996     SrcChildName = PatternName;
997   }
998 
999   OperandMatcher &OM =
1000       PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
1001               : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
1002   if (OM.isSameAsAnotherOperand())
1003     return Error::success();
1004 
1005   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild.getExtTypes();
1006   if (ChildTypes.size() != 1)
1007     return failedImport("Src pattern child has multiple results");
1008 
1009   // Check MBB's before the type check since they are not a known type.
1010   if (!SrcChild.isLeaf()) {
1011     if (SrcChild.getOperator()->getName() == "bb") {
1012       OM.addPredicate<MBBOperandMatcher>();
1013       return Error::success();
1014     }
1015     if (SrcChild.getOperator()->getName() == "timm") {
1016       OM.addPredicate<ImmOperandMatcher>();
1017 
1018       // Add predicates, if any
1019       for (const TreePredicateCall &Call : SrcChild.getPredicateCalls()) {
1020         const TreePredicateFn &Predicate = Call.Fn;
1021 
1022         // Only handle immediate patterns for now
1023         if (Predicate.isImmediatePattern()) {
1024           OM.addPredicate<OperandImmPredicateMatcher>(Predicate);
1025         }
1026       }
1027 
1028       return Error::success();
1029     }
1030   } else if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild.getLeafValue())) {
1031     auto *ChildRec = ChildDefInit->getDef();
1032     if (ChildRec->isSubClassOf("ValueType") && !SrcChild.hasName()) {
1033       // An unnamed ValueType as in (sext_inreg GPR:$foo, i8). GISel represents
1034       // this as a literal constant with the scalar size.
1035       MVT::SimpleValueType VT = llvm::getValueType(ChildRec);
1036       OM.addPredicate<LiteralIntOperandMatcher>(MVT(VT).getScalarSizeInBits());
1037       return Error::success();
1038     }
1039   }
1040 
1041   // Immediate arguments have no meaningful type to check as they don't have
1042   // registers.
1043   if (!OperandIsImmArg) {
1044     if (auto Error =
1045             OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
1046       return failedImport(toString(std::move(Error)) + " for Src operand (" +
1047                           to_string(SrcChild) + ")");
1048   }
1049 
1050   // Try look up SrcChild for a (named) predicate operand if there is any.
1051   if (WaitingForNamedOperands) {
1052     auto &ScopedNames = SrcChild.getNamesAsPredicateArg();
1053     if (!ScopedNames.empty()) {
1054       auto PA = ScopedNames.begin();
1055       std::string Name = getScopedName(PA->getScope(), PA->getIdentifier());
1056       OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name);
1057       --WaitingForNamedOperands;
1058     }
1059   }
1060 
1061   // Check for nested instructions.
1062   if (!SrcChild.isLeaf()) {
1063     if (SrcChild.getOperator()->isSubClassOf("ComplexPattern")) {
1064       // When a ComplexPattern is used as an operator, it should do the same
1065       // thing as when used as a leaf. However, the children of the operator
1066       // name the sub-operands that make up the complex operand and we must
1067       // prepare to reference them in the renderer too.
1068       unsigned RendererID = TempOpIdx;
1069       if (auto Error = importComplexPatternOperandMatcher(
1070               OM, SrcChild.getOperator(), TempOpIdx))
1071         return Error;
1072 
1073       for (unsigned I = 0, E = SrcChild.getNumChildren(); I != E; ++I) {
1074         auto &SubOperand = SrcChild.getChild(I);
1075         if (!SubOperand.getName().empty()) {
1076           if (auto Error = Rule.defineComplexSubOperand(
1077                   SubOperand.getName(), SrcChild.getOperator(), RendererID, I,
1078                   SrcChildName))
1079             return Error;
1080         }
1081       }
1082 
1083       return Error::success();
1084     }
1085 
1086     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
1087         InsnMatcher.getRuleMatcher(), SrcChild.getName());
1088     if (!MaybeInsnOperand) {
1089       // This isn't strictly true. If the user were to provide exactly the same
1090       // matchers as the original operand then we could allow it. However, it's
1091       // simpler to not permit the redundant specification.
1092       return failedImport(
1093           "Nested instruction cannot be the same as another operand");
1094     }
1095 
1096     // Map the node to a gMIR instruction.
1097     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
1098     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
1099         Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
1100     if (auto Error = InsnMatcherOrError.takeError())
1101       return Error;
1102 
1103     return Error::success();
1104   }
1105 
1106   if (SrcChild.hasAnyPredicate())
1107     return failedImport("Src pattern child has unsupported predicate");
1108 
1109   // Check for constant immediates.
1110   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild.getLeafValue())) {
1111     if (OperandIsImmArg) {
1112       // Checks for argument directly in operand list
1113       OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
1114     } else {
1115       // Checks for materialized constant
1116       OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
1117     }
1118     return Error::success();
1119   }
1120 
1121   // Check for def's like register classes or ComplexPattern's.
1122   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild.getLeafValue())) {
1123     auto *ChildRec = ChildDefInit->getDef();
1124 
1125     // Check for register classes.
1126     if (ChildRec->isSubClassOf("RegisterClass") ||
1127         ChildRec->isSubClassOf("RegisterOperand")) {
1128       OM.addPredicate<RegisterBankOperandMatcher>(
1129           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
1130       return Error::success();
1131     }
1132 
1133     if (ChildRec->isSubClassOf("Register")) {
1134       // This just be emitted as a copy to the specific register.
1135       ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
1136       const CodeGenRegisterClass *RC =
1137           CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
1138       if (!RC) {
1139         return failedImport(
1140             "Could not determine physical register class of pattern source");
1141       }
1142 
1143       OM.addPredicate<RegisterBankOperandMatcher>(*RC);
1144       return Error::success();
1145     }
1146 
1147     // Check for ValueType.
1148     if (ChildRec->isSubClassOf("ValueType")) {
1149       // We already added a type check as standard practice so this doesn't need
1150       // to do anything.
1151       return Error::success();
1152     }
1153 
1154     // Check for ComplexPattern's.
1155     if (ChildRec->isSubClassOf("ComplexPattern"))
1156       return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
1157 
1158     if (ChildRec->isSubClassOf("ImmLeaf")) {
1159       return failedImport(
1160           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1161     }
1162 
1163     // Place holder for SRCVALUE nodes. Nothing to do here.
1164     if (ChildRec->getName() == "srcvalue")
1165       return Error::success();
1166 
1167     const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
1168     if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
1169       auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
1170           InsnMatcher.getRuleMatcher(), SrcChild.getName(), false);
1171       InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
1172 
1173       ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
1174 
1175       const CodeGenInstruction &BuildVector =
1176           Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
1177       const CodeGenInstruction &BuildVectorTrunc =
1178           Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
1179 
1180       // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
1181       // as an alternative.
1182       InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
1183           ArrayRef({&BuildVector, &BuildVectorTrunc}));
1184 
1185       // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
1186       // theoretically not emit any opcode check, but getOpcodeMatcher currently
1187       // has to succeed.
1188       OperandMatcher &OM =
1189           InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
1190       if (auto Error = OM.addTypeCheckPredicate(TypeSetByHwMode(VTy),
1191                                                 /*OperandIsAPointer=*/false))
1192         return failedImport(toString(std::move(Error)) +
1193                             " for result of Src pattern operator");
1194 
1195       InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
1196           ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
1197                       : VectorSplatImmPredicateMatcher::AllZeros);
1198       return Error::success();
1199     }
1200 
1201     return failedImport(
1202         "Src pattern child def is an unsupported tablegen class");
1203   }
1204 
1205   return failedImport("Src pattern child is an unsupported kind");
1206 }
1207 
1208 // Equivalent of MatcherGen::EmitResultOfNamedOperand.
1209 Error GlobalISelEmitter::importNamedNodeRenderer(
1210     RuleMatcher &M, BuildMIAction &MIBuilder, const TreePatternNode &N) const {
1211   StringRef NodeName = N.getName();
1212 
1213   if (auto SubOperand = M.getComplexSubOperand(NodeName)) {
1214     auto [ComplexPatternRec, RendererID, SubOperandIdx] = *SubOperand;
1215     MIBuilder.addRenderer<RenderComplexPatternOperand>(
1216         *ComplexPatternRec, NodeName, RendererID, SubOperandIdx);
1217     return Error::success();
1218   }
1219 
1220   if (!N.isLeaf()) {
1221     StringRef OperatorName = N.getOperator()->getName();
1222 
1223     if (OperatorName == "imm") {
1224       MIBuilder.addRenderer<CopyConstantAsImmRenderer>(NodeName);
1225       return Error::success();
1226     }
1227 
1228     if (OperatorName == "fpimm") {
1229       MIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(NodeName);
1230       return Error::success();
1231     }
1232 
1233     // TODO: 'imm' and 'fpimm' are the only nodes that need special treatment.
1234     //   Remove this check and add CopyRenderer unconditionally for other nodes.
1235     if (OperatorName == "bb" || OperatorName == "timm" ||
1236         OperatorName == "tframeindex") {
1237       MIBuilder.addRenderer<CopyRenderer>(NodeName);
1238       return Error::success();
1239     }
1240 
1241     return failedImport("node has unsupported operator " + to_string(N));
1242   }
1243 
1244   if (const auto *DI = dyn_cast<DefInit>(N.getLeafValue())) {
1245     const Record *R = DI->getDef();
1246 
1247     if (N.getNumResults() != 1)
1248       return failedImport("node does not have one result " + to_string(N));
1249 
1250     if (R->isSubClassOf("ComplexPattern")) {
1251       auto I = ComplexPatternEquivs.find(R);
1252       if (I == ComplexPatternEquivs.end())
1253         return failedImport("ComplexPattern " + R->getName() +
1254                             " does not have GISel equivalent");
1255 
1256       const OperandMatcher &OM = M.getOperandMatcher(NodeName);
1257       MIBuilder.addRenderer<RenderComplexPatternOperand>(
1258           *I->second, NodeName, OM.getAllocatedTemporariesBaseID());
1259       return Error::success();
1260     }
1261 
1262     if (R->isSubClassOf("RegisterOperand") &&
1263         !R->isValueUnset("GIZeroRegister")) {
1264       MIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
1265           NodeName, R->getValueAsDef("GIZeroRegister"));
1266       return Error::success();
1267     }
1268 
1269     // TODO: All special cases are handled above. Remove this check and add
1270     //   CopyRenderer unconditionally.
1271     if (R->isSubClassOf("RegisterClass") ||
1272         R->isSubClassOf("RegisterOperand") || R->isSubClassOf("ValueType")) {
1273       MIBuilder.addRenderer<CopyRenderer>(NodeName);
1274       return Error::success();
1275     }
1276   }
1277 
1278   // TODO: Change this to assert and move to the beginning of the function.
1279   if (!M.hasOperand(NodeName))
1280     return failedImport("could not find node $" + NodeName +
1281                         " in the source DAG");
1282 
1283   // TODO: Remove this check and add CopyRenderer unconditionally.
1284   // TODO: Handle nodes with multiple results (provided they can reach here).
1285   if (isa<UnsetInit>(N.getLeafValue())) {
1286     MIBuilder.addRenderer<CopyRenderer>(NodeName);
1287     return Error::success();
1288   }
1289 
1290   return failedImport("unsupported node " + to_string(N));
1291 }
1292 
1293 // Equivalent of MatcherGen::EmitResultLeafAsOperand.
1294 Error GlobalISelEmitter::importLeafNodeRenderer(
1295     RuleMatcher &M, BuildMIAction &MIBuilder, const TreePatternNode &N,
1296     action_iterator InsertPt) const {
1297   if (const auto *II = dyn_cast<IntInit>(N.getLeafValue())) {
1298     MIBuilder.addRenderer<ImmRenderer>(II->getValue());
1299     return Error::success();
1300   }
1301 
1302   if (const auto *DI = dyn_cast<DefInit>(N.getLeafValue())) {
1303     const Record *R = DI->getDef();
1304 
1305     if (R->isSubClassOf("Register") || R->getName() == "zero_reg") {
1306       MIBuilder.addRenderer<AddRegisterRenderer>(Target, R);
1307       return Error::success();
1308     }
1309 
1310     if (R->getName() == "undef_tied_input") {
1311       std::optional<LLTCodeGen> OpTyOrNone = MVTToLLT(N.getSimpleType(0));
1312       if (!OpTyOrNone)
1313         return failedImport("unsupported type");
1314 
1315       unsigned TempRegID = M.allocateTempRegID();
1316       M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTyOrNone, TempRegID);
1317 
1318       auto I = M.insertAction<BuildMIAction>(
1319           InsertPt, M.allocateOutputInsnID(),
1320           &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
1321       auto &ImpDefBuilder = static_cast<BuildMIAction &>(**I);
1322       ImpDefBuilder.addRenderer<TempRegRenderer>(TempRegID, /*IsDef=*/true);
1323 
1324       MIBuilder.addRenderer<TempRegRenderer>(TempRegID);
1325       return Error::success();
1326     }
1327 
1328     if (R->isSubClassOf("SubRegIndex")) {
1329       const CodeGenSubRegIndex *SubRegIndex = CGRegs.getSubRegIdx(R);
1330       MIBuilder.addRenderer<ImmRenderer>(SubRegIndex->EnumValue);
1331       return Error::success();
1332     }
1333 
1334     // There are also RegisterClass / RegisterOperand operands of REG_SEQUENCE /
1335     // COPY_TO_REGCLASS, but these instructions are currently handled elsewhere.
1336   }
1337 
1338   return failedImport("unrecognized node " + to_string(N));
1339 }
1340 
1341 // Equivalent of MatcherGen::EmitResultSDNodeXFormAsOperand.
1342 Error GlobalISelEmitter::importXFormNodeRenderer(
1343     RuleMatcher &M, BuildMIAction &MIBuilder, const TreePatternNode &N) const {
1344   const Record *XFormRec = N.getOperator();
1345   auto I = SDNodeXFormEquivs.find(XFormRec);
1346   if (I == SDNodeXFormEquivs.end())
1347     return failedImport("SDNodeXForm " + XFormRec->getName() +
1348                         " does not have GISel equivalent");
1349 
1350   // TODO: Fail to import if GISDNodeXForm does not have RendererFn.
1351   //   This currently results in a fatal error in emitRenderOpcodes.
1352   const Record *XFormEquivRec = I->second;
1353 
1354   // The node to apply the transformation function to.
1355   // FIXME: The node may not have a name and may be a leaf. It should be
1356   //   rendered first, like any other nodes. This may or may not require
1357   //   introducing a temporary register, and we can't tell that without
1358   //   inspecting the node (possibly recursively). This is a general drawback
1359   //   of appending renderers directly to BuildMIAction.
1360   const TreePatternNode &Node = N.getChild(0);
1361   StringRef NodeName = Node.getName();
1362 
1363   const Record *XFormOpc = CGP.getSDNodeTransform(XFormRec).first;
1364   if (XFormOpc->getName() == "timm") {
1365     // If this is a TargetConstant, there won't be a corresponding
1366     // instruction to transform. Instead, this will refer directly to an
1367     // operand in an instruction's operand list.
1368     MIBuilder.addRenderer<CustomOperandRenderer>(*XFormEquivRec, NodeName);
1369   } else {
1370     MIBuilder.addRenderer<CustomRenderer>(*XFormEquivRec, NodeName);
1371   }
1372 
1373   return Error::success();
1374 }
1375 
1376 // Equivalent of MatcherGen::EmitResultInstructionAsOperand.
1377 Error GlobalISelEmitter::importInstructionNodeRenderer(
1378     RuleMatcher &M, BuildMIAction &MIBuilder, const TreePatternNode &N,
1379     action_iterator &InsertPt) const {
1380   Expected<LLTCodeGen> OpTy = getInstResultType(N, Target);
1381   if (!OpTy)
1382     return OpTy.takeError();
1383 
1384   // TODO: See the comment in importXFormNodeRenderer. We rely on the node
1385   //   requiring a temporary register, which prevents us from using this
1386   //   function on the root of the destination DAG.
1387   unsigned TempRegID = M.allocateTempRegID();
1388   InsertPt = M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
1389   MIBuilder.addRenderer<TempRegRenderer>(TempRegID);
1390 
1391   auto InsertPtOrError =
1392       createAndImportSubInstructionRenderer(++InsertPt, M, N, TempRegID);
1393   if (!InsertPtOrError)
1394     return InsertPtOrError.takeError();
1395 
1396   InsertPt = *InsertPtOrError;
1397   return Error::success();
1398 }
1399 
1400 // Equivalent of MatcherGen::EmitResultOperand.
1401 Error GlobalISelEmitter::importNodeRenderer(RuleMatcher &M,
1402                                             BuildMIAction &MIBuilder,
1403                                             const TreePatternNode &N,
1404                                             action_iterator &InsertPt) const {
1405   if (N.hasName())
1406     return importNamedNodeRenderer(M, MIBuilder, N);
1407 
1408   if (N.isLeaf())
1409     return importLeafNodeRenderer(M, MIBuilder, N, InsertPt);
1410 
1411   if (N.getOperator()->isSubClassOf("SDNodeXForm"))
1412     return importXFormNodeRenderer(M, MIBuilder, N);
1413 
1414   if (N.getOperator()->isSubClassOf("Instruction"))
1415     return importInstructionNodeRenderer(M, MIBuilder, N, InsertPt);
1416 
1417   // Should not reach here.
1418   return failedImport("unrecognized node " + llvm::to_string(N));
1419 }
1420 
1421 /// Generates code that builds the resulting instruction(s) from the destination
1422 /// DAG. Note that to do this we do not and should not need the source DAG.
1423 /// We do need to know whether a generated instruction defines a result of the
1424 /// source DAG; this information is available via RuleMatcher::hasOperand.
1425 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
1426     RuleMatcher &M, InstructionMatcher &InsnMatcher,
1427     const TreePatternNode &Dst) const {
1428   auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
1429   if (auto Error = InsertPtOrError.takeError())
1430     return std::move(Error);
1431 
1432   action_iterator InsertPt = InsertPtOrError.get();
1433   BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
1434 
1435   for (auto PhysOp : M.physoperands()) {
1436     InsertPt = M.insertAction<BuildMIAction>(
1437         InsertPt, M.allocateOutputInsnID(),
1438         &Target.getInstruction(RK.getDef("COPY")));
1439     BuildMIAction &CopyToPhysRegMIBuilder =
1440         *static_cast<BuildMIAction *>(InsertPt->get());
1441     CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target,
1442                                                             PhysOp.first, true);
1443     CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysOp.first);
1444   }
1445 
1446   if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst,
1447                                               /*IsRoot=*/true)
1448                        .takeError())
1449     return std::move(Error);
1450 
1451   if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
1452                        .takeError())
1453     return std::move(Error);
1454 
1455   return DstMIBuilder;
1456 }
1457 
1458 Expected<action_iterator>
1459 GlobalISelEmitter::createAndImportSubInstructionRenderer(
1460     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode &Dst,
1461     unsigned TempRegID) const {
1462   auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
1463 
1464   // TODO: Assert there's exactly one result.
1465 
1466   if (auto Error = InsertPtOrError.takeError())
1467     return std::move(Error);
1468 
1469   BuildMIAction &DstMIBuilder =
1470       *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
1471 
1472   // Assign the result to TempReg.
1473   DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
1474 
1475   // Handle additional (ignored) results.
1476   InsertPtOrError = importExplicitDefRenderers(
1477       std::prev(*InsertPtOrError), M, DstMIBuilder, Dst, /*IsRoot=*/false);
1478   if (auto Error = InsertPtOrError.takeError())
1479     return std::move(Error);
1480 
1481   InsertPtOrError =
1482       importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
1483   if (auto Error = InsertPtOrError.takeError())
1484     return std::move(Error);
1485 
1486   if (auto Error =
1487           constrainOperands(InsertPt, M, DstMIBuilder.getInsnID(), Dst))
1488     return std::move(Error);
1489 
1490   return InsertPtOrError.get();
1491 }
1492 
1493 Expected<action_iterator>
1494 GlobalISelEmitter::createInstructionRenderer(action_iterator InsertPt,
1495                                              RuleMatcher &M,
1496                                              const TreePatternNode &Dst) const {
1497   const Record *DstOp = Dst.getOperator();
1498   if (!DstOp->isSubClassOf("Instruction")) {
1499     if (DstOp->isSubClassOf("ValueType"))
1500       return failedImport(
1501           "Pattern operator isn't an instruction (it's a ValueType)");
1502     return failedImport("Pattern operator isn't an instruction");
1503   }
1504   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
1505 
1506   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
1507   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
1508   StringRef Name = DstI->TheDef->getName();
1509   if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
1510     DstI = &Target.getInstruction(RK.getDef("COPY"));
1511 
1512   return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
1513                                        DstI);
1514 }
1515 
1516 Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
1517     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
1518     const TreePatternNode &Dst, bool IsRoot) const {
1519   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
1520 
1521   // Process explicit defs. The caller may have already handled the first def.
1522   for (unsigned I = IsRoot ? 0 : 1, E = DstI->Operands.NumDefs; I != E; ++I) {
1523     const CGIOperandList::OperandInfo &OpInfo = DstI->Operands[I];
1524     std::string OpName = getMangledRootDefName(OpInfo.Name);
1525 
1526     // If the def is used in the source DAG, forward it.
1527     if (IsRoot && M.hasOperand(OpName)) {
1528       // CopyRenderer saves a StringRef, so cannot pass OpName itself -
1529       // let's use a string with an appropriate lifetime.
1530       StringRef PermanentRef = M.getOperandMatcher(OpName).getSymbolicName();
1531       DstMIBuilder.addRenderer<CopyRenderer>(PermanentRef);
1532       continue;
1533     }
1534 
1535     // A discarded explicit def may be an optional physical register.
1536     // If this is the case, add the default register and mark it as dead.
1537     if (OpInfo.Rec->isSubClassOf("OptionalDefOperand")) {
1538       for (const TreePatternNode &DefaultOp :
1539            make_pointee_range(CGP.getDefaultOperand(OpInfo.Rec).DefaultOps)) {
1540         // TODO: Do these checks in ParseDefaultOperands.
1541         if (!DefaultOp.isLeaf())
1542           return failedImport("optional def is not a leaf");
1543 
1544         const auto *RegDI = dyn_cast<DefInit>(DefaultOp.getLeafValue());
1545         if (!RegDI)
1546           return failedImport("optional def is not a record");
1547 
1548         const Record *Reg = RegDI->getDef();
1549         if (!Reg->isSubClassOf("Register") && Reg->getName() != "zero_reg")
1550           return failedImport("optional def is not a register");
1551 
1552         DstMIBuilder.addRenderer<AddRegisterRenderer>(
1553             Target, Reg, /*IsDef=*/true, /*IsDead=*/true);
1554       }
1555       continue;
1556     }
1557 
1558     // The def is discarded, create a dead virtual register for it.
1559     const TypeSetByHwMode &ExtTy = Dst.getExtType(I);
1560     if (!ExtTy.isMachineValueType())
1561       return failedImport("unsupported typeset");
1562 
1563     auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
1564     if (!OpTy)
1565       return failedImport("unsupported type");
1566 
1567     unsigned TempRegID = M.allocateTempRegID();
1568     InsertPt =
1569         M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
1570     DstMIBuilder.addRenderer<TempRegRenderer>(
1571         TempRegID, /*IsDef=*/true, /*SubReg=*/nullptr, /*IsDead=*/true);
1572   }
1573 
1574   // Implicit defs are not currently supported, mark all of them as dead.
1575   for (const Record *Reg : DstI->ImplicitDefs) {
1576     std::string OpName = getMangledRootDefName(Reg->getName());
1577     assert(!M.hasOperand(OpName) && "The pattern should've been rejected");
1578     DstMIBuilder.setDeadImplicitDef(Reg);
1579   }
1580 
1581   return InsertPt;
1582 }
1583 
1584 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
1585     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
1586     const TreePatternNode &Dst) const {
1587   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
1588   CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst.getOperator());
1589 
1590   StringRef Name = OrigDstI->TheDef->getName();
1591   unsigned ExpectedDstINumUses = Dst.getNumChildren();
1592 
1593   // EXTRACT_SUBREG needs to use a subregister COPY.
1594   if (Name == "EXTRACT_SUBREG") {
1595     if (!Dst.getChild(1).isLeaf())
1596       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1597     const DefInit *SubRegInit =
1598         dyn_cast<DefInit>(Dst.getChild(1).getLeafValue());
1599     if (!SubRegInit)
1600       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1601 
1602     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1603     const TreePatternNode &ValChild = Dst.getChild(0);
1604     if (!ValChild.isLeaf()) {
1605       // We really have to handle the source instruction, and then insert a
1606       // copy from the subregister.
1607       auto ExtractSrcTy = getInstResultType(ValChild, Target);
1608       if (!ExtractSrcTy)
1609         return ExtractSrcTy.takeError();
1610 
1611       unsigned TempRegID = M.allocateTempRegID();
1612       InsertPt = M.insertAction<MakeTempRegisterAction>(InsertPt, *ExtractSrcTy,
1613                                                         TempRegID);
1614 
1615       auto InsertPtOrError = createAndImportSubInstructionRenderer(
1616           ++InsertPt, M, ValChild, TempRegID);
1617       if (auto Error = InsertPtOrError.takeError())
1618         return std::move(Error);
1619 
1620       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
1621       return InsertPt;
1622     }
1623 
1624     // If this is a source operand, this is just a subregister copy.
1625     const Record *RCDef = getInitValueAsRegClass(ValChild.getLeafValue());
1626     if (!RCDef)
1627       return failedImport("EXTRACT_SUBREG child #0 could not "
1628                           "be coerced to a register class");
1629 
1630     CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
1631 
1632     const auto SrcRCDstRCPair =
1633         RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1634     if (SrcRCDstRCPair) {
1635       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1636       if (SrcRCDstRCPair->first != RC)
1637         return failedImport("EXTRACT_SUBREG requires an additional COPY");
1638     }
1639 
1640     StringRef RegOperandName = Dst.getChild(0).getName();
1641     if (const auto &SubOperand = M.getComplexSubOperand(RegOperandName)) {
1642       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1643           *std::get<0>(*SubOperand), RegOperandName, std::get<1>(*SubOperand),
1644           std::get<2>(*SubOperand), SubIdx);
1645       return InsertPt;
1646     }
1647 
1648     DstMIBuilder.addRenderer<CopySubRegRenderer>(RegOperandName, SubIdx);
1649     return InsertPt;
1650   }
1651 
1652   if (Name == "REG_SEQUENCE") {
1653     if (!Dst.getChild(0).isLeaf())
1654       return failedImport("REG_SEQUENCE child #0 is not a leaf");
1655 
1656     const Record *RCDef =
1657         getInitValueAsRegClass(Dst.getChild(0).getLeafValue());
1658     if (!RCDef)
1659       return failedImport("REG_SEQUENCE child #0 could not "
1660                           "be coerced to a register class");
1661 
1662     if ((ExpectedDstINumUses - 1) % 2 != 0)
1663       return failedImport("Malformed REG_SEQUENCE");
1664 
1665     for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
1666       const TreePatternNode &ValChild = Dst.getChild(I);
1667       const TreePatternNode &SubRegChild = Dst.getChild(I + 1);
1668 
1669       if (const DefInit *SubRegInit =
1670               dyn_cast<DefInit>(SubRegChild.getLeafValue())) {
1671         CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1672 
1673         if (Error Err = importNodeRenderer(M, DstMIBuilder, ValChild, InsertPt))
1674           return Err;
1675 
1676         DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
1677       }
1678     }
1679 
1680     return InsertPt;
1681   }
1682 
1683   // Render the explicit uses.
1684   unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
1685   if (Name == "COPY_TO_REGCLASS") {
1686     DstINumUses--; // Ignore the class constraint.
1687     ExpectedDstINumUses--;
1688   }
1689 
1690   // NumResults - This is the number of results produced by the instruction in
1691   // the "outs" list.
1692   unsigned NumResults = OrigDstI->Operands.NumDefs;
1693 
1694   // Number of operands we know the output instruction must have. If it is
1695   // variadic, we could have more operands.
1696   unsigned NumFixedOperands = DstI->Operands.size();
1697 
1698   // Loop over all of the fixed operands of the instruction pattern, emitting
1699   // code to fill them all in. The node 'N' usually has number children equal to
1700   // the number of input operands of the instruction.  However, in cases where
1701   // there are predicate operands for an instruction, we need to fill in the
1702   // 'execute always' values. Match up the node operands to the instruction
1703   // operands to do this.
1704   unsigned Child = 0;
1705 
1706   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
1707   // number of operands at the end of the list which have default values.
1708   // Those can come from the pattern if it provides enough arguments, or be
1709   // filled in with the default if the pattern hasn't provided them. But any
1710   // operand with a default value _before_ the last mandatory one will be
1711   // filled in with their defaults unconditionally.
1712   unsigned NonOverridableOperands = NumFixedOperands;
1713   while (NonOverridableOperands > NumResults &&
1714          CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
1715     --NonOverridableOperands;
1716 
1717   unsigned NumDefaultOps = 0;
1718   for (unsigned I = 0; I != DstINumUses; ++I) {
1719     unsigned InstOpNo = DstI->Operands.NumDefs + I;
1720 
1721     // Determine what to emit for this operand.
1722     const Record *OperandNode = DstI->Operands[InstOpNo].Rec;
1723 
1724     // If the operand has default values, introduce them now.
1725     if (CGP.operandHasDefault(OperandNode) &&
1726         (InstOpNo < NonOverridableOperands || Child >= Dst.getNumChildren())) {
1727       // This is a predicate or optional def operand which the pattern has not
1728       // overridden, or which we aren't letting it override; emit the 'default
1729       // ops' operands.
1730       for (const TreePatternNode &OpNode :
1731            make_pointee_range(CGP.getDefaultOperand(OperandNode).DefaultOps)) {
1732         if (Error Err = importNodeRenderer(M, DstMIBuilder, OpNode, InsertPt))
1733           return Err;
1734       }
1735 
1736       ++NumDefaultOps;
1737       continue;
1738     }
1739 
1740     if (Error Err =
1741             importNodeRenderer(M, DstMIBuilder, Dst.getChild(Child), InsertPt))
1742       return Err;
1743 
1744     ++Child;
1745   }
1746 
1747   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
1748     return failedImport("Expected " + llvm::to_string(DstINumUses) +
1749                         " used operands but found " +
1750                         llvm::to_string(ExpectedDstINumUses) +
1751                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
1752                         " default ones");
1753 
1754   return InsertPt;
1755 }
1756 
1757 Error GlobalISelEmitter::importImplicitDefRenderers(
1758     BuildMIAction &DstMIBuilder, ArrayRef<const Record *> ImplicitDefs) const {
1759   if (!ImplicitDefs.empty())
1760     return failedImport("Pattern defines a physical register");
1761   return Error::success();
1762 }
1763 
1764 Error GlobalISelEmitter::constrainOperands(action_iterator InsertPt,
1765                                            RuleMatcher &M, unsigned InsnID,
1766                                            const TreePatternNode &Dst) const {
1767   const Record *DstOp = Dst.getOperator();
1768   const CodeGenInstruction &DstI = Target.getInstruction(DstOp);
1769   StringRef DstIName = DstI.TheDef->getName();
1770 
1771   if (DstIName == "COPY_TO_REGCLASS") {
1772     // COPY_TO_REGCLASS does not provide operand constraints itself but the
1773     // result is constrained to the class given by the second child.
1774     const Record *DstIOpRec =
1775         getInitValueAsRegClass(Dst.getChild(1).getLeafValue());
1776 
1777     if (DstIOpRec == nullptr)
1778       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
1779 
1780     M.insertAction<ConstrainOperandToRegClassAction>(
1781         InsertPt, InsnID, 0, Target.getRegisterClass(DstIOpRec));
1782   } else if (DstIName == "EXTRACT_SUBREG") {
1783     const CodeGenRegisterClass *SuperClass =
1784         inferRegClassFromPattern(Dst.getChild(0));
1785     if (!SuperClass)
1786       return failedImport(
1787           "Cannot infer register class from EXTRACT_SUBREG operand #0");
1788 
1789     const CodeGenSubRegIndex *SubIdx = inferSubRegIndexForNode(Dst.getChild(1));
1790     if (!SubIdx)
1791       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1792 
1793     // It would be nice to leave this constraint implicit but we're required
1794     // to pick a register class so constrain the result to a register class
1795     // that can hold the correct MVT.
1796     //
1797     // FIXME: This may introduce an extra copy if the chosen class doesn't
1798     //        actually contain the subregisters.
1799     const auto SrcRCDstRCPair =
1800         SuperClass->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1801     if (!SrcRCDstRCPair) {
1802       return failedImport("subreg index is incompatible "
1803                           "with inferred reg class");
1804     }
1805 
1806     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1807     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 0,
1808                                                      *SrcRCDstRCPair->second);
1809     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 1,
1810                                                      *SrcRCDstRCPair->first);
1811   } else if (DstIName == "INSERT_SUBREG") {
1812     // We need to constrain the destination, a super regsister source, and a
1813     // subregister source.
1814     const CodeGenRegisterClass *SubClass =
1815         inferRegClassFromPattern(Dst.getChild(1));
1816     if (!SubClass)
1817       return failedImport(
1818           "Cannot infer register class from INSERT_SUBREG operand #1");
1819     const CodeGenRegisterClass *SuperClass = inferSuperRegisterClassForNode(
1820         Dst.getExtType(0), Dst.getChild(0), Dst.getChild(2));
1821     if (!SuperClass)
1822       return failedImport(
1823           "Cannot infer register class for INSERT_SUBREG operand #0");
1824     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 0,
1825                                                      *SuperClass);
1826     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 1,
1827                                                      *SuperClass);
1828     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 2,
1829                                                      *SubClass);
1830   } else if (DstIName == "SUBREG_TO_REG") {
1831     // We need to constrain the destination and subregister source.
1832     // Attempt to infer the subregister source from the first child. If it has
1833     // an explicitly given register class, we'll use that. Otherwise, we will
1834     // fail.
1835     const CodeGenRegisterClass *SubClass =
1836         inferRegClassFromPattern(Dst.getChild(1));
1837     if (!SubClass)
1838       return failedImport(
1839           "Cannot infer register class from SUBREG_TO_REG child #1");
1840     // We don't have a child to look at that might have a super register node.
1841     const CodeGenRegisterClass *SuperClass =
1842         inferSuperRegisterClass(Dst.getExtType(0), Dst.getChild(2));
1843     if (!SuperClass)
1844       return failedImport(
1845           "Cannot infer register class for SUBREG_TO_REG operand #0");
1846     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 0,
1847                                                      *SuperClass);
1848     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 2,
1849                                                      *SubClass);
1850   } else if (DstIName == "REG_SEQUENCE") {
1851     const CodeGenRegisterClass *SuperClass =
1852         inferRegClassFromPattern(Dst.getChild(0));
1853 
1854     M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, 0,
1855                                                      *SuperClass);
1856 
1857     unsigned Num = Dst.getNumChildren();
1858     for (unsigned I = 1; I != Num; I += 2) {
1859       const TreePatternNode &SubRegChild = Dst.getChild(I + 1);
1860 
1861       const CodeGenSubRegIndex *SubIdx = inferSubRegIndexForNode(SubRegChild);
1862       if (!SubIdx)
1863         return failedImport("REG_SEQUENCE child is not a subreg index");
1864 
1865       const auto SrcRCDstRCPair =
1866           SuperClass->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1867 
1868       M.insertAction<ConstrainOperandToRegClassAction>(InsertPt, InsnID, I,
1869                                                        *SrcRCDstRCPair->second);
1870     }
1871   } else {
1872     M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt, InsnID);
1873   }
1874 
1875   return Error::success();
1876 }
1877 
1878 const CodeGenRegisterClass *
1879 GlobalISelEmitter::getRegClassFromLeaf(const TreePatternNode &Leaf) const {
1880   assert(Leaf.isLeaf() && "Expected leaf?");
1881   const Record *RCRec = getInitValueAsRegClass(Leaf.getLeafValue());
1882   if (!RCRec)
1883     return nullptr;
1884   return CGRegs.getRegClass(RCRec);
1885 }
1886 
1887 const CodeGenRegisterClass *
1888 GlobalISelEmitter::inferRegClassFromPattern(const TreePatternNode &N) const {
1889   if (N.isLeaf())
1890     return getRegClassFromLeaf(N);
1891 
1892   // We don't have a leaf node, so we have to try and infer something. Check
1893   // that we have an instruction that we can infer something from.
1894 
1895   // Only handle things that produce at least one value (if multiple values,
1896   // just take the first one).
1897   if (N.getNumTypes() < 1)
1898     return nullptr;
1899   const Record *OpRec = N.getOperator();
1900 
1901   // We only want instructions.
1902   if (!OpRec->isSubClassOf("Instruction"))
1903     return nullptr;
1904 
1905   // Don't want to try and infer things when there could potentially be more
1906   // than one candidate register class.
1907   return inferRegClassFromInstructionPattern(N, /*ResIdx=*/0);
1908 }
1909 
1910 const CodeGenRegisterClass *
1911 GlobalISelEmitter::inferRegClassFromInstructionPattern(const TreePatternNode &N,
1912                                                        unsigned ResIdx) const {
1913   const CodeGenInstruction &Inst = Target.getInstruction(N.getOperator());
1914   assert(ResIdx < Inst.Operands.NumDefs &&
1915          "Can only infer register class for explicit defs");
1916 
1917   // Handle any special-case instructions which we can safely infer register
1918   // classes from.
1919   StringRef InstName = Inst.TheDef->getName();
1920   if (InstName == "REG_SEQUENCE") {
1921     // (outs $super_dst), (ins $dst_regclass, variable_ops)
1922     // Destination register class is explicitly specified by the first operand.
1923     const TreePatternNode &RCChild = N.getChild(0);
1924     if (!RCChild.isLeaf())
1925       return nullptr;
1926     return getRegClassFromLeaf(RCChild);
1927   }
1928 
1929   if (InstName == "COPY_TO_REGCLASS") {
1930     // (outs $dst), (ins $src, $dst_regclass)
1931     // Destination register class is explicitly specified by the second operand.
1932     const TreePatternNode &RCChild = N.getChild(1);
1933     if (!RCChild.isLeaf())
1934       return nullptr;
1935     return getRegClassFromLeaf(RCChild);
1936   }
1937 
1938   if (InstName == "INSERT_SUBREG") {
1939     // (outs $super_dst), (ins $super_src, $sub_src, $sub_idx);
1940     // If we can infer the register class for the first operand, use that.
1941     // Otherwise, find a register class that supports both the specified
1942     // sub-register index and the type of the instruction's result.
1943     const TreePatternNode &Child0 = N.getChild(0);
1944     assert(Child0.getNumTypes() == 1 && "Unexpected number of types!");
1945     return inferSuperRegisterClassForNode(N.getExtType(0), Child0,
1946                                           N.getChild(2));
1947   }
1948 
1949   if (InstName == "EXTRACT_SUBREG") {
1950     // (outs $sub_dst), (ins $super_src, $sub_idx)
1951     // Find a register class that can be used for a sub-register copy from
1952     // the specified source at the specified sub-register index.
1953     const CodeGenRegisterClass *SuperRC =
1954         inferRegClassFromPattern(N.getChild(0));
1955     if (!SuperRC)
1956       return nullptr;
1957 
1958     const CodeGenSubRegIndex *SubIdx = inferSubRegIndexForNode(N.getChild(1));
1959     if (!SubIdx)
1960       return nullptr;
1961 
1962     const auto SubRCAndSubRegRC =
1963         SuperRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1964     if (!SubRCAndSubRegRC)
1965       return nullptr;
1966 
1967     return SubRCAndSubRegRC->second;
1968   }
1969 
1970   if (InstName == "SUBREG_TO_REG") {
1971     // (outs $super_dst), (ins $super_src, $sub_src, $sub_idx)
1972     // Find a register class that supports both the specified sub-register
1973     // index and the type of the instruction's result.
1974     return inferSuperRegisterClass(N.getExtType(0), N.getChild(2));
1975   }
1976 
1977   // Handle destination record types that we can safely infer a register class
1978   // from.
1979   const auto &DstIOperand = Inst.Operands[ResIdx];
1980   const Record *DstIOpRec = DstIOperand.Rec;
1981   if (DstIOpRec->isSubClassOf("RegisterOperand"))
1982     return &Target.getRegisterClass(DstIOpRec->getValueAsDef("RegClass"));
1983 
1984   if (DstIOpRec->isSubClassOf("RegisterClass"))
1985     return &Target.getRegisterClass(DstIOpRec);
1986 
1987   return nullptr;
1988 }
1989 
1990 const CodeGenRegisterClass *GlobalISelEmitter::inferSuperRegisterClass(
1991     const TypeSetByHwMode &Ty, const TreePatternNode &SubRegIdxNode) const {
1992   // We need a ValueTypeByHwMode for getSuperRegForSubReg.
1993   if (!Ty.isValueTypeByHwMode(false))
1994     return nullptr;
1995   if (!SubRegIdxNode.isLeaf())
1996     return nullptr;
1997   const DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode.getLeafValue());
1998   if (!SubRegInit)
1999     return nullptr;
2000   const CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2001 
2002   // Use the information we found above to find a minimal register class which
2003   // supports the subregister and type we want.
2004   return Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx,
2005                                      /*MustBeAllocatable=*/true);
2006 }
2007 
2008 const CodeGenRegisterClass *GlobalISelEmitter::inferSuperRegisterClassForNode(
2009     const TypeSetByHwMode &Ty, const TreePatternNode &SuperRegNode,
2010     const TreePatternNode &SubRegIdxNode) const {
2011   // Check if we already have a defined register class for the super register
2012   // node. If we do, then we should preserve that rather than inferring anything
2013   // from the subregister index node. We can assume that whoever wrote the
2014   // pattern in the first place made sure that the super register and
2015   // subregister are compatible.
2016   if (const CodeGenRegisterClass *SuperRegisterClass =
2017           inferRegClassFromPattern(SuperRegNode))
2018     return SuperRegisterClass;
2019   return inferSuperRegisterClass(Ty, SubRegIdxNode);
2020 }
2021 
2022 const CodeGenSubRegIndex *GlobalISelEmitter::inferSubRegIndexForNode(
2023     const TreePatternNode &SubRegIdxNode) const {
2024   if (!SubRegIdxNode.isLeaf())
2025     return nullptr;
2026 
2027   const DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode.getLeafValue());
2028   if (!SubRegInit)
2029     return nullptr;
2030   return CGRegs.getSubRegIdx(SubRegInit->getDef());
2031 }
2032 
2033 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
2034   // Keep track of the matchers and actions to emit.
2035   int Score = P.getPatternComplexity(CGP);
2036   RuleMatcher M(P.getSrcRecord()->getLoc());
2037   RuleMatcherScores[M.getRuleID()] = Score;
2038   M.addAction<DebugCommentAction>(llvm::to_string(P.getSrcPattern()) +
2039                                   "  =>  " +
2040                                   llvm::to_string(P.getDstPattern()));
2041 
2042   SmallVector<const Record *, 4> Predicates;
2043   P.getPredicateRecords(Predicates);
2044   if (auto Error = importRulePredicates(M, Predicates))
2045     return std::move(Error);
2046 
2047   if (!P.getHwModeFeatures().empty())
2048     M.addHwModeIdx(declareHwModeCheck(P.getHwModeFeatures()));
2049 
2050   // Next, analyze the pattern operators.
2051   TreePatternNode &Src = P.getSrcPattern();
2052   TreePatternNode &Dst = P.getDstPattern();
2053 
2054   // If the root of either pattern isn't a simple operator, ignore it.
2055   if (auto Err = isTrivialOperatorNode(Dst))
2056     return failedImport("Dst pattern root isn't a trivial operator (" +
2057                         toString(std::move(Err)) + ")");
2058   if (auto Err = isTrivialOperatorNode(Src))
2059     return failedImport("Src pattern root isn't a trivial operator (" +
2060                         toString(std::move(Err)) + ")");
2061 
2062   // The different predicates and matchers created during
2063   // addInstructionMatcher use the RuleMatcher M to set up their
2064   // instruction ID (InsnVarID) that are going to be used when
2065   // M is going to be emitted.
2066   // However, the code doing the emission still relies on the IDs
2067   // returned during that process by the RuleMatcher when issuing
2068   // the recordInsn opcodes.
2069   // Because of that:
2070   // 1. The order in which we created the predicates
2071   //    and such must be the same as the order in which we emit them,
2072   //    and
2073   // 2. We need to reset the generation of the IDs in M somewhere between
2074   //    addInstructionMatcher and emit
2075   //
2076   // FIXME: Long term, we don't want to have to rely on this implicit
2077   // naming being the same. One possible solution would be to have
2078   // explicit operator for operation capture and reference those.
2079   // The plus side is that it would expose opportunities to share
2080   // the capture accross rules. The downside is that it would
2081   // introduce a dependency between predicates (captures must happen
2082   // before their first use.)
2083   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src.getName());
2084   unsigned TempOpIdx = 0;
2085 
2086   const auto SavedFlags = M.setGISelFlags(P.getSrcRecord());
2087 
2088   auto InsnMatcherOrError =
2089       createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
2090   if (auto Error = InsnMatcherOrError.takeError())
2091     return std::move(Error);
2092   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2093 
2094   if (Dst.isLeaf()) {
2095     if (const Record *RCDef = getInitValueAsRegClass(Dst.getLeafValue())) {
2096       const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2097 
2098       // We need to replace the def and all its uses with the specified
2099       // operand. However, we must also insert COPY's wherever needed.
2100       // For now, emit a copy and let the register allocator clean up.
2101       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2102       const auto &DstIOperand = DstI.Operands[0];
2103 
2104       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2105       OM0.setSymbolicName(DstIOperand.Name);
2106       M.defineOperand(OM0.getSymbolicName(), OM0);
2107       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2108 
2109       auto &DstMIBuilder =
2110           M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
2111       DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
2112       DstMIBuilder.addRenderer<CopyRenderer>(Dst.getName());
2113       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2114 
2115       // Erase the root.
2116       unsigned RootInsnID = M.getInsnVarID(InsnMatcher);
2117       M.addAction<EraseInstAction>(RootInsnID);
2118 
2119       // We're done with this pattern!  It's eligible for GISel emission; return
2120       // it.
2121       ++NumPatternImported;
2122       return std::move(M);
2123     }
2124 
2125     return failedImport("Dst pattern root isn't a known leaf");
2126   }
2127 
2128   // Start with the defined operands (i.e., the results of the root operator).
2129   const Record *DstOp = Dst.getOperator();
2130   if (!DstOp->isSubClassOf("Instruction"))
2131     return failedImport("Pattern operator isn't an instruction");
2132 
2133   const CodeGenInstruction &DstI = Target.getInstruction(DstOp);
2134 
2135   // Count both implicit and explicit defs in the dst instruction.
2136   // This avoids errors importing patterns that have inherent implicit defs.
2137   unsigned DstExpDefs = DstI.Operands.NumDefs,
2138            DstNumDefs = DstI.ImplicitDefs.size() + DstExpDefs,
2139            SrcNumDefs = Src.getExtTypes().size();
2140   if (DstNumDefs < SrcNumDefs) {
2141     if (DstNumDefs != 0)
2142       return failedImport("Src pattern result has more defs than dst MI (" +
2143                           to_string(SrcNumDefs) + " def(s) vs " +
2144                           to_string(DstNumDefs) + " def(s))");
2145 
2146     bool FoundNoUsePred = false;
2147     for (const auto &Pred : InsnMatcher.predicates()) {
2148       if ((FoundNoUsePred = isa<NoUsePredicateMatcher>(Pred.get())))
2149         break;
2150     }
2151     if (!FoundNoUsePred)
2152       return failedImport("Src pattern result has " + to_string(SrcNumDefs) +
2153                           " def(s) without the HasNoUse predicate set to true "
2154                           "but Dst MI has no def");
2155   }
2156 
2157   // The root of the match also has constraints on the register bank so that it
2158   // matches the result instruction.
2159   unsigned N = std::min(DstExpDefs, SrcNumDefs);
2160   for (unsigned I = 0; I < N; ++I) {
2161     const auto &DstIOperand = DstI.Operands[I];
2162 
2163     OperandMatcher &OM = InsnMatcher.getOperand(I);
2164     // The operand names declared in the DstI instruction are unrelated to
2165     // those used in pattern's source and destination DAGs, so mangle the
2166     // former to prevent implicitly adding unexpected
2167     // GIM_CheckIsSameOperand predicates by the defineOperand method.
2168     OM.setSymbolicName(getMangledRootDefName(DstIOperand.Name));
2169     M.defineOperand(OM.getSymbolicName(), OM);
2170 
2171     const CodeGenRegisterClass *RC =
2172         inferRegClassFromInstructionPattern(Dst, I);
2173     if (!RC)
2174       return failedImport("Could not infer register class for result #" +
2175                           Twine(I) + " from pattern " + to_string(Dst));
2176     OM.addPredicate<RegisterBankOperandMatcher>(*RC);
2177   }
2178 
2179   auto DstMIBuilderOrError =
2180       createAndImportInstructionRenderer(M, InsnMatcher, Dst);
2181   if (auto Error = DstMIBuilderOrError.takeError())
2182     return std::move(Error);
2183   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
2184 
2185   // Render the implicit defs.
2186   // These are only added to the root of the result.
2187   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
2188     return std::move(Error);
2189 
2190   DstMIBuilder.chooseInsnToMutate(M);
2191 
2192   // Constrain the registers to classes. This is normally derived from the
2193   // emitted instruction but a few instructions require special handling.
2194   if (auto Error =
2195           constrainOperands(M.actions_end(), M, DstMIBuilder.getInsnID(), Dst))
2196     return std::move(Error);
2197 
2198   // Erase the root.
2199   unsigned RootInsnID = M.getInsnVarID(InsnMatcher);
2200   M.addAction<EraseInstAction>(RootInsnID);
2201 
2202   // We're done with this pattern!  It's eligible for GISel emission; return it.
2203   ++NumPatternImported;
2204   return std::move(M);
2205 }
2206 
2207 MatchTable
2208 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
2209                                    bool Optimize, bool WithCoverage) {
2210   std::vector<Matcher *> InputRules;
2211   for (Matcher &Rule : Rules)
2212     InputRules.push_back(&Rule);
2213 
2214   if (!Optimize)
2215     return MatchTable::buildTable(InputRules, WithCoverage);
2216 
2217   unsigned CurrentOrdering = 0;
2218   StringMap<unsigned> OpcodeOrder;
2219   for (RuleMatcher &Rule : Rules) {
2220     const StringRef Opcode = Rule.getOpcode();
2221     assert(!Opcode.empty() && "Didn't expect an undefined opcode");
2222     if (OpcodeOrder.try_emplace(Opcode, CurrentOrdering).second)
2223       ++CurrentOrdering;
2224   }
2225 
2226   llvm::stable_sort(
2227       InputRules, [&OpcodeOrder](const Matcher *A, const Matcher *B) {
2228         auto *L = static_cast<const RuleMatcher *>(A);
2229         auto *R = static_cast<const RuleMatcher *>(B);
2230         return std::tuple(OpcodeOrder[L->getOpcode()],
2231                           L->insnmatchers_front().getNumOperandMatchers()) <
2232                std::tuple(OpcodeOrder[R->getOpcode()],
2233                           R->insnmatchers_front().getNumOperandMatchers());
2234       });
2235 
2236   for (Matcher *Rule : InputRules)
2237     Rule->optimize();
2238 
2239   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
2240   std::vector<Matcher *> OptRules =
2241       optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
2242 
2243   for (Matcher *Rule : OptRules)
2244     Rule->optimize();
2245 
2246   OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
2247 
2248   return MatchTable::buildTable(OptRules, WithCoverage);
2249 }
2250 
2251 void GlobalISelEmitter::emitAdditionalImpl(raw_ostream &OS) {
2252   OS << "bool " << getClassName()
2253      << "::selectImpl(MachineInstr &I, CodeGenCoverage "
2254         "&CoverageInfo) const {\n"
2255      << "  const PredicateBitset AvailableFeatures = "
2256         "getAvailableFeatures();\n"
2257      << "  MachineIRBuilder B(I);\n"
2258      << "  State.MIs.clear();\n"
2259      << "  State.MIs.push_back(&I);\n\n"
2260      << "  if (executeMatchTable(*this, State, ExecInfo, B"
2261      << ", getMatchTable(), TII, MF->getRegInfo(), TRI, RBI, AvailableFeatures"
2262      << ", &CoverageInfo)) {\n"
2263      << "    return true;\n"
2264      << "  }\n\n"
2265      << "  return false;\n"
2266      << "}\n\n";
2267 }
2268 
2269 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
2270   std::vector<const Record *> MatchedRecords;
2271   std::copy_if(AllPatFrags.begin(), AllPatFrags.end(),
2272                std::back_inserter(MatchedRecords), [](const Record *R) {
2273                  return !R->getValueAsString("GISelPredicateCode").empty();
2274                });
2275   emitMIPredicateFnsImpl<const Record *>(
2276       OS,
2277       "  const MachineFunction &MF = *MI.getParent()->getParent();\n"
2278       "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2279       "  const auto &Operands = State.RecordedOperands;\n"
2280       "  (void)Operands;\n"
2281       "  (void)MRI;",
2282       ArrayRef<const Record *>(MatchedRecords), &getPatFragPredicateEnumName,
2283       [](const Record *R) { return R->getValueAsString("GISelPredicateCode"); },
2284       "PatFrag predicates.");
2285 }
2286 
2287 void GlobalISelEmitter::emitI64ImmPredicateFns(raw_ostream &OS) {
2288   std::vector<const Record *> MatchedRecords;
2289   std::copy_if(AllPatFrags.begin(), AllPatFrags.end(),
2290                std::back_inserter(MatchedRecords), [](const Record *R) {
2291                  bool Unset;
2292                  return !R->getValueAsString("ImmediateCode").empty() &&
2293                         !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
2294                         !R->getValueAsBit("IsAPInt");
2295                });
2296   emitImmPredicateFnsImpl<const Record *>(
2297       OS, "I64", "int64_t", ArrayRef<const Record *>(MatchedRecords),
2298       &getPatFragPredicateEnumName,
2299       [](const Record *R) { return R->getValueAsString("ImmediateCode"); },
2300       "PatFrag predicates.");
2301 }
2302 
2303 void GlobalISelEmitter::emitAPFloatImmPredicateFns(raw_ostream &OS) {
2304   std::vector<const Record *> MatchedRecords;
2305   std::copy_if(AllPatFrags.begin(), AllPatFrags.end(),
2306                std::back_inserter(MatchedRecords), [](const Record *R) {
2307                  bool Unset;
2308                  return !R->getValueAsString("ImmediateCode").empty() &&
2309                         R->getValueAsBitOrUnset("IsAPFloat", Unset);
2310                });
2311   emitImmPredicateFnsImpl<const Record *>(
2312       OS, "APFloat", "const APFloat &",
2313       ArrayRef<const Record *>(MatchedRecords), &getPatFragPredicateEnumName,
2314       [](const Record *R) { return R->getValueAsString("ImmediateCode"); },
2315       "PatFrag predicates.");
2316 }
2317 
2318 void GlobalISelEmitter::emitAPIntImmPredicateFns(raw_ostream &OS) {
2319   std::vector<const Record *> MatchedRecords;
2320   std::copy_if(AllPatFrags.begin(), AllPatFrags.end(),
2321                std::back_inserter(MatchedRecords), [](const Record *R) {
2322                  return !R->getValueAsString("ImmediateCode").empty() &&
2323                         R->getValueAsBit("IsAPInt");
2324                });
2325   emitImmPredicateFnsImpl<const Record *>(
2326       OS, "APInt", "const APInt &", ArrayRef<const Record *>(MatchedRecords),
2327       &getPatFragPredicateEnumName,
2328       [](const Record *R) { return R->getValueAsString("ImmediateCode"); },
2329       "PatFrag predicates.");
2330 }
2331 
2332 void GlobalISelEmitter::emitTestSimplePredicate(raw_ostream &OS) {
2333   OS << "bool " << getClassName() << "::testSimplePredicate(unsigned) const {\n"
2334      << "    llvm_unreachable(\"" + getClassName() +
2335             " does not support simple predicates!\");\n"
2336      << "  return false;\n"
2337      << "}\n";
2338 }
2339 
2340 void GlobalISelEmitter::emitRunCustomAction(raw_ostream &OS) {
2341   OS << "bool " << getClassName()
2342      << "::runCustomAction(unsigned, const MatcherState&, NewMIVector &) const "
2343         "{\n"
2344      << "    llvm_unreachable(\"" + getClassName() +
2345             " does not support custom C++ actions!\");\n"
2346      << "}\n";
2347 }
2348 
2349 bool hasBFloatType(const TreePatternNode &Node) {
2350   for (unsigned I = 0, E = Node.getNumTypes(); I < E; I++) {
2351     auto Ty = Node.getType(I);
2352     for (auto T : Ty)
2353       if (T.second == MVT::bf16 ||
2354           (T.second.isVector() && T.second.getScalarType() == MVT::bf16))
2355         return true;
2356   }
2357   for (const TreePatternNode &C : Node.children())
2358     if (hasBFloatType(C))
2359       return true;
2360   return false;
2361 }
2362 
2363 void GlobalISelEmitter::run(raw_ostream &OS) {
2364   if (!UseCoverageFile.empty()) {
2365     RuleCoverage = CodeGenCoverage();
2366     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
2367     if (!RuleCoverageBufOrErr) {
2368       PrintWarning(SMLoc(), "Missing rule coverage data");
2369       RuleCoverage = std::nullopt;
2370     } else {
2371       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
2372         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
2373         RuleCoverage = std::nullopt;
2374       }
2375     }
2376   }
2377 
2378   // Track the run-time opcode values
2379   gatherOpcodeValues();
2380   // Track the run-time LLT ID values
2381   gatherTypeIDValues();
2382 
2383   // Track the GINodeEquiv definitions.
2384   gatherNodeEquivs();
2385 
2386   AllPatFrags = RK.getAllDerivedDefinitions("PatFrags");
2387 
2388   emitSourceFileHeader(
2389       ("Global Instruction Selector for the " + Target.getName() + " target")
2390           .str(),
2391       OS);
2392   std::vector<RuleMatcher> Rules;
2393   // Look through the SelectionDAG patterns we found, possibly emitting some.
2394   for (const PatternToMatch &Pat : CGP.ptms()) {
2395     ++NumPatternTotal;
2396 
2397     if (Pat.getGISelShouldIgnore())
2398       continue; // skip without warning
2399 
2400     // Skip any patterns containing BF16 types, as GISel cannot currently tell
2401     // the difference between fp16 and bf16. FIXME: This can be removed once
2402     // BF16 is supported properly.
2403     if (hasBFloatType(Pat.getSrcPattern()))
2404       continue;
2405 
2406     auto MatcherOrErr = runOnPattern(Pat);
2407 
2408     // The pattern analysis can fail, indicating an unsupported pattern.
2409     // Report that if we've been asked to do so.
2410     if (auto Err = MatcherOrErr.takeError()) {
2411       if (WarnOnSkippedPatterns) {
2412         PrintWarning(Pat.getSrcRecord()->getLoc(),
2413                      "Skipped pattern: " + toString(std::move(Err)));
2414       } else {
2415         consumeError(std::move(Err));
2416       }
2417       ++NumPatternImportsSkipped;
2418       continue;
2419     }
2420 
2421     if (RuleCoverage) {
2422       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
2423         ++NumPatternsTested;
2424       else
2425         PrintWarning(Pat.getSrcRecord()->getLoc(),
2426                      "Pattern is not covered by a test");
2427     }
2428     Rules.push_back(std::move(MatcherOrErr.get()));
2429   }
2430 
2431   // Comparison function to order records by name.
2432   auto OrderByName = [](const Record *A, const Record *B) {
2433     return A->getName() < B->getName();
2434   };
2435 
2436   std::vector<const Record *> ComplexPredicates =
2437       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2438   llvm::sort(ComplexPredicates, OrderByName);
2439 
2440   std::vector<StringRef> CustomRendererFns;
2441   transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"),
2442             std::back_inserter(CustomRendererFns), [](const auto &Record) {
2443               return Record->getValueAsString("RendererFn");
2444             });
2445   // Sort and remove duplicates to get a list of unique renderer functions, in
2446   // case some were mentioned more than once.
2447   llvm::sort(CustomRendererFns);
2448   CustomRendererFns.erase(llvm::unique(CustomRendererFns),
2449                           CustomRendererFns.end());
2450 
2451   // Create a table containing the LLT objects needed by the matcher and an enum
2452   // for the matcher to reference them with.
2453   std::vector<LLTCodeGen> TypeObjects;
2454   append_range(TypeObjects, KnownTypes);
2455   llvm::sort(TypeObjects);
2456 
2457   // Sort rules.
2458   llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
2459     int ScoreA = RuleMatcherScores[A.getRuleID()];
2460     int ScoreB = RuleMatcherScores[B.getRuleID()];
2461     if (ScoreA > ScoreB)
2462       return true;
2463     if (ScoreB > ScoreA)
2464       return false;
2465     if (A.isHigherPriorityThan(B)) {
2466       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2467                                            "and less important at "
2468                                            "the same time");
2469       return true;
2470     }
2471     return false;
2472   });
2473 
2474   unsigned MaxTemporaries = 0;
2475   for (const auto &Rule : Rules)
2476     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
2477 
2478   // Build match table
2479   const MatchTable Table =
2480       buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
2481 
2482   emitPredicateBitset(OS, "GET_GLOBALISEL_PREDICATE_BITSET");
2483   emitTemporariesDecl(OS, "GET_GLOBALISEL_TEMPORARIES_DECL");
2484   emitTemporariesInit(OS, MaxTemporaries, "GET_GLOBALISEL_TEMPORARIES_INIT");
2485   emitExecutorImpl(OS, Table, TypeObjects, Rules, ComplexPredicates,
2486                    CustomRendererFns, "GET_GLOBALISEL_IMPL");
2487   emitPredicatesDecl(OS, "GET_GLOBALISEL_PREDICATES_DECL");
2488   emitPredicatesInit(OS, "GET_GLOBALISEL_PREDICATES_INIT");
2489 }
2490 
2491 void GlobalISelEmitter::declareSubtargetFeature(const Record *Predicate) {
2492   SubtargetFeatures.try_emplace(Predicate, Predicate, SubtargetFeatures.size());
2493 }
2494 
2495 unsigned GlobalISelEmitter::declareHwModeCheck(StringRef HwModeFeatures) {
2496   return HwModes.emplace(HwModeFeatures.str(), HwModes.size()).first->second;
2497 }
2498 
2499 } // end anonymous namespace
2500 
2501 //===----------------------------------------------------------------------===//
2502 
2503 static TableGen::Emitter::OptClass<GlobalISelEmitter>
2504     X("gen-global-isel", "Generate GlobalISel selector");
2505