1 //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===// 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 // This file defines the RAGreedy function pass for register allocation in 10 // optimized builds. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AllocationOrder.h" 15 #include "InterferenceCache.h" 16 #include "LiveDebugVariables.h" 17 #include "RegAllocBase.h" 18 #include "SpillPlacement.h" 19 #include "SplitKit.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/BitVector.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/IndexedMap.h" 24 #include "llvm/ADT/MapVector.h" 25 #include "llvm/ADT/SetVector.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/Analysis/AliasAnalysis.h" 32 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 33 #include "llvm/CodeGen/CalcSpillWeights.h" 34 #include "llvm/CodeGen/EdgeBundles.h" 35 #include "llvm/CodeGen/LiveInterval.h" 36 #include "llvm/CodeGen/LiveIntervalUnion.h" 37 #include "llvm/CodeGen/LiveIntervals.h" 38 #include "llvm/CodeGen/LiveRangeEdit.h" 39 #include "llvm/CodeGen/LiveRegMatrix.h" 40 #include "llvm/CodeGen/LiveStacks.h" 41 #include "llvm/CodeGen/MachineBasicBlock.h" 42 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 43 #include "llvm/CodeGen/MachineDominators.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineFunctionPass.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineOperand.h" 50 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RegAllocRegistry.h" 53 #include "llvm/CodeGen/RegisterClassInfo.h" 54 #include "llvm/CodeGen/SlotIndexes.h" 55 #include "llvm/CodeGen/Spiller.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetRegisterInfo.h" 58 #include "llvm/CodeGen/TargetSubtargetInfo.h" 59 #include "llvm/CodeGen/VirtRegMap.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/LLVMContext.h" 62 #include "llvm/MC/MCRegisterInfo.h" 63 #include "llvm/Pass.h" 64 #include "llvm/Support/BlockFrequency.h" 65 #include "llvm/Support/BranchProbability.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Support/MathExtras.h" 69 #include "llvm/Support/Timer.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include "llvm/Target/TargetMachine.h" 72 #include "llvm/IR/DebugInfoMetadata.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <memory> 77 #include <queue> 78 #include <tuple> 79 #include <utility> 80 81 using namespace llvm; 82 83 #define DEBUG_TYPE "regalloc" 84 85 STATISTIC(NumGlobalSplits, "Number of split global live ranges"); 86 STATISTIC(NumLocalSplits, "Number of split local live ranges"); 87 STATISTIC(NumEvicted, "Number of interferences evicted"); 88 89 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode( 90 "split-spill-mode", cl::Hidden, 91 cl::desc("Spill mode for splitting live ranges"), 92 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"), 93 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"), 94 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")), 95 cl::init(SplitEditor::SM_Speed)); 96 97 static cl::opt<unsigned> 98 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden, 99 cl::desc("Last chance recoloring max depth"), 100 cl::init(5)); 101 102 static cl::opt<unsigned> LastChanceRecoloringMaxInterference( 103 "lcr-max-interf", cl::Hidden, 104 cl::desc("Last chance recoloring maximum number of considered" 105 " interference at a time"), 106 cl::init(8)); 107 108 static cl::opt<bool> ExhaustiveSearch( 109 "exhaustive-register-search", cl::NotHidden, 110 cl::desc("Exhaustive Search for registers bypassing the depth " 111 "and interference cutoffs of last chance recoloring"), 112 cl::Hidden); 113 114 static cl::opt<bool> EnableLocalReassignment( 115 "enable-local-reassign", cl::Hidden, 116 cl::desc("Local reassignment can yield better allocation decisions, but " 117 "may be compile time intensive"), 118 cl::init(false)); 119 120 static cl::opt<bool> EnableDeferredSpilling( 121 "enable-deferred-spilling", cl::Hidden, 122 cl::desc("Instead of spilling a variable right away, defer the actual " 123 "code insertion to the end of the allocation. That way the " 124 "allocator might still find a suitable coloring for this " 125 "variable because of other evicted variables."), 126 cl::init(false)); 127 128 // FIXME: Find a good default for this flag and remove the flag. 129 static cl::opt<unsigned> 130 CSRFirstTimeCost("regalloc-csr-first-time-cost", 131 cl::desc("Cost for first time use of callee-saved register."), 132 cl::init(0), cl::Hidden); 133 134 static cl::opt<bool> ConsiderLocalIntervalCost( 135 "consider-local-interval-cost", cl::Hidden, 136 cl::desc("Consider the cost of local intervals created by a split " 137 "candidate when choosing the best split candidate."), 138 cl::init(false)); 139 140 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator", 141 createGreedyRegisterAllocator); 142 143 namespace { 144 145 class RAGreedy : public MachineFunctionPass, 146 public RegAllocBase, 147 private LiveRangeEdit::Delegate { 148 // Convenient shortcuts. 149 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>; 150 using SmallLISet = SmallPtrSet<LiveInterval *, 4>; 151 using SmallVirtRegSet = SmallSet<Register, 16>; 152 153 // context 154 MachineFunction *MF; 155 156 // Shortcuts to some useful interface. 157 const TargetInstrInfo *TII; 158 const TargetRegisterInfo *TRI; 159 RegisterClassInfo RCI; 160 161 // analyses 162 SlotIndexes *Indexes; 163 MachineBlockFrequencyInfo *MBFI; 164 MachineDominatorTree *DomTree; 165 MachineLoopInfo *Loops; 166 MachineOptimizationRemarkEmitter *ORE; 167 EdgeBundles *Bundles; 168 SpillPlacement *SpillPlacer; 169 LiveDebugVariables *DebugVars; 170 AliasAnalysis *AA; 171 172 // state 173 std::unique_ptr<Spiller> SpillerInstance; 174 PQueue Queue; 175 unsigned NextCascade; 176 std::unique_ptr<VirtRegAuxInfo> VRAI; 177 178 // Live ranges pass through a number of stages as we try to allocate them. 179 // Some of the stages may also create new live ranges: 180 // 181 // - Region splitting. 182 // - Per-block splitting. 183 // - Local splitting. 184 // - Spilling. 185 // 186 // Ranges produced by one of the stages skip the previous stages when they are 187 // dequeued. This improves performance because we can skip interference checks 188 // that are unlikely to give any results. It also guarantees that the live 189 // range splitting algorithm terminates, something that is otherwise hard to 190 // ensure. 191 enum LiveRangeStage { 192 /// Newly created live range that has never been queued. 193 RS_New, 194 195 /// Only attempt assignment and eviction. Then requeue as RS_Split. 196 RS_Assign, 197 198 /// Attempt live range splitting if assignment is impossible. 199 RS_Split, 200 201 /// Attempt more aggressive live range splitting that is guaranteed to make 202 /// progress. This is used for split products that may not be making 203 /// progress. 204 RS_Split2, 205 206 /// Live range will be spilled. No more splitting will be attempted. 207 RS_Spill, 208 209 210 /// Live range is in memory. Because of other evictions, it might get moved 211 /// in a register in the end. 212 RS_Memory, 213 214 /// There is nothing more we can do to this live range. Abort compilation 215 /// if it can't be assigned. 216 RS_Done 217 }; 218 219 // Enum CutOffStage to keep a track whether the register allocation failed 220 // because of the cutoffs encountered in last chance recoloring. 221 // Note: This is used as bitmask. New value should be next power of 2. 222 enum CutOffStage { 223 // No cutoffs encountered 224 CO_None = 0, 225 226 // lcr-max-depth cutoff encountered 227 CO_Depth = 1, 228 229 // lcr-max-interf cutoff encountered 230 CO_Interf = 2 231 }; 232 233 uint8_t CutOffInfo; 234 235 #ifndef NDEBUG 236 static const char *const StageName[]; 237 #endif 238 239 // RegInfo - Keep additional information about each live range. 240 struct RegInfo { 241 LiveRangeStage Stage = RS_New; 242 243 // Cascade - Eviction loop prevention. See canEvictInterference(). 244 unsigned Cascade = 0; 245 246 RegInfo() = default; 247 }; 248 249 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo; 250 251 LiveRangeStage getStage(const LiveInterval &VirtReg) const { 252 return ExtraRegInfo[VirtReg.reg()].Stage; 253 } 254 255 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) { 256 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 257 ExtraRegInfo[VirtReg.reg()].Stage = Stage; 258 } 259 260 template<typename Iterator> 261 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) { 262 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 263 for (;Begin != End; ++Begin) { 264 Register Reg = *Begin; 265 if (ExtraRegInfo[Reg].Stage == RS_New) 266 ExtraRegInfo[Reg].Stage = NewStage; 267 } 268 } 269 270 /// Cost of evicting interference. 271 struct EvictionCost { 272 unsigned BrokenHints = 0; ///< Total number of broken hints. 273 float MaxWeight = 0; ///< Maximum spill weight evicted. 274 275 EvictionCost() = default; 276 277 bool isMax() const { return BrokenHints == ~0u; } 278 279 void setMax() { BrokenHints = ~0u; } 280 281 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; } 282 283 bool operator<(const EvictionCost &O) const { 284 return std::tie(BrokenHints, MaxWeight) < 285 std::tie(O.BrokenHints, O.MaxWeight); 286 } 287 }; 288 289 /// EvictionTrack - Keeps track of past evictions in order to optimize region 290 /// split decision. 291 class EvictionTrack { 292 293 public: 294 using EvictorInfo = 295 std::pair<Register /* evictor */, MCRegister /* physreg */>; 296 using EvicteeInfo = llvm::DenseMap<Register /* evictee */, EvictorInfo>; 297 298 private: 299 /// Each Vreg that has been evicted in the last stage of selectOrSplit will 300 /// be mapped to the evictor Vreg and the PhysReg it was evicted from. 301 EvicteeInfo Evictees; 302 303 public: 304 /// Clear all eviction information. 305 void clear() { Evictees.clear(); } 306 307 /// Clear eviction information for the given evictee Vreg. 308 /// E.g. when Vreg get's a new allocation, the old eviction info is no 309 /// longer relevant. 310 /// \param Evictee The evictee Vreg for whom we want to clear collected 311 /// eviction info. 312 void clearEvicteeInfo(Register Evictee) { Evictees.erase(Evictee); } 313 314 /// Track new eviction. 315 /// The Evictor vreg has evicted the Evictee vreg from Physreg. 316 /// \param PhysReg The physical register Evictee was evicted from. 317 /// \param Evictor The evictor Vreg that evicted Evictee. 318 /// \param Evictee The evictee Vreg. 319 void addEviction(MCRegister PhysReg, Register Evictor, Register Evictee) { 320 Evictees[Evictee].first = Evictor; 321 Evictees[Evictee].second = PhysReg; 322 } 323 324 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg. 325 /// \param Evictee The evictee vreg. 326 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if 327 /// nobody has evicted Evictee from PhysReg. 328 EvictorInfo getEvictor(Register Evictee) { 329 if (Evictees.count(Evictee)) { 330 return Evictees[Evictee]; 331 } 332 333 return EvictorInfo(0, 0); 334 } 335 }; 336 337 // Keeps track of past evictions in order to optimize region split decision. 338 EvictionTrack LastEvicted; 339 340 // splitting state. 341 std::unique_ptr<SplitAnalysis> SA; 342 std::unique_ptr<SplitEditor> SE; 343 344 /// Cached per-block interference maps 345 InterferenceCache IntfCache; 346 347 /// All basic blocks where the current register has uses. 348 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints; 349 350 /// Global live range splitting candidate info. 351 struct GlobalSplitCandidate { 352 // Register intended for assignment, or 0. 353 MCRegister PhysReg; 354 355 // SplitKit interval index for this candidate. 356 unsigned IntvIdx; 357 358 // Interference for PhysReg. 359 InterferenceCache::Cursor Intf; 360 361 // Bundles where this candidate should be live. 362 BitVector LiveBundles; 363 SmallVector<unsigned, 8> ActiveBlocks; 364 365 void reset(InterferenceCache &Cache, MCRegister Reg) { 366 PhysReg = Reg; 367 IntvIdx = 0; 368 Intf.setPhysReg(Cache, Reg); 369 LiveBundles.clear(); 370 ActiveBlocks.clear(); 371 } 372 373 // Set B[I] = C for every live bundle where B[I] was NoCand. 374 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) { 375 unsigned Count = 0; 376 for (unsigned I : LiveBundles.set_bits()) 377 if (B[I] == NoCand) { 378 B[I] = C; 379 Count++; 380 } 381 return Count; 382 } 383 }; 384 385 /// Candidate info for each PhysReg in AllocationOrder. 386 /// This vector never shrinks, but grows to the size of the largest register 387 /// class. 388 SmallVector<GlobalSplitCandidate, 32> GlobalCand; 389 390 enum : unsigned { NoCand = ~0u }; 391 392 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to 393 /// NoCand which indicates the stack interval. 394 SmallVector<unsigned, 32> BundleCand; 395 396 /// Callee-save register cost, calculated once per machine function. 397 BlockFrequency CSRCost; 398 399 /// Run or not the local reassignment heuristic. This information is 400 /// obtained from the TargetSubtargetInfo. 401 bool EnableLocalReassign; 402 403 /// Enable or not the consideration of the cost of local intervals created 404 /// by a split candidate when choosing the best split candidate. 405 bool EnableAdvancedRASplitCost; 406 407 /// Set of broken hints that may be reconciled later because of eviction. 408 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints; 409 410 /// The register cost values. This list will be recreated for each Machine 411 /// Function 412 ArrayRef<uint8_t> RegCosts; 413 414 public: 415 RAGreedy(const RegClassFilterFunc F = allocateAllRegClasses); 416 417 /// Return the pass name. 418 StringRef getPassName() const override { return "Greedy Register Allocator"; } 419 420 /// RAGreedy analysis usage. 421 void getAnalysisUsage(AnalysisUsage &AU) const override; 422 void releaseMemory() override; 423 Spiller &spiller() override { return *SpillerInstance; } 424 void enqueueImpl(LiveInterval *LI) override; 425 LiveInterval *dequeue() override; 426 MCRegister selectOrSplit(LiveInterval &, 427 SmallVectorImpl<Register> &) override; 428 void aboutToRemoveInterval(LiveInterval &) override; 429 430 /// Perform register allocation. 431 bool runOnMachineFunction(MachineFunction &mf) override; 432 433 MachineFunctionProperties getRequiredProperties() const override { 434 return MachineFunctionProperties().set( 435 MachineFunctionProperties::Property::NoPHIs); 436 } 437 438 MachineFunctionProperties getClearedProperties() const override { 439 return MachineFunctionProperties().set( 440 MachineFunctionProperties::Property::IsSSA); 441 } 442 443 static char ID; 444 445 private: 446 MCRegister selectOrSplitImpl(LiveInterval &, SmallVectorImpl<Register> &, 447 SmallVirtRegSet &, unsigned = 0); 448 449 bool LRE_CanEraseVirtReg(Register) override; 450 void LRE_WillShrinkVirtReg(Register) override; 451 void LRE_DidCloneVirtReg(Register, Register) override; 452 void enqueue(PQueue &CurQueue, LiveInterval *LI); 453 LiveInterval *dequeue(PQueue &CurQueue); 454 455 BlockFrequency calcSpillCost(); 456 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&); 457 bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>); 458 bool growRegion(GlobalSplitCandidate &Cand); 459 bool splitCanCauseEvictionChain(Register Evictee, GlobalSplitCandidate &Cand, 460 unsigned BBNumber, 461 const AllocationOrder &Order); 462 bool splitCanCauseLocalSpill(unsigned VirtRegToSplit, 463 GlobalSplitCandidate &Cand, unsigned BBNumber, 464 const AllocationOrder &Order); 465 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &, 466 const AllocationOrder &Order, 467 bool *CanCauseEvictionChain); 468 bool calcCompactRegion(GlobalSplitCandidate&); 469 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>); 470 void calcGapWeights(MCRegister, SmallVectorImpl<float> &); 471 Register canReassign(LiveInterval &VirtReg, Register PrevReg) const; 472 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool) const; 473 bool canEvictInterference(LiveInterval &, MCRegister, bool, EvictionCost &, 474 const SmallVirtRegSet &) const; 475 bool canEvictInterferenceInRange(const LiveInterval &VirtReg, 476 MCRegister PhysReg, SlotIndex Start, 477 SlotIndex End, EvictionCost &MaxCost) const; 478 MCRegister getCheapestEvicteeWeight(const AllocationOrder &Order, 479 const LiveInterval &VirtReg, 480 SlotIndex Start, SlotIndex End, 481 float *BestEvictWeight) const; 482 void evictInterference(LiveInterval &, MCRegister, 483 SmallVectorImpl<Register> &); 484 bool mayRecolorAllInterferences(MCRegister PhysReg, LiveInterval &VirtReg, 485 SmallLISet &RecoloringCandidates, 486 const SmallVirtRegSet &FixedRegisters); 487 488 MCRegister tryAssign(LiveInterval&, AllocationOrder&, 489 SmallVectorImpl<Register>&, 490 const SmallVirtRegSet&); 491 MCRegister tryEvict(LiveInterval &, AllocationOrder &, 492 SmallVectorImpl<Register> &, uint8_t, 493 const SmallVirtRegSet &); 494 MCRegister tryRegionSplit(LiveInterval &, AllocationOrder &, 495 SmallVectorImpl<Register> &); 496 /// Calculate cost of region splitting. 497 unsigned calculateRegionSplitCost(LiveInterval &VirtReg, 498 AllocationOrder &Order, 499 BlockFrequency &BestCost, 500 unsigned &NumCands, bool IgnoreCSR, 501 bool *CanCauseEvictionChain = nullptr); 502 /// Perform region splitting. 503 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand, 504 bool HasCompact, 505 SmallVectorImpl<Register> &NewVRegs); 506 /// Check other options before using a callee-saved register for the first 507 /// time. 508 MCRegister tryAssignCSRFirstTime(LiveInterval &VirtReg, 509 AllocationOrder &Order, MCRegister PhysReg, 510 uint8_t &CostPerUseLimit, 511 SmallVectorImpl<Register> &NewVRegs); 512 void initializeCSRCost(); 513 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&, 514 SmallVectorImpl<Register>&); 515 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&, 516 SmallVectorImpl<Register>&); 517 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&, 518 SmallVectorImpl<Register>&); 519 unsigned trySplit(LiveInterval&, AllocationOrder&, 520 SmallVectorImpl<Register>&, 521 const SmallVirtRegSet&); 522 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &, 523 SmallVectorImpl<Register> &, 524 SmallVirtRegSet &, unsigned); 525 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &, 526 SmallVirtRegSet &, unsigned); 527 void tryHintRecoloring(LiveInterval &); 528 void tryHintsRecoloring(); 529 530 /// Model the information carried by one end of a copy. 531 struct HintInfo { 532 /// The frequency of the copy. 533 BlockFrequency Freq; 534 /// The virtual register or physical register. 535 Register Reg; 536 /// Its currently assigned register. 537 /// In case of a physical register Reg == PhysReg. 538 MCRegister PhysReg; 539 540 HintInfo(BlockFrequency Freq, Register Reg, MCRegister PhysReg) 541 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {} 542 }; 543 using HintsInfo = SmallVector<HintInfo, 4>; 544 545 BlockFrequency getBrokenHintFreq(const HintsInfo &, MCRegister); 546 void collectHintInfo(Register, HintsInfo &); 547 548 bool isUnusedCalleeSavedReg(MCRegister PhysReg) const; 549 550 /// Greedy RA statistic to remark. 551 struct RAGreedyStats { 552 unsigned Reloads = 0; 553 unsigned FoldedReloads = 0; 554 unsigned ZeroCostFoldedReloads = 0; 555 unsigned Spills = 0; 556 unsigned FoldedSpills = 0; 557 unsigned Copies = 0; 558 float ReloadsCost = 0.0f; 559 float FoldedReloadsCost = 0.0f; 560 float SpillsCost = 0.0f; 561 float FoldedSpillsCost = 0.0f; 562 float CopiesCost = 0.0f; 563 564 bool isEmpty() { 565 return !(Reloads || FoldedReloads || Spills || FoldedSpills || 566 ZeroCostFoldedReloads || Copies); 567 } 568 569 void add(RAGreedyStats other) { 570 Reloads += other.Reloads; 571 FoldedReloads += other.FoldedReloads; 572 ZeroCostFoldedReloads += other.ZeroCostFoldedReloads; 573 Spills += other.Spills; 574 FoldedSpills += other.FoldedSpills; 575 Copies += other.Copies; 576 ReloadsCost += other.ReloadsCost; 577 FoldedReloadsCost += other.FoldedReloadsCost; 578 SpillsCost += other.SpillsCost; 579 FoldedSpillsCost += other.FoldedSpillsCost; 580 CopiesCost += other.CopiesCost; 581 } 582 583 void report(MachineOptimizationRemarkMissed &R); 584 }; 585 586 /// Compute statistic for a basic block. 587 RAGreedyStats computeStats(MachineBasicBlock &MBB); 588 589 /// Compute and report statistic through a remark. 590 RAGreedyStats reportStats(MachineLoop *L); 591 592 /// Report the statistic for each loop. 593 void reportStats(); 594 }; 595 596 } // end anonymous namespace 597 598 char RAGreedy::ID = 0; 599 char &llvm::RAGreedyID = RAGreedy::ID; 600 601 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy", 602 "Greedy Register Allocator", false, false) 603 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables) 604 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 605 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 606 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer) 607 INITIALIZE_PASS_DEPENDENCY(MachineScheduler) 608 INITIALIZE_PASS_DEPENDENCY(LiveStacks) 609 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 610 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 611 INITIALIZE_PASS_DEPENDENCY(VirtRegMap) 612 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix) 613 INITIALIZE_PASS_DEPENDENCY(EdgeBundles) 614 INITIALIZE_PASS_DEPENDENCY(SpillPlacement) 615 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass) 616 INITIALIZE_PASS_END(RAGreedy, "greedy", 617 "Greedy Register Allocator", false, false) 618 619 #ifndef NDEBUG 620 const char *const RAGreedy::StageName[] = { 621 "RS_New", 622 "RS_Assign", 623 "RS_Split", 624 "RS_Split2", 625 "RS_Spill", 626 "RS_Memory", 627 "RS_Done" 628 }; 629 #endif 630 631 // Hysteresis to use when comparing floats. 632 // This helps stabilize decisions based on float comparisons. 633 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875 634 635 FunctionPass* llvm::createGreedyRegisterAllocator() { 636 return new RAGreedy(); 637 } 638 639 namespace llvm { 640 FunctionPass* createGreedyRegisterAllocator( 641 std::function<bool(const TargetRegisterInfo &TRI, 642 const TargetRegisterClass &RC)> Ftor); 643 644 } 645 646 FunctionPass* llvm::createGreedyRegisterAllocator( 647 std::function<bool(const TargetRegisterInfo &TRI, 648 const TargetRegisterClass &RC)> Ftor) { 649 return new RAGreedy(Ftor); 650 } 651 652 RAGreedy::RAGreedy(RegClassFilterFunc F): 653 MachineFunctionPass(ID), 654 RegAllocBase(F) { 655 } 656 657 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const { 658 AU.setPreservesCFG(); 659 AU.addRequired<MachineBlockFrequencyInfo>(); 660 AU.addPreserved<MachineBlockFrequencyInfo>(); 661 AU.addRequired<AAResultsWrapperPass>(); 662 AU.addPreserved<AAResultsWrapperPass>(); 663 AU.addRequired<LiveIntervals>(); 664 AU.addPreserved<LiveIntervals>(); 665 AU.addRequired<SlotIndexes>(); 666 AU.addPreserved<SlotIndexes>(); 667 AU.addRequired<LiveDebugVariables>(); 668 AU.addPreserved<LiveDebugVariables>(); 669 AU.addRequired<LiveStacks>(); 670 AU.addPreserved<LiveStacks>(); 671 AU.addRequired<MachineDominatorTree>(); 672 AU.addPreserved<MachineDominatorTree>(); 673 AU.addRequired<MachineLoopInfo>(); 674 AU.addPreserved<MachineLoopInfo>(); 675 AU.addRequired<VirtRegMap>(); 676 AU.addPreserved<VirtRegMap>(); 677 AU.addRequired<LiveRegMatrix>(); 678 AU.addPreserved<LiveRegMatrix>(); 679 AU.addRequired<EdgeBundles>(); 680 AU.addRequired<SpillPlacement>(); 681 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 682 MachineFunctionPass::getAnalysisUsage(AU); 683 } 684 685 //===----------------------------------------------------------------------===// 686 // LiveRangeEdit delegate methods 687 //===----------------------------------------------------------------------===// 688 689 bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) { 690 LiveInterval &LI = LIS->getInterval(VirtReg); 691 if (VRM->hasPhys(VirtReg)) { 692 Matrix->unassign(LI); 693 aboutToRemoveInterval(LI); 694 return true; 695 } 696 // Unassigned virtreg is probably in the priority queue. 697 // RegAllocBase will erase it after dequeueing. 698 // Nonetheless, clear the live-range so that the debug 699 // dump will show the right state for that VirtReg. 700 LI.clear(); 701 return false; 702 } 703 704 void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) { 705 if (!VRM->hasPhys(VirtReg)) 706 return; 707 708 // Register is assigned, put it back on the queue for reassignment. 709 LiveInterval &LI = LIS->getInterval(VirtReg); 710 Matrix->unassign(LI); 711 RegAllocBase::enqueue(&LI); 712 } 713 714 void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) { 715 // Cloning a register we haven't even heard about yet? Just ignore it. 716 if (!ExtraRegInfo.inBounds(Old)) 717 return; 718 719 // LRE may clone a virtual register because dead code elimination causes it to 720 // be split into connected components. The new components are much smaller 721 // than the original, so they should get a new chance at being assigned. 722 // same stage as the parent. 723 ExtraRegInfo[Old].Stage = RS_Assign; 724 ExtraRegInfo.grow(New); 725 ExtraRegInfo[New] = ExtraRegInfo[Old]; 726 } 727 728 void RAGreedy::releaseMemory() { 729 SpillerInstance.reset(); 730 ExtraRegInfo.clear(); 731 GlobalCand.clear(); 732 } 733 734 void RAGreedy::enqueueImpl(LiveInterval *LI) { enqueue(Queue, LI); } 735 736 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) { 737 // Prioritize live ranges by size, assigning larger ranges first. 738 // The queue holds (size, reg) pairs. 739 const unsigned Size = LI->getSize(); 740 const Register Reg = LI->reg(); 741 assert(Reg.isVirtual() && "Can only enqueue virtual registers"); 742 unsigned Prio; 743 744 ExtraRegInfo.grow(Reg); 745 if (ExtraRegInfo[Reg].Stage == RS_New) 746 ExtraRegInfo[Reg].Stage = RS_Assign; 747 748 if (ExtraRegInfo[Reg].Stage == RS_Split) { 749 // Unsplit ranges that couldn't be allocated immediately are deferred until 750 // everything else has been allocated. 751 Prio = Size; 752 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) { 753 // Memory operand should be considered last. 754 // Change the priority such that Memory operand are assigned in 755 // the reverse order that they came in. 756 // TODO: Make this a member variable and probably do something about hints. 757 static unsigned MemOp = 0; 758 Prio = MemOp++; 759 } else { 760 // Giant live ranges fall back to the global assignment heuristic, which 761 // prevents excessive spilling in pathological cases. 762 bool ReverseLocal = TRI->reverseLocalAssignment(); 763 const TargetRegisterClass &RC = *MRI->getRegClass(Reg); 764 bool ForceGlobal = !ReverseLocal && 765 (Size / SlotIndex::InstrDist) > (2 * RCI.getNumAllocatableRegs(&RC)); 766 767 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() && 768 LIS->intervalIsInOneMBB(*LI)) { 769 // Allocate original local ranges in linear instruction order. Since they 770 // are singly defined, this produces optimal coloring in the absence of 771 // global interference and other constraints. 772 if (!ReverseLocal) 773 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex()); 774 else { 775 // Allocating bottom up may allow many short LRGs to be assigned first 776 // to one of the cheap registers. This could be much faster for very 777 // large blocks on targets with many physical registers. 778 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex()); 779 } 780 Prio |= RC.AllocationPriority << 24; 781 } else { 782 // Allocate global and split ranges in long->short order. Long ranges that 783 // don't fit should be spilled (or split) ASAP so they don't create 784 // interference. Mark a bit to prioritize global above local ranges. 785 Prio = (1u << 29) + Size; 786 787 Prio |= RC.AllocationPriority << 24; 788 } 789 // Mark a higher bit to prioritize global and local above RS_Split. 790 Prio |= (1u << 31); 791 792 // Boost ranges that have a physical register hint. 793 if (VRM->hasKnownPreference(Reg)) 794 Prio |= (1u << 30); 795 } 796 // The virtual register number is a tie breaker for same-sized ranges. 797 // Give lower vreg numbers higher priority to assign them first. 798 CurQueue.push(std::make_pair(Prio, ~Reg)); 799 } 800 801 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); } 802 803 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) { 804 if (CurQueue.empty()) 805 return nullptr; 806 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second); 807 CurQueue.pop(); 808 return LI; 809 } 810 811 //===----------------------------------------------------------------------===// 812 // Direct Assignment 813 //===----------------------------------------------------------------------===// 814 815 /// tryAssign - Try to assign VirtReg to an available register. 816 MCRegister RAGreedy::tryAssign(LiveInterval &VirtReg, 817 AllocationOrder &Order, 818 SmallVectorImpl<Register> &NewVRegs, 819 const SmallVirtRegSet &FixedRegisters) { 820 MCRegister PhysReg; 821 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) { 822 assert(*I); 823 if (!Matrix->checkInterference(VirtReg, *I)) { 824 if (I.isHint()) 825 return *I; 826 else 827 PhysReg = *I; 828 } 829 } 830 if (!PhysReg.isValid()) 831 return PhysReg; 832 833 // PhysReg is available, but there may be a better choice. 834 835 // If we missed a simple hint, try to cheaply evict interference from the 836 // preferred register. 837 if (Register Hint = MRI->getSimpleHint(VirtReg.reg())) 838 if (Order.isHint(Hint)) { 839 MCRegister PhysHint = Hint.asMCReg(); 840 LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n'); 841 EvictionCost MaxCost; 842 MaxCost.setBrokenHints(1); 843 if (canEvictInterference(VirtReg, PhysHint, true, MaxCost, 844 FixedRegisters)) { 845 evictInterference(VirtReg, PhysHint, NewVRegs); 846 return PhysHint; 847 } 848 // Record the missed hint, we may be able to recover 849 // at the end if the surrounding allocation changed. 850 SetOfBrokenHints.insert(&VirtReg); 851 } 852 853 // Try to evict interference from a cheaper alternative. 854 uint8_t Cost = RegCosts[PhysReg]; 855 856 // Most registers have 0 additional cost. 857 if (!Cost) 858 return PhysReg; 859 860 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost " 861 << (unsigned)Cost << '\n'); 862 MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters); 863 return CheapReg ? CheapReg : PhysReg; 864 } 865 866 //===----------------------------------------------------------------------===// 867 // Interference eviction 868 //===----------------------------------------------------------------------===// 869 870 Register RAGreedy::canReassign(LiveInterval &VirtReg, Register PrevReg) const { 871 auto Order = 872 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix); 873 MCRegister PhysReg; 874 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) { 875 if ((*I).id() == PrevReg.id()) 876 continue; 877 878 MCRegUnitIterator Units(*I, TRI); 879 for (; Units.isValid(); ++Units) { 880 // Instantiate a "subquery", not to be confused with the Queries array. 881 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]); 882 if (subQ.checkInterference()) 883 break; 884 } 885 // If no units have interference, break out with the current PhysReg. 886 if (!Units.isValid()) 887 PhysReg = *I; 888 } 889 if (PhysReg) 890 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from " 891 << printReg(PrevReg, TRI) << " to " 892 << printReg(PhysReg, TRI) << '\n'); 893 return PhysReg; 894 } 895 896 /// shouldEvict - determine if A should evict the assigned live range B. The 897 /// eviction policy defined by this function together with the allocation order 898 /// defined by enqueue() decides which registers ultimately end up being split 899 /// and spilled. 900 /// 901 /// Cascade numbers are used to prevent infinite loops if this function is a 902 /// cyclic relation. 903 /// 904 /// @param A The live range to be assigned. 905 /// @param IsHint True when A is about to be assigned to its preferred 906 /// register. 907 /// @param B The live range to be evicted. 908 /// @param BreaksHint True when B is already assigned to its preferred register. 909 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint, 910 LiveInterval &B, bool BreaksHint) const { 911 bool CanSplit = getStage(B) < RS_Spill; 912 913 // Be fairly aggressive about following hints as long as the evictee can be 914 // split. 915 if (CanSplit && IsHint && !BreaksHint) 916 return true; 917 918 if (A.weight() > B.weight()) { 919 LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight() << '\n'); 920 return true; 921 } 922 return false; 923 } 924 925 /// canEvictInterference - Return true if all interferences between VirtReg and 926 /// PhysReg can be evicted. 927 /// 928 /// @param VirtReg Live range that is about to be assigned. 929 /// @param PhysReg Desired register for assignment. 930 /// @param IsHint True when PhysReg is VirtReg's preferred register. 931 /// @param MaxCost Only look for cheaper candidates and update with new cost 932 /// when returning true. 933 /// @returns True when interference can be evicted cheaper than MaxCost. 934 bool RAGreedy::canEvictInterference( 935 LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint, 936 EvictionCost &MaxCost, const SmallVirtRegSet &FixedRegisters) const { 937 // It is only possible to evict virtual register interference. 938 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) 939 return false; 940 941 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg); 942 943 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never 944 // involved in an eviction before. If a cascade number was assigned, deny 945 // evicting anything with the same or a newer cascade number. This prevents 946 // infinite eviction loops. 947 // 948 // This works out so a register without a cascade number is allowed to evict 949 // anything, and it can be evicted by anything. 950 unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade; 951 if (!Cascade) 952 Cascade = NextCascade; 953 954 EvictionCost Cost; 955 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 956 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 957 // If there is 10 or more interferences, chances are one is heavier. 958 const auto &Interferences = Q.interferingVRegs(10); 959 if (Interferences.size() >= 10) 960 return false; 961 962 // Check if any interfering live range is heavier than MaxWeight. 963 for (LiveInterval *Intf : reverse(Interferences)) { 964 assert(Register::isVirtualRegister(Intf->reg()) && 965 "Only expecting virtual register interference from query"); 966 967 // Do not allow eviction of a virtual register if we are in the middle 968 // of last-chance recoloring and this virtual register is one that we 969 // have scavenged a physical register for. 970 if (FixedRegisters.count(Intf->reg())) 971 return false; 972 973 // Never evict spill products. They cannot split or spill. 974 if (getStage(*Intf) == RS_Done) 975 return false; 976 // Once a live range becomes small enough, it is urgent that we find a 977 // register for it. This is indicated by an infinite spill weight. These 978 // urgent live ranges get to evict almost anything. 979 // 980 // Also allow urgent evictions of unspillable ranges from a strictly 981 // larger allocation order. 982 bool Urgent = 983 !VirtReg.isSpillable() && 984 (Intf->isSpillable() || 985 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) < 986 RegClassInfo.getNumAllocatableRegs( 987 MRI->getRegClass(Intf->reg()))); 988 // Only evict older cascades or live ranges without a cascade. 989 unsigned IntfCascade = ExtraRegInfo[Intf->reg()].Cascade; 990 if (Cascade <= IntfCascade) { 991 if (!Urgent) 992 return false; 993 // We permit breaking cascades for urgent evictions. It should be the 994 // last resort, though, so make it really expensive. 995 Cost.BrokenHints += 10; 996 } 997 // Would this break a satisfied hint? 998 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg()); 999 // Update eviction cost. 1000 Cost.BrokenHints += BreaksHint; 1001 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight()); 1002 // Abort if this would be too expensive. 1003 if (!(Cost < MaxCost)) 1004 return false; 1005 if (Urgent) 1006 continue; 1007 // Apply the eviction policy for non-urgent evictions. 1008 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint)) 1009 return false; 1010 // If !MaxCost.isMax(), then we're just looking for a cheap register. 1011 // Evicting another local live range in this case could lead to suboptimal 1012 // coloring. 1013 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) && 1014 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) { 1015 return false; 1016 } 1017 } 1018 } 1019 MaxCost = Cost; 1020 return true; 1021 } 1022 1023 /// Return true if all interferences between VirtReg and PhysReg between 1024 /// Start and End can be evicted. 1025 /// 1026 /// \param VirtReg Live range that is about to be assigned. 1027 /// \param PhysReg Desired register for assignment. 1028 /// \param Start Start of range to look for interferences. 1029 /// \param End End of range to look for interferences. 1030 /// \param MaxCost Only look for cheaper candidates and update with new cost 1031 /// when returning true. 1032 /// \return True when interference can be evicted cheaper than MaxCost. 1033 bool RAGreedy::canEvictInterferenceInRange(const LiveInterval &VirtReg, 1034 MCRegister PhysReg, SlotIndex Start, 1035 SlotIndex End, 1036 EvictionCost &MaxCost) const { 1037 EvictionCost Cost; 1038 1039 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 1040 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 1041 1042 // Check if any interfering live range is heavier than MaxWeight. 1043 for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) { 1044 // Check if interference overlast the segment in interest. 1045 if (!Intf->overlaps(Start, End)) 1046 continue; 1047 1048 // Cannot evict non virtual reg interference. 1049 if (!Register::isVirtualRegister(Intf->reg())) 1050 return false; 1051 // Never evict spill products. They cannot split or spill. 1052 if (getStage(*Intf) == RS_Done) 1053 return false; 1054 1055 // Would this break a satisfied hint? 1056 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg()); 1057 // Update eviction cost. 1058 Cost.BrokenHints += BreaksHint; 1059 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight()); 1060 // Abort if this would be too expensive. 1061 if (!(Cost < MaxCost)) 1062 return false; 1063 } 1064 } 1065 1066 if (Cost.MaxWeight == 0) 1067 return false; 1068 1069 MaxCost = Cost; 1070 return true; 1071 } 1072 1073 /// Return the physical register that will be best 1074 /// candidate for eviction by a local split interval that will be created 1075 /// between Start and End. 1076 /// 1077 /// \param Order The allocation order 1078 /// \param VirtReg Live range that is about to be assigned. 1079 /// \param Start Start of range to look for interferences 1080 /// \param End End of range to look for interferences 1081 /// \param BestEvictweight The eviction cost of that eviction 1082 /// \return The PhysReg which is the best candidate for eviction and the 1083 /// eviction cost in BestEvictweight 1084 MCRegister RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order, 1085 const LiveInterval &VirtReg, 1086 SlotIndex Start, SlotIndex End, 1087 float *BestEvictweight) const { 1088 EvictionCost BestEvictCost; 1089 BestEvictCost.setMax(); 1090 BestEvictCost.MaxWeight = VirtReg.weight(); 1091 MCRegister BestEvicteePhys; 1092 1093 // Go over all physical registers and find the best candidate for eviction 1094 for (MCRegister PhysReg : Order.getOrder()) { 1095 1096 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End, 1097 BestEvictCost)) 1098 continue; 1099 1100 // Best so far. 1101 BestEvicteePhys = PhysReg; 1102 } 1103 *BestEvictweight = BestEvictCost.MaxWeight; 1104 return BestEvicteePhys; 1105 } 1106 1107 /// evictInterference - Evict any interferring registers that prevent VirtReg 1108 /// from being assigned to Physreg. This assumes that canEvictInterference 1109 /// returned true. 1110 void RAGreedy::evictInterference(LiveInterval &VirtReg, MCRegister PhysReg, 1111 SmallVectorImpl<Register> &NewVRegs) { 1112 // Make sure that VirtReg has a cascade number, and assign that cascade 1113 // number to every evicted register. These live ranges than then only be 1114 // evicted by a newer cascade, preventing infinite loops. 1115 unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade; 1116 if (!Cascade) 1117 Cascade = ExtraRegInfo[VirtReg.reg()].Cascade = NextCascade++; 1118 1119 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI) 1120 << " interference: Cascade " << Cascade << '\n'); 1121 1122 // Collect all interfering virtregs first. 1123 SmallVector<LiveInterval*, 8> Intfs; 1124 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 1125 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 1126 // We usually have the interfering VRegs cached so collectInterferingVRegs() 1127 // should be fast, we may need to recalculate if when different physregs 1128 // overlap the same register unit so we had different SubRanges queried 1129 // against it. 1130 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs(); 1131 Intfs.append(IVR.begin(), IVR.end()); 1132 } 1133 1134 // Evict them second. This will invalidate the queries. 1135 for (LiveInterval *Intf : Intfs) { 1136 // The same VirtReg may be present in multiple RegUnits. Skip duplicates. 1137 if (!VRM->hasPhys(Intf->reg())) 1138 continue; 1139 1140 LastEvicted.addEviction(PhysReg, VirtReg.reg(), Intf->reg()); 1141 1142 Matrix->unassign(*Intf); 1143 assert((ExtraRegInfo[Intf->reg()].Cascade < Cascade || 1144 VirtReg.isSpillable() < Intf->isSpillable()) && 1145 "Cannot decrease cascade number, illegal eviction"); 1146 ExtraRegInfo[Intf->reg()].Cascade = Cascade; 1147 ++NumEvicted; 1148 NewVRegs.push_back(Intf->reg()); 1149 } 1150 } 1151 1152 /// Returns true if the given \p PhysReg is a callee saved register and has not 1153 /// been used for allocation yet. 1154 bool RAGreedy::isUnusedCalleeSavedReg(MCRegister PhysReg) const { 1155 MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg); 1156 if (!CSR) 1157 return false; 1158 1159 return !Matrix->isPhysRegUsed(PhysReg); 1160 } 1161 1162 /// tryEvict - Try to evict all interferences for a physreg. 1163 /// @param VirtReg Currently unassigned virtual register. 1164 /// @param Order Physregs to try. 1165 /// @return Physreg to assign VirtReg, or 0. 1166 MCRegister RAGreedy::tryEvict(LiveInterval &VirtReg, AllocationOrder &Order, 1167 SmallVectorImpl<Register> &NewVRegs, 1168 uint8_t CostPerUseLimit, 1169 const SmallVirtRegSet &FixedRegisters) { 1170 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription, 1171 TimePassesIsEnabled); 1172 1173 // Keep track of the cheapest interference seen so far. 1174 EvictionCost BestCost; 1175 BestCost.setMax(); 1176 MCRegister BestPhys; 1177 unsigned OrderLimit = Order.getOrder().size(); 1178 1179 // When we are just looking for a reduced cost per use, don't break any 1180 // hints, and only evict smaller spill weights. 1181 if (CostPerUseLimit < uint8_t(~0u)) { 1182 BestCost.BrokenHints = 0; 1183 BestCost.MaxWeight = VirtReg.weight(); 1184 1185 // Check of any registers in RC are below CostPerUseLimit. 1186 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg()); 1187 uint8_t MinCost = RegClassInfo.getMinCost(RC); 1188 if (MinCost >= CostPerUseLimit) { 1189 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " 1190 << MinCost << ", no cheaper registers to be found.\n"); 1191 return 0; 1192 } 1193 1194 // It is normal for register classes to have a long tail of registers with 1195 // the same cost. We don't need to look at them if they're too expensive. 1196 if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) { 1197 OrderLimit = RegClassInfo.getLastCostChange(RC); 1198 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit 1199 << " regs.\n"); 1200 } 1201 } 1202 1203 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E; 1204 ++I) { 1205 MCRegister PhysReg = *I; 1206 assert(PhysReg); 1207 if (RegCosts[PhysReg] >= CostPerUseLimit) 1208 continue; 1209 // The first use of a callee-saved register in a function has cost 1. 1210 // Don't start using a CSR when the CostPerUseLimit is low. 1211 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) { 1212 LLVM_DEBUG( 1213 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR " 1214 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI) 1215 << '\n'); 1216 continue; 1217 } 1218 1219 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost, 1220 FixedRegisters)) 1221 continue; 1222 1223 // Best so far. 1224 BestPhys = PhysReg; 1225 1226 // Stop if the hint can be used. 1227 if (I.isHint()) 1228 break; 1229 } 1230 1231 if (BestPhys.isValid()) 1232 evictInterference(VirtReg, BestPhys, NewVRegs); 1233 return BestPhys; 1234 } 1235 1236 //===----------------------------------------------------------------------===// 1237 // Region Splitting 1238 //===----------------------------------------------------------------------===// 1239 1240 /// addSplitConstraints - Fill out the SplitConstraints vector based on the 1241 /// interference pattern in Physreg and its aliases. Add the constraints to 1242 /// SpillPlacement and return the static cost of this split in Cost, assuming 1243 /// that all preferences in SplitConstraints are met. 1244 /// Return false if there are no bundles with positive bias. 1245 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf, 1246 BlockFrequency &Cost) { 1247 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 1248 1249 // Reset interference dependent info. 1250 SplitConstraints.resize(UseBlocks.size()); 1251 BlockFrequency StaticCost = 0; 1252 for (unsigned I = 0; I != UseBlocks.size(); ++I) { 1253 const SplitAnalysis::BlockInfo &BI = UseBlocks[I]; 1254 SpillPlacement::BlockConstraint &BC = SplitConstraints[I]; 1255 1256 BC.Number = BI.MBB->getNumber(); 1257 Intf.moveToBlock(BC.Number); 1258 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare; 1259 BC.Exit = (BI.LiveOut && 1260 !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef()) 1261 ? SpillPlacement::PrefReg 1262 : SpillPlacement::DontCare; 1263 BC.ChangesValue = BI.FirstDef.isValid(); 1264 1265 if (!Intf.hasInterference()) 1266 continue; 1267 1268 // Number of spill code instructions to insert. 1269 unsigned Ins = 0; 1270 1271 // Interference for the live-in value. 1272 if (BI.LiveIn) { 1273 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) { 1274 BC.Entry = SpillPlacement::MustSpill; 1275 ++Ins; 1276 } else if (Intf.first() < BI.FirstInstr) { 1277 BC.Entry = SpillPlacement::PrefSpill; 1278 ++Ins; 1279 } else if (Intf.first() < BI.LastInstr) { 1280 ++Ins; 1281 } 1282 1283 // Abort if the spill cannot be inserted at the MBB' start 1284 if (((BC.Entry == SpillPlacement::MustSpill) || 1285 (BC.Entry == SpillPlacement::PrefSpill)) && 1286 SlotIndex::isEarlierInstr(BI.FirstInstr, 1287 SA->getFirstSplitPoint(BC.Number))) 1288 return false; 1289 } 1290 1291 // Interference for the live-out value. 1292 if (BI.LiveOut) { 1293 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) { 1294 BC.Exit = SpillPlacement::MustSpill; 1295 ++Ins; 1296 } else if (Intf.last() > BI.LastInstr) { 1297 BC.Exit = SpillPlacement::PrefSpill; 1298 ++Ins; 1299 } else if (Intf.last() > BI.FirstInstr) { 1300 ++Ins; 1301 } 1302 } 1303 1304 // Accumulate the total frequency of inserted spill code. 1305 while (Ins--) 1306 StaticCost += SpillPlacer->getBlockFrequency(BC.Number); 1307 } 1308 Cost = StaticCost; 1309 1310 // Add constraints for use-blocks. Note that these are the only constraints 1311 // that may add a positive bias, it is downhill from here. 1312 SpillPlacer->addConstraints(SplitConstraints); 1313 return SpillPlacer->scanActiveBundles(); 1314 } 1315 1316 /// addThroughConstraints - Add constraints and links to SpillPlacer from the 1317 /// live-through blocks in Blocks. 1318 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf, 1319 ArrayRef<unsigned> Blocks) { 1320 const unsigned GroupSize = 8; 1321 SpillPlacement::BlockConstraint BCS[GroupSize]; 1322 unsigned TBS[GroupSize]; 1323 unsigned B = 0, T = 0; 1324 1325 for (unsigned Number : Blocks) { 1326 Intf.moveToBlock(Number); 1327 1328 if (!Intf.hasInterference()) { 1329 assert(T < GroupSize && "Array overflow"); 1330 TBS[T] = Number; 1331 if (++T == GroupSize) { 1332 SpillPlacer->addLinks(makeArrayRef(TBS, T)); 1333 T = 0; 1334 } 1335 continue; 1336 } 1337 1338 assert(B < GroupSize && "Array overflow"); 1339 BCS[B].Number = Number; 1340 1341 // Abort if the spill cannot be inserted at the MBB' start 1342 MachineBasicBlock *MBB = MF->getBlockNumbered(Number); 1343 auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr(); 1344 if (FirstNonDebugInstr != MBB->end() && 1345 SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr), 1346 SA->getFirstSplitPoint(Number))) 1347 return false; 1348 // Interference for the live-in value. 1349 if (Intf.first() <= Indexes->getMBBStartIdx(Number)) 1350 BCS[B].Entry = SpillPlacement::MustSpill; 1351 else 1352 BCS[B].Entry = SpillPlacement::PrefSpill; 1353 1354 // Interference for the live-out value. 1355 if (Intf.last() >= SA->getLastSplitPoint(Number)) 1356 BCS[B].Exit = SpillPlacement::MustSpill; 1357 else 1358 BCS[B].Exit = SpillPlacement::PrefSpill; 1359 1360 if (++B == GroupSize) { 1361 SpillPlacer->addConstraints(makeArrayRef(BCS, B)); 1362 B = 0; 1363 } 1364 } 1365 1366 SpillPlacer->addConstraints(makeArrayRef(BCS, B)); 1367 SpillPlacer->addLinks(makeArrayRef(TBS, T)); 1368 return true; 1369 } 1370 1371 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) { 1372 // Keep track of through blocks that have not been added to SpillPlacer. 1373 BitVector Todo = SA->getThroughBlocks(); 1374 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks; 1375 unsigned AddedTo = 0; 1376 #ifndef NDEBUG 1377 unsigned Visited = 0; 1378 #endif 1379 1380 while (true) { 1381 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive(); 1382 // Find new through blocks in the periphery of PrefRegBundles. 1383 for (unsigned Bundle : NewBundles) { 1384 // Look at all blocks connected to Bundle in the full graph. 1385 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle); 1386 for (unsigned Block : Blocks) { 1387 if (!Todo.test(Block)) 1388 continue; 1389 Todo.reset(Block); 1390 // This is a new through block. Add it to SpillPlacer later. 1391 ActiveBlocks.push_back(Block); 1392 #ifndef NDEBUG 1393 ++Visited; 1394 #endif 1395 } 1396 } 1397 // Any new blocks to add? 1398 if (ActiveBlocks.size() == AddedTo) 1399 break; 1400 1401 // Compute through constraints from the interference, or assume that all 1402 // through blocks prefer spilling when forming compact regions. 1403 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo); 1404 if (Cand.PhysReg) { 1405 if (!addThroughConstraints(Cand.Intf, NewBlocks)) 1406 return false; 1407 } else 1408 // Provide a strong negative bias on through blocks to prevent unwanted 1409 // liveness on loop backedges. 1410 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true); 1411 AddedTo = ActiveBlocks.size(); 1412 1413 // Perhaps iterating can enable more bundles? 1414 SpillPlacer->iterate(); 1415 } 1416 LLVM_DEBUG(dbgs() << ", v=" << Visited); 1417 return true; 1418 } 1419 1420 /// calcCompactRegion - Compute the set of edge bundles that should be live 1421 /// when splitting the current live range into compact regions. Compact 1422 /// regions can be computed without looking at interference. They are the 1423 /// regions formed by removing all the live-through blocks from the live range. 1424 /// 1425 /// Returns false if the current live range is already compact, or if the 1426 /// compact regions would form single block regions anyway. 1427 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) { 1428 // Without any through blocks, the live range is already compact. 1429 if (!SA->getNumThroughBlocks()) 1430 return false; 1431 1432 // Compact regions don't correspond to any physreg. 1433 Cand.reset(IntfCache, MCRegister::NoRegister); 1434 1435 LLVM_DEBUG(dbgs() << "Compact region bundles"); 1436 1437 // Use the spill placer to determine the live bundles. GrowRegion pretends 1438 // that all the through blocks have interference when PhysReg is unset. 1439 SpillPlacer->prepare(Cand.LiveBundles); 1440 1441 // The static split cost will be zero since Cand.Intf reports no interference. 1442 BlockFrequency Cost; 1443 if (!addSplitConstraints(Cand.Intf, Cost)) { 1444 LLVM_DEBUG(dbgs() << ", none.\n"); 1445 return false; 1446 } 1447 1448 if (!growRegion(Cand)) { 1449 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n"); 1450 return false; 1451 } 1452 1453 SpillPlacer->finish(); 1454 1455 if (!Cand.LiveBundles.any()) { 1456 LLVM_DEBUG(dbgs() << ", none.\n"); 1457 return false; 1458 } 1459 1460 LLVM_DEBUG({ 1461 for (int I : Cand.LiveBundles.set_bits()) 1462 dbgs() << " EB#" << I; 1463 dbgs() << ".\n"; 1464 }); 1465 return true; 1466 } 1467 1468 /// calcSpillCost - Compute how expensive it would be to split the live range in 1469 /// SA around all use blocks instead of forming bundle regions. 1470 BlockFrequency RAGreedy::calcSpillCost() { 1471 BlockFrequency Cost = 0; 1472 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 1473 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 1474 unsigned Number = BI.MBB->getNumber(); 1475 // We normally only need one spill instruction - a load or a store. 1476 Cost += SpillPlacer->getBlockFrequency(Number); 1477 1478 // Unless the value is redefined in the block. 1479 if (BI.LiveIn && BI.LiveOut && BI.FirstDef) 1480 Cost += SpillPlacer->getBlockFrequency(Number); 1481 } 1482 return Cost; 1483 } 1484 1485 /// Check if splitting Evictee will create a local split interval in 1486 /// basic block number BBNumber that may cause a bad eviction chain. This is 1487 /// intended to prevent bad eviction sequences like: 1488 /// movl %ebp, 8(%esp) # 4-byte Spill 1489 /// movl %ecx, %ebp 1490 /// movl %ebx, %ecx 1491 /// movl %edi, %ebx 1492 /// movl %edx, %edi 1493 /// cltd 1494 /// idivl %esi 1495 /// movl %edi, %edx 1496 /// movl %ebx, %edi 1497 /// movl %ecx, %ebx 1498 /// movl %ebp, %ecx 1499 /// movl 16(%esp), %ebp # 4 - byte Reload 1500 /// 1501 /// Such sequences are created in 2 scenarios: 1502 /// 1503 /// Scenario #1: 1504 /// %0 is evicted from physreg0 by %1. 1505 /// Evictee %0 is intended for region splitting with split candidate 1506 /// physreg0 (the reg %0 was evicted from). 1507 /// Region splitting creates a local interval because of interference with the 1508 /// evictor %1 (normally region splitting creates 2 interval, the "by reg" 1509 /// and "by stack" intervals and local interval created when interference 1510 /// occurs). 1511 /// One of the split intervals ends up evicting %2 from physreg1. 1512 /// Evictee %2 is intended for region splitting with split candidate 1513 /// physreg1. 1514 /// One of the split intervals ends up evicting %3 from physreg2, etc. 1515 /// 1516 /// Scenario #2 1517 /// %0 is evicted from physreg0 by %1. 1518 /// %2 is evicted from physreg2 by %3 etc. 1519 /// Evictee %0 is intended for region splitting with split candidate 1520 /// physreg1. 1521 /// Region splitting creates a local interval because of interference with the 1522 /// evictor %1. 1523 /// One of the split intervals ends up evicting back original evictor %1 1524 /// from physreg0 (the reg %0 was evicted from). 1525 /// Another evictee %2 is intended for region splitting with split candidate 1526 /// physreg1. 1527 /// One of the split intervals ends up evicting %3 from physreg2, etc. 1528 /// 1529 /// \param Evictee The register considered to be split. 1530 /// \param Cand The split candidate that determines the physical register 1531 /// we are splitting for and the interferences. 1532 /// \param BBNumber The number of a BB for which the region split process will 1533 /// create a local split interval. 1534 /// \param Order The physical registers that may get evicted by a split 1535 /// artifact of Evictee. 1536 /// \return True if splitting Evictee may cause a bad eviction chain, false 1537 /// otherwise. 1538 bool RAGreedy::splitCanCauseEvictionChain(Register Evictee, 1539 GlobalSplitCandidate &Cand, 1540 unsigned BBNumber, 1541 const AllocationOrder &Order) { 1542 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee); 1543 unsigned Evictor = VregEvictorInfo.first; 1544 MCRegister PhysReg = VregEvictorInfo.second; 1545 1546 // No actual evictor. 1547 if (!Evictor || !PhysReg) 1548 return false; 1549 1550 float MaxWeight = 0; 1551 MCRegister FutureEvictedPhysReg = 1552 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee), 1553 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight); 1554 1555 // The bad eviction chain occurs when either the split candidate is the 1556 // evicting reg or one of the split artifact will evict the evicting reg. 1557 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg)) 1558 return false; 1559 1560 Cand.Intf.moveToBlock(BBNumber); 1561 1562 // Check to see if the Evictor contains interference (with Evictee) in the 1563 // given BB. If so, this interference caused the eviction of Evictee from 1564 // PhysReg. This suggest that we will create a local interval during the 1565 // region split to avoid this interference This local interval may cause a bad 1566 // eviction chain. 1567 if (!LIS->hasInterval(Evictor)) 1568 return false; 1569 LiveInterval &EvictorLI = LIS->getInterval(Evictor); 1570 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end()) 1571 return false; 1572 1573 // Now, check to see if the local interval we will create is going to be 1574 // expensive enough to evict somebody If so, this may cause a bad eviction 1575 // chain. 1576 float splitArtifactWeight = 1577 VRAI->futureWeight(LIS->getInterval(Evictee), 1578 Cand.Intf.first().getPrevIndex(), Cand.Intf.last()); 1579 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight) 1580 return false; 1581 1582 return true; 1583 } 1584 1585 /// Check if splitting VirtRegToSplit will create a local split interval 1586 /// in basic block number BBNumber that may cause a spill. 1587 /// 1588 /// \param VirtRegToSplit The register considered to be split. 1589 /// \param Cand The split candidate that determines the physical 1590 /// register we are splitting for and the interferences. 1591 /// \param BBNumber The number of a BB for which the region split process 1592 /// will create a local split interval. 1593 /// \param Order The physical registers that may get evicted by a 1594 /// split artifact of VirtRegToSplit. 1595 /// \return True if splitting VirtRegToSplit may cause a spill, false 1596 /// otherwise. 1597 bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit, 1598 GlobalSplitCandidate &Cand, 1599 unsigned BBNumber, 1600 const AllocationOrder &Order) { 1601 Cand.Intf.moveToBlock(BBNumber); 1602 1603 // Check if the local interval will find a non interfereing assignment. 1604 for (auto PhysReg : Order.getOrder()) { 1605 if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(), 1606 Cand.Intf.last(), PhysReg)) 1607 return false; 1608 } 1609 1610 // The local interval is not able to find non interferencing assignment 1611 // and not able to evict a less worthy interval, therfore, it can cause a 1612 // spill. 1613 return true; 1614 } 1615 1616 /// calcGlobalSplitCost - Return the global split cost of following the split 1617 /// pattern in LiveBundles. This cost should be added to the local cost of the 1618 /// interference pattern in SplitConstraints. 1619 /// 1620 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand, 1621 const AllocationOrder &Order, 1622 bool *CanCauseEvictionChain) { 1623 BlockFrequency GlobalCost = 0; 1624 const BitVector &LiveBundles = Cand.LiveBundles; 1625 Register VirtRegToSplit = SA->getParent().reg(); 1626 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 1627 for (unsigned I = 0; I != UseBlocks.size(); ++I) { 1628 const SplitAnalysis::BlockInfo &BI = UseBlocks[I]; 1629 SpillPlacement::BlockConstraint &BC = SplitConstraints[I]; 1630 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)]; 1631 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)]; 1632 unsigned Ins = 0; 1633 1634 Cand.Intf.moveToBlock(BC.Number); 1635 // Check wheather a local interval is going to be created during the region 1636 // split. Calculate adavanced spilt cost (cost of local intervals) if option 1637 // is enabled. 1638 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn && 1639 BI.LiveOut && RegIn && RegOut) { 1640 1641 if (CanCauseEvictionChain && 1642 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) { 1643 // This interference causes our eviction from this assignment, we might 1644 // evict somebody else and eventually someone will spill, add that cost. 1645 // See splitCanCauseEvictionChain for detailed description of scenarios. 1646 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 1647 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 1648 1649 *CanCauseEvictionChain = true; 1650 1651 } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number, 1652 Order)) { 1653 // This interference causes local interval to spill, add that cost. 1654 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 1655 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 1656 } 1657 } 1658 1659 if (BI.LiveIn) 1660 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg); 1661 if (BI.LiveOut) 1662 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg); 1663 while (Ins--) 1664 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 1665 } 1666 1667 for (unsigned Number : Cand.ActiveBlocks) { 1668 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)]; 1669 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)]; 1670 if (!RegIn && !RegOut) 1671 continue; 1672 if (RegIn && RegOut) { 1673 // We need double spill code if this block has interference. 1674 Cand.Intf.moveToBlock(Number); 1675 if (Cand.Intf.hasInterference()) { 1676 GlobalCost += SpillPlacer->getBlockFrequency(Number); 1677 GlobalCost += SpillPlacer->getBlockFrequency(Number); 1678 1679 // Check wheather a local interval is going to be created during the 1680 // region split. 1681 if (EnableAdvancedRASplitCost && CanCauseEvictionChain && 1682 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) { 1683 // This interference cause our eviction from this assignment, we might 1684 // evict somebody else, add that cost. 1685 // See splitCanCauseEvictionChain for detailed description of 1686 // scenarios. 1687 GlobalCost += SpillPlacer->getBlockFrequency(Number); 1688 GlobalCost += SpillPlacer->getBlockFrequency(Number); 1689 1690 *CanCauseEvictionChain = true; 1691 } 1692 } 1693 continue; 1694 } 1695 // live-in / stack-out or stack-in live-out. 1696 GlobalCost += SpillPlacer->getBlockFrequency(Number); 1697 } 1698 return GlobalCost; 1699 } 1700 1701 /// splitAroundRegion - Split the current live range around the regions 1702 /// determined by BundleCand and GlobalCand. 1703 /// 1704 /// Before calling this function, GlobalCand and BundleCand must be initialized 1705 /// so each bundle is assigned to a valid candidate, or NoCand for the 1706 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor 1707 /// objects must be initialized for the current live range, and intervals 1708 /// created for the used candidates. 1709 /// 1710 /// @param LREdit The LiveRangeEdit object handling the current split. 1711 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value 1712 /// must appear in this list. 1713 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit, 1714 ArrayRef<unsigned> UsedCands) { 1715 // These are the intervals created for new global ranges. We may create more 1716 // intervals for local ranges. 1717 const unsigned NumGlobalIntvs = LREdit.size(); 1718 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs 1719 << " globals.\n"); 1720 assert(NumGlobalIntvs && "No global intervals configured"); 1721 1722 // Isolate even single instructions when dealing with a proper sub-class. 1723 // That guarantees register class inflation for the stack interval because it 1724 // is all copies. 1725 Register Reg = SA->getParent().reg(); 1726 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)); 1727 1728 // First handle all the blocks with uses. 1729 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 1730 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 1731 unsigned Number = BI.MBB->getNumber(); 1732 unsigned IntvIn = 0, IntvOut = 0; 1733 SlotIndex IntfIn, IntfOut; 1734 if (BI.LiveIn) { 1735 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)]; 1736 if (CandIn != NoCand) { 1737 GlobalSplitCandidate &Cand = GlobalCand[CandIn]; 1738 IntvIn = Cand.IntvIdx; 1739 Cand.Intf.moveToBlock(Number); 1740 IntfIn = Cand.Intf.first(); 1741 } 1742 } 1743 if (BI.LiveOut) { 1744 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)]; 1745 if (CandOut != NoCand) { 1746 GlobalSplitCandidate &Cand = GlobalCand[CandOut]; 1747 IntvOut = Cand.IntvIdx; 1748 Cand.Intf.moveToBlock(Number); 1749 IntfOut = Cand.Intf.last(); 1750 } 1751 } 1752 1753 // Create separate intervals for isolated blocks with multiple uses. 1754 if (!IntvIn && !IntvOut) { 1755 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n"); 1756 if (SA->shouldSplitSingleBlock(BI, SingleInstrs)) 1757 SE->splitSingleBlock(BI); 1758 continue; 1759 } 1760 1761 if (IntvIn && IntvOut) 1762 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut); 1763 else if (IntvIn) 1764 SE->splitRegInBlock(BI, IntvIn, IntfIn); 1765 else 1766 SE->splitRegOutBlock(BI, IntvOut, IntfOut); 1767 } 1768 1769 // Handle live-through blocks. The relevant live-through blocks are stored in 1770 // the ActiveBlocks list with each candidate. We need to filter out 1771 // duplicates. 1772 BitVector Todo = SA->getThroughBlocks(); 1773 for (unsigned c = 0; c != UsedCands.size(); ++c) { 1774 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks; 1775 for (unsigned Number : Blocks) { 1776 if (!Todo.test(Number)) 1777 continue; 1778 Todo.reset(Number); 1779 1780 unsigned IntvIn = 0, IntvOut = 0; 1781 SlotIndex IntfIn, IntfOut; 1782 1783 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)]; 1784 if (CandIn != NoCand) { 1785 GlobalSplitCandidate &Cand = GlobalCand[CandIn]; 1786 IntvIn = Cand.IntvIdx; 1787 Cand.Intf.moveToBlock(Number); 1788 IntfIn = Cand.Intf.first(); 1789 } 1790 1791 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)]; 1792 if (CandOut != NoCand) { 1793 GlobalSplitCandidate &Cand = GlobalCand[CandOut]; 1794 IntvOut = Cand.IntvIdx; 1795 Cand.Intf.moveToBlock(Number); 1796 IntfOut = Cand.Intf.last(); 1797 } 1798 if (!IntvIn && !IntvOut) 1799 continue; 1800 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut); 1801 } 1802 } 1803 1804 ++NumGlobalSplits; 1805 1806 SmallVector<unsigned, 8> IntvMap; 1807 SE->finish(&IntvMap); 1808 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS); 1809 1810 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 1811 unsigned OrigBlocks = SA->getNumLiveBlocks(); 1812 1813 // Sort out the new intervals created by splitting. We get four kinds: 1814 // - Remainder intervals should not be split again. 1815 // - Candidate intervals can be assigned to Cand.PhysReg. 1816 // - Block-local splits are candidates for local splitting. 1817 // - DCE leftovers should go back on the queue. 1818 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) { 1819 LiveInterval &Reg = LIS->getInterval(LREdit.get(I)); 1820 1821 // Ignore old intervals from DCE. 1822 if (getStage(Reg) != RS_New) 1823 continue; 1824 1825 // Remainder interval. Don't try splitting again, spill if it doesn't 1826 // allocate. 1827 if (IntvMap[I] == 0) { 1828 setStage(Reg, RS_Spill); 1829 continue; 1830 } 1831 1832 // Global intervals. Allow repeated splitting as long as the number of live 1833 // blocks is strictly decreasing. 1834 if (IntvMap[I] < NumGlobalIntvs) { 1835 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) { 1836 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks 1837 << " blocks as original.\n"); 1838 // Don't allow repeated splitting as a safe guard against looping. 1839 setStage(Reg, RS_Split2); 1840 } 1841 continue; 1842 } 1843 1844 // Other intervals are treated as new. This includes local intervals created 1845 // for blocks with multiple uses, and anything created by DCE. 1846 } 1847 1848 if (VerifyEnabled) 1849 MF->verify(this, "After splitting live range around region"); 1850 } 1851 1852 MCRegister RAGreedy::tryRegionSplit(LiveInterval &VirtReg, 1853 AllocationOrder &Order, 1854 SmallVectorImpl<Register> &NewVRegs) { 1855 if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg)) 1856 return MCRegister::NoRegister; 1857 unsigned NumCands = 0; 1858 BlockFrequency SpillCost = calcSpillCost(); 1859 BlockFrequency BestCost; 1860 1861 // Check if we can split this live range around a compact region. 1862 bool HasCompact = calcCompactRegion(GlobalCand.front()); 1863 if (HasCompact) { 1864 // Yes, keep GlobalCand[0] as the compact region candidate. 1865 NumCands = 1; 1866 BestCost = BlockFrequency::getMaxFrequency(); 1867 } else { 1868 // No benefit from the compact region, our fallback will be per-block 1869 // splitting. Make sure we find a solution that is cheaper than spilling. 1870 BestCost = SpillCost; 1871 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = "; 1872 MBFI->printBlockFreq(dbgs(), BestCost) << '\n'); 1873 } 1874 1875 bool CanCauseEvictionChain = false; 1876 unsigned BestCand = 1877 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands, 1878 false /*IgnoreCSR*/, &CanCauseEvictionChain); 1879 1880 // Split candidates with compact regions can cause a bad eviction sequence. 1881 // See splitCanCauseEvictionChain for detailed description of scenarios. 1882 // To avoid it, we need to comapre the cost with the spill cost and not the 1883 // current max frequency. 1884 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) && 1885 CanCauseEvictionChain) { 1886 return MCRegister::NoRegister; 1887 } 1888 1889 // No solutions found, fall back to single block splitting. 1890 if (!HasCompact && BestCand == NoCand) 1891 return MCRegister::NoRegister; 1892 1893 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs); 1894 } 1895 1896 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg, 1897 AllocationOrder &Order, 1898 BlockFrequency &BestCost, 1899 unsigned &NumCands, bool IgnoreCSR, 1900 bool *CanCauseEvictionChain) { 1901 unsigned BestCand = NoCand; 1902 for (MCPhysReg PhysReg : Order) { 1903 assert(PhysReg); 1904 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg)) 1905 continue; 1906 1907 // Discard bad candidates before we run out of interference cache cursors. 1908 // This will only affect register classes with a lot of registers (>32). 1909 if (NumCands == IntfCache.getMaxCursors()) { 1910 unsigned WorstCount = ~0u; 1911 unsigned Worst = 0; 1912 for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) { 1913 if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg) 1914 continue; 1915 unsigned Count = GlobalCand[CandIndex].LiveBundles.count(); 1916 if (Count < WorstCount) { 1917 Worst = CandIndex; 1918 WorstCount = Count; 1919 } 1920 } 1921 --NumCands; 1922 GlobalCand[Worst] = GlobalCand[NumCands]; 1923 if (BestCand == NumCands) 1924 BestCand = Worst; 1925 } 1926 1927 if (GlobalCand.size() <= NumCands) 1928 GlobalCand.resize(NumCands+1); 1929 GlobalSplitCandidate &Cand = GlobalCand[NumCands]; 1930 Cand.reset(IntfCache, PhysReg); 1931 1932 SpillPlacer->prepare(Cand.LiveBundles); 1933 BlockFrequency Cost; 1934 if (!addSplitConstraints(Cand.Intf, Cost)) { 1935 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n"); 1936 continue; 1937 } 1938 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = "; 1939 MBFI->printBlockFreq(dbgs(), Cost)); 1940 if (Cost >= BestCost) { 1941 LLVM_DEBUG({ 1942 if (BestCand == NoCand) 1943 dbgs() << " worse than no bundles\n"; 1944 else 1945 dbgs() << " worse than " 1946 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n'; 1947 }); 1948 continue; 1949 } 1950 if (!growRegion(Cand)) { 1951 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n"); 1952 continue; 1953 } 1954 1955 SpillPlacer->finish(); 1956 1957 // No live bundles, defer to splitSingleBlocks(). 1958 if (!Cand.LiveBundles.any()) { 1959 LLVM_DEBUG(dbgs() << " no bundles.\n"); 1960 continue; 1961 } 1962 1963 bool HasEvictionChain = false; 1964 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain); 1965 LLVM_DEBUG({ 1966 dbgs() << ", total = "; 1967 MBFI->printBlockFreq(dbgs(), Cost) << " with bundles"; 1968 for (int I : Cand.LiveBundles.set_bits()) 1969 dbgs() << " EB#" << I; 1970 dbgs() << ".\n"; 1971 }); 1972 if (Cost < BestCost) { 1973 BestCand = NumCands; 1974 BestCost = Cost; 1975 // See splitCanCauseEvictionChain for detailed description of bad 1976 // eviction chain scenarios. 1977 if (CanCauseEvictionChain) 1978 *CanCauseEvictionChain = HasEvictionChain; 1979 } 1980 ++NumCands; 1981 } 1982 1983 if (CanCauseEvictionChain && BestCand != NoCand) { 1984 // See splitCanCauseEvictionChain for detailed description of bad 1985 // eviction chain scenarios. 1986 LLVM_DEBUG(dbgs() << "Best split candidate of vreg " 1987 << printReg(VirtReg.reg(), TRI) << " may "); 1988 if (!(*CanCauseEvictionChain)) 1989 LLVM_DEBUG(dbgs() << "not "); 1990 LLVM_DEBUG(dbgs() << "cause bad eviction chain\n"); 1991 } 1992 1993 return BestCand; 1994 } 1995 1996 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand, 1997 bool HasCompact, 1998 SmallVectorImpl<Register> &NewVRegs) { 1999 SmallVector<unsigned, 8> UsedCands; 2000 // Prepare split editor. 2001 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 2002 SE->reset(LREdit, SplitSpillMode); 2003 2004 // Assign all edge bundles to the preferred candidate, or NoCand. 2005 BundleCand.assign(Bundles->getNumBundles(), NoCand); 2006 2007 // Assign bundles for the best candidate region. 2008 if (BestCand != NoCand) { 2009 GlobalSplitCandidate &Cand = GlobalCand[BestCand]; 2010 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) { 2011 UsedCands.push_back(BestCand); 2012 Cand.IntvIdx = SE->openIntv(); 2013 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in " 2014 << B << " bundles, intv " << Cand.IntvIdx << ".\n"); 2015 (void)B; 2016 } 2017 } 2018 2019 // Assign bundles for the compact region. 2020 if (HasCompact) { 2021 GlobalSplitCandidate &Cand = GlobalCand.front(); 2022 assert(!Cand.PhysReg && "Compact region has no physreg"); 2023 if (unsigned B = Cand.getBundles(BundleCand, 0)) { 2024 UsedCands.push_back(0); 2025 Cand.IntvIdx = SE->openIntv(); 2026 LLVM_DEBUG(dbgs() << "Split for compact region in " << B 2027 << " bundles, intv " << Cand.IntvIdx << ".\n"); 2028 (void)B; 2029 } 2030 } 2031 2032 splitAroundRegion(LREdit, UsedCands); 2033 return 0; 2034 } 2035 2036 //===----------------------------------------------------------------------===// 2037 // Per-Block Splitting 2038 //===----------------------------------------------------------------------===// 2039 2040 /// tryBlockSplit - Split a global live range around every block with uses. This 2041 /// creates a lot of local live ranges, that will be split by tryLocalSplit if 2042 /// they don't allocate. 2043 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order, 2044 SmallVectorImpl<Register> &NewVRegs) { 2045 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed"); 2046 Register Reg = VirtReg.reg(); 2047 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)); 2048 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 2049 SE->reset(LREdit, SplitSpillMode); 2050 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 2051 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 2052 if (SA->shouldSplitSingleBlock(BI, SingleInstrs)) 2053 SE->splitSingleBlock(BI); 2054 } 2055 // No blocks were split. 2056 if (LREdit.empty()) 2057 return 0; 2058 2059 // We did split for some blocks. 2060 SmallVector<unsigned, 8> IntvMap; 2061 SE->finish(&IntvMap); 2062 2063 // Tell LiveDebugVariables about the new ranges. 2064 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS); 2065 2066 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 2067 2068 // Sort out the new intervals created by splitting. The remainder interval 2069 // goes straight to spilling, the new local ranges get to stay RS_New. 2070 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) { 2071 LiveInterval &LI = LIS->getInterval(LREdit.get(I)); 2072 if (getStage(LI) == RS_New && IntvMap[I] == 0) 2073 setStage(LI, RS_Spill); 2074 } 2075 2076 if (VerifyEnabled) 2077 MF->verify(this, "After splitting live range around basic blocks"); 2078 return 0; 2079 } 2080 2081 //===----------------------------------------------------------------------===// 2082 // Per-Instruction Splitting 2083 //===----------------------------------------------------------------------===// 2084 2085 /// Get the number of allocatable registers that match the constraints of \p Reg 2086 /// on \p MI and that are also in \p SuperRC. 2087 static unsigned getNumAllocatableRegsForConstraints( 2088 const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC, 2089 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, 2090 const RegisterClassInfo &RCI) { 2091 assert(SuperRC && "Invalid register class"); 2092 2093 const TargetRegisterClass *ConstrainedRC = 2094 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI, 2095 /* ExploreBundle */ true); 2096 if (!ConstrainedRC) 2097 return 0; 2098 return RCI.getNumAllocatableRegs(ConstrainedRC); 2099 } 2100 2101 /// tryInstructionSplit - Split a live range around individual instructions. 2102 /// This is normally not worthwhile since the spiller is doing essentially the 2103 /// same thing. However, when the live range is in a constrained register 2104 /// class, it may help to insert copies such that parts of the live range can 2105 /// be moved to a larger register class. 2106 /// 2107 /// This is similar to spilling to a larger register class. 2108 unsigned 2109 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order, 2110 SmallVectorImpl<Register> &NewVRegs) { 2111 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg()); 2112 // There is no point to this if there are no larger sub-classes. 2113 if (!RegClassInfo.isProperSubClass(CurRC)) 2114 return 0; 2115 2116 // Always enable split spill mode, since we're effectively spilling to a 2117 // register. 2118 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 2119 SE->reset(LREdit, SplitEditor::SM_Size); 2120 2121 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 2122 if (Uses.size() <= 1) 2123 return 0; 2124 2125 LLVM_DEBUG(dbgs() << "Split around " << Uses.size() 2126 << " individual instrs.\n"); 2127 2128 const TargetRegisterClass *SuperRC = 2129 TRI->getLargestLegalSuperClass(CurRC, *MF); 2130 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC); 2131 // Split around every non-copy instruction if this split will relax 2132 // the constraints on the virtual register. 2133 // Otherwise, splitting just inserts uncoalescable copies that do not help 2134 // the allocation. 2135 for (const SlotIndex Use : Uses) { 2136 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Use)) 2137 if (MI->isFullCopy() || 2138 SuperRCNumAllocatableRegs == 2139 getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC, 2140 TII, TRI, RCI)) { 2141 LLVM_DEBUG(dbgs() << " skip:\t" << Use << '\t' << *MI); 2142 continue; 2143 } 2144 SE->openIntv(); 2145 SlotIndex SegStart = SE->enterIntvBefore(Use); 2146 SlotIndex SegStop = SE->leaveIntvAfter(Use); 2147 SE->useIntv(SegStart, SegStop); 2148 } 2149 2150 if (LREdit.empty()) { 2151 LLVM_DEBUG(dbgs() << "All uses were copies.\n"); 2152 return 0; 2153 } 2154 2155 SmallVector<unsigned, 8> IntvMap; 2156 SE->finish(&IntvMap); 2157 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS); 2158 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 2159 2160 // Assign all new registers to RS_Spill. This was the last chance. 2161 setStage(LREdit.begin(), LREdit.end(), RS_Spill); 2162 return 0; 2163 } 2164 2165 //===----------------------------------------------------------------------===// 2166 // Local Splitting 2167 //===----------------------------------------------------------------------===// 2168 2169 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted 2170 /// in order to use PhysReg between two entries in SA->UseSlots. 2171 /// 2172 /// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1]. 2173 /// 2174 void RAGreedy::calcGapWeights(MCRegister PhysReg, 2175 SmallVectorImpl<float> &GapWeight) { 2176 assert(SA->getUseBlocks().size() == 1 && "Not a local interval"); 2177 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front(); 2178 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 2179 const unsigned NumGaps = Uses.size()-1; 2180 2181 // Start and end points for the interference check. 2182 SlotIndex StartIdx = 2183 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr; 2184 SlotIndex StopIdx = 2185 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr; 2186 2187 GapWeight.assign(NumGaps, 0.0f); 2188 2189 // Add interference from each overlapping register. 2190 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 2191 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units) 2192 .checkInterference()) 2193 continue; 2194 2195 // We know that VirtReg is a continuous interval from FirstInstr to 2196 // LastInstr, so we don't need InterferenceQuery. 2197 // 2198 // Interference that overlaps an instruction is counted in both gaps 2199 // surrounding the instruction. The exception is interference before 2200 // StartIdx and after StopIdx. 2201 // 2202 LiveIntervalUnion::SegmentIter IntI = 2203 Matrix->getLiveUnions()[*Units] .find(StartIdx); 2204 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) { 2205 // Skip the gaps before IntI. 2206 while (Uses[Gap+1].getBoundaryIndex() < IntI.start()) 2207 if (++Gap == NumGaps) 2208 break; 2209 if (Gap == NumGaps) 2210 break; 2211 2212 // Update the gaps covered by IntI. 2213 const float weight = IntI.value()->weight(); 2214 for (; Gap != NumGaps; ++Gap) { 2215 GapWeight[Gap] = std::max(GapWeight[Gap], weight); 2216 if (Uses[Gap+1].getBaseIndex() >= IntI.stop()) 2217 break; 2218 } 2219 if (Gap == NumGaps) 2220 break; 2221 } 2222 } 2223 2224 // Add fixed interference. 2225 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 2226 const LiveRange &LR = LIS->getRegUnit(*Units); 2227 LiveRange::const_iterator I = LR.find(StartIdx); 2228 LiveRange::const_iterator E = LR.end(); 2229 2230 // Same loop as above. Mark any overlapped gaps as HUGE_VALF. 2231 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) { 2232 while (Uses[Gap+1].getBoundaryIndex() < I->start) 2233 if (++Gap == NumGaps) 2234 break; 2235 if (Gap == NumGaps) 2236 break; 2237 2238 for (; Gap != NumGaps; ++Gap) { 2239 GapWeight[Gap] = huge_valf; 2240 if (Uses[Gap+1].getBaseIndex() >= I->end) 2241 break; 2242 } 2243 if (Gap == NumGaps) 2244 break; 2245 } 2246 } 2247 } 2248 2249 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only 2250 /// basic block. 2251 /// 2252 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order, 2253 SmallVectorImpl<Register> &NewVRegs) { 2254 // TODO: the function currently only handles a single UseBlock; it should be 2255 // possible to generalize. 2256 if (SA->getUseBlocks().size() != 1) 2257 return 0; 2258 2259 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front(); 2260 2261 // Note that it is possible to have an interval that is live-in or live-out 2262 // while only covering a single block - A phi-def can use undef values from 2263 // predecessors, and the block could be a single-block loop. 2264 // We don't bother doing anything clever about such a case, we simply assume 2265 // that the interval is continuous from FirstInstr to LastInstr. We should 2266 // make sure that we don't do anything illegal to such an interval, though. 2267 2268 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 2269 if (Uses.size() <= 2) 2270 return 0; 2271 const unsigned NumGaps = Uses.size()-1; 2272 2273 LLVM_DEBUG({ 2274 dbgs() << "tryLocalSplit: "; 2275 for (const auto &Use : Uses) 2276 dbgs() << ' ' << Use; 2277 dbgs() << '\n'; 2278 }); 2279 2280 // If VirtReg is live across any register mask operands, compute a list of 2281 // gaps with register masks. 2282 SmallVector<unsigned, 8> RegMaskGaps; 2283 if (Matrix->checkRegMaskInterference(VirtReg)) { 2284 // Get regmask slots for the whole block. 2285 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber()); 2286 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:"); 2287 // Constrain to VirtReg's live range. 2288 unsigned RI = 2289 llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin(); 2290 unsigned RE = RMS.size(); 2291 for (unsigned I = 0; I != NumGaps && RI != RE; ++I) { 2292 // Look for Uses[I] <= RMS <= Uses[I + 1]. 2293 assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I])); 2294 if (SlotIndex::isEarlierInstr(Uses[I + 1], RMS[RI])) 2295 continue; 2296 // Skip a regmask on the same instruction as the last use. It doesn't 2297 // overlap the live range. 2298 if (SlotIndex::isSameInstr(Uses[I + 1], RMS[RI]) && I + 1 == NumGaps) 2299 break; 2300 LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-' 2301 << Uses[I + 1]); 2302 RegMaskGaps.push_back(I); 2303 // Advance ri to the next gap. A regmask on one of the uses counts in 2304 // both gaps. 2305 while (RI != RE && SlotIndex::isEarlierInstr(RMS[RI], Uses[I + 1])) 2306 ++RI; 2307 } 2308 LLVM_DEBUG(dbgs() << '\n'); 2309 } 2310 2311 // Since we allow local split results to be split again, there is a risk of 2312 // creating infinite loops. It is tempting to require that the new live 2313 // ranges have less instructions than the original. That would guarantee 2314 // convergence, but it is too strict. A live range with 3 instructions can be 2315 // split 2+3 (including the COPY), and we want to allow that. 2316 // 2317 // Instead we use these rules: 2318 // 2319 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the 2320 // noop split, of course). 2321 // 2. Require progress be made for ranges with getStage() == RS_Split2. All 2322 // the new ranges must have fewer instructions than before the split. 2323 // 3. New ranges with the same number of instructions are marked RS_Split2, 2324 // smaller ranges are marked RS_New. 2325 // 2326 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent 2327 // excessive splitting and infinite loops. 2328 // 2329 bool ProgressRequired = getStage(VirtReg) >= RS_Split2; 2330 2331 // Best split candidate. 2332 unsigned BestBefore = NumGaps; 2333 unsigned BestAfter = 0; 2334 float BestDiff = 0; 2335 2336 const float blockFreq = 2337 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() * 2338 (1.0f / MBFI->getEntryFreq()); 2339 SmallVector<float, 8> GapWeight; 2340 2341 for (MCPhysReg PhysReg : Order) { 2342 assert(PhysReg); 2343 // Keep track of the largest spill weight that would need to be evicted in 2344 // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1]. 2345 calcGapWeights(PhysReg, GapWeight); 2346 2347 // Remove any gaps with regmask clobbers. 2348 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg)) 2349 for (unsigned I = 0, E = RegMaskGaps.size(); I != E; ++I) 2350 GapWeight[RegMaskGaps[I]] = huge_valf; 2351 2352 // Try to find the best sequence of gaps to close. 2353 // The new spill weight must be larger than any gap interference. 2354 2355 // We will split before Uses[SplitBefore] and after Uses[SplitAfter]. 2356 unsigned SplitBefore = 0, SplitAfter = 1; 2357 2358 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]). 2359 // It is the spill weight that needs to be evicted. 2360 float MaxGap = GapWeight[0]; 2361 2362 while (true) { 2363 // Live before/after split? 2364 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn; 2365 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut; 2366 2367 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore] 2368 << '-' << Uses[SplitAfter] << " I=" << MaxGap); 2369 2370 // Stop before the interval gets so big we wouldn't be making progress. 2371 if (!LiveBefore && !LiveAfter) { 2372 LLVM_DEBUG(dbgs() << " all\n"); 2373 break; 2374 } 2375 // Should the interval be extended or shrunk? 2376 bool Shrink = true; 2377 2378 // How many gaps would the new range have? 2379 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter; 2380 2381 // Legally, without causing looping? 2382 bool Legal = !ProgressRequired || NewGaps < NumGaps; 2383 2384 if (Legal && MaxGap < huge_valf) { 2385 // Estimate the new spill weight. Each instruction reads or writes the 2386 // register. Conservatively assume there are no read-modify-write 2387 // instructions. 2388 // 2389 // Try to guess the size of the new interval. 2390 const float EstWeight = normalizeSpillWeight( 2391 blockFreq * (NewGaps + 1), 2392 Uses[SplitBefore].distance(Uses[SplitAfter]) + 2393 (LiveBefore + LiveAfter) * SlotIndex::InstrDist, 2394 1); 2395 // Would this split be possible to allocate? 2396 // Never allocate all gaps, we wouldn't be making progress. 2397 LLVM_DEBUG(dbgs() << " w=" << EstWeight); 2398 if (EstWeight * Hysteresis >= MaxGap) { 2399 Shrink = false; 2400 float Diff = EstWeight - MaxGap; 2401 if (Diff > BestDiff) { 2402 LLVM_DEBUG(dbgs() << " (best)"); 2403 BestDiff = Hysteresis * Diff; 2404 BestBefore = SplitBefore; 2405 BestAfter = SplitAfter; 2406 } 2407 } 2408 } 2409 2410 // Try to shrink. 2411 if (Shrink) { 2412 if (++SplitBefore < SplitAfter) { 2413 LLVM_DEBUG(dbgs() << " shrink\n"); 2414 // Recompute the max when necessary. 2415 if (GapWeight[SplitBefore - 1] >= MaxGap) { 2416 MaxGap = GapWeight[SplitBefore]; 2417 for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I) 2418 MaxGap = std::max(MaxGap, GapWeight[I]); 2419 } 2420 continue; 2421 } 2422 MaxGap = 0; 2423 } 2424 2425 // Try to extend the interval. 2426 if (SplitAfter >= NumGaps) { 2427 LLVM_DEBUG(dbgs() << " end\n"); 2428 break; 2429 } 2430 2431 LLVM_DEBUG(dbgs() << " extend\n"); 2432 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]); 2433 } 2434 } 2435 2436 // Didn't find any candidates? 2437 if (BestBefore == NumGaps) 2438 return 0; 2439 2440 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-' 2441 << Uses[BestAfter] << ", " << BestDiff << ", " 2442 << (BestAfter - BestBefore + 1) << " instrs\n"); 2443 2444 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 2445 SE->reset(LREdit); 2446 2447 SE->openIntv(); 2448 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]); 2449 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]); 2450 SE->useIntv(SegStart, SegStop); 2451 SmallVector<unsigned, 8> IntvMap; 2452 SE->finish(&IntvMap); 2453 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS); 2454 2455 // If the new range has the same number of instructions as before, mark it as 2456 // RS_Split2 so the next split will be forced to make progress. Otherwise, 2457 // leave the new intervals as RS_New so they can compete. 2458 bool LiveBefore = BestBefore != 0 || BI.LiveIn; 2459 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut; 2460 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter; 2461 if (NewGaps >= NumGaps) { 2462 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:"); 2463 assert(!ProgressRequired && "Didn't make progress when it was required."); 2464 for (unsigned I = 0, E = IntvMap.size(); I != E; ++I) 2465 if (IntvMap[I] == 1) { 2466 setStage(LIS->getInterval(LREdit.get(I)), RS_Split2); 2467 LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I))); 2468 } 2469 LLVM_DEBUG(dbgs() << '\n'); 2470 } 2471 ++NumLocalSplits; 2472 2473 return 0; 2474 } 2475 2476 //===----------------------------------------------------------------------===// 2477 // Live Range Splitting 2478 //===----------------------------------------------------------------------===// 2479 2480 /// trySplit - Try to split VirtReg or one of its interferences, making it 2481 /// assignable. 2482 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs. 2483 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order, 2484 SmallVectorImpl<Register> &NewVRegs, 2485 const SmallVirtRegSet &FixedRegisters) { 2486 // Ranges must be Split2 or less. 2487 if (getStage(VirtReg) >= RS_Spill) 2488 return 0; 2489 2490 // Local intervals are handled separately. 2491 if (LIS->intervalIsInOneMBB(VirtReg)) { 2492 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName, 2493 TimerGroupDescription, TimePassesIsEnabled); 2494 SA->analyze(&VirtReg); 2495 Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs); 2496 if (PhysReg || !NewVRegs.empty()) 2497 return PhysReg; 2498 return tryInstructionSplit(VirtReg, Order, NewVRegs); 2499 } 2500 2501 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName, 2502 TimerGroupDescription, TimePassesIsEnabled); 2503 2504 SA->analyze(&VirtReg); 2505 2506 // First try to split around a region spanning multiple blocks. RS_Split2 2507 // ranges already made dubious progress with region splitting, so they go 2508 // straight to single block splitting. 2509 if (getStage(VirtReg) < RS_Split2) { 2510 MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs); 2511 if (PhysReg || !NewVRegs.empty()) 2512 return PhysReg; 2513 } 2514 2515 // Then isolate blocks. 2516 return tryBlockSplit(VirtReg, Order, NewVRegs); 2517 } 2518 2519 //===----------------------------------------------------------------------===// 2520 // Last Chance Recoloring 2521 //===----------------------------------------------------------------------===// 2522 2523 /// Return true if \p reg has any tied def operand. 2524 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) { 2525 for (const MachineOperand &MO : MRI->def_operands(reg)) 2526 if (MO.isTied()) 2527 return true; 2528 2529 return false; 2530 } 2531 2532 /// mayRecolorAllInterferences - Check if the virtual registers that 2533 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be 2534 /// recolored to free \p PhysReg. 2535 /// When true is returned, \p RecoloringCandidates has been augmented with all 2536 /// the live intervals that need to be recolored in order to free \p PhysReg 2537 /// for \p VirtReg. 2538 /// \p FixedRegisters contains all the virtual registers that cannot be 2539 /// recolored. 2540 bool RAGreedy::mayRecolorAllInterferences( 2541 MCRegister PhysReg, LiveInterval &VirtReg, SmallLISet &RecoloringCandidates, 2542 const SmallVirtRegSet &FixedRegisters) { 2543 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg()); 2544 2545 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 2546 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 2547 // If there is LastChanceRecoloringMaxInterference or more interferences, 2548 // chances are one would not be recolorable. 2549 if (Q.interferingVRegs(LastChanceRecoloringMaxInterference).size() >= 2550 LastChanceRecoloringMaxInterference && 2551 !ExhaustiveSearch) { 2552 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n"); 2553 CutOffInfo |= CO_Interf; 2554 return false; 2555 } 2556 for (LiveInterval *Intf : reverse(Q.interferingVRegs())) { 2557 // If Intf is done and sit on the same register class as VirtReg, 2558 // it would not be recolorable as it is in the same state as VirtReg. 2559 // However, if VirtReg has tied defs and Intf doesn't, then 2560 // there is still a point in examining if it can be recolorable. 2561 if (((getStage(*Intf) == RS_Done && 2562 MRI->getRegClass(Intf->reg()) == CurRC) && 2563 !(hasTiedDef(MRI, VirtReg.reg()) && 2564 !hasTiedDef(MRI, Intf->reg()))) || 2565 FixedRegisters.count(Intf->reg())) { 2566 LLVM_DEBUG( 2567 dbgs() << "Early abort: the interference is not recolorable.\n"); 2568 return false; 2569 } 2570 RecoloringCandidates.insert(Intf); 2571 } 2572 } 2573 return true; 2574 } 2575 2576 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring 2577 /// its interferences. 2578 /// Last chance recoloring chooses a color for \p VirtReg and recolors every 2579 /// virtual register that was using it. The recoloring process may recursively 2580 /// use the last chance recoloring. Therefore, when a virtual register has been 2581 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot 2582 /// be last-chance-recolored again during this recoloring "session". 2583 /// E.g., 2584 /// Let 2585 /// vA can use {R1, R2 } 2586 /// vB can use { R2, R3} 2587 /// vC can use {R1 } 2588 /// Where vA, vB, and vC cannot be split anymore (they are reloads for 2589 /// instance) and they all interfere. 2590 /// 2591 /// vA is assigned R1 2592 /// vB is assigned R2 2593 /// vC tries to evict vA but vA is already done. 2594 /// Regular register allocation fails. 2595 /// 2596 /// Last chance recoloring kicks in: 2597 /// vC does as if vA was evicted => vC uses R1. 2598 /// vC is marked as fixed. 2599 /// vA needs to find a color. 2600 /// None are available. 2601 /// vA cannot evict vC: vC is a fixed virtual register now. 2602 /// vA does as if vB was evicted => vA uses R2. 2603 /// vB needs to find a color. 2604 /// R3 is available. 2605 /// Recoloring => vC = R1, vA = R2, vB = R3 2606 /// 2607 /// \p Order defines the preferred allocation order for \p VirtReg. 2608 /// \p NewRegs will contain any new virtual register that have been created 2609 /// (split, spill) during the process and that must be assigned. 2610 /// \p FixedRegisters contains all the virtual registers that cannot be 2611 /// recolored. 2612 /// \p Depth gives the current depth of the last chance recoloring. 2613 /// \return a physical register that can be used for VirtReg or ~0u if none 2614 /// exists. 2615 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg, 2616 AllocationOrder &Order, 2617 SmallVectorImpl<Register> &NewVRegs, 2618 SmallVirtRegSet &FixedRegisters, 2619 unsigned Depth) { 2620 if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg)) 2621 return ~0u; 2622 2623 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n'); 2624 // Ranges must be Done. 2625 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) && 2626 "Last chance recoloring should really be last chance"); 2627 // Set the max depth to LastChanceRecoloringMaxDepth. 2628 // We may want to reconsider that if we end up with a too large search space 2629 // for target with hundreds of registers. 2630 // Indeed, in that case we may want to cut the search space earlier. 2631 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) { 2632 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n"); 2633 CutOffInfo |= CO_Depth; 2634 return ~0u; 2635 } 2636 2637 // Set of Live intervals that will need to be recolored. 2638 SmallLISet RecoloringCandidates; 2639 // Record the original mapping virtual register to physical register in case 2640 // the recoloring fails. 2641 DenseMap<Register, MCRegister> VirtRegToPhysReg; 2642 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in 2643 // this recoloring "session". 2644 assert(!FixedRegisters.count(VirtReg.reg())); 2645 FixedRegisters.insert(VirtReg.reg()); 2646 SmallVector<Register, 4> CurrentNewVRegs; 2647 2648 for (MCRegister PhysReg : Order) { 2649 assert(PhysReg.isValid()); 2650 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to " 2651 << printReg(PhysReg, TRI) << '\n'); 2652 RecoloringCandidates.clear(); 2653 VirtRegToPhysReg.clear(); 2654 CurrentNewVRegs.clear(); 2655 2656 // It is only possible to recolor virtual register interference. 2657 if (Matrix->checkInterference(VirtReg, PhysReg) > 2658 LiveRegMatrix::IK_VirtReg) { 2659 LLVM_DEBUG( 2660 dbgs() << "Some interferences are not with virtual registers.\n"); 2661 2662 continue; 2663 } 2664 2665 // Early give up on this PhysReg if it is obvious we cannot recolor all 2666 // the interferences. 2667 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates, 2668 FixedRegisters)) { 2669 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n"); 2670 continue; 2671 } 2672 2673 // RecoloringCandidates contains all the virtual registers that interfer 2674 // with VirtReg on PhysReg (or one of its aliases). 2675 // Enqueue them for recoloring and perform the actual recoloring. 2676 PQueue RecoloringQueue; 2677 for (LiveInterval *RC : RecoloringCandidates) { 2678 Register ItVirtReg = RC->reg(); 2679 enqueue(RecoloringQueue, RC); 2680 assert(VRM->hasPhys(ItVirtReg) && 2681 "Interferences are supposed to be with allocated variables"); 2682 2683 // Record the current allocation. 2684 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg); 2685 // unset the related struct. 2686 Matrix->unassign(*RC); 2687 } 2688 2689 // Do as if VirtReg was assigned to PhysReg so that the underlying 2690 // recoloring has the right information about the interferes and 2691 // available colors. 2692 Matrix->assign(VirtReg, PhysReg); 2693 2694 // Save the current recoloring state. 2695 // If we cannot recolor all the interferences, we will have to start again 2696 // at this point for the next physical register. 2697 SmallVirtRegSet SaveFixedRegisters(FixedRegisters); 2698 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs, 2699 FixedRegisters, Depth)) { 2700 // Push the queued vregs into the main queue. 2701 for (Register NewVReg : CurrentNewVRegs) 2702 NewVRegs.push_back(NewVReg); 2703 // Do not mess up with the global assignment process. 2704 // I.e., VirtReg must be unassigned. 2705 Matrix->unassign(VirtReg); 2706 return PhysReg; 2707 } 2708 2709 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to " 2710 << printReg(PhysReg, TRI) << '\n'); 2711 2712 // The recoloring attempt failed, undo the changes. 2713 FixedRegisters = SaveFixedRegisters; 2714 Matrix->unassign(VirtReg); 2715 2716 // For a newly created vreg which is also in RecoloringCandidates, 2717 // don't add it to NewVRegs because its physical register will be restored 2718 // below. Other vregs in CurrentNewVRegs are created by calling 2719 // selectOrSplit and should be added into NewVRegs. 2720 for (Register &R : CurrentNewVRegs) { 2721 if (RecoloringCandidates.count(&LIS->getInterval(R))) 2722 continue; 2723 NewVRegs.push_back(R); 2724 } 2725 2726 for (LiveInterval *RC : RecoloringCandidates) { 2727 Register ItVirtReg = RC->reg(); 2728 if (VRM->hasPhys(ItVirtReg)) 2729 Matrix->unassign(*RC); 2730 MCRegister ItPhysReg = VirtRegToPhysReg[ItVirtReg]; 2731 Matrix->assign(*RC, ItPhysReg); 2732 } 2733 } 2734 2735 // Last chance recoloring did not worked either, give up. 2736 return ~0u; 2737 } 2738 2739 /// tryRecoloringCandidates - Try to assign a new color to every register 2740 /// in \RecoloringQueue. 2741 /// \p NewRegs will contain any new virtual register created during the 2742 /// recoloring process. 2743 /// \p FixedRegisters[in/out] contains all the registers that have been 2744 /// recolored. 2745 /// \return true if all virtual registers in RecoloringQueue were successfully 2746 /// recolored, false otherwise. 2747 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue, 2748 SmallVectorImpl<Register> &NewVRegs, 2749 SmallVirtRegSet &FixedRegisters, 2750 unsigned Depth) { 2751 while (!RecoloringQueue.empty()) { 2752 LiveInterval *LI = dequeue(RecoloringQueue); 2753 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n'); 2754 MCRegister PhysReg = 2755 selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1); 2756 // When splitting happens, the live-range may actually be empty. 2757 // In that case, this is okay to continue the recoloring even 2758 // if we did not find an alternative color for it. Indeed, 2759 // there will not be anything to color for LI in the end. 2760 if (PhysReg == ~0u || (!PhysReg && !LI->empty())) 2761 return false; 2762 2763 if (!PhysReg) { 2764 assert(LI->empty() && "Only empty live-range do not require a register"); 2765 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI 2766 << " succeeded. Empty LI.\n"); 2767 continue; 2768 } 2769 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI 2770 << " succeeded with: " << printReg(PhysReg, TRI) << '\n'); 2771 2772 Matrix->assign(*LI, PhysReg); 2773 FixedRegisters.insert(LI->reg()); 2774 } 2775 return true; 2776 } 2777 2778 //===----------------------------------------------------------------------===// 2779 // Main Entry Point 2780 //===----------------------------------------------------------------------===// 2781 2782 MCRegister RAGreedy::selectOrSplit(LiveInterval &VirtReg, 2783 SmallVectorImpl<Register> &NewVRegs) { 2784 CutOffInfo = CO_None; 2785 LLVMContext &Ctx = MF->getFunction().getContext(); 2786 SmallVirtRegSet FixedRegisters; 2787 MCRegister Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters); 2788 if (Reg == ~0U && (CutOffInfo != CO_None)) { 2789 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf); 2790 if (CutOffEncountered == CO_Depth) 2791 Ctx.emitError("register allocation failed: maximum depth for recoloring " 2792 "reached. Use -fexhaustive-register-search to skip " 2793 "cutoffs"); 2794 else if (CutOffEncountered == CO_Interf) 2795 Ctx.emitError("register allocation failed: maximum interference for " 2796 "recoloring reached. Use -fexhaustive-register-search " 2797 "to skip cutoffs"); 2798 else if (CutOffEncountered == (CO_Depth | CO_Interf)) 2799 Ctx.emitError("register allocation failed: maximum interference and " 2800 "depth for recoloring reached. Use " 2801 "-fexhaustive-register-search to skip cutoffs"); 2802 } 2803 return Reg; 2804 } 2805 2806 /// Using a CSR for the first time has a cost because it causes push|pop 2807 /// to be added to prologue|epilogue. Splitting a cold section of the live 2808 /// range can have lower cost than using the CSR for the first time; 2809 /// Spilling a live range in the cold path can have lower cost than using 2810 /// the CSR for the first time. Returns the physical register if we decide 2811 /// to use the CSR; otherwise return 0. 2812 MCRegister 2813 RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order, 2814 MCRegister PhysReg, uint8_t &CostPerUseLimit, 2815 SmallVectorImpl<Register> &NewVRegs) { 2816 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) { 2817 // We choose spill over using the CSR for the first time if the spill cost 2818 // is lower than CSRCost. 2819 SA->analyze(&VirtReg); 2820 if (calcSpillCost() >= CSRCost) 2821 return PhysReg; 2822 2823 // We are going to spill, set CostPerUseLimit to 1 to make sure that 2824 // we will not use a callee-saved register in tryEvict. 2825 CostPerUseLimit = 1; 2826 return 0; 2827 } 2828 if (getStage(VirtReg) < RS_Split) { 2829 // We choose pre-splitting over using the CSR for the first time if 2830 // the cost of splitting is lower than CSRCost. 2831 SA->analyze(&VirtReg); 2832 unsigned NumCands = 0; 2833 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost. 2834 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost, 2835 NumCands, true /*IgnoreCSR*/); 2836 if (BestCand == NoCand) 2837 // Use the CSR if we can't find a region split below CSRCost. 2838 return PhysReg; 2839 2840 // Perform the actual pre-splitting. 2841 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs); 2842 return 0; 2843 } 2844 return PhysReg; 2845 } 2846 2847 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) { 2848 // Do not keep invalid information around. 2849 SetOfBrokenHints.remove(&LI); 2850 } 2851 2852 void RAGreedy::initializeCSRCost() { 2853 // We use the larger one out of the command-line option and the value report 2854 // by TRI. 2855 CSRCost = BlockFrequency( 2856 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost())); 2857 if (!CSRCost.getFrequency()) 2858 return; 2859 2860 // Raw cost is relative to Entry == 2^14; scale it appropriately. 2861 uint64_t ActualEntry = MBFI->getEntryFreq(); 2862 if (!ActualEntry) { 2863 CSRCost = 0; 2864 return; 2865 } 2866 uint64_t FixedEntry = 1 << 14; 2867 if (ActualEntry < FixedEntry) 2868 CSRCost *= BranchProbability(ActualEntry, FixedEntry); 2869 else if (ActualEntry <= UINT32_MAX) 2870 // Invert the fraction and divide. 2871 CSRCost /= BranchProbability(FixedEntry, ActualEntry); 2872 else 2873 // Can't use BranchProbability in general, since it takes 32-bit numbers. 2874 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry); 2875 } 2876 2877 /// Collect the hint info for \p Reg. 2878 /// The results are stored into \p Out. 2879 /// \p Out is not cleared before being populated. 2880 void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) { 2881 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) { 2882 if (!Instr.isFullCopy()) 2883 continue; 2884 // Look for the other end of the copy. 2885 Register OtherReg = Instr.getOperand(0).getReg(); 2886 if (OtherReg == Reg) { 2887 OtherReg = Instr.getOperand(1).getReg(); 2888 if (OtherReg == Reg) 2889 continue; 2890 } 2891 // Get the current assignment. 2892 MCRegister OtherPhysReg = 2893 OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg); 2894 // Push the collected information. 2895 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg, 2896 OtherPhysReg)); 2897 } 2898 } 2899 2900 /// Using the given \p List, compute the cost of the broken hints if 2901 /// \p PhysReg was used. 2902 /// \return The cost of \p List for \p PhysReg. 2903 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List, 2904 MCRegister PhysReg) { 2905 BlockFrequency Cost = 0; 2906 for (const HintInfo &Info : List) { 2907 if (Info.PhysReg != PhysReg) 2908 Cost += Info.Freq; 2909 } 2910 return Cost; 2911 } 2912 2913 /// Using the register assigned to \p VirtReg, try to recolor 2914 /// all the live ranges that are copy-related with \p VirtReg. 2915 /// The recoloring is then propagated to all the live-ranges that have 2916 /// been recolored and so on, until no more copies can be coalesced or 2917 /// it is not profitable. 2918 /// For a given live range, profitability is determined by the sum of the 2919 /// frequencies of the non-identity copies it would introduce with the old 2920 /// and new register. 2921 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) { 2922 // We have a broken hint, check if it is possible to fix it by 2923 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted 2924 // some register and PhysReg may be available for the other live-ranges. 2925 SmallSet<Register, 4> Visited; 2926 SmallVector<unsigned, 2> RecoloringCandidates; 2927 HintsInfo Info; 2928 Register Reg = VirtReg.reg(); 2929 MCRegister PhysReg = VRM->getPhys(Reg); 2930 // Start the recoloring algorithm from the input live-interval, then 2931 // it will propagate to the ones that are copy-related with it. 2932 Visited.insert(Reg); 2933 RecoloringCandidates.push_back(Reg); 2934 2935 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI) 2936 << '(' << printReg(PhysReg, TRI) << ")\n"); 2937 2938 do { 2939 Reg = RecoloringCandidates.pop_back_val(); 2940 2941 // We cannot recolor physical register. 2942 if (Register::isPhysicalRegister(Reg)) 2943 continue; 2944 2945 // This may be a skipped class 2946 if (!VRM->hasPhys(Reg)) { 2947 assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) && 2948 "We have an unallocated variable which should have been handled"); 2949 continue; 2950 } 2951 2952 // Get the live interval mapped with this virtual register to be able 2953 // to check for the interference with the new color. 2954 LiveInterval &LI = LIS->getInterval(Reg); 2955 MCRegister CurrPhys = VRM->getPhys(Reg); 2956 // Check that the new color matches the register class constraints and 2957 // that it is free for this live range. 2958 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) || 2959 Matrix->checkInterference(LI, PhysReg))) 2960 continue; 2961 2962 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI) 2963 << ") is recolorable.\n"); 2964 2965 // Gather the hint info. 2966 Info.clear(); 2967 collectHintInfo(Reg, Info); 2968 // Check if recoloring the live-range will increase the cost of the 2969 // non-identity copies. 2970 if (CurrPhys != PhysReg) { 2971 LLVM_DEBUG(dbgs() << "Checking profitability:\n"); 2972 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys); 2973 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg); 2974 LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency() 2975 << "\nNew Cost: " << NewCopiesCost.getFrequency() 2976 << '\n'); 2977 if (OldCopiesCost < NewCopiesCost) { 2978 LLVM_DEBUG(dbgs() << "=> Not profitable.\n"); 2979 continue; 2980 } 2981 // At this point, the cost is either cheaper or equal. If it is 2982 // equal, we consider this is profitable because it may expose 2983 // more recoloring opportunities. 2984 LLVM_DEBUG(dbgs() << "=> Profitable.\n"); 2985 // Recolor the live-range. 2986 Matrix->unassign(LI); 2987 Matrix->assign(LI, PhysReg); 2988 } 2989 // Push all copy-related live-ranges to keep reconciling the broken 2990 // hints. 2991 for (const HintInfo &HI : Info) { 2992 if (Visited.insert(HI.Reg).second) 2993 RecoloringCandidates.push_back(HI.Reg); 2994 } 2995 } while (!RecoloringCandidates.empty()); 2996 } 2997 2998 /// Try to recolor broken hints. 2999 /// Broken hints may be repaired by recoloring when an evicted variable 3000 /// freed up a register for a larger live-range. 3001 /// Consider the following example: 3002 /// BB1: 3003 /// a = 3004 /// b = 3005 /// BB2: 3006 /// ... 3007 /// = b 3008 /// = a 3009 /// Let us assume b gets split: 3010 /// BB1: 3011 /// a = 3012 /// b = 3013 /// BB2: 3014 /// c = b 3015 /// ... 3016 /// d = c 3017 /// = d 3018 /// = a 3019 /// Because of how the allocation work, b, c, and d may be assigned different 3020 /// colors. Now, if a gets evicted later: 3021 /// BB1: 3022 /// a = 3023 /// st a, SpillSlot 3024 /// b = 3025 /// BB2: 3026 /// c = b 3027 /// ... 3028 /// d = c 3029 /// = d 3030 /// e = ld SpillSlot 3031 /// = e 3032 /// This is likely that we can assign the same register for b, c, and d, 3033 /// getting rid of 2 copies. 3034 void RAGreedy::tryHintsRecoloring() { 3035 for (LiveInterval *LI : SetOfBrokenHints) { 3036 assert(Register::isVirtualRegister(LI->reg()) && 3037 "Recoloring is possible only for virtual registers"); 3038 // Some dead defs may be around (e.g., because of debug uses). 3039 // Ignore those. 3040 if (!VRM->hasPhys(LI->reg())) 3041 continue; 3042 tryHintRecoloring(*LI); 3043 } 3044 } 3045 3046 MCRegister RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg, 3047 SmallVectorImpl<Register> &NewVRegs, 3048 SmallVirtRegSet &FixedRegisters, 3049 unsigned Depth) { 3050 uint8_t CostPerUseLimit = uint8_t(~0u); 3051 // First try assigning a free register. 3052 auto Order = 3053 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix); 3054 if (MCRegister PhysReg = 3055 tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) { 3056 // If VirtReg got an assignment, the eviction info is no longer relevant. 3057 LastEvicted.clearEvicteeInfo(VirtReg.reg()); 3058 // When NewVRegs is not empty, we may have made decisions such as evicting 3059 // a virtual register, go with the earlier decisions and use the physical 3060 // register. 3061 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) && 3062 NewVRegs.empty()) { 3063 MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg, 3064 CostPerUseLimit, NewVRegs); 3065 if (CSRReg || !NewVRegs.empty()) 3066 // Return now if we decide to use a CSR or create new vregs due to 3067 // pre-splitting. 3068 return CSRReg; 3069 } else 3070 return PhysReg; 3071 } 3072 3073 LiveRangeStage Stage = getStage(VirtReg); 3074 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade " 3075 << ExtraRegInfo[VirtReg.reg()].Cascade << '\n'); 3076 3077 // Try to evict a less worthy live range, but only for ranges from the primary 3078 // queue. The RS_Split ranges already failed to do this, and they should not 3079 // get a second chance until they have been split. 3080 if (Stage != RS_Split) 3081 if (Register PhysReg = 3082 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit, 3083 FixedRegisters)) { 3084 Register Hint = MRI->getSimpleHint(VirtReg.reg()); 3085 // If VirtReg has a hint and that hint is broken record this 3086 // virtual register as a recoloring candidate for broken hint. 3087 // Indeed, since we evicted a variable in its neighborhood it is 3088 // likely we can at least partially recolor some of the 3089 // copy-related live-ranges. 3090 if (Hint && Hint != PhysReg) 3091 SetOfBrokenHints.insert(&VirtReg); 3092 // If VirtReg eviction someone, the eviction info for it as an evictee is 3093 // no longer relevant. 3094 LastEvicted.clearEvicteeInfo(VirtReg.reg()); 3095 return PhysReg; 3096 } 3097 3098 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs"); 3099 3100 // The first time we see a live range, don't try to split or spill. 3101 // Wait until the second time, when all smaller ranges have been allocated. 3102 // This gives a better picture of the interference to split around. 3103 if (Stage < RS_Split) { 3104 setStage(VirtReg, RS_Split); 3105 LLVM_DEBUG(dbgs() << "wait for second round\n"); 3106 NewVRegs.push_back(VirtReg.reg()); 3107 return 0; 3108 } 3109 3110 if (Stage < RS_Spill) { 3111 // Try splitting VirtReg or interferences. 3112 unsigned NewVRegSizeBefore = NewVRegs.size(); 3113 Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters); 3114 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) { 3115 // If VirtReg got split, the eviction info is no longer relevant. 3116 LastEvicted.clearEvicteeInfo(VirtReg.reg()); 3117 return PhysReg; 3118 } 3119 } 3120 3121 // If we couldn't allocate a register from spilling, there is probably some 3122 // invalid inline assembly. The base class will report it. 3123 if (Stage >= RS_Done || !VirtReg.isSpillable()) 3124 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters, 3125 Depth); 3126 3127 // Finally spill VirtReg itself. 3128 if ((EnableDeferredSpilling || 3129 TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) && 3130 getStage(VirtReg) < RS_Memory) { 3131 // TODO: This is experimental and in particular, we do not model 3132 // the live range splitting done by spilling correctly. 3133 // We would need a deep integration with the spiller to do the 3134 // right thing here. Anyway, that is still good for early testing. 3135 setStage(VirtReg, RS_Memory); 3136 LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n"); 3137 NewVRegs.push_back(VirtReg.reg()); 3138 } else { 3139 NamedRegionTimer T("spill", "Spiller", TimerGroupName, 3140 TimerGroupDescription, TimePassesIsEnabled); 3141 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 3142 spiller().spill(LRE); 3143 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done); 3144 3145 // Tell LiveDebugVariables about the new ranges. Ranges not being covered by 3146 // the new regs are kept in LDV (still mapping to the old register), until 3147 // we rewrite spilled locations in LDV at a later stage. 3148 DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS); 3149 3150 if (VerifyEnabled) 3151 MF->verify(this, "After spilling"); 3152 } 3153 3154 // The live virtual register requesting allocation was spilled, so tell 3155 // the caller not to allocate anything during this round. 3156 return 0; 3157 } 3158 3159 void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) { 3160 using namespace ore; 3161 if (Spills) { 3162 R << NV("NumSpills", Spills) << " spills "; 3163 R << NV("TotalSpillsCost", SpillsCost) << " total spills cost "; 3164 } 3165 if (FoldedSpills) { 3166 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills "; 3167 R << NV("TotalFoldedSpillsCost", FoldedSpillsCost) 3168 << " total folded spills cost "; 3169 } 3170 if (Reloads) { 3171 R << NV("NumReloads", Reloads) << " reloads "; 3172 R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost "; 3173 } 3174 if (FoldedReloads) { 3175 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads "; 3176 R << NV("TotalFoldedReloadsCost", FoldedReloadsCost) 3177 << " total folded reloads cost "; 3178 } 3179 if (ZeroCostFoldedReloads) 3180 R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads) 3181 << " zero cost folded reloads "; 3182 if (Copies) { 3183 R << NV("NumVRCopies", Copies) << " virtual registers copies "; 3184 R << NV("TotalCopiesCost", CopiesCost) << " total copies cost "; 3185 } 3186 } 3187 3188 RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) { 3189 RAGreedyStats Stats; 3190 const MachineFrameInfo &MFI = MF->getFrameInfo(); 3191 int FI; 3192 3193 auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) { 3194 return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>( 3195 A->getPseudoValue())->getFrameIndex()); 3196 }; 3197 auto isPatchpointInstr = [](const MachineInstr &MI) { 3198 return MI.getOpcode() == TargetOpcode::PATCHPOINT || 3199 MI.getOpcode() == TargetOpcode::STACKMAP || 3200 MI.getOpcode() == TargetOpcode::STATEPOINT; 3201 }; 3202 for (MachineInstr &MI : MBB) { 3203 if (MI.isCopy()) { 3204 MachineOperand &Dest = MI.getOperand(0); 3205 MachineOperand &Src = MI.getOperand(1); 3206 if (Dest.isReg() && Src.isReg() && Dest.getReg().isVirtual() && 3207 Src.getReg().isVirtual()) 3208 ++Stats.Copies; 3209 continue; 3210 } 3211 3212 SmallVector<const MachineMemOperand *, 2> Accesses; 3213 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) { 3214 ++Stats.Reloads; 3215 continue; 3216 } 3217 if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) { 3218 ++Stats.Spills; 3219 continue; 3220 } 3221 if (TII->hasLoadFromStackSlot(MI, Accesses) && 3222 llvm::any_of(Accesses, isSpillSlotAccess)) { 3223 if (!isPatchpointInstr(MI)) { 3224 Stats.FoldedReloads += Accesses.size(); 3225 continue; 3226 } 3227 // For statepoint there may be folded and zero cost folded stack reloads. 3228 std::pair<unsigned, unsigned> NonZeroCostRange = 3229 TII->getPatchpointUnfoldableRange(MI); 3230 SmallSet<unsigned, 16> FoldedReloads; 3231 SmallSet<unsigned, 16> ZeroCostFoldedReloads; 3232 for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) { 3233 MachineOperand &MO = MI.getOperand(Idx); 3234 if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex())) 3235 continue; 3236 if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second) 3237 FoldedReloads.insert(MO.getIndex()); 3238 else 3239 ZeroCostFoldedReloads.insert(MO.getIndex()); 3240 } 3241 // If stack slot is used in folded reload it is not zero cost then. 3242 for (unsigned Slot : FoldedReloads) 3243 ZeroCostFoldedReloads.erase(Slot); 3244 Stats.FoldedReloads += FoldedReloads.size(); 3245 Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size(); 3246 continue; 3247 } 3248 Accesses.clear(); 3249 if (TII->hasStoreToStackSlot(MI, Accesses) && 3250 llvm::any_of(Accesses, isSpillSlotAccess)) { 3251 Stats.FoldedSpills += Accesses.size(); 3252 } 3253 } 3254 // Set cost of collected statistic by multiplication to relative frequency of 3255 // this basic block. 3256 float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB); 3257 Stats.ReloadsCost = RelFreq * Stats.Reloads; 3258 Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads; 3259 Stats.SpillsCost = RelFreq * Stats.Spills; 3260 Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills; 3261 Stats.CopiesCost = RelFreq * Stats.Copies; 3262 return Stats; 3263 } 3264 3265 RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) { 3266 RAGreedyStats Stats; 3267 3268 // Sum up the spill and reloads in subloops. 3269 for (MachineLoop *SubLoop : *L) 3270 Stats.add(reportStats(SubLoop)); 3271 3272 for (MachineBasicBlock *MBB : L->getBlocks()) 3273 // Handle blocks that were not included in subloops. 3274 if (Loops->getLoopFor(MBB) == L) 3275 Stats.add(computeStats(*MBB)); 3276 3277 if (!Stats.isEmpty()) { 3278 using namespace ore; 3279 3280 ORE->emit([&]() { 3281 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies", 3282 L->getStartLoc(), L->getHeader()); 3283 Stats.report(R); 3284 R << "generated in loop"; 3285 return R; 3286 }); 3287 } 3288 return Stats; 3289 } 3290 3291 void RAGreedy::reportStats() { 3292 if (!ORE->allowExtraAnalysis(DEBUG_TYPE)) 3293 return; 3294 RAGreedyStats Stats; 3295 for (MachineLoop *L : *Loops) 3296 Stats.add(reportStats(L)); 3297 // Process non-loop blocks. 3298 for (MachineBasicBlock &MBB : *MF) 3299 if (!Loops->getLoopFor(&MBB)) 3300 Stats.add(computeStats(MBB)); 3301 if (!Stats.isEmpty()) { 3302 using namespace ore; 3303 3304 ORE->emit([&]() { 3305 DebugLoc Loc; 3306 if (auto *SP = MF->getFunction().getSubprogram()) 3307 Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP); 3308 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc, 3309 &MF->front()); 3310 Stats.report(R); 3311 R << "generated in function"; 3312 return R; 3313 }); 3314 } 3315 } 3316 3317 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) { 3318 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n" 3319 << "********** Function: " << mf.getName() << '\n'); 3320 3321 MF = &mf; 3322 TRI = MF->getSubtarget().getRegisterInfo(); 3323 TII = MF->getSubtarget().getInstrInfo(); 3324 RCI.runOnMachineFunction(mf); 3325 3326 EnableLocalReassign = EnableLocalReassignment || 3327 MF->getSubtarget().enableRALocalReassignment( 3328 MF->getTarget().getOptLevel()); 3329 3330 EnableAdvancedRASplitCost = 3331 ConsiderLocalIntervalCost.getNumOccurrences() 3332 ? ConsiderLocalIntervalCost 3333 : MF->getSubtarget().enableAdvancedRASplitCost(); 3334 3335 if (VerifyEnabled) 3336 MF->verify(this, "Before greedy register allocator"); 3337 3338 RegAllocBase::init(getAnalysis<VirtRegMap>(), 3339 getAnalysis<LiveIntervals>(), 3340 getAnalysis<LiveRegMatrix>()); 3341 Indexes = &getAnalysis<SlotIndexes>(); 3342 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 3343 DomTree = &getAnalysis<MachineDominatorTree>(); 3344 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 3345 Loops = &getAnalysis<MachineLoopInfo>(); 3346 Bundles = &getAnalysis<EdgeBundles>(); 3347 SpillPlacer = &getAnalysis<SpillPlacement>(); 3348 DebugVars = &getAnalysis<LiveDebugVariables>(); 3349 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3350 3351 initializeCSRCost(); 3352 3353 RegCosts = TRI->getRegisterCosts(*MF); 3354 3355 VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI); 3356 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI)); 3357 3358 VRAI->calculateSpillWeightsAndHints(); 3359 3360 LLVM_DEBUG(LIS->dump()); 3361 3362 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops)); 3363 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI, *VRAI)); 3364 ExtraRegInfo.clear(); 3365 ExtraRegInfo.resize(MRI->getNumVirtRegs()); 3366 NextCascade = 1; 3367 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI); 3368 GlobalCand.resize(32); // This will grow as needed. 3369 SetOfBrokenHints.clear(); 3370 LastEvicted.clear(); 3371 3372 allocatePhysRegs(); 3373 tryHintsRecoloring(); 3374 3375 if (VerifyEnabled) 3376 MF->verify(this, "Before post optimization"); 3377 postOptimization(); 3378 reportStats(); 3379 3380 releaseMemory(); 3381 return true; 3382 } 3383