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