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