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