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