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