1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RAGreedy function pass for register allocation in
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/PassAnalysisSupport.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
49 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50 STATISTIC(NumLocalSplits, "Number of split local live ranges");
51 STATISTIC(NumEvicted, "Number of interferences evicted");
53 static cl::opt<SplitEditor::ComplementSpillMode>
54 SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 cl::init(SplitEditor::SM_Partition));
62 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
66 class RAGreedy : public MachineFunctionPass,
68 private LiveRangeEdit::Delegate {
75 MachineBlockFrequencyInfo *MBFI;
76 MachineDominatorTree *DomTree;
77 MachineLoopInfo *Loops;
79 SpillPlacement *SpillPlacer;
80 LiveDebugVariables *DebugVars;
83 OwningPtr<Spiller> SpillerInstance;
84 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
90 // - Region splitting.
91 // - Per-block splitting.
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
100 enum LiveRangeStage {
101 /// Newly created live range that has never been queued.
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
107 /// Attempt live range splitting if assignment is impossible.
110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
115 /// Live range will be spilled. No more splitting will be attempted.
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
123 static const char *const StageName[];
125 // RegInfo - Keep additional information about each live range.
127 LiveRangeStage Stage;
129 // Cascade - Eviction loop prevention. See canEvictInterference().
132 RegInfo() : Stage(RS_New), Cascade(0) {}
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
138 return ExtraRegInfo[VirtReg.reg].Stage;
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163 bool isMax() const { return BrokenHints == ~0u; }
165 bool operator<(const EvictionCost &O) const {
166 if (BrokenHints != O.BrokenHints)
167 return BrokenHints < O.BrokenHints;
168 return MaxWeight < O.MaxWeight;
173 OwningPtr<SplitAnalysis> SA;
174 OwningPtr<SplitEditor> SE;
176 /// Cached per-block interference maps
177 InterferenceCache IntfCache;
179 /// All basic blocks where the current register has uses.
180 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
182 /// Global live range splitting candidate info.
183 struct GlobalSplitCandidate {
184 // Register intended for assignment, or 0.
187 // SplitKit interval index for this candidate.
190 // Interference for PhysReg.
191 InterferenceCache::Cursor Intf;
193 // Bundles where this candidate should be live.
194 BitVector LiveBundles;
195 SmallVector<unsigned, 8> ActiveBlocks;
197 void reset(InterferenceCache &Cache, unsigned Reg) {
200 Intf.setPhysReg(Cache, Reg);
202 ActiveBlocks.clear();
205 // Set B[i] = C for every live bundle where B[i] was NoCand.
206 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
208 for (int i = LiveBundles.find_first(); i >= 0;
209 i = LiveBundles.find_next(i))
210 if (B[i] == NoCand) {
218 /// Candidate info for for each PhysReg in AllocationOrder.
219 /// This vector never shrinks, but grows to the size of the largest register
221 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
223 enum { NoCand = ~0u };
225 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
226 /// NoCand which indicates the stack interval.
227 SmallVector<unsigned, 32> BundleCand;
232 /// Return the pass name.
233 virtual const char* getPassName() const {
234 return "Greedy Register Allocator";
237 /// RAGreedy analysis usage.
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
239 virtual void releaseMemory();
240 virtual Spiller &spiller() { return *SpillerInstance; }
241 virtual void enqueue(LiveInterval *LI);
242 virtual LiveInterval *dequeue();
243 virtual unsigned selectOrSplit(LiveInterval&,
244 SmallVectorImpl<LiveInterval*>&);
246 /// Perform register allocation.
247 virtual bool runOnMachineFunction(MachineFunction &mf);
252 bool LRE_CanEraseVirtReg(unsigned);
253 void LRE_WillShrinkVirtReg(unsigned);
254 void LRE_DidCloneVirtReg(unsigned, unsigned);
256 BlockFrequency calcSpillCost();
257 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
258 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
259 void growRegion(GlobalSplitCandidate &Cand);
260 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
261 bool calcCompactRegion(GlobalSplitCandidate&);
262 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
263 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
264 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
265 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
266 void evictInterference(LiveInterval&, unsigned,
267 SmallVectorImpl<LiveInterval*>&);
269 unsigned tryAssign(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
271 unsigned tryEvict(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
273 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
275 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
279 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
281 unsigned trySplit(LiveInterval&, AllocationOrder&,
282 SmallVectorImpl<LiveInterval*>&);
284 } // end anonymous namespace
286 char RAGreedy::ID = 0;
289 const char *const RAGreedy::StageName[] = {
299 // Hysteresis to use when comparing floats.
300 // This helps stabilize decisions based on float comparisons.
301 const float Hysteresis = 0.98f;
304 FunctionPass* llvm::createGreedyRegisterAllocator() {
305 return new RAGreedy();
308 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
309 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
312 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
313 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
314 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
315 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
316 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
317 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
318 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
319 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
320 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
321 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
322 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
325 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
326 AU.setPreservesCFG();
327 AU.addRequired<MachineBlockFrequencyInfo>();
328 AU.addPreserved<MachineBlockFrequencyInfo>();
329 AU.addRequired<AliasAnalysis>();
330 AU.addPreserved<AliasAnalysis>();
331 AU.addRequired<LiveIntervals>();
332 AU.addPreserved<LiveIntervals>();
333 AU.addRequired<SlotIndexes>();
334 AU.addPreserved<SlotIndexes>();
335 AU.addRequired<LiveDebugVariables>();
336 AU.addPreserved<LiveDebugVariables>();
337 AU.addRequired<LiveStacks>();
338 AU.addPreserved<LiveStacks>();
339 AU.addRequired<CalculateSpillWeights>();
340 AU.addRequired<MachineDominatorTree>();
341 AU.addPreserved<MachineDominatorTree>();
342 AU.addRequired<MachineLoopInfo>();
343 AU.addPreserved<MachineLoopInfo>();
344 AU.addRequired<VirtRegMap>();
345 AU.addPreserved<VirtRegMap>();
346 AU.addRequired<LiveRegMatrix>();
347 AU.addPreserved<LiveRegMatrix>();
348 AU.addRequired<EdgeBundles>();
349 AU.addRequired<SpillPlacement>();
350 MachineFunctionPass::getAnalysisUsage(AU);
354 //===----------------------------------------------------------------------===//
355 // LiveRangeEdit delegate methods
356 //===----------------------------------------------------------------------===//
358 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
359 if (VRM->hasPhys(VirtReg)) {
360 Matrix->unassign(LIS->getInterval(VirtReg));
363 // Unassigned virtreg is probably in the priority queue.
364 // RegAllocBase will erase it after dequeueing.
368 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
369 if (!VRM->hasPhys(VirtReg))
372 // Register is assigned, put it back on the queue for reassignment.
373 LiveInterval &LI = LIS->getInterval(VirtReg);
374 Matrix->unassign(LI);
378 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
379 // Cloning a register we haven't even heard about yet? Just ignore it.
380 if (!ExtraRegInfo.inBounds(Old))
383 // LRE may clone a virtual register because dead code elimination causes it to
384 // be split into connected components. The new components are much smaller
385 // than the original, so they should get a new chance at being assigned.
386 // same stage as the parent.
387 ExtraRegInfo[Old].Stage = RS_Assign;
388 ExtraRegInfo.grow(New);
389 ExtraRegInfo[New] = ExtraRegInfo[Old];
392 void RAGreedy::releaseMemory() {
393 SpillerInstance.reset(0);
394 ExtraRegInfo.clear();
398 void RAGreedy::enqueue(LiveInterval *LI) {
399 // Prioritize live ranges by size, assigning larger ranges first.
400 // The queue holds (size, reg) pairs.
401 const unsigned Size = LI->getSize();
402 const unsigned Reg = LI->reg;
403 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
404 "Can only enqueue virtual registers");
407 ExtraRegInfo.grow(Reg);
408 if (ExtraRegInfo[Reg].Stage == RS_New)
409 ExtraRegInfo[Reg].Stage = RS_Assign;
411 if (ExtraRegInfo[Reg].Stage == RS_Split) {
412 // Unsplit ranges that couldn't be allocated immediately are deferred until
413 // everything else has been allocated.
416 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
417 LIS->intervalIsInOneMBB(*LI)) {
418 // Allocate original local ranges in linear instruction order. Since they
419 // are singly defined, this produces optimal coloring in the absence of
420 // global interference and other constraints.
421 Prio = LI->beginIndex().distance(Indexes->getLastIndex());
424 // Allocate global and split ranges in long->short order. Long ranges that
425 // don't fit should be spilled (or split) ASAP so they don't create
426 // interference. Mark a bit to prioritize global above local ranges.
427 Prio = (1u << 29) + Size;
429 // Mark a higher bit to prioritize global and local above RS_Split.
432 // Boost ranges that have a physical register hint.
433 if (VRM->hasKnownPreference(Reg))
437 Queue.push(std::make_pair(Prio, ~Reg));
440 LiveInterval *RAGreedy::dequeue() {
443 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
449 //===----------------------------------------------------------------------===//
451 //===----------------------------------------------------------------------===//
453 /// tryAssign - Try to assign VirtReg to an available register.
454 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
455 AllocationOrder &Order,
456 SmallVectorImpl<LiveInterval*> &NewVRegs) {
459 while ((PhysReg = Order.next()))
460 if (!Matrix->checkInterference(VirtReg, PhysReg))
462 if (!PhysReg || Order.isHint())
465 // PhysReg is available, but there may be a better choice.
467 // If we missed a simple hint, try to cheaply evict interference from the
468 // preferred register.
469 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
470 if (Order.isHint(Hint)) {
471 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
472 EvictionCost MaxCost(1);
473 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
474 evictInterference(VirtReg, Hint, NewVRegs);
479 // Try to evict interference from a cheaper alternative.
480 unsigned Cost = TRI->getCostPerUse(PhysReg);
482 // Most registers have 0 additional cost.
486 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
488 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
489 return CheapReg ? CheapReg : PhysReg;
493 //===----------------------------------------------------------------------===//
494 // Interference eviction
495 //===----------------------------------------------------------------------===//
497 /// shouldEvict - determine if A should evict the assigned live range B. The
498 /// eviction policy defined by this function together with the allocation order
499 /// defined by enqueue() decides which registers ultimately end up being split
502 /// Cascade numbers are used to prevent infinite loops if this function is a
505 /// @param A The live range to be assigned.
506 /// @param IsHint True when A is about to be assigned to its preferred
508 /// @param B The live range to be evicted.
509 /// @param BreaksHint True when B is already assigned to its preferred register.
510 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
511 LiveInterval &B, bool BreaksHint) {
512 bool CanSplit = getStage(B) < RS_Spill;
514 // Be fairly aggressive about following hints as long as the evictee can be
516 if (CanSplit && IsHint && !BreaksHint)
519 return A.weight > B.weight;
522 /// canEvictInterference - Return true if all interferences between VirtReg and
523 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
525 /// @param VirtReg Live range that is about to be assigned.
526 /// @param PhysReg Desired register for assignment.
527 /// @param IsHint True when PhysReg is VirtReg's preferred register.
528 /// @param MaxCost Only look for cheaper candidates and update with new cost
529 /// when returning true.
530 /// @returns True when interference can be evicted cheaper than MaxCost.
531 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
532 bool IsHint, EvictionCost &MaxCost) {
533 // It is only possible to evict virtual register interference.
534 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
537 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
539 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
540 // involved in an eviction before. If a cascade number was assigned, deny
541 // evicting anything with the same or a newer cascade number. This prevents
542 // infinite eviction loops.
544 // This works out so a register without a cascade number is allowed to evict
545 // anything, and it can be evicted by anything.
546 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
548 Cascade = NextCascade;
551 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
552 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
553 // If there is 10 or more interferences, chances are one is heavier.
554 if (Q.collectInterferingVRegs(10) >= 10)
557 // Check if any interfering live range is heavier than MaxWeight.
558 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
559 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
560 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
561 "Only expecting virtual register interference from query");
562 // Never evict spill products. They cannot split or spill.
563 if (getStage(*Intf) == RS_Done)
565 // Once a live range becomes small enough, it is urgent that we find a
566 // register for it. This is indicated by an infinite spill weight. These
567 // urgent live ranges get to evict almost anything.
569 // Also allow urgent evictions of unspillable ranges from a strictly
570 // larger allocation order.
571 bool Urgent = !VirtReg.isSpillable() &&
572 (Intf->isSpillable() ||
573 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
574 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
575 // Only evict older cascades or live ranges without a cascade.
576 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
577 if (Cascade <= IntfCascade) {
580 // We permit breaking cascades for urgent evictions. It should be the
581 // last resort, though, so make it really expensive.
582 Cost.BrokenHints += 10;
584 // Would this break a satisfied hint?
585 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
586 // Update eviction cost.
587 Cost.BrokenHints += BreaksHint;
588 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
589 // Abort if this would be too expensive.
590 if (!(Cost < MaxCost))
594 // If !MaxCost.isMax(), then we're just looking for a cheap register.
595 // Evicting another local live range in this case could lead to suboptimal
597 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf))
599 // Finally, apply the eviction policy for non-urgent evictions.
600 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
608 /// evictInterference - Evict any interferring registers that prevent VirtReg
609 /// from being assigned to Physreg. This assumes that canEvictInterference
611 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
612 SmallVectorImpl<LiveInterval*> &NewVRegs) {
613 // Make sure that VirtReg has a cascade number, and assign that cascade
614 // number to every evicted register. These live ranges than then only be
615 // evicted by a newer cascade, preventing infinite loops.
616 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
618 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
620 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
621 << " interference: Cascade " << Cascade << '\n');
623 // Collect all interfering virtregs first.
624 SmallVector<LiveInterval*, 8> Intfs;
625 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
626 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
627 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
628 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
629 Intfs.append(IVR.begin(), IVR.end());
632 // Evict them second. This will invalidate the queries.
633 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
634 LiveInterval *Intf = Intfs[i];
635 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
636 if (!VRM->hasPhys(Intf->reg))
638 Matrix->unassign(*Intf);
639 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
640 VirtReg.isSpillable() < Intf->isSpillable()) &&
641 "Cannot decrease cascade number, illegal eviction");
642 ExtraRegInfo[Intf->reg].Cascade = Cascade;
644 NewVRegs.push_back(Intf);
648 /// tryEvict - Try to evict all interferences for a physreg.
649 /// @param VirtReg Currently unassigned virtual register.
650 /// @param Order Physregs to try.
651 /// @return Physreg to assign VirtReg, or 0.
652 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
653 AllocationOrder &Order,
654 SmallVectorImpl<LiveInterval*> &NewVRegs,
655 unsigned CostPerUseLimit) {
656 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
658 // Keep track of the cheapest interference seen so far.
659 EvictionCost BestCost(~0u);
660 unsigned BestPhys = 0;
661 unsigned OrderLimit = Order.getOrder().size();
663 // When we are just looking for a reduced cost per use, don't break any
664 // hints, and only evict smaller spill weights.
665 if (CostPerUseLimit < ~0u) {
666 BestCost.BrokenHints = 0;
667 BestCost.MaxWeight = VirtReg.weight;
669 // Check of any registers in RC are below CostPerUseLimit.
670 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
671 unsigned MinCost = RegClassInfo.getMinCost(RC);
672 if (MinCost >= CostPerUseLimit) {
673 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
674 << ", no cheaper registers to be found.\n");
678 // It is normal for register classes to have a long tail of registers with
679 // the same cost. We don't need to look at them if they're too expensive.
680 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
681 OrderLimit = RegClassInfo.getLastCostChange(RC);
682 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
687 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
688 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
690 // The first use of a callee-saved register in a function has cost 1.
691 // Don't start using a CSR when the CostPerUseLimit is low.
692 if (CostPerUseLimit == 1)
693 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
694 if (!MRI->isPhysRegUsed(CSR)) {
695 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
696 << PrintReg(CSR, TRI) << '\n');
700 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
706 // Stop if the hint can be used.
714 evictInterference(VirtReg, BestPhys, NewVRegs);
719 //===----------------------------------------------------------------------===//
721 //===----------------------------------------------------------------------===//
723 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
724 /// interference pattern in Physreg and its aliases. Add the constraints to
725 /// SpillPlacement and return the static cost of this split in Cost, assuming
726 /// that all preferences in SplitConstraints are met.
727 /// Return false if there are no bundles with positive bias.
728 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
729 BlockFrequency &Cost) {
730 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
732 // Reset interference dependent info.
733 SplitConstraints.resize(UseBlocks.size());
734 BlockFrequency StaticCost = 0;
735 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
736 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
737 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
739 BC.Number = BI.MBB->getNumber();
740 Intf.moveToBlock(BC.Number);
741 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
742 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
743 BC.ChangesValue = BI.FirstDef.isValid();
745 if (!Intf.hasInterference())
748 // Number of spill code instructions to insert.
751 // Interference for the live-in value.
753 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
754 BC.Entry = SpillPlacement::MustSpill, ++Ins;
755 else if (Intf.first() < BI.FirstInstr)
756 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
757 else if (Intf.first() < BI.LastInstr)
761 // Interference for the live-out value.
763 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
764 BC.Exit = SpillPlacement::MustSpill, ++Ins;
765 else if (Intf.last() > BI.LastInstr)
766 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
767 else if (Intf.last() > BI.FirstInstr)
771 // Accumulate the total frequency of inserted spill code.
773 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
777 // Add constraints for use-blocks. Note that these are the only constraints
778 // that may add a positive bias, it is downhill from here.
779 SpillPlacer->addConstraints(SplitConstraints);
780 return SpillPlacer->scanActiveBundles();
784 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
785 /// live-through blocks in Blocks.
786 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
787 ArrayRef<unsigned> Blocks) {
788 const unsigned GroupSize = 8;
789 SpillPlacement::BlockConstraint BCS[GroupSize];
790 unsigned TBS[GroupSize];
791 unsigned B = 0, T = 0;
793 for (unsigned i = 0; i != Blocks.size(); ++i) {
794 unsigned Number = Blocks[i];
795 Intf.moveToBlock(Number);
797 if (!Intf.hasInterference()) {
798 assert(T < GroupSize && "Array overflow");
800 if (++T == GroupSize) {
801 SpillPlacer->addLinks(makeArrayRef(TBS, T));
807 assert(B < GroupSize && "Array overflow");
808 BCS[B].Number = Number;
810 // Interference for the live-in value.
811 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
812 BCS[B].Entry = SpillPlacement::MustSpill;
814 BCS[B].Entry = SpillPlacement::PrefSpill;
816 // Interference for the live-out value.
817 if (Intf.last() >= SA->getLastSplitPoint(Number))
818 BCS[B].Exit = SpillPlacement::MustSpill;
820 BCS[B].Exit = SpillPlacement::PrefSpill;
822 if (++B == GroupSize) {
823 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
824 SpillPlacer->addConstraints(Array);
829 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
830 SpillPlacer->addConstraints(Array);
831 SpillPlacer->addLinks(makeArrayRef(TBS, T));
834 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
835 // Keep track of through blocks that have not been added to SpillPlacer.
836 BitVector Todo = SA->getThroughBlocks();
837 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
838 unsigned AddedTo = 0;
840 unsigned Visited = 0;
844 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
845 // Find new through blocks in the periphery of PrefRegBundles.
846 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
847 unsigned Bundle = NewBundles[i];
848 // Look at all blocks connected to Bundle in the full graph.
849 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
850 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
853 if (!Todo.test(Block))
856 // This is a new through block. Add it to SpillPlacer later.
857 ActiveBlocks.push_back(Block);
863 // Any new blocks to add?
864 if (ActiveBlocks.size() == AddedTo)
867 // Compute through constraints from the interference, or assume that all
868 // through blocks prefer spilling when forming compact regions.
869 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
871 addThroughConstraints(Cand.Intf, NewBlocks);
873 // Provide a strong negative bias on through blocks to prevent unwanted
874 // liveness on loop backedges.
875 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
876 AddedTo = ActiveBlocks.size();
878 // Perhaps iterating can enable more bundles?
879 SpillPlacer->iterate();
881 DEBUG(dbgs() << ", v=" << Visited);
884 /// calcCompactRegion - Compute the set of edge bundles that should be live
885 /// when splitting the current live range into compact regions. Compact
886 /// regions can be computed without looking at interference. They are the
887 /// regions formed by removing all the live-through blocks from the live range.
889 /// Returns false if the current live range is already compact, or if the
890 /// compact regions would form single block regions anyway.
891 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
892 // Without any through blocks, the live range is already compact.
893 if (!SA->getNumThroughBlocks())
896 // Compact regions don't correspond to any physreg.
897 Cand.reset(IntfCache, 0);
899 DEBUG(dbgs() << "Compact region bundles");
901 // Use the spill placer to determine the live bundles. GrowRegion pretends
902 // that all the through blocks have interference when PhysReg is unset.
903 SpillPlacer->prepare(Cand.LiveBundles);
905 // The static split cost will be zero since Cand.Intf reports no interference.
907 if (!addSplitConstraints(Cand.Intf, Cost)) {
908 DEBUG(dbgs() << ", none.\n");
913 SpillPlacer->finish();
915 if (!Cand.LiveBundles.any()) {
916 DEBUG(dbgs() << ", none.\n");
921 for (int i = Cand.LiveBundles.find_first(); i>=0;
922 i = Cand.LiveBundles.find_next(i))
923 dbgs() << " EB#" << i;
929 /// calcSpillCost - Compute how expensive it would be to split the live range in
930 /// SA around all use blocks instead of forming bundle regions.
931 BlockFrequency RAGreedy::calcSpillCost() {
932 BlockFrequency Cost = 0;
933 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
934 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
935 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
936 unsigned Number = BI.MBB->getNumber();
937 // We normally only need one spill instruction - a load or a store.
938 Cost += SpillPlacer->getBlockFrequency(Number);
940 // Unless the value is redefined in the block.
941 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
942 Cost += SpillPlacer->getBlockFrequency(Number);
947 /// calcGlobalSplitCost - Return the global split cost of following the split
948 /// pattern in LiveBundles. This cost should be added to the local cost of the
949 /// interference pattern in SplitConstraints.
951 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
952 BlockFrequency GlobalCost = 0;
953 const BitVector &LiveBundles = Cand.LiveBundles;
954 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
955 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
956 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
957 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
958 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
959 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
963 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
965 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
967 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
970 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
971 unsigned Number = Cand.ActiveBlocks[i];
972 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
973 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
974 if (!RegIn && !RegOut)
976 if (RegIn && RegOut) {
977 // We need double spill code if this block has interference.
978 Cand.Intf.moveToBlock(Number);
979 if (Cand.Intf.hasInterference()) {
980 GlobalCost += SpillPlacer->getBlockFrequency(Number);
981 GlobalCost += SpillPlacer->getBlockFrequency(Number);
985 // live-in / stack-out or stack-in live-out.
986 GlobalCost += SpillPlacer->getBlockFrequency(Number);
991 /// splitAroundRegion - Split the current live range around the regions
992 /// determined by BundleCand and GlobalCand.
994 /// Before calling this function, GlobalCand and BundleCand must be initialized
995 /// so each bundle is assigned to a valid candidate, or NoCand for the
996 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
997 /// objects must be initialized for the current live range, and intervals
998 /// created for the used candidates.
1000 /// @param LREdit The LiveRangeEdit object handling the current split.
1001 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1002 /// must appear in this list.
1003 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1004 ArrayRef<unsigned> UsedCands) {
1005 // These are the intervals created for new global ranges. We may create more
1006 // intervals for local ranges.
1007 const unsigned NumGlobalIntvs = LREdit.size();
1008 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1009 assert(NumGlobalIntvs && "No global intervals configured");
1011 // Isolate even single instructions when dealing with a proper sub-class.
1012 // That guarantees register class inflation for the stack interval because it
1014 unsigned Reg = SA->getParent().reg;
1015 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1017 // First handle all the blocks with uses.
1018 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1019 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1020 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1021 unsigned Number = BI.MBB->getNumber();
1022 unsigned IntvIn = 0, IntvOut = 0;
1023 SlotIndex IntfIn, IntfOut;
1025 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1026 if (CandIn != NoCand) {
1027 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1028 IntvIn = Cand.IntvIdx;
1029 Cand.Intf.moveToBlock(Number);
1030 IntfIn = Cand.Intf.first();
1034 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1035 if (CandOut != NoCand) {
1036 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1037 IntvOut = Cand.IntvIdx;
1038 Cand.Intf.moveToBlock(Number);
1039 IntfOut = Cand.Intf.last();
1043 // Create separate intervals for isolated blocks with multiple uses.
1044 if (!IntvIn && !IntvOut) {
1045 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1046 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1047 SE->splitSingleBlock(BI);
1051 if (IntvIn && IntvOut)
1052 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1054 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1056 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1059 // Handle live-through blocks. The relevant live-through blocks are stored in
1060 // the ActiveBlocks list with each candidate. We need to filter out
1062 BitVector Todo = SA->getThroughBlocks();
1063 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1064 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1065 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1066 unsigned Number = Blocks[i];
1067 if (!Todo.test(Number))
1071 unsigned IntvIn = 0, IntvOut = 0;
1072 SlotIndex IntfIn, IntfOut;
1074 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1075 if (CandIn != NoCand) {
1076 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1077 IntvIn = Cand.IntvIdx;
1078 Cand.Intf.moveToBlock(Number);
1079 IntfIn = Cand.Intf.first();
1082 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1083 if (CandOut != NoCand) {
1084 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1085 IntvOut = Cand.IntvIdx;
1086 Cand.Intf.moveToBlock(Number);
1087 IntfOut = Cand.Intf.last();
1089 if (!IntvIn && !IntvOut)
1091 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1097 SmallVector<unsigned, 8> IntvMap;
1098 SE->finish(&IntvMap);
1099 DebugVars->splitRegister(Reg, LREdit.regs());
1101 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1102 unsigned OrigBlocks = SA->getNumLiveBlocks();
1104 // Sort out the new intervals created by splitting. We get four kinds:
1105 // - Remainder intervals should not be split again.
1106 // - Candidate intervals can be assigned to Cand.PhysReg.
1107 // - Block-local splits are candidates for local splitting.
1108 // - DCE leftovers should go back on the queue.
1109 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1110 LiveInterval &Reg = *LREdit.get(i);
1112 // Ignore old intervals from DCE.
1113 if (getStage(Reg) != RS_New)
1116 // Remainder interval. Don't try splitting again, spill if it doesn't
1118 if (IntvMap[i] == 0) {
1119 setStage(Reg, RS_Spill);
1123 // Global intervals. Allow repeated splitting as long as the number of live
1124 // blocks is strictly decreasing.
1125 if (IntvMap[i] < NumGlobalIntvs) {
1126 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1127 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1128 << " blocks as original.\n");
1129 // Don't allow repeated splitting as a safe guard against looping.
1130 setStage(Reg, RS_Split2);
1135 // Other intervals are treated as new. This includes local intervals created
1136 // for blocks with multiple uses, and anything created by DCE.
1140 MF->verify(this, "After splitting live range around region");
1143 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1144 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1145 unsigned NumCands = 0;
1146 unsigned BestCand = NoCand;
1147 BlockFrequency BestCost;
1148 SmallVector<unsigned, 8> UsedCands;
1150 // Check if we can split this live range around a compact region.
1151 bool HasCompact = calcCompactRegion(GlobalCand.front());
1153 // Yes, keep GlobalCand[0] as the compact region candidate.
1155 BestCost = BlockFrequency::getMaxFrequency();
1157 // No benefit from the compact region, our fallback will be per-block
1158 // splitting. Make sure we find a solution that is cheaper than spilling.
1159 BestCost = calcSpillCost();
1160 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1164 while (unsigned PhysReg = Order.next()) {
1165 // Discard bad candidates before we run out of interference cache cursors.
1166 // This will only affect register classes with a lot of registers (>32).
1167 if (NumCands == IntfCache.getMaxCursors()) {
1168 unsigned WorstCount = ~0u;
1170 for (unsigned i = 0; i != NumCands; ++i) {
1171 if (i == BestCand || !GlobalCand[i].PhysReg)
1173 unsigned Count = GlobalCand[i].LiveBundles.count();
1174 if (Count < WorstCount)
1175 Worst = i, WorstCount = Count;
1178 GlobalCand[Worst] = GlobalCand[NumCands];
1179 if (BestCand == NumCands)
1183 if (GlobalCand.size() <= NumCands)
1184 GlobalCand.resize(NumCands+1);
1185 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1186 Cand.reset(IntfCache, PhysReg);
1188 SpillPlacer->prepare(Cand.LiveBundles);
1189 BlockFrequency Cost;
1190 if (!addSplitConstraints(Cand.Intf, Cost)) {
1191 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1194 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1195 if (Cost >= BestCost) {
1197 if (BestCand == NoCand)
1198 dbgs() << " worse than no bundles\n";
1200 dbgs() << " worse than "
1201 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1207 SpillPlacer->finish();
1209 // No live bundles, defer to splitSingleBlocks().
1210 if (!Cand.LiveBundles.any()) {
1211 DEBUG(dbgs() << " no bundles.\n");
1215 Cost += calcGlobalSplitCost(Cand);
1217 dbgs() << ", total = " << Cost << " with bundles";
1218 for (int i = Cand.LiveBundles.find_first(); i>=0;
1219 i = Cand.LiveBundles.find_next(i))
1220 dbgs() << " EB#" << i;
1223 if (Cost < BestCost) {
1224 BestCand = NumCands;
1230 // No solutions found, fall back to single block splitting.
1231 if (!HasCompact && BestCand == NoCand)
1234 // Prepare split editor.
1235 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1236 SE->reset(LREdit, SplitSpillMode);
1238 // Assign all edge bundles to the preferred candidate, or NoCand.
1239 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1241 // Assign bundles for the best candidate region.
1242 if (BestCand != NoCand) {
1243 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1244 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1245 UsedCands.push_back(BestCand);
1246 Cand.IntvIdx = SE->openIntv();
1247 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1248 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1253 // Assign bundles for the compact region.
1255 GlobalSplitCandidate &Cand = GlobalCand.front();
1256 assert(!Cand.PhysReg && "Compact region has no physreg");
1257 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1258 UsedCands.push_back(0);
1259 Cand.IntvIdx = SE->openIntv();
1260 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1261 << Cand.IntvIdx << ".\n");
1266 splitAroundRegion(LREdit, UsedCands);
1271 //===----------------------------------------------------------------------===//
1272 // Per-Block Splitting
1273 //===----------------------------------------------------------------------===//
1275 /// tryBlockSplit - Split a global live range around every block with uses. This
1276 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1277 /// they don't allocate.
1278 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1279 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1280 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1281 unsigned Reg = VirtReg.reg;
1282 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1283 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1284 SE->reset(LREdit, SplitSpillMode);
1285 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1286 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1287 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1288 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1289 SE->splitSingleBlock(BI);
1291 // No blocks were split.
1295 // We did split for some blocks.
1296 SmallVector<unsigned, 8> IntvMap;
1297 SE->finish(&IntvMap);
1299 // Tell LiveDebugVariables about the new ranges.
1300 DebugVars->splitRegister(Reg, LREdit.regs());
1302 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1304 // Sort out the new intervals created by splitting. The remainder interval
1305 // goes straight to spilling, the new local ranges get to stay RS_New.
1306 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1307 LiveInterval &LI = *LREdit.get(i);
1308 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1309 setStage(LI, RS_Spill);
1313 MF->verify(this, "After splitting live range around basic blocks");
1318 //===----------------------------------------------------------------------===//
1319 // Per-Instruction Splitting
1320 //===----------------------------------------------------------------------===//
1322 /// tryInstructionSplit - Split a live range around individual instructions.
1323 /// This is normally not worthwhile since the spiller is doing essentially the
1324 /// same thing. However, when the live range is in a constrained register
1325 /// class, it may help to insert copies such that parts of the live range can
1326 /// be moved to a larger register class.
1328 /// This is similar to spilling to a larger register class.
1330 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1331 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1332 // There is no point to this if there are no larger sub-classes.
1333 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1336 // Always enable split spill mode, since we're effectively spilling to a
1338 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1339 SE->reset(LREdit, SplitEditor::SM_Size);
1341 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1342 if (Uses.size() <= 1)
1345 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1347 // Split around every non-copy instruction.
1348 for (unsigned i = 0; i != Uses.size(); ++i) {
1349 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1350 if (MI->isFullCopy()) {
1351 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1355 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1356 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1357 SE->useIntv(SegStart, SegStop);
1360 if (LREdit.empty()) {
1361 DEBUG(dbgs() << "All uses were copies.\n");
1365 SmallVector<unsigned, 8> IntvMap;
1366 SE->finish(&IntvMap);
1367 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1368 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1370 // Assign all new registers to RS_Spill. This was the last chance.
1371 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1376 //===----------------------------------------------------------------------===//
1378 //===----------------------------------------------------------------------===//
1381 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1382 /// in order to use PhysReg between two entries in SA->UseSlots.
1384 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1386 void RAGreedy::calcGapWeights(unsigned PhysReg,
1387 SmallVectorImpl<float> &GapWeight) {
1388 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1389 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1390 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1391 const unsigned NumGaps = Uses.size()-1;
1393 // Start and end points for the interference check.
1394 SlotIndex StartIdx =
1395 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1397 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1399 GapWeight.assign(NumGaps, 0.0f);
1401 // Add interference from each overlapping register.
1402 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1403 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1404 .checkInterference())
1407 // We know that VirtReg is a continuous interval from FirstInstr to
1408 // LastInstr, so we don't need InterferenceQuery.
1410 // Interference that overlaps an instruction is counted in both gaps
1411 // surrounding the instruction. The exception is interference before
1412 // StartIdx and after StopIdx.
1414 LiveIntervalUnion::SegmentIter IntI =
1415 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1416 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1417 // Skip the gaps before IntI.
1418 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1419 if (++Gap == NumGaps)
1424 // Update the gaps covered by IntI.
1425 const float weight = IntI.value()->weight;
1426 for (; Gap != NumGaps; ++Gap) {
1427 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1428 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1436 // Add fixed interference.
1437 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1438 const LiveInterval &LI = LIS->getRegUnit(*Units);
1439 LiveInterval::const_iterator I = LI.find(StartIdx);
1440 LiveInterval::const_iterator E = LI.end();
1442 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1443 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1444 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1445 if (++Gap == NumGaps)
1450 for (; Gap != NumGaps; ++Gap) {
1451 GapWeight[Gap] = HUGE_VALF;
1452 if (Uses[Gap+1].getBaseIndex() >= I->end)
1461 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1464 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1465 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1466 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1467 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1469 // Note that it is possible to have an interval that is live-in or live-out
1470 // while only covering a single block - A phi-def can use undef values from
1471 // predecessors, and the block could be a single-block loop.
1472 // We don't bother doing anything clever about such a case, we simply assume
1473 // that the interval is continuous from FirstInstr to LastInstr. We should
1474 // make sure that we don't do anything illegal to such an interval, though.
1476 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1477 if (Uses.size() <= 2)
1479 const unsigned NumGaps = Uses.size()-1;
1482 dbgs() << "tryLocalSplit: ";
1483 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1484 dbgs() << ' ' << Uses[i];
1488 // If VirtReg is live across any register mask operands, compute a list of
1489 // gaps with register masks.
1490 SmallVector<unsigned, 8> RegMaskGaps;
1491 if (Matrix->checkRegMaskInterference(VirtReg)) {
1492 // Get regmask slots for the whole block.
1493 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1494 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1495 // Constrain to VirtReg's live range.
1496 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1497 Uses.front().getRegSlot()) - RMS.begin();
1498 unsigned re = RMS.size();
1499 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1500 // Look for Uses[i] <= RMS <= Uses[i+1].
1501 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1502 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1504 // Skip a regmask on the same instruction as the last use. It doesn't
1505 // overlap the live range.
1506 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1508 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1509 RegMaskGaps.push_back(i);
1510 // Advance ri to the next gap. A regmask on one of the uses counts in
1512 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1515 DEBUG(dbgs() << '\n');
1518 // Since we allow local split results to be split again, there is a risk of
1519 // creating infinite loops. It is tempting to require that the new live
1520 // ranges have less instructions than the original. That would guarantee
1521 // convergence, but it is too strict. A live range with 3 instructions can be
1522 // split 2+3 (including the COPY), and we want to allow that.
1524 // Instead we use these rules:
1526 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1527 // noop split, of course).
1528 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1529 // the new ranges must have fewer instructions than before the split.
1530 // 3. New ranges with the same number of instructions are marked RS_Split2,
1531 // smaller ranges are marked RS_New.
1533 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1534 // excessive splitting and infinite loops.
1536 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1538 // Best split candidate.
1539 unsigned BestBefore = NumGaps;
1540 unsigned BestAfter = 0;
1543 const float blockFreq =
1544 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1545 (1.0f / BlockFrequency::getEntryFrequency());
1546 SmallVector<float, 8> GapWeight;
1549 while (unsigned PhysReg = Order.next()) {
1550 // Keep track of the largest spill weight that would need to be evicted in
1551 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1552 calcGapWeights(PhysReg, GapWeight);
1554 // Remove any gaps with regmask clobbers.
1555 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1556 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1557 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1559 // Try to find the best sequence of gaps to close.
1560 // The new spill weight must be larger than any gap interference.
1562 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1563 unsigned SplitBefore = 0, SplitAfter = 1;
1565 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1566 // It is the spill weight that needs to be evicted.
1567 float MaxGap = GapWeight[0];
1570 // Live before/after split?
1571 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1572 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1574 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1575 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1576 << " i=" << MaxGap);
1578 // Stop before the interval gets so big we wouldn't be making progress.
1579 if (!LiveBefore && !LiveAfter) {
1580 DEBUG(dbgs() << " all\n");
1583 // Should the interval be extended or shrunk?
1586 // How many gaps would the new range have?
1587 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1589 // Legally, without causing looping?
1590 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1592 if (Legal && MaxGap < HUGE_VALF) {
1593 // Estimate the new spill weight. Each instruction reads or writes the
1594 // register. Conservatively assume there are no read-modify-write
1597 // Try to guess the size of the new interval.
1598 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1599 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1600 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1601 // Would this split be possible to allocate?
1602 // Never allocate all gaps, we wouldn't be making progress.
1603 DEBUG(dbgs() << " w=" << EstWeight);
1604 if (EstWeight * Hysteresis >= MaxGap) {
1606 float Diff = EstWeight - MaxGap;
1607 if (Diff > BestDiff) {
1608 DEBUG(dbgs() << " (best)");
1609 BestDiff = Hysteresis * Diff;
1610 BestBefore = SplitBefore;
1611 BestAfter = SplitAfter;
1618 if (++SplitBefore < SplitAfter) {
1619 DEBUG(dbgs() << " shrink\n");
1620 // Recompute the max when necessary.
1621 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1622 MaxGap = GapWeight[SplitBefore];
1623 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1624 MaxGap = std::max(MaxGap, GapWeight[i]);
1631 // Try to extend the interval.
1632 if (SplitAfter >= NumGaps) {
1633 DEBUG(dbgs() << " end\n");
1637 DEBUG(dbgs() << " extend\n");
1638 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1642 // Didn't find any candidates?
1643 if (BestBefore == NumGaps)
1646 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1647 << '-' << Uses[BestAfter] << ", " << BestDiff
1648 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1650 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1654 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1655 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1656 SE->useIntv(SegStart, SegStop);
1657 SmallVector<unsigned, 8> IntvMap;
1658 SE->finish(&IntvMap);
1659 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1661 // If the new range has the same number of instructions as before, mark it as
1662 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1663 // leave the new intervals as RS_New so they can compete.
1664 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1665 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1666 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1667 if (NewGaps >= NumGaps) {
1668 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1669 assert(!ProgressRequired && "Didn't make progress when it was required.");
1670 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1671 if (IntvMap[i] == 1) {
1672 setStage(*LREdit.get(i), RS_Split2);
1673 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1675 DEBUG(dbgs() << '\n');
1682 //===----------------------------------------------------------------------===//
1683 // Live Range Splitting
1684 //===----------------------------------------------------------------------===//
1686 /// trySplit - Try to split VirtReg or one of its interferences, making it
1688 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1689 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1690 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1691 // Ranges must be Split2 or less.
1692 if (getStage(VirtReg) >= RS_Spill)
1695 // Local intervals are handled separately.
1696 if (LIS->intervalIsInOneMBB(VirtReg)) {
1697 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1698 SA->analyze(&VirtReg);
1699 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1700 if (PhysReg || !NewVRegs.empty())
1702 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1705 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1707 SA->analyze(&VirtReg);
1709 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1710 // coalescer. That may cause the range to become allocatable which means that
1711 // tryRegionSplit won't be making progress. This check should be replaced with
1712 // an assertion when the coalescer is fixed.
1713 if (SA->didRepairRange()) {
1714 // VirtReg has changed, so all cached queries are invalid.
1715 Matrix->invalidateVirtRegs();
1716 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1720 // First try to split around a region spanning multiple blocks. RS_Split2
1721 // ranges already made dubious progress with region splitting, so they go
1722 // straight to single block splitting.
1723 if (getStage(VirtReg) < RS_Split2) {
1724 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1725 if (PhysReg || !NewVRegs.empty())
1729 // Then isolate blocks.
1730 return tryBlockSplit(VirtReg, Order, NewVRegs);
1734 //===----------------------------------------------------------------------===//
1736 //===----------------------------------------------------------------------===//
1738 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1739 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1740 // First try assigning a free register.
1741 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1742 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1745 LiveRangeStage Stage = getStage(VirtReg);
1746 DEBUG(dbgs() << StageName[Stage]
1747 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1749 // Try to evict a less worthy live range, but only for ranges from the primary
1750 // queue. The RS_Split ranges already failed to do this, and they should not
1751 // get a second chance until they have been split.
1752 if (Stage != RS_Split)
1753 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1756 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1758 // The first time we see a live range, don't try to split or spill.
1759 // Wait until the second time, when all smaller ranges have been allocated.
1760 // This gives a better picture of the interference to split around.
1761 if (Stage < RS_Split) {
1762 setStage(VirtReg, RS_Split);
1763 DEBUG(dbgs() << "wait for second round\n");
1764 NewVRegs.push_back(&VirtReg);
1768 // If we couldn't allocate a register from spilling, there is probably some
1769 // invalid inline assembly. The base class wil report it.
1770 if (Stage >= RS_Done || !VirtReg.isSpillable())
1773 // Try splitting VirtReg or interferences.
1774 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1775 if (PhysReg || !NewVRegs.empty())
1778 // Finally spill VirtReg itself.
1779 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1780 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1781 spiller().spill(LRE);
1782 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1785 MF->verify(this, "After spilling");
1787 // The live virtual register requesting allocation was spilled, so tell
1788 // the caller not to allocate anything during this round.
1792 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1793 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1794 << "********** Function: " << mf.getName() << '\n');
1798 MF->verify(this, "Before greedy register allocator");
1800 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1801 getAnalysis<LiveIntervals>(),
1802 getAnalysis<LiveRegMatrix>());
1803 Indexes = &getAnalysis<SlotIndexes>();
1804 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1805 DomTree = &getAnalysis<MachineDominatorTree>();
1806 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1807 Loops = &getAnalysis<MachineLoopInfo>();
1808 Bundles = &getAnalysis<EdgeBundles>();
1809 SpillPlacer = &getAnalysis<SpillPlacement>();
1810 DebugVars = &getAnalysis<LiveDebugVariables>();
1814 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1815 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1816 ExtraRegInfo.clear();
1817 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1819 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1820 GlobalCand.resize(32); // This will grow as needed.