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