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/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/RegAllocRegistry.h"
37 #include "llvm/CodeGen/VirtRegMap.h"
38 #include "llvm/PassAnalysisSupport.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
48 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
49 STATISTIC(NumLocalSplits, "Number of split local live ranges");
50 STATISTIC(NumEvicted, "Number of interferences evicted");
52 static cl::opt<SplitEditor::ComplementSpillMode>
53 SplitSpillMode("split-spill-mode", cl::Hidden,
54 cl::desc("Spill mode for splitting live ranges"),
55 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
56 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
57 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
59 cl::init(SplitEditor::SM_Partition));
61 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
62 createGreedyRegisterAllocator);
65 class RAGreedy : public MachineFunctionPass,
67 private LiveRangeEdit::Delegate {
74 MachineDominatorTree *DomTree;
75 MachineLoopInfo *Loops;
77 SpillPlacement *SpillPlacer;
78 LiveDebugVariables *DebugVars;
81 std::auto_ptr<Spiller> SpillerInstance;
82 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
85 // Live ranges pass through a number of stages as we try to allocate them.
86 // Some of the stages may also create new live ranges:
88 // - Region splitting.
89 // - Per-block splitting.
93 // Ranges produced by one of the stages skip the previous stages when they are
94 // dequeued. This improves performance because we can skip interference checks
95 // that are unlikely to give any results. It also guarantees that the live
96 // range splitting algorithm terminates, something that is otherwise hard to
99 /// Newly created live range that has never been queued.
102 /// Only attempt assignment and eviction. Then requeue as RS_Split.
105 /// Attempt live range splitting if assignment is impossible.
108 /// Attempt more aggressive live range splitting that is guaranteed to make
109 /// progress. This is used for split products that may not be making
113 /// Live range will be spilled. No more splitting will be attempted.
116 /// There is nothing more we can do to this live range. Abort compilation
117 /// if it can't be assigned.
121 static const char *const StageName[];
123 // RegInfo - Keep additional information about each live range.
125 LiveRangeStage Stage;
127 // Cascade - Eviction loop prevention. See canEvictInterference().
130 RegInfo() : Stage(RS_New), Cascade(0) {}
133 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
135 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
136 return ExtraRegInfo[VirtReg.reg].Stage;
139 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
140 ExtraRegInfo.resize(MRI->getNumVirtRegs());
141 ExtraRegInfo[VirtReg.reg].Stage = Stage;
144 template<typename Iterator>
145 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
146 ExtraRegInfo.resize(MRI->getNumVirtRegs());
147 for (;Begin != End; ++Begin) {
148 unsigned Reg = (*Begin)->reg;
149 if (ExtraRegInfo[Reg].Stage == RS_New)
150 ExtraRegInfo[Reg].Stage = NewStage;
154 /// Cost of evicting interference.
155 struct EvictionCost {
156 unsigned BrokenHints; ///< Total number of broken hints.
157 float MaxWeight; ///< Maximum spill weight evicted.
159 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
161 bool operator<(const EvictionCost &O) const {
162 if (BrokenHints != O.BrokenHints)
163 return BrokenHints < O.BrokenHints;
164 return MaxWeight < O.MaxWeight;
169 std::auto_ptr<SplitAnalysis> SA;
170 std::auto_ptr<SplitEditor> SE;
172 /// Cached per-block interference maps
173 InterferenceCache IntfCache;
175 /// All basic blocks where the current register has uses.
176 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
178 /// Global live range splitting candidate info.
179 struct GlobalSplitCandidate {
180 // Register intended for assignment, or 0.
183 // SplitKit interval index for this candidate.
186 // Interference for PhysReg.
187 InterferenceCache::Cursor Intf;
189 // Bundles where this candidate should be live.
190 BitVector LiveBundles;
191 SmallVector<unsigned, 8> ActiveBlocks;
193 void reset(InterferenceCache &Cache, unsigned Reg) {
196 Intf.setPhysReg(Cache, Reg);
198 ActiveBlocks.clear();
201 // Set B[i] = C for every live bundle where B[i] was NoCand.
202 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
204 for (int i = LiveBundles.find_first(); i >= 0;
205 i = LiveBundles.find_next(i))
206 if (B[i] == NoCand) {
214 /// Candidate info for for each PhysReg in AllocationOrder.
215 /// This vector never shrinks, but grows to the size of the largest register
217 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
219 enum { NoCand = ~0u };
221 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
222 /// NoCand which indicates the stack interval.
223 SmallVector<unsigned, 32> BundleCand;
228 /// Return the pass name.
229 virtual const char* getPassName() const {
230 return "Greedy Register Allocator";
233 /// RAGreedy analysis usage.
234 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
235 virtual void releaseMemory();
236 virtual Spiller &spiller() { return *SpillerInstance; }
237 virtual void enqueue(LiveInterval *LI);
238 virtual LiveInterval *dequeue();
239 virtual unsigned selectOrSplit(LiveInterval&,
240 SmallVectorImpl<LiveInterval*>&);
242 /// Perform register allocation.
243 virtual bool runOnMachineFunction(MachineFunction &mf);
248 bool LRE_CanEraseVirtReg(unsigned);
249 void LRE_WillShrinkVirtReg(unsigned);
250 void LRE_DidCloneVirtReg(unsigned, unsigned);
252 float calcSpillCost();
253 bool addSplitConstraints(InterferenceCache::Cursor, float&);
254 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
255 void growRegion(GlobalSplitCandidate &Cand);
256 float calcGlobalSplitCost(GlobalSplitCandidate&);
257 bool calcCompactRegion(GlobalSplitCandidate&);
258 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
259 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
260 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
261 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
262 void evictInterference(LiveInterval&, unsigned,
263 SmallVectorImpl<LiveInterval*>&);
265 unsigned tryAssign(LiveInterval&, AllocationOrder&,
266 SmallVectorImpl<LiveInterval*>&);
267 unsigned tryEvict(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
269 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
271 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
273 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
275 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned trySplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
280 } // end anonymous namespace
282 char RAGreedy::ID = 0;
285 const char *const RAGreedy::StageName[] = {
295 // Hysteresis to use when comparing floats.
296 // This helps stabilize decisions based on float comparisons.
297 const float Hysteresis = 0.98f;
300 FunctionPass* llvm::createGreedyRegisterAllocator() {
301 return new RAGreedy();
304 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
305 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
306 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
307 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
309 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
310 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
311 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
312 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
313 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
314 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
315 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
316 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
317 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
318 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
321 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
322 AU.setPreservesCFG();
323 AU.addRequired<AliasAnalysis>();
324 AU.addPreserved<AliasAnalysis>();
325 AU.addRequired<LiveIntervals>();
326 AU.addPreserved<LiveIntervals>();
327 AU.addRequired<SlotIndexes>();
328 AU.addPreserved<SlotIndexes>();
329 AU.addRequired<LiveDebugVariables>();
330 AU.addPreserved<LiveDebugVariables>();
331 AU.addRequired<LiveStacks>();
332 AU.addPreserved<LiveStacks>();
333 AU.addRequired<CalculateSpillWeights>();
334 AU.addRequired<MachineDominatorTree>();
335 AU.addPreserved<MachineDominatorTree>();
336 AU.addRequired<MachineLoopInfo>();
337 AU.addPreserved<MachineLoopInfo>();
338 AU.addRequired<VirtRegMap>();
339 AU.addPreserved<VirtRegMap>();
340 AU.addRequired<LiveRegMatrix>();
341 AU.addPreserved<LiveRegMatrix>();
342 AU.addRequired<EdgeBundles>();
343 AU.addRequired<SpillPlacement>();
344 MachineFunctionPass::getAnalysisUsage(AU);
348 //===----------------------------------------------------------------------===//
349 // LiveRangeEdit delegate methods
350 //===----------------------------------------------------------------------===//
352 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
353 if (VRM->hasPhys(VirtReg)) {
354 Matrix->unassign(LIS->getInterval(VirtReg));
357 // Unassigned virtreg is probably in the priority queue.
358 // RegAllocBase will erase it after dequeueing.
362 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
363 if (!VRM->hasPhys(VirtReg))
366 // Register is assigned, put it back on the queue for reassignment.
367 LiveInterval &LI = LIS->getInterval(VirtReg);
368 Matrix->unassign(LI);
372 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
373 // Cloning a register we haven't even heard about yet? Just ignore it.
374 if (!ExtraRegInfo.inBounds(Old))
377 // LRE may clone a virtual register because dead code elimination causes it to
378 // be split into connected components. The new components are much smaller
379 // than the original, so they should get a new chance at being assigned.
380 // same stage as the parent.
381 ExtraRegInfo[Old].Stage = RS_Assign;
382 ExtraRegInfo.grow(New);
383 ExtraRegInfo[New] = ExtraRegInfo[Old];
386 void RAGreedy::releaseMemory() {
387 SpillerInstance.reset(0);
388 ExtraRegInfo.clear();
392 void RAGreedy::enqueue(LiveInterval *LI) {
393 // Prioritize live ranges by size, assigning larger ranges first.
394 // The queue holds (size, reg) pairs.
395 const unsigned Size = LI->getSize();
396 const unsigned Reg = LI->reg;
397 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
398 "Can only enqueue virtual registers");
401 ExtraRegInfo.grow(Reg);
402 if (ExtraRegInfo[Reg].Stage == RS_New)
403 ExtraRegInfo[Reg].Stage = RS_Assign;
405 if (ExtraRegInfo[Reg].Stage == RS_Split) {
406 // Unsplit ranges that couldn't be allocated immediately are deferred until
407 // everything else has been allocated.
410 // Everything is allocated in long->short order. Long ranges that don't fit
411 // should be spilled (or split) ASAP so they don't create interference.
412 Prio = (1u << 31) + Size;
414 // Boost ranges that have a physical register hint.
415 if (VRM->hasKnownPreference(Reg))
419 Queue.push(std::make_pair(Prio, ~Reg));
422 LiveInterval *RAGreedy::dequeue() {
425 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
431 //===----------------------------------------------------------------------===//
433 //===----------------------------------------------------------------------===//
435 /// tryAssign - Try to assign VirtReg to an available register.
436 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
437 AllocationOrder &Order,
438 SmallVectorImpl<LiveInterval*> &NewVRegs) {
441 while ((PhysReg = Order.next()))
442 if (!Matrix->checkInterference(VirtReg, PhysReg))
444 if (!PhysReg || Order.isHint())
447 // PhysReg is available, but there may be a better choice.
449 // If we missed a simple hint, try to cheaply evict interference from the
450 // preferred register.
451 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
452 if (Order.isHint(Hint)) {
453 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
454 EvictionCost MaxCost(1);
455 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
456 evictInterference(VirtReg, Hint, NewVRegs);
461 // Try to evict interference from a cheaper alternative.
462 unsigned Cost = TRI->getCostPerUse(PhysReg);
464 // Most registers have 0 additional cost.
468 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
470 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
471 return CheapReg ? CheapReg : PhysReg;
475 //===----------------------------------------------------------------------===//
476 // Interference eviction
477 //===----------------------------------------------------------------------===//
479 /// shouldEvict - determine if A should evict the assigned live range B. The
480 /// eviction policy defined by this function together with the allocation order
481 /// defined by enqueue() decides which registers ultimately end up being split
484 /// Cascade numbers are used to prevent infinite loops if this function is a
487 /// @param A The live range to be assigned.
488 /// @param IsHint True when A is about to be assigned to its preferred
490 /// @param B The live range to be evicted.
491 /// @param BreaksHint True when B is already assigned to its preferred register.
492 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
493 LiveInterval &B, bool BreaksHint) {
494 bool CanSplit = getStage(B) < RS_Spill;
496 // Be fairly aggressive about following hints as long as the evictee can be
498 if (CanSplit && IsHint && !BreaksHint)
501 return A.weight > B.weight;
504 /// canEvictInterference - Return true if all interferences between VirtReg and
505 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
507 /// @param VirtReg Live range that is about to be assigned.
508 /// @param PhysReg Desired register for assignment.
509 /// @param IsHint True when PhysReg is VirtReg's preferred register.
510 /// @param MaxCost Only look for cheaper candidates and update with new cost
511 /// when returning true.
512 /// @returns True when interference can be evicted cheaper than MaxCost.
513 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
514 bool IsHint, EvictionCost &MaxCost) {
515 // It is only possible to evict virtual register interference.
516 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
519 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
520 // involved in an eviction before. If a cascade number was assigned, deny
521 // evicting anything with the same or a newer cascade number. This prevents
522 // infinite eviction loops.
524 // This works out so a register without a cascade number is allowed to evict
525 // anything, and it can be evicted by anything.
526 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
528 Cascade = NextCascade;
531 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
532 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
533 // If there is 10 or more interferences, chances are one is heavier.
534 if (Q.collectInterferingVRegs(10) >= 10)
537 // Check if any interfering live range is heavier than MaxWeight.
538 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
539 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
540 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
541 "Only expecting virtual register interference from query");
542 // Never evict spill products. They cannot split or spill.
543 if (getStage(*Intf) == RS_Done)
545 // Once a live range becomes small enough, it is urgent that we find a
546 // register for it. This is indicated by an infinite spill weight. These
547 // urgent live ranges get to evict almost anything.
549 // Also allow urgent evictions of unspillable ranges from a strictly
550 // larger allocation order.
551 bool Urgent = !VirtReg.isSpillable() &&
552 (Intf->isSpillable() ||
553 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
554 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
555 // Only evict older cascades or live ranges without a cascade.
556 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
557 if (Cascade <= IntfCascade) {
560 // We permit breaking cascades for urgent evictions. It should be the
561 // last resort, though, so make it really expensive.
562 Cost.BrokenHints += 10;
564 // Would this break a satisfied hint?
565 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
566 // Update eviction cost.
567 Cost.BrokenHints += BreaksHint;
568 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
569 // Abort if this would be too expensive.
570 if (!(Cost < MaxCost))
572 // Finally, apply the eviction policy for non-urgent evictions.
573 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
581 /// evictInterference - Evict any interferring registers that prevent VirtReg
582 /// from being assigned to Physreg. This assumes that canEvictInterference
584 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
585 SmallVectorImpl<LiveInterval*> &NewVRegs) {
586 // Make sure that VirtReg has a cascade number, and assign that cascade
587 // number to every evicted register. These live ranges than then only be
588 // evicted by a newer cascade, preventing infinite loops.
589 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
591 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
593 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
594 << " interference: Cascade " << Cascade << '\n');
596 // Collect all interfering virtregs first.
597 SmallVector<LiveInterval*, 8> Intfs;
598 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
599 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
600 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
601 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
602 Intfs.append(IVR.begin(), IVR.end());
605 // Evict them second. This will invalidate the queries.
606 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
607 LiveInterval *Intf = Intfs[i];
608 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
609 if (!VRM->hasPhys(Intf->reg))
611 Matrix->unassign(*Intf);
612 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
613 VirtReg.isSpillable() < Intf->isSpillable()) &&
614 "Cannot decrease cascade number, illegal eviction");
615 ExtraRegInfo[Intf->reg].Cascade = Cascade;
617 NewVRegs.push_back(Intf);
621 /// tryEvict - Try to evict all interferences for a physreg.
622 /// @param VirtReg Currently unassigned virtual register.
623 /// @param Order Physregs to try.
624 /// @return Physreg to assign VirtReg, or 0.
625 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
626 AllocationOrder &Order,
627 SmallVectorImpl<LiveInterval*> &NewVRegs,
628 unsigned CostPerUseLimit) {
629 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
631 // Keep track of the cheapest interference seen so far.
632 EvictionCost BestCost(~0u);
633 unsigned BestPhys = 0;
634 unsigned OrderLimit = Order.getOrder().size();
636 // When we are just looking for a reduced cost per use, don't break any
637 // hints, and only evict smaller spill weights.
638 if (CostPerUseLimit < ~0u) {
639 BestCost.BrokenHints = 0;
640 BestCost.MaxWeight = VirtReg.weight;
642 // Check of any registers in RC are below CostPerUseLimit.
643 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
644 unsigned MinCost = RegClassInfo.getMinCost(RC);
645 if (MinCost >= CostPerUseLimit) {
646 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
647 << ", no cheaper registers to be found.\n");
651 // It is normal for register classes to have a long tail of registers with
652 // the same cost. We don't need to look at them if they're too expensive.
653 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
654 OrderLimit = RegClassInfo.getLastCostChange(RC);
655 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
660 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
661 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
663 // The first use of a callee-saved register in a function has cost 1.
664 // Don't start using a CSR when the CostPerUseLimit is low.
665 if (CostPerUseLimit == 1)
666 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
667 if (!MRI->isPhysRegUsed(CSR)) {
668 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
669 << PrintReg(CSR, TRI) << '\n');
673 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
679 // Stop if the hint can be used.
687 evictInterference(VirtReg, BestPhys, NewVRegs);
692 //===----------------------------------------------------------------------===//
694 //===----------------------------------------------------------------------===//
696 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
697 /// interference pattern in Physreg and its aliases. Add the constraints to
698 /// SpillPlacement and return the static cost of this split in Cost, assuming
699 /// that all preferences in SplitConstraints are met.
700 /// Return false if there are no bundles with positive bias.
701 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
703 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
705 // Reset interference dependent info.
706 SplitConstraints.resize(UseBlocks.size());
707 float StaticCost = 0;
708 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
709 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
710 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
712 BC.Number = BI.MBB->getNumber();
713 Intf.moveToBlock(BC.Number);
714 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
715 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
716 BC.ChangesValue = BI.FirstDef;
718 if (!Intf.hasInterference())
721 // Number of spill code instructions to insert.
724 // Interference for the live-in value.
726 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
727 BC.Entry = SpillPlacement::MustSpill, ++Ins;
728 else if (Intf.first() < BI.FirstInstr)
729 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
730 else if (Intf.first() < BI.LastInstr)
734 // Interference for the live-out value.
736 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
737 BC.Exit = SpillPlacement::MustSpill, ++Ins;
738 else if (Intf.last() > BI.LastInstr)
739 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
740 else if (Intf.last() > BI.FirstInstr)
744 // Accumulate the total frequency of inserted spill code.
746 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
750 // Add constraints for use-blocks. Note that these are the only constraints
751 // that may add a positive bias, it is downhill from here.
752 SpillPlacer->addConstraints(SplitConstraints);
753 return SpillPlacer->scanActiveBundles();
757 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
758 /// live-through blocks in Blocks.
759 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
760 ArrayRef<unsigned> Blocks) {
761 const unsigned GroupSize = 8;
762 SpillPlacement::BlockConstraint BCS[GroupSize];
763 unsigned TBS[GroupSize];
764 unsigned B = 0, T = 0;
766 for (unsigned i = 0; i != Blocks.size(); ++i) {
767 unsigned Number = Blocks[i];
768 Intf.moveToBlock(Number);
770 if (!Intf.hasInterference()) {
771 assert(T < GroupSize && "Array overflow");
773 if (++T == GroupSize) {
774 SpillPlacer->addLinks(makeArrayRef(TBS, T));
780 assert(B < GroupSize && "Array overflow");
781 BCS[B].Number = Number;
783 // Interference for the live-in value.
784 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
785 BCS[B].Entry = SpillPlacement::MustSpill;
787 BCS[B].Entry = SpillPlacement::PrefSpill;
789 // Interference for the live-out value.
790 if (Intf.last() >= SA->getLastSplitPoint(Number))
791 BCS[B].Exit = SpillPlacement::MustSpill;
793 BCS[B].Exit = SpillPlacement::PrefSpill;
795 if (++B == GroupSize) {
796 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
797 SpillPlacer->addConstraints(Array);
802 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
803 SpillPlacer->addConstraints(Array);
804 SpillPlacer->addLinks(makeArrayRef(TBS, T));
807 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
808 // Keep track of through blocks that have not been added to SpillPlacer.
809 BitVector Todo = SA->getThroughBlocks();
810 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
811 unsigned AddedTo = 0;
813 unsigned Visited = 0;
817 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
818 // Find new through blocks in the periphery of PrefRegBundles.
819 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
820 unsigned Bundle = NewBundles[i];
821 // Look at all blocks connected to Bundle in the full graph.
822 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
823 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
826 if (!Todo.test(Block))
829 // This is a new through block. Add it to SpillPlacer later.
830 ActiveBlocks.push_back(Block);
836 // Any new blocks to add?
837 if (ActiveBlocks.size() == AddedTo)
840 // Compute through constraints from the interference, or assume that all
841 // through blocks prefer spilling when forming compact regions.
842 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
844 addThroughConstraints(Cand.Intf, NewBlocks);
846 // Provide a strong negative bias on through blocks to prevent unwanted
847 // liveness on loop backedges.
848 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
849 AddedTo = ActiveBlocks.size();
851 // Perhaps iterating can enable more bundles?
852 SpillPlacer->iterate();
854 DEBUG(dbgs() << ", v=" << Visited);
857 /// calcCompactRegion - Compute the set of edge bundles that should be live
858 /// when splitting the current live range into compact regions. Compact
859 /// regions can be computed without looking at interference. They are the
860 /// regions formed by removing all the live-through blocks from the live range.
862 /// Returns false if the current live range is already compact, or if the
863 /// compact regions would form single block regions anyway.
864 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
865 // Without any through blocks, the live range is already compact.
866 if (!SA->getNumThroughBlocks())
869 // Compact regions don't correspond to any physreg.
870 Cand.reset(IntfCache, 0);
872 DEBUG(dbgs() << "Compact region bundles");
874 // Use the spill placer to determine the live bundles. GrowRegion pretends
875 // that all the through blocks have interference when PhysReg is unset.
876 SpillPlacer->prepare(Cand.LiveBundles);
878 // The static split cost will be zero since Cand.Intf reports no interference.
880 if (!addSplitConstraints(Cand.Intf, Cost)) {
881 DEBUG(dbgs() << ", none.\n");
886 SpillPlacer->finish();
888 if (!Cand.LiveBundles.any()) {
889 DEBUG(dbgs() << ", none.\n");
894 for (int i = Cand.LiveBundles.find_first(); i>=0;
895 i = Cand.LiveBundles.find_next(i))
896 dbgs() << " EB#" << i;
902 /// calcSpillCost - Compute how expensive it would be to split the live range in
903 /// SA around all use blocks instead of forming bundle regions.
904 float RAGreedy::calcSpillCost() {
906 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
907 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
908 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
909 unsigned Number = BI.MBB->getNumber();
910 // We normally only need one spill instruction - a load or a store.
911 Cost += SpillPlacer->getBlockFrequency(Number);
913 // Unless the value is redefined in the block.
914 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
915 Cost += SpillPlacer->getBlockFrequency(Number);
920 /// calcGlobalSplitCost - Return the global split cost of following the split
921 /// pattern in LiveBundles. This cost should be added to the local cost of the
922 /// interference pattern in SplitConstraints.
924 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
925 float GlobalCost = 0;
926 const BitVector &LiveBundles = Cand.LiveBundles;
927 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
928 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
929 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
930 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
931 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
932 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
936 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
938 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
940 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
943 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
944 unsigned Number = Cand.ActiveBlocks[i];
945 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
946 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
947 if (!RegIn && !RegOut)
949 if (RegIn && RegOut) {
950 // We need double spill code if this block has interference.
951 Cand.Intf.moveToBlock(Number);
952 if (Cand.Intf.hasInterference())
953 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
956 // live-in / stack-out or stack-in live-out.
957 GlobalCost += SpillPlacer->getBlockFrequency(Number);
962 /// splitAroundRegion - Split the current live range around the regions
963 /// determined by BundleCand and GlobalCand.
965 /// Before calling this function, GlobalCand and BundleCand must be initialized
966 /// so each bundle is assigned to a valid candidate, or NoCand for the
967 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
968 /// objects must be initialized for the current live range, and intervals
969 /// created for the used candidates.
971 /// @param LREdit The LiveRangeEdit object handling the current split.
972 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
973 /// must appear in this list.
974 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
975 ArrayRef<unsigned> UsedCands) {
976 // These are the intervals created for new global ranges. We may create more
977 // intervals for local ranges.
978 const unsigned NumGlobalIntvs = LREdit.size();
979 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
980 assert(NumGlobalIntvs && "No global intervals configured");
982 // Isolate even single instructions when dealing with a proper sub-class.
983 // That guarantees register class inflation for the stack interval because it
985 unsigned Reg = SA->getParent().reg;
986 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
988 // First handle all the blocks with uses.
989 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
990 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
991 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
992 unsigned Number = BI.MBB->getNumber();
993 unsigned IntvIn = 0, IntvOut = 0;
994 SlotIndex IntfIn, IntfOut;
996 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
997 if (CandIn != NoCand) {
998 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
999 IntvIn = Cand.IntvIdx;
1000 Cand.Intf.moveToBlock(Number);
1001 IntfIn = Cand.Intf.first();
1005 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1006 if (CandOut != NoCand) {
1007 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1008 IntvOut = Cand.IntvIdx;
1009 Cand.Intf.moveToBlock(Number);
1010 IntfOut = Cand.Intf.last();
1014 // Create separate intervals for isolated blocks with multiple uses.
1015 if (!IntvIn && !IntvOut) {
1016 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1017 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1018 SE->splitSingleBlock(BI);
1022 if (IntvIn && IntvOut)
1023 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1025 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1027 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1030 // Handle live-through blocks. The relevant live-through blocks are stored in
1031 // the ActiveBlocks list with each candidate. We need to filter out
1033 BitVector Todo = SA->getThroughBlocks();
1034 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1035 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1036 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1037 unsigned Number = Blocks[i];
1038 if (!Todo.test(Number))
1042 unsigned IntvIn = 0, IntvOut = 0;
1043 SlotIndex IntfIn, IntfOut;
1045 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1046 if (CandIn != NoCand) {
1047 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1048 IntvIn = Cand.IntvIdx;
1049 Cand.Intf.moveToBlock(Number);
1050 IntfIn = Cand.Intf.first();
1053 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1054 if (CandOut != NoCand) {
1055 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1056 IntvOut = Cand.IntvIdx;
1057 Cand.Intf.moveToBlock(Number);
1058 IntfOut = Cand.Intf.last();
1060 if (!IntvIn && !IntvOut)
1062 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1068 SmallVector<unsigned, 8> IntvMap;
1069 SE->finish(&IntvMap);
1070 DebugVars->splitRegister(Reg, LREdit.regs());
1072 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1073 unsigned OrigBlocks = SA->getNumLiveBlocks();
1075 // Sort out the new intervals created by splitting. We get four kinds:
1076 // - Remainder intervals should not be split again.
1077 // - Candidate intervals can be assigned to Cand.PhysReg.
1078 // - Block-local splits are candidates for local splitting.
1079 // - DCE leftovers should go back on the queue.
1080 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1081 LiveInterval &Reg = *LREdit.get(i);
1083 // Ignore old intervals from DCE.
1084 if (getStage(Reg) != RS_New)
1087 // Remainder interval. Don't try splitting again, spill if it doesn't
1089 if (IntvMap[i] == 0) {
1090 setStage(Reg, RS_Spill);
1094 // Global intervals. Allow repeated splitting as long as the number of live
1095 // blocks is strictly decreasing.
1096 if (IntvMap[i] < NumGlobalIntvs) {
1097 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1098 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1099 << " blocks as original.\n");
1100 // Don't allow repeated splitting as a safe guard against looping.
1101 setStage(Reg, RS_Split2);
1106 // Other intervals are treated as new. This includes local intervals created
1107 // for blocks with multiple uses, and anything created by DCE.
1111 MF->verify(this, "After splitting live range around region");
1114 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1115 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1116 unsigned NumCands = 0;
1117 unsigned BestCand = NoCand;
1119 SmallVector<unsigned, 8> UsedCands;
1121 // Check if we can split this live range around a compact region.
1122 bool HasCompact = calcCompactRegion(GlobalCand.front());
1124 // Yes, keep GlobalCand[0] as the compact region candidate.
1126 BestCost = HUGE_VALF;
1128 // No benefit from the compact region, our fallback will be per-block
1129 // splitting. Make sure we find a solution that is cheaper than spilling.
1130 BestCost = Hysteresis * calcSpillCost();
1131 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1135 while (unsigned PhysReg = Order.next()) {
1136 // Discard bad candidates before we run out of interference cache cursors.
1137 // This will only affect register classes with a lot of registers (>32).
1138 if (NumCands == IntfCache.getMaxCursors()) {
1139 unsigned WorstCount = ~0u;
1141 for (unsigned i = 0; i != NumCands; ++i) {
1142 if (i == BestCand || !GlobalCand[i].PhysReg)
1144 unsigned Count = GlobalCand[i].LiveBundles.count();
1145 if (Count < WorstCount)
1146 Worst = i, WorstCount = Count;
1149 GlobalCand[Worst] = GlobalCand[NumCands];
1150 if (BestCand == NumCands)
1154 if (GlobalCand.size() <= NumCands)
1155 GlobalCand.resize(NumCands+1);
1156 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1157 Cand.reset(IntfCache, PhysReg);
1159 SpillPlacer->prepare(Cand.LiveBundles);
1161 if (!addSplitConstraints(Cand.Intf, Cost)) {
1162 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1165 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1166 if (Cost >= BestCost) {
1168 if (BestCand == NoCand)
1169 dbgs() << " worse than no bundles\n";
1171 dbgs() << " worse than "
1172 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1178 SpillPlacer->finish();
1180 // No live bundles, defer to splitSingleBlocks().
1181 if (!Cand.LiveBundles.any()) {
1182 DEBUG(dbgs() << " no bundles.\n");
1186 Cost += calcGlobalSplitCost(Cand);
1188 dbgs() << ", total = " << Cost << " with bundles";
1189 for (int i = Cand.LiveBundles.find_first(); i>=0;
1190 i = Cand.LiveBundles.find_next(i))
1191 dbgs() << " EB#" << i;
1194 if (Cost < BestCost) {
1195 BestCand = NumCands;
1196 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1201 // No solutions found, fall back to single block splitting.
1202 if (!HasCompact && BestCand == NoCand)
1205 // Prepare split editor.
1206 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1207 SE->reset(LREdit, SplitSpillMode);
1209 // Assign all edge bundles to the preferred candidate, or NoCand.
1210 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1212 // Assign bundles for the best candidate region.
1213 if (BestCand != NoCand) {
1214 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1215 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1216 UsedCands.push_back(BestCand);
1217 Cand.IntvIdx = SE->openIntv();
1218 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1219 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1224 // Assign bundles for the compact region.
1226 GlobalSplitCandidate &Cand = GlobalCand.front();
1227 assert(!Cand.PhysReg && "Compact region has no physreg");
1228 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1229 UsedCands.push_back(0);
1230 Cand.IntvIdx = SE->openIntv();
1231 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1232 << Cand.IntvIdx << ".\n");
1237 splitAroundRegion(LREdit, UsedCands);
1242 //===----------------------------------------------------------------------===//
1243 // Per-Block Splitting
1244 //===----------------------------------------------------------------------===//
1246 /// tryBlockSplit - Split a global live range around every block with uses. This
1247 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1248 /// they don't allocate.
1249 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1250 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1251 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1252 unsigned Reg = VirtReg.reg;
1253 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1254 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1255 SE->reset(LREdit, SplitSpillMode);
1256 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1257 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1258 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1259 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1260 SE->splitSingleBlock(BI);
1262 // No blocks were split.
1266 // We did split for some blocks.
1267 SmallVector<unsigned, 8> IntvMap;
1268 SE->finish(&IntvMap);
1270 // Tell LiveDebugVariables about the new ranges.
1271 DebugVars->splitRegister(Reg, LREdit.regs());
1273 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1275 // Sort out the new intervals created by splitting. The remainder interval
1276 // goes straight to spilling, the new local ranges get to stay RS_New.
1277 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1278 LiveInterval &LI = *LREdit.get(i);
1279 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1280 setStage(LI, RS_Spill);
1284 MF->verify(this, "After splitting live range around basic blocks");
1289 //===----------------------------------------------------------------------===//
1290 // Per-Instruction Splitting
1291 //===----------------------------------------------------------------------===//
1293 /// tryInstructionSplit - Split a live range around individual instructions.
1294 /// This is normally not worthwhile since the spiller is doing essentially the
1295 /// same thing. However, when the live range is in a constrained register
1296 /// class, it may help to insert copies such that parts of the live range can
1297 /// be moved to a larger register class.
1299 /// This is similar to spilling to a larger register class.
1301 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1302 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1303 // There is no point to this if there are no larger sub-classes.
1304 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1307 // Always enable split spill mode, since we're effectively spilling to a
1309 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1310 SE->reset(LREdit, SplitEditor::SM_Size);
1312 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1313 if (Uses.size() <= 1)
1316 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1318 // Split around every non-copy instruction.
1319 for (unsigned i = 0; i != Uses.size(); ++i) {
1320 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1321 if (MI->isFullCopy()) {
1322 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1326 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1327 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1328 SE->useIntv(SegStart, SegStop);
1331 if (LREdit.empty()) {
1332 DEBUG(dbgs() << "All uses were copies.\n");
1336 SmallVector<unsigned, 8> IntvMap;
1337 SE->finish(&IntvMap);
1338 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1339 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1341 // Assign all new registers to RS_Spill. This was the last chance.
1342 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1347 //===----------------------------------------------------------------------===//
1349 //===----------------------------------------------------------------------===//
1352 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1353 /// in order to use PhysReg between two entries in SA->UseSlots.
1355 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1357 void RAGreedy::calcGapWeights(unsigned PhysReg,
1358 SmallVectorImpl<float> &GapWeight) {
1359 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1360 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1361 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1362 const unsigned NumGaps = Uses.size()-1;
1364 // Start and end points for the interference check.
1365 SlotIndex StartIdx =
1366 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1368 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1370 GapWeight.assign(NumGaps, 0.0f);
1372 // Add interference from each overlapping register.
1373 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1374 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1375 .checkInterference())
1378 // We know that VirtReg is a continuous interval from FirstInstr to
1379 // LastInstr, so we don't need InterferenceQuery.
1381 // Interference that overlaps an instruction is counted in both gaps
1382 // surrounding the instruction. The exception is interference before
1383 // StartIdx and after StopIdx.
1385 LiveIntervalUnion::SegmentIter IntI =
1386 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1387 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1388 // Skip the gaps before IntI.
1389 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1390 if (++Gap == NumGaps)
1395 // Update the gaps covered by IntI.
1396 const float weight = IntI.value()->weight;
1397 for (; Gap != NumGaps; ++Gap) {
1398 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1399 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1407 // Add fixed interference.
1408 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1409 const LiveInterval &LI = LIS->getRegUnit(*Units);
1410 LiveInterval::const_iterator I = LI.find(StartIdx);
1411 LiveInterval::const_iterator E = LI.end();
1413 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1414 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1415 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1416 if (++Gap == NumGaps)
1421 for (; Gap != NumGaps; ++Gap) {
1422 GapWeight[Gap] = HUGE_VALF;
1423 if (Uses[Gap+1].getBaseIndex() >= I->end)
1432 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1435 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1436 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1437 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1438 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1440 // Note that it is possible to have an interval that is live-in or live-out
1441 // while only covering a single block - A phi-def can use undef values from
1442 // predecessors, and the block could be a single-block loop.
1443 // We don't bother doing anything clever about such a case, we simply assume
1444 // that the interval is continuous from FirstInstr to LastInstr. We should
1445 // make sure that we don't do anything illegal to such an interval, though.
1447 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1448 if (Uses.size() <= 2)
1450 const unsigned NumGaps = Uses.size()-1;
1453 dbgs() << "tryLocalSplit: ";
1454 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1455 dbgs() << ' ' << Uses[i];
1459 // If VirtReg is live across any register mask operands, compute a list of
1460 // gaps with register masks.
1461 SmallVector<unsigned, 8> RegMaskGaps;
1462 if (Matrix->checkRegMaskInterference(VirtReg)) {
1463 // Get regmask slots for the whole block.
1464 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1465 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1466 // Constrain to VirtReg's live range.
1467 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1468 Uses.front().getRegSlot()) - RMS.begin();
1469 unsigned re = RMS.size();
1470 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1471 // Look for Uses[i] <= RMS <= Uses[i+1].
1472 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1473 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1475 // Skip a regmask on the same instruction as the last use. It doesn't
1476 // overlap the live range.
1477 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1479 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1480 RegMaskGaps.push_back(i);
1481 // Advance ri to the next gap. A regmask on one of the uses counts in
1483 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1486 DEBUG(dbgs() << '\n');
1489 // Since we allow local split results to be split again, there is a risk of
1490 // creating infinite loops. It is tempting to require that the new live
1491 // ranges have less instructions than the original. That would guarantee
1492 // convergence, but it is too strict. A live range with 3 instructions can be
1493 // split 2+3 (including the COPY), and we want to allow that.
1495 // Instead we use these rules:
1497 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1498 // noop split, of course).
1499 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1500 // the new ranges must have fewer instructions than before the split.
1501 // 3. New ranges with the same number of instructions are marked RS_Split2,
1502 // smaller ranges are marked RS_New.
1504 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1505 // excessive splitting and infinite loops.
1507 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1509 // Best split candidate.
1510 unsigned BestBefore = NumGaps;
1511 unsigned BestAfter = 0;
1514 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1515 SmallVector<float, 8> GapWeight;
1518 while (unsigned PhysReg = Order.next()) {
1519 // Keep track of the largest spill weight that would need to be evicted in
1520 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1521 calcGapWeights(PhysReg, GapWeight);
1523 // Remove any gaps with regmask clobbers.
1524 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1525 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1526 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1528 // Try to find the best sequence of gaps to close.
1529 // The new spill weight must be larger than any gap interference.
1531 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1532 unsigned SplitBefore = 0, SplitAfter = 1;
1534 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1535 // It is the spill weight that needs to be evicted.
1536 float MaxGap = GapWeight[0];
1539 // Live before/after split?
1540 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1541 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1543 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1544 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1545 << " i=" << MaxGap);
1547 // Stop before the interval gets so big we wouldn't be making progress.
1548 if (!LiveBefore && !LiveAfter) {
1549 DEBUG(dbgs() << " all\n");
1552 // Should the interval be extended or shrunk?
1555 // How many gaps would the new range have?
1556 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1558 // Legally, without causing looping?
1559 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1561 if (Legal && MaxGap < HUGE_VALF) {
1562 // Estimate the new spill weight. Each instruction reads or writes the
1563 // register. Conservatively assume there are no read-modify-write
1566 // Try to guess the size of the new interval.
1567 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1568 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1569 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1570 // Would this split be possible to allocate?
1571 // Never allocate all gaps, we wouldn't be making progress.
1572 DEBUG(dbgs() << " w=" << EstWeight);
1573 if (EstWeight * Hysteresis >= MaxGap) {
1575 float Diff = EstWeight - MaxGap;
1576 if (Diff > BestDiff) {
1577 DEBUG(dbgs() << " (best)");
1578 BestDiff = Hysteresis * Diff;
1579 BestBefore = SplitBefore;
1580 BestAfter = SplitAfter;
1587 if (++SplitBefore < SplitAfter) {
1588 DEBUG(dbgs() << " shrink\n");
1589 // Recompute the max when necessary.
1590 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1591 MaxGap = GapWeight[SplitBefore];
1592 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1593 MaxGap = std::max(MaxGap, GapWeight[i]);
1600 // Try to extend the interval.
1601 if (SplitAfter >= NumGaps) {
1602 DEBUG(dbgs() << " end\n");
1606 DEBUG(dbgs() << " extend\n");
1607 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1611 // Didn't find any candidates?
1612 if (BestBefore == NumGaps)
1615 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1616 << '-' << Uses[BestAfter] << ", " << BestDiff
1617 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1619 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1623 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1624 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1625 SE->useIntv(SegStart, SegStop);
1626 SmallVector<unsigned, 8> IntvMap;
1627 SE->finish(&IntvMap);
1628 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1630 // If the new range has the same number of instructions as before, mark it as
1631 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1632 // leave the new intervals as RS_New so they can compete.
1633 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1634 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1635 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1636 if (NewGaps >= NumGaps) {
1637 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1638 assert(!ProgressRequired && "Didn't make progress when it was required.");
1639 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1640 if (IntvMap[i] == 1) {
1641 setStage(*LREdit.get(i), RS_Split2);
1642 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1644 DEBUG(dbgs() << '\n');
1651 //===----------------------------------------------------------------------===//
1652 // Live Range Splitting
1653 //===----------------------------------------------------------------------===//
1655 /// trySplit - Try to split VirtReg or one of its interferences, making it
1657 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1658 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1659 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1660 // Ranges must be Split2 or less.
1661 if (getStage(VirtReg) >= RS_Spill)
1664 // Local intervals are handled separately.
1665 if (LIS->intervalIsInOneMBB(VirtReg)) {
1666 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1667 SA->analyze(&VirtReg);
1668 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1669 if (PhysReg || !NewVRegs.empty())
1671 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1674 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1676 SA->analyze(&VirtReg);
1678 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1679 // coalescer. That may cause the range to become allocatable which means that
1680 // tryRegionSplit won't be making progress. This check should be replaced with
1681 // an assertion when the coalescer is fixed.
1682 if (SA->didRepairRange()) {
1683 // VirtReg has changed, so all cached queries are invalid.
1684 Matrix->invalidateVirtRegs();
1685 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1689 // First try to split around a region spanning multiple blocks. RS_Split2
1690 // ranges already made dubious progress with region splitting, so they go
1691 // straight to single block splitting.
1692 if (getStage(VirtReg) < RS_Split2) {
1693 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1694 if (PhysReg || !NewVRegs.empty())
1698 // Then isolate blocks.
1699 return tryBlockSplit(VirtReg, Order, NewVRegs);
1703 //===----------------------------------------------------------------------===//
1705 //===----------------------------------------------------------------------===//
1707 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1708 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1709 // First try assigning a free register.
1710 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1711 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1714 LiveRangeStage Stage = getStage(VirtReg);
1715 DEBUG(dbgs() << StageName[Stage]
1716 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1718 // Try to evict a less worthy live range, but only for ranges from the primary
1719 // queue. The RS_Split ranges already failed to do this, and they should not
1720 // get a second chance until they have been split.
1721 if (Stage != RS_Split)
1722 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1725 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1727 // The first time we see a live range, don't try to split or spill.
1728 // Wait until the second time, when all smaller ranges have been allocated.
1729 // This gives a better picture of the interference to split around.
1730 if (Stage < RS_Split) {
1731 setStage(VirtReg, RS_Split);
1732 DEBUG(dbgs() << "wait for second round\n");
1733 NewVRegs.push_back(&VirtReg);
1737 // If we couldn't allocate a register from spilling, there is probably some
1738 // invalid inline assembly. The base class wil report it.
1739 if (Stage >= RS_Done || !VirtReg.isSpillable())
1742 // Try splitting VirtReg or interferences.
1743 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1744 if (PhysReg || !NewVRegs.empty())
1747 // Finally spill VirtReg itself.
1748 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1749 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1750 spiller().spill(LRE);
1751 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1754 MF->verify(this, "After spilling");
1756 // The live virtual register requesting allocation was spilled, so tell
1757 // the caller not to allocate anything during this round.
1761 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1762 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1763 << "********** Function: " << mf.getName() << '\n');
1767 MF->verify(this, "Before greedy register allocator");
1769 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1770 getAnalysis<LiveIntervals>(),
1771 getAnalysis<LiveRegMatrix>());
1772 Indexes = &getAnalysis<SlotIndexes>();
1773 DomTree = &getAnalysis<MachineDominatorTree>();
1774 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1775 Loops = &getAnalysis<MachineLoopInfo>();
1776 Bundles = &getAnalysis<EdgeBundles>();
1777 SpillPlacer = &getAnalysis<SpillPlacement>();
1778 DebugVars = &getAnalysis<LiveDebugVariables>();
1780 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1781 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1782 ExtraRegInfo.clear();
1783 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1785 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1786 GlobalCand.resize(32); // This will grow as needed.