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