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