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