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