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 "AllocationOrder.h"
17 #include "InterferenceCache.h"
18 #include "LiveDebugVariables.h"
19 #include "LiveRangeEdit.h"
20 #include "RegAllocBase.h"
22 #include "SpillPlacement.h"
24 #include "VirtRegMap.h"
25 #include "RegisterCoalescer.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Function.h"
29 #include "llvm/PassAnalysisSupport.h"
30 #include "llvm/CodeGen/CalcSpillWeights.h"
31 #include "llvm/CodeGen/EdgeBundles.h"
32 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
33 #include "llvm/CodeGen/LiveStackAnalysis.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/Timer.h"
51 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52 STATISTIC(NumLocalSplits, "Number of split local live ranges");
53 STATISTIC(NumEvicted, "Number of interferences evicted");
55 cl::opt<bool> CompactRegions("compact-regions");
57 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
58 createGreedyRegisterAllocator);
61 class RAGreedy : public MachineFunctionPass,
63 private LiveRangeEdit::Delegate {
71 MachineDominatorTree *DomTree;
72 MachineLoopInfo *Loops;
74 SpillPlacement *SpillPlacer;
75 LiveDebugVariables *DebugVars;
78 std::auto_ptr<Spiller> SpillerInstance;
79 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
82 // Live ranges pass through a number of stages as we try to allocate them.
83 // Some of the stages may also create new live ranges:
85 // - Region splitting.
86 // - Per-block splitting.
90 // Ranges produced by one of the stages skip the previous stages when they are
91 // dequeued. This improves performance because we can skip interference checks
92 // that are unlikely to give any results. It also guarantees that the live
93 // range splitting algorithm terminates, something that is otherwise hard to
96 /// Newly created live range that has never been queued.
99 /// Only attempt assignment and eviction. Then requeue as RS_Split.
102 /// Attempt live range splitting if assignment is impossible.
105 /// Attempt more aggressive live range splitting that is guaranteed to make
106 /// progress. This is used for split products that may not be making
110 /// Live range will be spilled. No more splitting will be attempted.
113 /// There is nothing more we can do to this live range. Abort compilation
114 /// if it can't be assigned.
118 static const char *const StageName[];
120 // RegInfo - Keep additional information about each live range.
122 LiveRangeStage Stage;
124 // Cascade - Eviction loop prevention. See canEvictInterference().
127 RegInfo() : Stage(RS_New), Cascade(0) {}
130 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
132 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
133 return ExtraRegInfo[VirtReg.reg].Stage;
136 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
137 ExtraRegInfo.resize(MRI->getNumVirtRegs());
138 ExtraRegInfo[VirtReg.reg].Stage = Stage;
141 template<typename Iterator>
142 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
144 for (;Begin != End; ++Begin) {
145 unsigned Reg = (*Begin)->reg;
146 if (ExtraRegInfo[Reg].Stage == RS_New)
147 ExtraRegInfo[Reg].Stage = NewStage;
151 /// Cost of evicting interference.
152 struct EvictionCost {
153 unsigned BrokenHints; ///< Total number of broken hints.
154 float MaxWeight; ///< Maximum spill weight evicted.
156 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
158 bool operator<(const EvictionCost &O) const {
159 if (BrokenHints != O.BrokenHints)
160 return BrokenHints < O.BrokenHints;
161 return MaxWeight < O.MaxWeight;
166 std::auto_ptr<SplitAnalysis> SA;
167 std::auto_ptr<SplitEditor> SE;
169 /// Cached per-block interference maps
170 InterferenceCache IntfCache;
172 /// All basic blocks where the current register has uses.
173 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
175 /// Global live range splitting candidate info.
176 struct GlobalSplitCandidate {
177 // Register intended for assignment, or 0.
180 // SplitKit interval index for this candidate.
183 // Interference for PhysReg.
184 InterferenceCache::Cursor Intf;
186 // Bundles where this candidate should be live.
187 BitVector LiveBundles;
188 SmallVector<unsigned, 8> ActiveBlocks;
190 void reset(InterferenceCache &Cache, unsigned Reg) {
193 Intf.setPhysReg(Cache, Reg);
195 ActiveBlocks.clear();
198 // Set B[i] = C for every live bundle where B[i] was NoCand.
199 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
201 for (int i = LiveBundles.find_first(); i >= 0;
202 i = LiveBundles.find_next(i))
203 if (B[i] == NoCand) {
211 /// Candidate info for for each PhysReg in AllocationOrder.
212 /// This vector never shrinks, but grows to the size of the largest register
214 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
216 enum { NoCand = ~0u };
218 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
219 /// NoCand which indicates the stack interval.
220 SmallVector<unsigned, 32> BundleCand;
225 /// Return the pass name.
226 virtual const char* getPassName() const {
227 return "Greedy Register Allocator";
230 /// RAGreedy analysis usage.
231 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
232 virtual void releaseMemory();
233 virtual Spiller &spiller() { return *SpillerInstance; }
234 virtual void enqueue(LiveInterval *LI);
235 virtual LiveInterval *dequeue();
236 virtual unsigned selectOrSplit(LiveInterval&,
237 SmallVectorImpl<LiveInterval*>&);
239 /// Perform register allocation.
240 virtual bool runOnMachineFunction(MachineFunction &mf);
245 void LRE_WillEraseInstruction(MachineInstr*);
246 bool LRE_CanEraseVirtReg(unsigned);
247 void LRE_WillShrinkVirtReg(unsigned);
248 void LRE_DidCloneVirtReg(unsigned, unsigned);
250 float calcSpillCost();
251 bool addSplitConstraints(InterferenceCache::Cursor, float&);
252 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
253 void growRegion(GlobalSplitCandidate &Cand);
254 float calcGlobalSplitCost(GlobalSplitCandidate&);
255 bool calcCompactRegion(GlobalSplitCandidate&);
256 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
257 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
258 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
259 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
260 void evictInterference(LiveInterval&, unsigned,
261 SmallVectorImpl<LiveInterval*>&);
263 unsigned tryAssign(LiveInterval&, AllocationOrder&,
264 SmallVectorImpl<LiveInterval*>&);
265 unsigned tryEvict(LiveInterval&, AllocationOrder&,
266 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
267 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
269 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
271 unsigned trySplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
274 } // end anonymous namespace
276 char RAGreedy::ID = 0;
279 const char *const RAGreedy::StageName[] = {
289 // Hysteresis to use when comparing floats.
290 // This helps stabilize decisions based on float comparisons.
291 const float Hysteresis = 0.98f;
294 FunctionPass* llvm::createGreedyRegisterAllocator() {
295 return new RAGreedy();
298 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
299 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
300 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
301 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
302 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
303 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
304 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
305 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
306 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
307 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
308 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
309 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
310 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
311 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
314 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
315 AU.setPreservesCFG();
316 AU.addRequired<AliasAnalysis>();
317 AU.addPreserved<AliasAnalysis>();
318 AU.addRequired<LiveIntervals>();
319 AU.addRequired<SlotIndexes>();
320 AU.addPreserved<SlotIndexes>();
321 AU.addRequired<LiveDebugVariables>();
322 AU.addPreserved<LiveDebugVariables>();
324 AU.addRequiredID(StrongPHIEliminationID);
325 AU.addRequiredTransitive<RegisterCoalescer>();
326 AU.addRequired<CalculateSpillWeights>();
327 AU.addRequired<LiveStacks>();
328 AU.addPreserved<LiveStacks>();
329 AU.addRequired<MachineDominatorTree>();
330 AU.addPreserved<MachineDominatorTree>();
331 AU.addRequired<MachineLoopInfo>();
332 AU.addPreserved<MachineLoopInfo>();
333 AU.addRequired<VirtRegMap>();
334 AU.addPreserved<VirtRegMap>();
335 AU.addRequired<EdgeBundles>();
336 AU.addRequired<SpillPlacement>();
337 MachineFunctionPass::getAnalysisUsage(AU);
341 //===----------------------------------------------------------------------===//
342 // LiveRangeEdit delegate methods
343 //===----------------------------------------------------------------------===//
345 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
346 // LRE itself will remove from SlotIndexes and parent basic block.
347 VRM->RemoveMachineInstrFromMaps(MI);
350 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
351 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
352 unassign(LIS->getInterval(VirtReg), PhysReg);
355 // Unassigned virtreg is probably in the priority queue.
356 // RegAllocBase will erase it after dequeueing.
360 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
361 unsigned PhysReg = VRM->getPhys(VirtReg);
365 // Register is assigned, put it back on the queue for reassignment.
366 LiveInterval &LI = LIS->getInterval(VirtReg);
367 unassign(LI, PhysReg);
371 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
372 // LRE may clone a virtual register because dead code elimination causes it to
373 // be split into connected components. The new components are much smaller
374 // than the original, so they should get a new chance at being assigned.
375 // same stage as the parent.
376 ExtraRegInfo[Old].Stage = RS_Assign;
377 ExtraRegInfo.grow(New);
378 ExtraRegInfo[New] = ExtraRegInfo[Old];
381 void RAGreedy::releaseMemory() {
382 SpillerInstance.reset(0);
383 ExtraRegInfo.clear();
385 RegAllocBase::releaseMemory();
388 void RAGreedy::enqueue(LiveInterval *LI) {
389 // Prioritize live ranges by size, assigning larger ranges first.
390 // The queue holds (size, reg) pairs.
391 const unsigned Size = LI->getSize();
392 const unsigned Reg = LI->reg;
393 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
394 "Can only enqueue virtual registers");
397 ExtraRegInfo.grow(Reg);
398 if (ExtraRegInfo[Reg].Stage == RS_New)
399 ExtraRegInfo[Reg].Stage = RS_Assign;
401 if (ExtraRegInfo[Reg].Stage == RS_Split) {
402 // Unsplit ranges that couldn't be allocated immediately are deferred until
403 // everything else has been allocated. Long ranges are allocated last so
404 // they are split against realistic interference.
408 Prio = (1u << 31) - Size;
410 // Everything else is allocated in long->short order. Long ranges that don't
411 // fit should be spilled ASAP so they don't create interference.
412 Prio = (1u << 31) + Size;
414 // Boost ranges that have a physical register hint.
415 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(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 (!checkPhysRegInterference(VirtReg, PhysReg))
444 if (!PhysReg || Order.isHint(PhysReg))
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 /// @prarm 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 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
516 // involved in an eviction before. If a cascade number was assigned, deny
517 // evicting anything with the same or a newer cascade number. This prevents
518 // infinite eviction loops.
520 // This works out so a register without a cascade number is allowed to evict
521 // anything, and it can be evicted by anything.
522 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
524 Cascade = NextCascade;
527 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
528 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
529 // If there is 10 or more interferences, chances are one is heavier.
530 if (Q.collectInterferingVRegs(10) >= 10)
533 // Check if any interfering live range is heavier than MaxWeight.
534 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
535 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
536 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
538 // Never evict spill products. They cannot split or spill.
539 if (getStage(*Intf) == RS_Done)
541 // Once a live range becomes small enough, it is urgent that we find a
542 // register for it. This is indicated by an infinite spill weight. These
543 // urgent live ranges get to evict almost anything.
544 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
545 // Only evict older cascades or live ranges without a cascade.
546 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
547 if (Cascade <= IntfCascade) {
550 // We permit breaking cascades for urgent evictions. It should be the
551 // last resort, though, so make it really expensive.
552 Cost.BrokenHints += 10;
554 // Would this break a satisfied hint?
555 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
556 // Update eviction cost.
557 Cost.BrokenHints += BreaksHint;
558 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
559 // Abort if this would be too expensive.
560 if (!(Cost < MaxCost))
562 // Finally, apply the eviction policy for non-urgent evictions.
563 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
571 /// evictInterference - Evict any interferring registers that prevent VirtReg
572 /// from being assigned to Physreg. This assumes that canEvictInterference
574 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
575 SmallVectorImpl<LiveInterval*> &NewVRegs) {
576 // Make sure that VirtReg has a cascade number, and assign that cascade
577 // number to every evicted register. These live ranges than then only be
578 // evicted by a newer cascade, preventing infinite loops.
579 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
581 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
583 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
584 << " interference: Cascade " << Cascade << '\n');
585 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
586 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
587 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
588 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
589 LiveInterval *Intf = Q.interferingVRegs()[i];
590 unassign(*Intf, VRM->getPhys(Intf->reg));
591 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
592 VirtReg.isSpillable() < Intf->isSpillable()) &&
593 "Cannot decrease cascade number, illegal eviction");
594 ExtraRegInfo[Intf->reg].Cascade = Cascade;
596 NewVRegs.push_back(Intf);
601 /// tryEvict - Try to evict all interferences for a physreg.
602 /// @param VirtReg Currently unassigned virtual register.
603 /// @param Order Physregs to try.
604 /// @return Physreg to assign VirtReg, or 0.
605 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
606 AllocationOrder &Order,
607 SmallVectorImpl<LiveInterval*> &NewVRegs,
608 unsigned CostPerUseLimit) {
609 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
611 // Keep track of the cheapest interference seen so far.
612 EvictionCost BestCost(~0u);
613 unsigned BestPhys = 0;
615 // When we are just looking for a reduced cost per use, don't break any
616 // hints, and only evict smaller spill weights.
617 if (CostPerUseLimit < ~0u) {
618 BestCost.BrokenHints = 0;
619 BestCost.MaxWeight = VirtReg.weight;
623 while (unsigned PhysReg = Order.next()) {
624 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
626 // The first use of a callee-saved register in a function has cost 1.
627 // Don't start using a CSR when the CostPerUseLimit is low.
628 if (CostPerUseLimit == 1)
629 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
630 if (!MRI->isPhysRegUsed(CSR)) {
631 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
632 << PrintReg(CSR, TRI) << '\n');
636 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
642 // Stop if the hint can be used.
643 if (Order.isHint(PhysReg))
650 evictInterference(VirtReg, BestPhys, NewVRegs);
655 //===----------------------------------------------------------------------===//
657 //===----------------------------------------------------------------------===//
659 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
660 /// interference pattern in Physreg and its aliases. Add the constraints to
661 /// SpillPlacement and return the static cost of this split in Cost, assuming
662 /// that all preferences in SplitConstraints are met.
663 /// Return false if there are no bundles with positive bias.
664 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
666 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
668 // Reset interference dependent info.
669 SplitConstraints.resize(UseBlocks.size());
670 float StaticCost = 0;
671 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
672 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
673 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
675 BC.Number = BI.MBB->getNumber();
676 Intf.moveToBlock(BC.Number);
677 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
678 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
680 if (!Intf.hasInterference())
683 // Number of spill code instructions to insert.
686 // Interference for the live-in value.
688 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
689 BC.Entry = SpillPlacement::MustSpill, ++Ins;
690 else if (Intf.first() < BI.FirstUse)
691 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
692 else if (Intf.first() < BI.LastUse)
696 // Interference for the live-out value.
698 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
699 BC.Exit = SpillPlacement::MustSpill, ++Ins;
700 else if (Intf.last() > BI.LastUse)
701 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
702 else if (Intf.last() > BI.FirstUse)
706 // Accumulate the total frequency of inserted spill code.
708 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
712 // Add constraints for use-blocks. Note that these are the only constraints
713 // that may add a positive bias, it is downhill from here.
714 SpillPlacer->addConstraints(SplitConstraints);
715 return SpillPlacer->scanActiveBundles();
719 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
720 /// live-through blocks in Blocks.
721 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
722 ArrayRef<unsigned> Blocks) {
723 const unsigned GroupSize = 8;
724 SpillPlacement::BlockConstraint BCS[GroupSize];
725 unsigned TBS[GroupSize];
726 unsigned B = 0, T = 0;
728 for (unsigned i = 0; i != Blocks.size(); ++i) {
729 unsigned Number = Blocks[i];
730 Intf.moveToBlock(Number);
732 if (!Intf.hasInterference()) {
733 assert(T < GroupSize && "Array overflow");
735 if (++T == GroupSize) {
736 SpillPlacer->addLinks(makeArrayRef(TBS, T));
742 assert(B < GroupSize && "Array overflow");
743 BCS[B].Number = Number;
745 // Interference for the live-in value.
746 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
747 BCS[B].Entry = SpillPlacement::MustSpill;
749 BCS[B].Entry = SpillPlacement::PrefSpill;
751 // Interference for the live-out value.
752 if (Intf.last() >= SA->getLastSplitPoint(Number))
753 BCS[B].Exit = SpillPlacement::MustSpill;
755 BCS[B].Exit = SpillPlacement::PrefSpill;
757 if (++B == GroupSize) {
758 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
759 SpillPlacer->addConstraints(Array);
764 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
765 SpillPlacer->addConstraints(Array);
766 SpillPlacer->addLinks(makeArrayRef(TBS, T));
769 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
770 // Keep track of through blocks that have not been added to SpillPlacer.
771 BitVector Todo = SA->getThroughBlocks();
772 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
773 unsigned AddedTo = 0;
775 unsigned Visited = 0;
779 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
780 // Find new through blocks in the periphery of PrefRegBundles.
781 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
782 unsigned Bundle = NewBundles[i];
783 // Look at all blocks connected to Bundle in the full graph.
784 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
785 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
788 if (!Todo.test(Block))
791 // This is a new through block. Add it to SpillPlacer later.
792 ActiveBlocks.push_back(Block);
798 // Any new blocks to add?
799 if (ActiveBlocks.size() == AddedTo)
802 // Compute through constraints from the interference, or assume that all
803 // through blocks prefer spilling when forming compact regions.
804 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
806 addThroughConstraints(Cand.Intf, NewBlocks);
808 SpillPlacer->addPrefSpill(NewBlocks);
809 AddedTo = ActiveBlocks.size();
811 // Perhaps iterating can enable more bundles?
812 SpillPlacer->iterate();
814 DEBUG(dbgs() << ", v=" << Visited);
817 /// calcCompactRegion - Compute the set of edge bundles that should be live
818 /// when splitting the current live range into compact regions. Compact
819 /// regions can be computed without looking at interference. They are the
820 /// regions formed by removing all the live-through blocks from the live range.
822 /// Returns false if the current live range is already compact, or if the
823 /// compact regions would form single block regions anyway.
824 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
825 // Without any through blocks, the live range is already compact.
826 if (!SA->getNumThroughBlocks())
829 // Compact regions don't correspond to any physreg.
830 Cand.reset(IntfCache, 0);
832 DEBUG(dbgs() << "Compact region bundles");
834 // Use the spill placer to determine the live bundles. GrowRegion pretends
835 // that all the through blocks have interference when PhysReg is unset.
836 SpillPlacer->prepare(Cand.LiveBundles);
838 // The static split cost will be zero since Cand.Intf reports no interference.
840 if (!addSplitConstraints(Cand.Intf, Cost)) {
841 DEBUG(dbgs() << ", none.\n");
846 SpillPlacer->finish();
848 if (!Cand.LiveBundles.any()) {
849 DEBUG(dbgs() << ", none.\n");
854 for (int i = Cand.LiveBundles.find_first(); i>=0;
855 i = Cand.LiveBundles.find_next(i))
856 dbgs() << " EB#" << i;
862 /// calcSpillCost - Compute how expensive it would be to split the live range in
863 /// SA around all use blocks instead of forming bundle regions.
864 float RAGreedy::calcSpillCost() {
866 const LiveInterval &LI = SA->getParent();
867 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
868 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
869 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
870 unsigned Number = BI.MBB->getNumber();
871 // We normally only need one spill instruction - a load or a store.
872 Cost += SpillPlacer->getBlockFrequency(Number);
874 // Unless the value is redefined in the block.
875 if (BI.LiveIn && BI.LiveOut) {
876 SlotIndex Start, Stop;
877 tie(Start, Stop) = Indexes->getMBBRange(Number);
878 LiveInterval::const_iterator I = LI.find(Start);
879 assert(I != LI.end() && "Expected live-in value");
880 // Is there a different live-out value? If so, we need an extra spill
883 Cost += SpillPlacer->getBlockFrequency(Number);
889 /// calcGlobalSplitCost - Return the global split cost of following the split
890 /// pattern in LiveBundles. This cost should be added to the local cost of the
891 /// interference pattern in SplitConstraints.
893 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
894 float GlobalCost = 0;
895 const BitVector &LiveBundles = Cand.LiveBundles;
896 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
897 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
898 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
899 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
900 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
901 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
905 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
907 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
909 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
912 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
913 unsigned Number = Cand.ActiveBlocks[i];
914 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
915 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
916 if (!RegIn && !RegOut)
918 if (RegIn && RegOut) {
919 // We need double spill code if this block has interference.
920 Cand.Intf.moveToBlock(Number);
921 if (Cand.Intf.hasInterference())
922 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
925 // live-in / stack-out or stack-in live-out.
926 GlobalCost += SpillPlacer->getBlockFrequency(Number);
931 /// splitAroundRegion - Split the current live range around the regions
932 /// determined by BundleCand and GlobalCand.
934 /// Before calling this function, GlobalCand and BundleCand must be initialized
935 /// so each bundle is assigned to a valid candidate, or NoCand for the
936 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
937 /// objects must be initialized for the current live range, and intervals
938 /// created for the used candidates.
940 /// @param LREdit The LiveRangeEdit object handling the current split.
941 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
942 /// must appear in this list.
943 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
944 ArrayRef<unsigned> UsedCands) {
945 // These are the intervals created for new global ranges. We may create more
946 // intervals for local ranges.
947 const unsigned NumGlobalIntvs = LREdit.size();
948 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
949 assert(NumGlobalIntvs && "No global intervals configured");
951 // First handle all the blocks with uses.
952 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
953 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
954 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
955 unsigned Number = BI.MBB->getNumber();
956 unsigned IntvIn = 0, IntvOut = 0;
957 SlotIndex IntfIn, IntfOut;
959 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
960 if (CandIn != NoCand) {
961 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
962 IntvIn = Cand.IntvIdx;
963 Cand.Intf.moveToBlock(Number);
964 IntfIn = Cand.Intf.first();
968 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
969 if (CandOut != NoCand) {
970 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
971 IntvOut = Cand.IntvIdx;
972 Cand.Intf.moveToBlock(Number);
973 IntfOut = Cand.Intf.last();
977 // Create separate intervals for isolated blocks with multiple uses.
978 if (!IntvIn && !IntvOut) {
979 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
980 if (!BI.isOneInstr())
981 SE->splitSingleBlock(BI);
985 if (IntvIn && IntvOut)
986 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
988 SE->splitRegInBlock(BI, IntvIn, IntfIn);
990 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
993 // Handle live-through blocks. The relevant live-through blocks are stored in
994 // the ActiveBlocks list with each candidate. We need to filter out
996 BitVector Todo = SA->getThroughBlocks();
997 for (unsigned c = 0; c != UsedCands.size(); ++c) {
998 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
999 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1000 unsigned Number = Blocks[i];
1001 if (!Todo.test(Number))
1005 unsigned IntvIn = 0, IntvOut = 0;
1006 SlotIndex IntfIn, IntfOut;
1008 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1009 if (CandIn != NoCand) {
1010 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1011 IntvIn = Cand.IntvIdx;
1012 Cand.Intf.moveToBlock(Number);
1013 IntfIn = Cand.Intf.first();
1016 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1017 if (CandOut != NoCand) {
1018 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1019 IntvOut = Cand.IntvIdx;
1020 Cand.Intf.moveToBlock(Number);
1021 IntfOut = Cand.Intf.last();
1023 if (!IntvIn && !IntvOut)
1025 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1031 SmallVector<unsigned, 8> IntvMap;
1032 SE->finish(&IntvMap);
1033 DebugVars->splitRegister(SA->getParent().reg, LREdit.regs());
1035 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1036 unsigned OrigBlocks = SA->getNumLiveBlocks();
1038 // Sort out the new intervals created by splitting. We get four kinds:
1039 // - Remainder intervals should not be split again.
1040 // - Candidate intervals can be assigned to Cand.PhysReg.
1041 // - Block-local splits are candidates for local splitting.
1042 // - DCE leftovers should go back on the queue.
1043 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1044 LiveInterval &Reg = *LREdit.get(i);
1046 // Ignore old intervals from DCE.
1047 if (getStage(Reg) != RS_New)
1050 // Remainder interval. Don't try splitting again, spill if it doesn't
1052 if (IntvMap[i] == 0) {
1053 setStage(Reg, RS_Spill);
1057 // Global intervals. Allow repeated splitting as long as the number of live
1058 // blocks is strictly decreasing.
1059 if (IntvMap[i] < NumGlobalIntvs) {
1060 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1061 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1062 << " blocks as original.\n");
1063 // Don't allow repeated splitting as a safe guard against looping.
1064 setStage(Reg, RS_Split2);
1069 // Other intervals are treated as new. This includes local intervals created
1070 // for blocks with multiple uses, and anything created by DCE.
1074 MF->verify(this, "After splitting live range around region");
1077 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1078 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1079 unsigned NumCands = 0;
1080 unsigned BestCand = NoCand;
1082 SmallVector<unsigned, 8> UsedCands;
1084 // Check if we can split this live range around a compact region.
1085 bool HasCompact = CompactRegions && calcCompactRegion(GlobalCand.front());
1087 // Yes, keep GlobalCand[0] as the compact region candidate.
1089 BestCost = HUGE_VALF;
1091 // No benefit from the compact region, our fallback will be per-block
1092 // splitting. Make sure we find a solution that is cheaper than spilling.
1093 BestCost = Hysteresis * calcSpillCost();
1094 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1098 while (unsigned PhysReg = Order.next()) {
1099 // Discard bad candidates before we run out of interference cache cursors.
1100 // This will only affect register classes with a lot of registers (>32).
1101 if (NumCands == IntfCache.getMaxCursors()) {
1102 unsigned WorstCount = ~0u;
1104 for (unsigned i = 0; i != NumCands; ++i) {
1105 if (i == BestCand || !GlobalCand[i].PhysReg)
1107 unsigned Count = GlobalCand[i].LiveBundles.count();
1108 if (Count < WorstCount)
1109 Worst = i, WorstCount = Count;
1112 GlobalCand[Worst] = GlobalCand[NumCands];
1115 if (GlobalCand.size() <= NumCands)
1116 GlobalCand.resize(NumCands+1);
1117 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1118 Cand.reset(IntfCache, PhysReg);
1120 SpillPlacer->prepare(Cand.LiveBundles);
1122 if (!addSplitConstraints(Cand.Intf, Cost)) {
1123 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1126 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1127 if (Cost >= BestCost) {
1129 if (BestCand == NoCand)
1130 dbgs() << " worse than no bundles\n";
1132 dbgs() << " worse than "
1133 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1139 SpillPlacer->finish();
1141 // No live bundles, defer to splitSingleBlocks().
1142 if (!Cand.LiveBundles.any()) {
1143 DEBUG(dbgs() << " no bundles.\n");
1147 Cost += calcGlobalSplitCost(Cand);
1149 dbgs() << ", total = " << Cost << " with bundles";
1150 for (int i = Cand.LiveBundles.find_first(); i>=0;
1151 i = Cand.LiveBundles.find_next(i))
1152 dbgs() << " EB#" << i;
1155 if (Cost < BestCost) {
1156 BestCand = NumCands;
1157 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1162 // No solutions found, fall back to single block splitting.
1163 if (!HasCompact && BestCand == NoCand)
1166 // Prepare split editor.
1167 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1170 // Assign all edge bundles to the preferred candidate, or NoCand.
1171 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1173 // Assign bundles for the best candidate region.
1174 if (BestCand != NoCand) {
1175 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1176 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1177 UsedCands.push_back(BestCand);
1178 Cand.IntvIdx = SE->openIntv();
1179 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1180 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1184 // Assign bundles for the compact region.
1186 GlobalSplitCandidate &Cand = GlobalCand.front();
1187 assert(!Cand.PhysReg && "Compact region has no physreg");
1188 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1189 UsedCands.push_back(0);
1190 Cand.IntvIdx = SE->openIntv();
1191 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1192 << Cand.IntvIdx << ".\n");
1196 splitAroundRegion(LREdit, UsedCands);
1201 //===----------------------------------------------------------------------===//
1203 //===----------------------------------------------------------------------===//
1206 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1207 /// in order to use PhysReg between two entries in SA->UseSlots.
1209 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1211 void RAGreedy::calcGapWeights(unsigned PhysReg,
1212 SmallVectorImpl<float> &GapWeight) {
1213 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1214 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1215 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1216 const unsigned NumGaps = Uses.size()-1;
1218 // Start and end points for the interference check.
1219 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1220 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1222 GapWeight.assign(NumGaps, 0.0f);
1224 // Add interference from each overlapping register.
1225 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1226 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1227 .checkInterference())
1230 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1231 // so we don't need InterferenceQuery.
1233 // Interference that overlaps an instruction is counted in both gaps
1234 // surrounding the instruction. The exception is interference before
1235 // StartIdx and after StopIdx.
1237 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1238 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1239 // Skip the gaps before IntI.
1240 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1241 if (++Gap == NumGaps)
1246 // Update the gaps covered by IntI.
1247 const float weight = IntI.value()->weight;
1248 for (; Gap != NumGaps; ++Gap) {
1249 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1250 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1259 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1262 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1263 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1264 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1265 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1267 // Note that it is possible to have an interval that is live-in or live-out
1268 // while only covering a single block - A phi-def can use undef values from
1269 // predecessors, and the block could be a single-block loop.
1270 // We don't bother doing anything clever about such a case, we simply assume
1271 // that the interval is continuous from FirstUse to LastUse. We should make
1272 // sure that we don't do anything illegal to such an interval, though.
1274 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1275 if (Uses.size() <= 2)
1277 const unsigned NumGaps = Uses.size()-1;
1280 dbgs() << "tryLocalSplit: ";
1281 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1282 dbgs() << ' ' << SA->UseSlots[i];
1286 // Since we allow local split results to be split again, there is a risk of
1287 // creating infinite loops. It is tempting to require that the new live
1288 // ranges have less instructions than the original. That would guarantee
1289 // convergence, but it is too strict. A live range with 3 instructions can be
1290 // split 2+3 (including the COPY), and we want to allow that.
1292 // Instead we use these rules:
1294 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1295 // noop split, of course).
1296 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1297 // the new ranges must have fewer instructions than before the split.
1298 // 3. New ranges with the same number of instructions are marked RS_Split2,
1299 // smaller ranges are marked RS_New.
1301 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1302 // excessive splitting and infinite loops.
1304 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1306 // Best split candidate.
1307 unsigned BestBefore = NumGaps;
1308 unsigned BestAfter = 0;
1311 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1312 SmallVector<float, 8> GapWeight;
1315 while (unsigned PhysReg = Order.next()) {
1316 // Keep track of the largest spill weight that would need to be evicted in
1317 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1318 calcGapWeights(PhysReg, GapWeight);
1320 // Try to find the best sequence of gaps to close.
1321 // The new spill weight must be larger than any gap interference.
1323 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1324 unsigned SplitBefore = 0, SplitAfter = 1;
1326 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1327 // It is the spill weight that needs to be evicted.
1328 float MaxGap = GapWeight[0];
1331 // Live before/after split?
1332 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1333 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1335 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1336 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1337 << " i=" << MaxGap);
1339 // Stop before the interval gets so big we wouldn't be making progress.
1340 if (!LiveBefore && !LiveAfter) {
1341 DEBUG(dbgs() << " all\n");
1344 // Should the interval be extended or shrunk?
1347 // How many gaps would the new range have?
1348 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1350 // Legally, without causing looping?
1351 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1353 if (Legal && MaxGap < HUGE_VALF) {
1354 // Estimate the new spill weight. Each instruction reads or writes the
1355 // register. Conservatively assume there are no read-modify-write
1358 // Try to guess the size of the new interval.
1359 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1360 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1361 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1362 // Would this split be possible to allocate?
1363 // Never allocate all gaps, we wouldn't be making progress.
1364 DEBUG(dbgs() << " w=" << EstWeight);
1365 if (EstWeight * Hysteresis >= MaxGap) {
1367 float Diff = EstWeight - MaxGap;
1368 if (Diff > BestDiff) {
1369 DEBUG(dbgs() << " (best)");
1370 BestDiff = Hysteresis * Diff;
1371 BestBefore = SplitBefore;
1372 BestAfter = SplitAfter;
1379 if (++SplitBefore < SplitAfter) {
1380 DEBUG(dbgs() << " shrink\n");
1381 // Recompute the max when necessary.
1382 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1383 MaxGap = GapWeight[SplitBefore];
1384 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1385 MaxGap = std::max(MaxGap, GapWeight[i]);
1392 // Try to extend the interval.
1393 if (SplitAfter >= NumGaps) {
1394 DEBUG(dbgs() << " end\n");
1398 DEBUG(dbgs() << " extend\n");
1399 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1403 // Didn't find any candidates?
1404 if (BestBefore == NumGaps)
1407 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1408 << '-' << Uses[BestAfter] << ", " << BestDiff
1409 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1411 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1415 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1416 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1417 SE->useIntv(SegStart, SegStop);
1418 SmallVector<unsigned, 8> IntvMap;
1419 SE->finish(&IntvMap);
1420 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1422 // If the new range has the same number of instructions as before, mark it as
1423 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1424 // leave the new intervals as RS_New so they can compete.
1425 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1426 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1427 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1428 if (NewGaps >= NumGaps) {
1429 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1430 assert(!ProgressRequired && "Didn't make progress when it was required.");
1431 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1432 if (IntvMap[i] == 1) {
1433 setStage(*LREdit.get(i), RS_Split2);
1434 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1436 DEBUG(dbgs() << '\n');
1443 //===----------------------------------------------------------------------===//
1444 // Live Range Splitting
1445 //===----------------------------------------------------------------------===//
1447 /// trySplit - Try to split VirtReg or one of its interferences, making it
1449 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1450 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1451 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1452 // Local intervals are handled separately.
1453 if (LIS->intervalIsInOneMBB(VirtReg)) {
1454 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1455 SA->analyze(&VirtReg);
1456 return tryLocalSplit(VirtReg, Order, NewVRegs);
1459 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1461 // Ranges must be Split2 or less.
1462 if (getStage(VirtReg) >= RS_Spill)
1465 SA->analyze(&VirtReg);
1467 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1468 // coalescer. That may cause the range to become allocatable which means that
1469 // tryRegionSplit won't be making progress. This check should be replaced with
1470 // an assertion when the coalescer is fixed.
1471 if (SA->didRepairRange()) {
1472 // VirtReg has changed, so all cached queries are invalid.
1473 invalidateVirtRegs();
1474 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1478 // First try to split around a region spanning multiple blocks. RS_Split2
1479 // ranges already made dubious progress with region splitting, so they go
1480 // straight to single block splitting.
1481 if (getStage(VirtReg) < RS_Split2) {
1482 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1483 if (PhysReg || !NewVRegs.empty())
1487 // Then isolate blocks with multiple uses.
1488 SplitAnalysis::BlockPtrSet Blocks;
1489 if (SA->getMultiUseBlocks(Blocks)) {
1490 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1492 SE->splitSingleBlocks(Blocks);
1493 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
1495 MF->verify(this, "After splitting live range around basic blocks");
1498 // Don't assign any physregs.
1503 //===----------------------------------------------------------------------===//
1505 //===----------------------------------------------------------------------===//
1507 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1508 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1509 // First try assigning a free register.
1510 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1511 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1514 LiveRangeStage Stage = getStage(VirtReg);
1515 DEBUG(dbgs() << StageName[Stage]
1516 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1518 // Try to evict a less worthy live range, but only for ranges from the primary
1519 // queue. The RS_Split ranges already failed to do this, and they should not
1520 // get a second chance until they have been split.
1521 if (Stage != RS_Split)
1522 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1525 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1527 // The first time we see a live range, don't try to split or spill.
1528 // Wait until the second time, when all smaller ranges have been allocated.
1529 // This gives a better picture of the interference to split around.
1530 if (Stage < RS_Split) {
1531 setStage(VirtReg, RS_Split);
1532 DEBUG(dbgs() << "wait for second round\n");
1533 NewVRegs.push_back(&VirtReg);
1537 // If we couldn't allocate a register from spilling, there is probably some
1538 // invalid inline assembly. The base class wil report it.
1539 if (Stage >= RS_Done || !VirtReg.isSpillable())
1542 // Try splitting VirtReg or interferences.
1543 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1544 if (PhysReg || !NewVRegs.empty())
1547 // Finally spill VirtReg itself.
1548 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1549 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1550 spiller().spill(LRE);
1551 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1554 MF->verify(this, "After spilling");
1556 // The live virtual register requesting allocation was spilled, so tell
1557 // the caller not to allocate anything during this round.
1561 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1562 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1563 << "********** Function: "
1564 << ((Value*)mf.getFunction())->getName() << '\n');
1568 MF->verify(this, "Before greedy register allocator");
1570 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1571 Indexes = &getAnalysis<SlotIndexes>();
1572 DomTree = &getAnalysis<MachineDominatorTree>();
1573 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1574 Loops = &getAnalysis<MachineLoopInfo>();
1575 Bundles = &getAnalysis<EdgeBundles>();
1576 SpillPlacer = &getAnalysis<SpillPlacement>();
1577 DebugVars = &getAnalysis<LiveDebugVariables>();
1579 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1580 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1581 ExtraRegInfo.clear();
1582 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1584 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1585 GlobalCand.resize(32); // This will grow as needed.
1589 LIS->addKillFlags();
1593 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1594 VRM->rewrite(Indexes);
1597 // Write out new DBG_VALUE instructions.
1598 DebugVars->emitDebugValues(VRM);
1600 // The pass output is in VirtRegMap. Release all the transient data.