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