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