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