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