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 "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Function.h"
28 #include "llvm/PassAnalysisSupport.h"
29 #include "llvm/CodeGen/CalcSpillWeights.h"
30 #include "llvm/CodeGen/EdgeBundles.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineLoopRanges.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/CodeGen/RegisterCoalescer.h"
41 #include "llvm/Target/TargetOptions.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 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
59 class RAGreedy : public MachineFunctionPass,
61 private LiveRangeEdit::Delegate {
65 BitVector ReservedRegs;
70 MachineDominatorTree *DomTree;
71 MachineLoopInfo *Loops;
72 MachineLoopRanges *LoopRanges;
74 SpillPlacement *SpillPlacer;
77 std::auto_ptr<Spiller> SpillerInstance;
78 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
80 // Live ranges pass through a number of stages as we try to allocate them.
81 // Some of the stages may also create new live ranges:
83 // - Region splitting.
84 // - Per-block splitting.
88 // Ranges produced by one of the stages skip the previous stages when they are
89 // dequeued. This improves performance because we can skip interference checks
90 // that are unlikely to give any results. It also guarantees that the live
91 // range splitting algorithm terminates, something that is otherwise hard to
94 RS_New, ///< Never seen before.
95 RS_First, ///< First time in the queue.
96 RS_Second, ///< Second time in the queue.
97 RS_Region, ///< Produced by region splitting.
98 RS_Block, ///< Produced by per-block splitting.
99 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
103 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
105 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
106 return LiveRangeStage(LRStage[VirtReg.reg]);
109 template<typename Iterator>
110 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
111 LRStage.resize(MRI->getNumVirtRegs());
112 for (;Begin != End; ++Begin) {
113 unsigned Reg = (*Begin)->reg;
114 if (LRStage[Reg] == RS_New)
115 LRStage[Reg] = NewStage;
120 std::auto_ptr<SplitAnalysis> SA;
121 std::auto_ptr<SplitEditor> SE;
123 /// Cached per-block interference maps
124 InterferenceCache IntfCache;
126 /// All basic blocks where the current register is live.
127 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
129 /// Global live range splitting candidate info.
130 struct GlobalSplitCandidate {
132 BitVector LiveBundles;
135 /// Candidate info for for each PhysReg in AllocationOrder.
136 /// This vector never shrinks, but grows to the size of the largest register
138 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
140 /// For every instruction in SA->UseSlots, store the previous non-copy
142 SmallVector<SlotIndex, 8> PrevSlot;
147 /// Return the pass name.
148 virtual const char* getPassName() const {
149 return "Greedy Register Allocator";
152 /// RAGreedy analysis usage.
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
154 virtual void releaseMemory();
155 virtual Spiller &spiller() { return *SpillerInstance; }
156 virtual void enqueue(LiveInterval *LI);
157 virtual LiveInterval *dequeue();
158 virtual unsigned selectOrSplit(LiveInterval&,
159 SmallVectorImpl<LiveInterval*>&);
161 /// Perform register allocation.
162 virtual bool runOnMachineFunction(MachineFunction &mf);
167 void LRE_WillEraseInstruction(MachineInstr*);
168 bool LRE_CanEraseVirtReg(unsigned);
169 void LRE_WillShrinkVirtReg(unsigned);
170 void LRE_DidCloneVirtReg(unsigned, unsigned);
172 bool addSplitConstraints(unsigned, float&);
173 float calcGlobalSplitCost(unsigned, const BitVector&);
174 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
175 SmallVectorImpl<LiveInterval*>&);
176 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
177 SlotIndex getPrevMappedIndex(const MachineInstr*);
178 void calcPrevSlots();
179 unsigned nextSplitPoint(unsigned);
180 bool canEvictInterference(LiveInterval&, unsigned, float&);
182 unsigned tryEvict(LiveInterval&, AllocationOrder&,
183 SmallVectorImpl<LiveInterval*>&);
184 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
185 SmallVectorImpl<LiveInterval*>&);
186 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
187 SmallVectorImpl<LiveInterval*>&);
188 unsigned trySplit(LiveInterval&, AllocationOrder&,
189 SmallVectorImpl<LiveInterval*>&);
191 } // end anonymous namespace
193 char RAGreedy::ID = 0;
195 FunctionPass* llvm::createGreedyRegisterAllocator() {
196 return new RAGreedy();
199 RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
200 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
201 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
202 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
203 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
204 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
205 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
206 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
207 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
208 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
209 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
210 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
211 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
212 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
213 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
216 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
217 AU.setPreservesCFG();
218 AU.addRequired<AliasAnalysis>();
219 AU.addPreserved<AliasAnalysis>();
220 AU.addRequired<LiveIntervals>();
221 AU.addRequired<SlotIndexes>();
222 AU.addPreserved<SlotIndexes>();
223 AU.addRequired<LiveDebugVariables>();
224 AU.addPreserved<LiveDebugVariables>();
226 AU.addRequiredID(StrongPHIEliminationID);
227 AU.addRequiredTransitive<RegisterCoalescer>();
228 AU.addRequired<CalculateSpillWeights>();
229 AU.addRequired<LiveStacks>();
230 AU.addPreserved<LiveStacks>();
231 AU.addRequired<MachineDominatorTree>();
232 AU.addPreserved<MachineDominatorTree>();
233 AU.addRequired<MachineLoopInfo>();
234 AU.addPreserved<MachineLoopInfo>();
235 AU.addRequired<MachineLoopRanges>();
236 AU.addPreserved<MachineLoopRanges>();
237 AU.addRequired<VirtRegMap>();
238 AU.addPreserved<VirtRegMap>();
239 AU.addRequired<EdgeBundles>();
240 AU.addRequired<SpillPlacement>();
241 MachineFunctionPass::getAnalysisUsage(AU);
245 //===----------------------------------------------------------------------===//
246 // LiveRangeEdit delegate methods
247 //===----------------------------------------------------------------------===//
249 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
250 // LRE itself will remove from SlotIndexes and parent basic block.
251 VRM->RemoveMachineInstrFromMaps(MI);
254 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
255 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
256 unassign(LIS->getInterval(VirtReg), PhysReg);
259 // Unassigned virtreg is probably in the priority queue.
260 // RegAllocBase will erase it after dequeueing.
264 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
265 unsigned PhysReg = VRM->getPhys(VirtReg);
269 // Register is assigned, put it back on the queue for reassignment.
270 LiveInterval &LI = LIS->getInterval(VirtReg);
271 unassign(LI, PhysReg);
275 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
276 // LRE may clone a virtual register because dead code elimination causes it to
277 // be split into connected components. Ensure that the new register gets the
278 // same stage as the parent.
280 LRStage[New] = LRStage[Old];
283 void RAGreedy::releaseMemory() {
284 SpillerInstance.reset(0);
286 RegAllocBase::releaseMemory();
289 void RAGreedy::enqueue(LiveInterval *LI) {
290 // Prioritize live ranges by size, assigning larger ranges first.
291 // The queue holds (size, reg) pairs.
292 const unsigned Size = LI->getSize();
293 const unsigned Reg = LI->reg;
294 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
295 "Can only enqueue virtual registers");
299 if (LRStage[Reg] == RS_New)
300 LRStage[Reg] = RS_First;
302 if (LRStage[Reg] == RS_Second)
303 // Unsplit ranges that couldn't be allocated immediately are deferred until
304 // everything else has been allocated. Long ranges are allocated last so
305 // they are split against realistic interference.
306 Prio = (1u << 31) - Size;
308 // Everything else is allocated in long->short order. Long ranges that don't
309 // fit should be spilled ASAP so they don't create interference.
310 Prio = (1u << 31) + Size;
312 // Boost ranges that have a physical register hint.
313 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
317 Queue.push(std::make_pair(Prio, Reg));
320 LiveInterval *RAGreedy::dequeue() {
323 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
328 //===----------------------------------------------------------------------===//
329 // Interference eviction
330 //===----------------------------------------------------------------------===//
332 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
333 /// be evicted. Set maxWeight to the maximal spill weight of an interference.
334 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
337 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
338 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
339 // If there is 10 or more interferences, chances are one is smaller.
340 if (Q.collectInterferingVRegs(10) >= 10)
343 // Check if any interfering live range is heavier than VirtReg.
344 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
345 LiveInterval *Intf = Q.interferingVRegs()[i];
346 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
348 if (Intf->weight >= VirtReg.weight)
350 Weight = std::max(Weight, Intf->weight);
357 /// tryEvict - Try to evict all interferences for a physreg.
358 /// @param VirtReg Currently unassigned virtual register.
359 /// @param Order Physregs to try.
360 /// @return Physreg to assign VirtReg, or 0.
361 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
362 AllocationOrder &Order,
363 SmallVectorImpl<LiveInterval*> &NewVRegs){
364 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
366 // Keep track of the lightest single interference seen so far.
367 float BestWeight = 0;
368 unsigned BestPhys = 0;
371 while (unsigned PhysReg = Order.next()) {
373 if (!canEvictInterference(VirtReg, PhysReg, Weight))
376 // This is an eviction candidate.
377 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
379 if (BestPhys && Weight >= BestWeight)
385 // Stop if the hint can be used.
386 if (Order.isHint(PhysReg))
393 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
394 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
395 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
396 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
397 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
398 LiveInterval *Intf = Q.interferingVRegs()[i];
399 unassign(*Intf, VRM->getPhys(Intf->reg));
401 NewVRegs.push_back(Intf);
408 //===----------------------------------------------------------------------===//
410 //===----------------------------------------------------------------------===//
412 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
413 /// interference pattern in Physreg and its aliases. Add the constraints to
414 /// SpillPlacement and return the static cost of this split in Cost, assuming
415 /// that all preferences in SplitConstraints are met.
416 /// If it is evident that no bundles will be live, abort early and return false.
417 bool RAGreedy::addSplitConstraints(unsigned PhysReg, float &Cost) {
418 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
419 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
421 // Reset interference dependent info.
422 SplitConstraints.resize(UseBlocks.size());
423 float StaticCost = 0;
424 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
425 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
426 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
428 BC.Number = BI.MBB->getNumber();
429 Intf.moveToBlock(BC.Number);
430 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
431 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
433 if (!Intf.hasInterference())
436 // Number of spill code instructions to insert.
439 // Interference for the live-in value.
441 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
442 BC.Entry = SpillPlacement::MustSpill, ++Ins;
443 else if (Intf.first() < BI.FirstUse)
444 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
445 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
449 // Interference for the live-out value.
451 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
452 BC.Exit = SpillPlacement::MustSpill, ++Ins;
453 else if (Intf.last() > BI.LastUse)
454 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
455 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
459 // Accumulate the total frequency of inserted spill code.
461 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
464 // Add constraints for use-blocks. Note that these are the only constraints
465 // that may add a positive bias, it is downhill from here.
466 SpillPlacer->addConstraints(SplitConstraints);
467 if (SpillPlacer->getPositiveNodes() == 0)
472 // Now handle the live-through blocks without uses. These can only add
473 // negative bias, so we can abort whenever there are no more positive nodes.
474 // Compute constraints for a group of 8 blocks at a time.
475 const unsigned GroupSize = 8;
476 SpillPlacement::BlockConstraint BCS[GroupSize];
479 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
480 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
481 unsigned Number = ThroughBlocks[i];
482 assert(B < GroupSize && "Array overflow");
483 BCS[B].Number = Number;
484 Intf.moveToBlock(Number);
486 if (Intf.hasInterference()) {
487 // Interference for the live-in value.
488 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
489 BCS[B].Entry = SpillPlacement::MustSpill;
491 BCS[B].Entry = SpillPlacement::PrefSpill;
493 // Interference for the live-out value.
494 if (Intf.last() >= SA->getLastSplitPoint(Number))
495 BCS[B].Exit = SpillPlacement::MustSpill;
497 BCS[B].Exit = SpillPlacement::PrefSpill;
499 // No interference, transparent block.
500 BCS[B].Entry = BCS[B].Exit = SpillPlacement::DontCare;
503 if (++B == GroupSize) {
504 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
505 SpillPlacer->addConstraints(Array);
507 // Abort early when all hope is lost.
508 if (SpillPlacer->getPositiveNodes() == 0)
513 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
514 SpillPlacer->addConstraints(Array);
515 return SpillPlacer->getPositiveNodes() != 0;
519 /// calcGlobalSplitCost - Return the global split cost of following the split
520 /// pattern in LiveBundles. This cost should be added to the local cost of the
521 /// interference pattern in SplitConstraints.
523 float RAGreedy::calcGlobalSplitCost(unsigned PhysReg,
524 const BitVector &LiveBundles) {
525 float GlobalCost = 0;
526 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
527 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
528 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
529 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
530 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
531 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
535 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
537 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
539 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
542 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
543 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
544 SplitConstraints.resize(UseBlocks.size() + ThroughBlocks.size());
545 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
546 unsigned Number = ThroughBlocks[i];
547 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
548 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
549 if (!RegIn && !RegOut)
551 if (RegIn && RegOut) {
552 // We need double spill code if this block has interference.
553 Intf.moveToBlock(Number);
554 if (Intf.hasInterference())
555 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
558 // live-in / stack-out or stack-in live-out.
559 GlobalCost += SpillPlacer->getBlockFrequency(Number);
564 /// splitAroundRegion - Split VirtReg around the region determined by
565 /// LiveBundles. Make an effort to avoid interference from PhysReg.
567 /// The 'register' interval is going to contain as many uses as possible while
568 /// avoiding interference. The 'stack' interval is the complement constructed by
569 /// SplitEditor. It will contain the rest.
571 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
572 const BitVector &LiveBundles,
573 SmallVectorImpl<LiveInterval*> &NewVRegs) {
575 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
577 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
578 dbgs() << " EB#" << i;
582 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
583 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
586 // Create the main cross-block interval.
589 // First add all defs that are live out of a block.
590 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
591 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
592 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
593 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
594 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
596 // Should the register be live out?
597 if (!BI.LiveOut || !RegOut)
600 SlotIndex Start, Stop;
601 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
602 Intf.moveToBlock(BI.MBB->getNumber());
603 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
604 << Bundles->getBundle(BI.MBB->getNumber(), 1)
605 << " [" << Start << ';'
606 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
607 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
609 // The interference interval should either be invalid or overlap MBB.
610 assert((!Intf.hasInterference() || Intf.first() < Stop)
611 && "Bad interference");
612 assert((!Intf.hasInterference() || Intf.last() > Start)
613 && "Bad interference");
615 // Check interference leaving the block.
616 if (!Intf.hasInterference()) {
617 // Block is interference-free.
618 DEBUG(dbgs() << ", no interference");
619 if (!BI.LiveThrough) {
620 DEBUG(dbgs() << ", not live-through.\n");
621 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
625 // Block is live-through, but entry bundle is on the stack.
626 // Reload just before the first use.
627 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
628 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
631 DEBUG(dbgs() << ", live-through.\n");
635 // Block has interference.
636 DEBUG(dbgs() << ", interference to " << Intf.last());
638 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
639 // The interference doesn't reach the outgoing segment.
640 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
641 SE->useIntv(BI.Def, Stop);
645 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
646 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
647 // There are interference-free uses at the end of the block.
648 // Find the first use that can get the live-out register.
649 SmallVectorImpl<SlotIndex>::const_iterator UI =
650 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
651 Intf.last().getBoundaryIndex());
652 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
654 assert(Use <= BI.LastUse && "Couldn't find last use");
655 // Only attempt a split befroe the last split point.
656 if (Use.getBaseIndex() <= LastSplitPoint) {
657 DEBUG(dbgs() << ", free use at " << Use << ".\n");
658 SlotIndex SegStart = SE->enterIntvBefore(Use);
659 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
660 assert(SegStart < LastSplitPoint && "Impossible split point");
661 SE->useIntv(SegStart, Stop);
666 // Interference is after the last use.
667 DEBUG(dbgs() << " after last use.\n");
668 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
669 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
672 // Now all defs leading to live bundles are handled, do everything else.
673 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
674 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
675 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
676 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
678 // Is the register live-in?
679 if (!BI.LiveIn || !RegIn)
682 // We have an incoming register. Check for interference.
683 SlotIndex Start, Stop;
684 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
685 Intf.moveToBlock(BI.MBB->getNumber());
686 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
687 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
688 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
691 // Check interference entering the block.
692 if (!Intf.hasInterference()) {
693 // Block is interference-free.
694 DEBUG(dbgs() << ", no interference");
695 if (!BI.LiveThrough) {
696 DEBUG(dbgs() << ", killed in block.\n");
697 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
701 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
702 // Block is live-through, but exit bundle is on the stack.
703 // Spill immediately after the last use.
704 if (BI.LastUse < LastSplitPoint) {
705 DEBUG(dbgs() << ", uses, stack-out.\n");
706 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
709 // The last use is after the last split point, it is probably an
711 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
712 << LastSplitPoint << ", stack-out.\n");
713 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
714 SE->useIntv(Start, SegEnd);
715 // Run a double interval from the split to the last use.
716 // This makes it possible to spill the complement without affecting the
718 SE->overlapIntv(SegEnd, BI.LastUse);
721 // Register is live-through.
722 DEBUG(dbgs() << ", uses, live-through.\n");
723 SE->useIntv(Start, Stop);
727 // Block has interference.
728 DEBUG(dbgs() << ", interference from " << Intf.first());
730 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
731 // The interference doesn't reach the outgoing segment.
732 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
733 SE->useIntv(Start, BI.Kill);
737 if (Intf.first().getBaseIndex() > BI.FirstUse) {
738 // There are interference-free uses at the beginning of the block.
739 // Find the last use that can get the register.
740 SmallVectorImpl<SlotIndex>::const_iterator UI =
741 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
742 Intf.first().getBaseIndex());
743 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
744 SlotIndex Use = (--UI)->getBoundaryIndex();
745 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
746 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
747 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
748 SE->useIntv(Start, SegEnd);
752 // Interference is before the first use.
753 DEBUG(dbgs() << " before first use.\n");
754 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
755 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
758 // Handle live-through blocks.
759 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
760 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
761 unsigned Number = ThroughBlocks[i];
762 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
763 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
764 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
765 if (RegIn && RegOut) {
766 Intf.moveToBlock(Number);
767 if (!Intf.hasInterference()) {
768 SE->useIntv(Indexes->getMBBStartIdx(Number),
769 Indexes->getMBBEndIdx(Number));
773 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
775 SE->leaveIntvAtTop(*MBB);
777 SE->enterIntvAtEnd(*MBB);
782 // FIXME: Should we be more aggressive about splitting the stack region into
783 // per-block segments? The current approach allows the stack region to
784 // separate into connected components. Some components may be allocatable.
789 MF->verify(this, "After splitting live range around region");
792 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
793 SmallVectorImpl<LiveInterval*> &NewVRegs) {
794 BitVector LiveBundles, BestBundles;
796 unsigned BestReg = 0;
799 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
800 if (GlobalCand.size() <= Cand)
801 GlobalCand.resize(Cand+1);
802 GlobalCand[Cand].PhysReg = PhysReg;
804 SpillPlacer->prepare(LiveBundles);
806 if (!addSplitConstraints(PhysReg, Cost)) {
807 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bias\n");
810 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tbiased = "
811 << SpillPlacer->getPositiveNodes() << ", static = " << Cost);
812 if (BestReg && Cost >= BestCost) {
813 DEBUG(dbgs() << " worse than " << PrintReg(BestReg, TRI) << '\n');
817 SpillPlacer->finish();
819 // No live bundles, defer to splitSingleBlocks().
820 if (!LiveBundles.any()) {
821 DEBUG(dbgs() << " no bundles.\n");
825 Cost += calcGlobalSplitCost(PhysReg, LiveBundles);
827 dbgs() << ", total = " << Cost << " with bundles";
828 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
829 dbgs() << " EB#" << i;
832 if (!BestReg || Cost < BestCost) {
834 BestCost = 0.98f * Cost; // Prevent rounding effects.
835 BestBundles.swap(LiveBundles);
842 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
843 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
848 //===----------------------------------------------------------------------===//
850 //===----------------------------------------------------------------------===//
853 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
854 /// in order to use PhysReg between two entries in SA->UseSlots.
856 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
858 void RAGreedy::calcGapWeights(unsigned PhysReg,
859 SmallVectorImpl<float> &GapWeight) {
860 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
861 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
862 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
863 const unsigned NumGaps = Uses.size()-1;
865 // Start and end points for the interference check.
866 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
867 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
869 GapWeight.assign(NumGaps, 0.0f);
871 // Add interference from each overlapping register.
872 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
873 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
874 .checkInterference())
877 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
878 // so we don't need InterferenceQuery.
880 // Interference that overlaps an instruction is counted in both gaps
881 // surrounding the instruction. The exception is interference before
882 // StartIdx and after StopIdx.
884 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
885 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
886 // Skip the gaps before IntI.
887 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
888 if (++Gap == NumGaps)
893 // Update the gaps covered by IntI.
894 const float weight = IntI.value()->weight;
895 for (; Gap != NumGaps; ++Gap) {
896 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
897 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
906 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
907 /// before MI that has a slot index. If MI is the first mapped instruction in
908 /// its block, return the block start index instead.
910 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
911 assert(MI && "Missing MachineInstr");
912 const MachineBasicBlock *MBB = MI->getParent();
913 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
915 if (!(--I)->isDebugValue() && !I->isCopy())
916 return Indexes->getInstructionIndex(I);
917 return Indexes->getMBBStartIdx(MBB);
920 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
921 /// real non-copy instruction for each instruction in SA->UseSlots.
923 void RAGreedy::calcPrevSlots() {
924 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
926 PrevSlot.reserve(Uses.size());
927 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
928 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
929 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
933 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
934 /// be beneficial to split before UseSlots[i].
936 /// 0 is always a valid split point
937 unsigned RAGreedy::nextSplitPoint(unsigned i) {
938 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
939 const unsigned Size = Uses.size();
940 assert(i != Size && "No split points after the end");
941 // Allow split before i when Uses[i] is not adjacent to the previous use.
942 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
947 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
950 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
951 SmallVectorImpl<LiveInterval*> &NewVRegs) {
952 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
953 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
955 // Note that it is possible to have an interval that is live-in or live-out
956 // while only covering a single block - A phi-def can use undef values from
957 // predecessors, and the block could be a single-block loop.
958 // We don't bother doing anything clever about such a case, we simply assume
959 // that the interval is continuous from FirstUse to LastUse. We should make
960 // sure that we don't do anything illegal to such an interval, though.
962 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
963 if (Uses.size() <= 2)
965 const unsigned NumGaps = Uses.size()-1;
968 dbgs() << "tryLocalSplit: ";
969 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
970 dbgs() << ' ' << SA->UseSlots[i];
974 // For every use, find the previous mapped non-copy instruction.
975 // We use this to detect valid split points, and to estimate new interval
979 unsigned BestBefore = NumGaps;
980 unsigned BestAfter = 0;
983 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
984 SmallVector<float, 8> GapWeight;
987 while (unsigned PhysReg = Order.next()) {
988 // Keep track of the largest spill weight that would need to be evicted in
989 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
990 calcGapWeights(PhysReg, GapWeight);
992 // Try to find the best sequence of gaps to close.
993 // The new spill weight must be larger than any gap interference.
995 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
996 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
998 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
999 // It is the spill weight that needs to be evicted.
1000 float MaxGap = GapWeight[0];
1001 for (unsigned i = 1; i != SplitAfter; ++i)
1002 MaxGap = std::max(MaxGap, GapWeight[i]);
1005 // Live before/after split?
1006 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1007 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1009 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1010 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1011 << " i=" << MaxGap);
1013 // Stop before the interval gets so big we wouldn't be making progress.
1014 if (!LiveBefore && !LiveAfter) {
1015 DEBUG(dbgs() << " all\n");
1018 // Should the interval be extended or shrunk?
1020 if (MaxGap < HUGE_VALF) {
1021 // Estimate the new spill weight.
1023 // Each instruction reads and writes the register, except the first
1024 // instr doesn't read when !FirstLive, and the last instr doesn't write
1027 // We will be inserting copies before and after, so the total number of
1028 // reads and writes is 2 * EstUses.
1030 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1031 2*(LiveBefore + LiveAfter);
1033 // Try to guess the size of the new interval. This should be trivial,
1034 // but the slot index of an inserted copy can be a lot smaller than the
1035 // instruction it is inserted before if there are many dead indexes
1038 // We measure the distance from the instruction before SplitBefore to
1039 // get a conservative estimate.
1041 // The final distance can still be different if inserting copies
1042 // triggers a slot index renumbering.
1044 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1045 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1046 // Would this split be possible to allocate?
1047 // Never allocate all gaps, we wouldn't be making progress.
1048 float Diff = EstWeight - MaxGap;
1049 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1052 if (Diff > BestDiff) {
1053 DEBUG(dbgs() << " (best)");
1055 BestBefore = SplitBefore;
1056 BestAfter = SplitAfter;
1063 SplitBefore = nextSplitPoint(SplitBefore);
1064 if (SplitBefore < SplitAfter) {
1065 DEBUG(dbgs() << " shrink\n");
1066 // Recompute the max when necessary.
1067 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1068 MaxGap = GapWeight[SplitBefore];
1069 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1070 MaxGap = std::max(MaxGap, GapWeight[i]);
1077 // Try to extend the interval.
1078 if (SplitAfter >= NumGaps) {
1079 DEBUG(dbgs() << " end\n");
1083 DEBUG(dbgs() << " extend\n");
1084 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1085 SplitAfter != e; ++SplitAfter)
1086 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1091 // Didn't find any candidates?
1092 if (BestBefore == NumGaps)
1095 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1096 << '-' << Uses[BestAfter] << ", " << BestDiff
1097 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1099 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1103 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1104 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1105 SE->useIntv(SegStart, SegStop);
1108 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
1114 //===----------------------------------------------------------------------===//
1115 // Live Range Splitting
1116 //===----------------------------------------------------------------------===//
1118 /// trySplit - Try to split VirtReg or one of its interferences, making it
1120 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1121 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1122 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1123 // Local intervals are handled separately.
1124 if (LIS->intervalIsInOneMBB(VirtReg)) {
1125 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1126 SA->analyze(&VirtReg);
1127 return tryLocalSplit(VirtReg, Order, NewVRegs);
1130 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1132 // Don't iterate global splitting.
1133 // Move straight to spilling if this range was produced by a global split.
1134 LiveRangeStage Stage = getStage(VirtReg);
1135 if (Stage >= RS_Block)
1138 SA->analyze(&VirtReg);
1140 // First try to split around a region spanning multiple blocks.
1141 if (Stage < RS_Region) {
1142 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1143 if (PhysReg || !NewVRegs.empty())
1147 // Then isolate blocks with multiple uses.
1148 if (Stage < RS_Block) {
1149 SplitAnalysis::BlockPtrSet Blocks;
1150 if (SA->getMultiUseBlocks(Blocks)) {
1151 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1153 SE->splitSingleBlocks(Blocks);
1154 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1156 MF->verify(this, "After splitting live range around basic blocks");
1160 // Don't assign any physregs.
1165 //===----------------------------------------------------------------------===//
1167 //===----------------------------------------------------------------------===//
1169 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1170 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1171 // First try assigning a free register.
1172 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1173 while (unsigned PhysReg = Order.next()) {
1174 if (!checkPhysRegInterference(VirtReg, PhysReg))
1178 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1181 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1183 // The first time we see a live range, don't try to split or spill.
1184 // Wait until the second time, when all smaller ranges have been allocated.
1185 // This gives a better picture of the interference to split around.
1186 LiveRangeStage Stage = getStage(VirtReg);
1187 if (Stage == RS_First) {
1188 LRStage[VirtReg.reg] = RS_Second;
1189 DEBUG(dbgs() << "wait for second round\n");
1190 NewVRegs.push_back(&VirtReg);
1194 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1196 // Try splitting VirtReg or interferences.
1197 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1198 if (PhysReg || !NewVRegs.empty())
1201 // Finally spill VirtReg itself.
1202 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1203 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1204 spiller().spill(LRE);
1205 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
1208 MF->verify(this, "After spilling");
1210 // The live virtual register requesting allocation was spilled, so tell
1211 // the caller not to allocate anything during this round.
1215 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1216 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1217 << "********** Function: "
1218 << ((Value*)mf.getFunction())->getName() << '\n');
1222 MF->verify(this, "Before greedy register allocator");
1224 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1225 Indexes = &getAnalysis<SlotIndexes>();
1226 DomTree = &getAnalysis<MachineDominatorTree>();
1227 ReservedRegs = TRI->getReservedRegs(*MF);
1228 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1229 Loops = &getAnalysis<MachineLoopInfo>();
1230 LoopRanges = &getAnalysis<MachineLoopRanges>();
1231 Bundles = &getAnalysis<EdgeBundles>();
1232 SpillPlacer = &getAnalysis<SpillPlacement>();
1234 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1235 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1237 LRStage.resize(MRI->getNumVirtRegs());
1238 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1242 LIS->addKillFlags();
1246 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1247 VRM->rewrite(Indexes);
1250 // Write out new DBG_VALUE instructions.
1251 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1253 // The pass output is in VirtRegMap. Release all the transient data.