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 "LiveIntervalUnion.h"
18 #include "LiveRangeEdit.h"
19 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
23 #include "VirtRegMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Function.h"
27 #include "llvm/PassAnalysisSupport.h"
28 #include "llvm/CodeGen/CalcSpillWeights.h"
29 #include "llvm/CodeGen/EdgeBundles.h"
30 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineLoopRanges.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/CodeGen/RegisterCoalescer.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Timer.h"
50 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51 STATISTIC(NumLocalSplits, "Number of split local live ranges");
52 STATISTIC(NumEvicted, "Number of interferences evicted");
54 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
55 createGreedyRegisterAllocator);
58 class RAGreedy : public MachineFunctionPass,
60 private LiveRangeEdit::Delegate {
64 BitVector ReservedRegs;
69 MachineDominatorTree *DomTree;
70 MachineLoopInfo *Loops;
71 MachineLoopRanges *LoopRanges;
73 SpillPlacement *SpillPlacer;
76 std::auto_ptr<Spiller> SpillerInstance;
77 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
79 // Live ranges pass through a number of stages as we try to allocate them.
80 // Some of the stages may also create new live ranges:
82 // - Region splitting.
83 // - Per-block splitting.
87 // Ranges produced by one of the stages skip the previous stages when they are
88 // dequeued. This improves performance because we can skip interference checks
89 // that are unlikely to give any results. It also guarantees that the live
90 // range splitting algorithm terminates, something that is otherwise hard to
93 RS_Original, ///< Never seen before, never split.
94 RS_Second, ///< Second time in the queue.
95 RS_Region, ///< Produced by region splitting.
96 RS_Block, ///< Produced by per-block splitting.
97 RS_Local, ///< Produced by local splitting.
98 RS_Spill ///< Produced by spilling.
101 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
103 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
104 return LiveRangeStage(LRStage[VirtReg.reg]);
107 template<typename Iterator>
108 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
109 LRStage.resize(MRI->getNumVirtRegs());
110 for (;Begin != End; ++Begin)
111 LRStage[(*Begin)->reg] = NewStage;
115 std::auto_ptr<SplitAnalysis> SA;
116 std::auto_ptr<SplitEditor> SE;
118 /// All basic blocks where the current register is live.
119 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
121 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
123 /// Global live range splitting candidate info.
124 struct GlobalSplitCandidate {
126 SmallVector<IndexPair, 8> Interference;
127 BitVector LiveBundles;
130 /// Candidate info for for each PhysReg in AllocationOrder.
131 /// This vector never shrinks, but grows to the size of the largest register
133 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
135 /// For every instruction in SA->UseSlots, store the previous non-copy
137 SmallVector<SlotIndex, 8> PrevSlot;
142 /// Return the pass name.
143 virtual const char* getPassName() const {
144 return "Greedy Register Allocator";
147 /// RAGreedy analysis usage.
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
149 virtual void releaseMemory();
150 virtual Spiller &spiller() { return *SpillerInstance; }
151 virtual void enqueue(LiveInterval *LI);
152 virtual LiveInterval *dequeue();
153 virtual unsigned selectOrSplit(LiveInterval&,
154 SmallVectorImpl<LiveInterval*>&);
156 /// Perform register allocation.
157 virtual bool runOnMachineFunction(MachineFunction &mf);
162 void LRE_WillEraseInstruction(MachineInstr*);
163 bool LRE_CanEraseVirtReg(unsigned);
164 void LRE_WillShrinkVirtReg(unsigned);
166 void mapGlobalInterference(unsigned, SmallVectorImpl<IndexPair>&);
167 float calcSplitConstraints(const SmallVectorImpl<IndexPair>&);
169 float calcGlobalSplitCost(const BitVector&);
170 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
171 SmallVectorImpl<LiveInterval*>&);
172 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
173 SlotIndex getPrevMappedIndex(const MachineInstr*);
174 void calcPrevSlots();
175 unsigned nextSplitPoint(unsigned);
176 bool canEvictInterference(LiveInterval&, unsigned, float&);
178 unsigned tryEvict(LiveInterval&, AllocationOrder&,
179 SmallVectorImpl<LiveInterval*>&);
180 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
181 SmallVectorImpl<LiveInterval*>&);
182 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
183 SmallVectorImpl<LiveInterval*>&);
184 unsigned trySplit(LiveInterval&, AllocationOrder&,
185 SmallVectorImpl<LiveInterval*>&);
187 } // end anonymous namespace
189 char RAGreedy::ID = 0;
191 FunctionPass* llvm::createGreedyRegisterAllocator() {
192 return new RAGreedy();
195 RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
196 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
197 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
198 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
199 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
200 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
201 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
202 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
203 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
204 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
205 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
206 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
207 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
208 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
211 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.setPreservesCFG();
213 AU.addRequired<AliasAnalysis>();
214 AU.addPreserved<AliasAnalysis>();
215 AU.addRequired<LiveIntervals>();
216 AU.addRequired<SlotIndexes>();
217 AU.addPreserved<SlotIndexes>();
219 AU.addRequiredID(StrongPHIEliminationID);
220 AU.addRequiredTransitive<RegisterCoalescer>();
221 AU.addRequired<CalculateSpillWeights>();
222 AU.addRequired<LiveStacks>();
223 AU.addPreserved<LiveStacks>();
224 AU.addRequired<MachineDominatorTree>();
225 AU.addPreserved<MachineDominatorTree>();
226 AU.addRequired<MachineLoopInfo>();
227 AU.addPreserved<MachineLoopInfo>();
228 AU.addRequired<MachineLoopRanges>();
229 AU.addPreserved<MachineLoopRanges>();
230 AU.addRequired<VirtRegMap>();
231 AU.addPreserved<VirtRegMap>();
232 AU.addRequired<EdgeBundles>();
233 AU.addRequired<SpillPlacement>();
234 MachineFunctionPass::getAnalysisUsage(AU);
238 //===----------------------------------------------------------------------===//
239 // LiveRangeEdit delegate methods
240 //===----------------------------------------------------------------------===//
242 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
243 // LRE itself will remove from SlotIndexes and parent basic block.
244 VRM->RemoveMachineInstrFromMaps(MI);
247 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
248 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
249 unassign(LIS->getInterval(VirtReg), PhysReg);
252 // Unassigned virtreg is probably in the priority queue.
253 // RegAllocBase will erase it after dequeueing.
257 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
258 unsigned PhysReg = VRM->getPhys(VirtReg);
262 // Register is assigned, put it back on the queue for reassignment.
263 LiveInterval &LI = LIS->getInterval(VirtReg);
264 unassign(LI, PhysReg);
268 void RAGreedy::releaseMemory() {
269 SpillerInstance.reset(0);
271 RegAllocBase::releaseMemory();
274 void RAGreedy::enqueue(LiveInterval *LI) {
275 // Prioritize live ranges by size, assigning larger ranges first.
276 // The queue holds (size, reg) pairs.
277 const unsigned Size = LI->getSize();
278 const unsigned Reg = LI->reg;
279 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
280 "Can only enqueue virtual registers");
284 if (LRStage[Reg] == RS_Second)
285 // Unsplit ranges that couldn't be allocated immediately are deferred until
286 // everything else has been allocated. Long ranges are allocated last so
287 // they are split against realistic interference.
288 Prio = (1u << 31) - Size;
290 // Everything else is allocated in long->short order. Long ranges that don't
291 // fit should be spilled ASAP so they don't create interference.
292 Prio = (1u << 31) + Size;
294 // Boost ranges that have a physical register hint.
295 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
299 Queue.push(std::make_pair(Prio, Reg));
302 LiveInterval *RAGreedy::dequeue() {
305 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
310 //===----------------------------------------------------------------------===//
311 // Interference eviction
312 //===----------------------------------------------------------------------===//
314 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
315 /// be evicted. Set maxWeight to the maximal spill weight of an interference.
316 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
319 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
320 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
321 // If there is 10 or more interferences, chances are one is smaller.
322 if (Q.collectInterferingVRegs(10) >= 10)
325 // Check if any interfering live range is heavier than VirtReg.
326 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
327 LiveInterval *Intf = Q.interferingVRegs()[i];
328 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
330 if (Intf->weight >= VirtReg.weight)
332 Weight = std::max(Weight, Intf->weight);
339 /// tryEvict - Try to evict all interferences for a physreg.
340 /// @param VirtReg Currently unassigned virtual register.
341 /// @param Order Physregs to try.
342 /// @return Physreg to assign VirtReg, or 0.
343 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
344 AllocationOrder &Order,
345 SmallVectorImpl<LiveInterval*> &NewVRegs){
346 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
348 // Keep track of the lightest single interference seen so far.
349 float BestWeight = 0;
350 unsigned BestPhys = 0;
353 while (unsigned PhysReg = Order.next()) {
355 if (!canEvictInterference(VirtReg, PhysReg, Weight))
358 // This is an eviction candidate.
359 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
361 if (BestPhys && Weight >= BestWeight)
367 // Stop if the hint can be used.
368 if (Order.isHint(PhysReg))
375 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
376 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
377 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
378 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
379 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
380 LiveInterval *Intf = Q.interferingVRegs()[i];
381 unassign(*Intf, VRM->getPhys(Intf->reg));
383 NewVRegs.push_back(Intf);
390 //===----------------------------------------------------------------------===//
392 //===----------------------------------------------------------------------===//
394 /// mapGlobalInterference - Compute a map of the interference from PhysReg and
395 /// its aliases in each block in SA->LiveBlocks.
396 /// If LiveBlocks[i] is live-in, Ranges[i].first is the first interference.
397 /// If LiveBlocks[i] is live-out, Ranges[i].second is the last interference.
398 void RAGreedy::mapGlobalInterference(unsigned PhysReg,
399 SmallVectorImpl<IndexPair> &Ranges) {
400 Ranges.assign(SA->LiveBlocks.size(), IndexPair());
401 LiveInterval &VirtReg = const_cast<LiveInterval&>(SA->getParent());
402 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
403 if (!query(VirtReg, *AI).checkInterference())
405 LiveIntervalUnion::SegmentIter IntI =
406 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
409 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
410 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
411 IndexPair &IP = Ranges[i];
413 // Skip interference-free blocks.
414 if (IntI.start() >= BI.Stop)
417 // First interference in block.
419 IntI.advanceTo(BI.Start);
422 if (IntI.start() >= BI.Stop)
424 if (!IP.first.isValid() || IntI.start() < IP.first)
425 IP.first = IntI.start();
428 // Last interference in block.
430 IntI.advanceTo(BI.Stop);
431 if (!IntI.valid() || IntI.start() >= BI.Stop)
433 if (IntI.stop() <= BI.Start)
435 if (!IP.second.isValid() || IntI.stop() > IP.second)
436 IP.second = IntI.stop();
442 /// calcSplitConstraints - Fill out the SplitConstraints vector based on the
443 /// interference pattern in Intf. Return the static cost of this split,
444 /// assuming that all preferences in SplitConstraints are met.
445 float RAGreedy::calcSplitConstraints(const SmallVectorImpl<IndexPair> &Intf) {
446 // Reset interference dependent info.
447 SplitConstraints.resize(SA->LiveBlocks.size());
448 float StaticCost = 0;
449 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
450 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
451 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
452 IndexPair IP = Intf[i];
454 BC.Number = BI.MBB->getNumber();
455 BC.Entry = (BI.Uses && BI.LiveIn) ?
456 SpillPlacement::PrefReg : SpillPlacement::DontCare;
457 BC.Exit = (BI.Uses && BI.LiveOut) ?
458 SpillPlacement::PrefReg : SpillPlacement::DontCare;
460 // Number of spill code instructions to insert.
463 // Interference for the live-in value.
464 if (IP.first.isValid()) {
465 if (IP.first <= BI.Start)
466 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
468 BC.Entry = SpillPlacement::PrefSpill;
469 else if (IP.first < BI.FirstUse)
470 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
471 else if (IP.first < (BI.LiveThrough ? BI.LastUse : BI.Kill))
475 // Interference for the live-out value.
476 if (IP.second.isValid()) {
477 if (IP.second >= BI.LastSplitPoint)
478 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
480 BC.Exit = SpillPlacement::PrefSpill;
481 else if (IP.second > BI.LastUse)
482 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
483 else if (IP.second > (BI.LiveThrough ? BI.FirstUse : BI.Def))
487 // Accumulate the total frequency of inserted spill code.
489 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
495 /// calcGlobalSplitCost - Return the global split cost of following the split
496 /// pattern in LiveBundles. This cost should be added to the local cost of the
497 /// interference pattern in SplitConstraints.
499 float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
500 float GlobalCost = 0;
501 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
502 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
503 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
504 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
505 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
509 Ins += RegIn != RegOut;
512 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
514 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
517 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
522 /// splitAroundRegion - Split VirtReg around the region determined by
523 /// LiveBundles. Make an effort to avoid interference from PhysReg.
525 /// The 'register' interval is going to contain as many uses as possible while
526 /// avoiding interference. The 'stack' interval is the complement constructed by
527 /// SplitEditor. It will contain the rest.
529 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
530 const BitVector &LiveBundles,
531 SmallVectorImpl<LiveInterval*> &NewVRegs) {
533 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
535 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
536 dbgs() << " EB#" << i;
540 // First compute interference ranges in the live blocks.
541 SmallVector<IndexPair, 8> InterferenceRanges;
542 mapGlobalInterference(PhysReg, InterferenceRanges);
544 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
547 // Create the main cross-block interval.
550 // First add all defs that are live out of a block.
551 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
552 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
553 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
554 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
556 // Should the register be live out?
557 if (!BI.LiveOut || !RegOut)
560 IndexPair &IP = InterferenceRanges[i];
561 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
562 << Bundles->getBundle(BI.MBB->getNumber(), 1)
563 << " [" << BI.Start << ';' << BI.LastSplitPoint << '-'
564 << BI.Stop << ") intf [" << IP.first << ';' << IP.second
567 // The interference interval should either be invalid or overlap MBB.
568 assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
569 assert((!IP.second.isValid() || IP.second > BI.Start)
570 && "Bad interference");
572 // Check interference leaving the block.
573 if (!IP.second.isValid()) {
574 // Block is interference-free.
575 DEBUG(dbgs() << ", no interference");
577 assert(BI.LiveThrough && "No uses, but not live through block?");
578 // Block is live-through without interference.
579 DEBUG(dbgs() << ", no uses"
580 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
582 SE->enterIntvAtEnd(*BI.MBB);
585 if (!BI.LiveThrough) {
586 DEBUG(dbgs() << ", not live-through.\n");
587 SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
591 // Block is live-through, but entry bundle is on the stack.
592 // Reload just before the first use.
593 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
594 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
597 DEBUG(dbgs() << ", live-through.\n");
601 // Block has interference.
602 DEBUG(dbgs() << ", interference to " << IP.second);
604 if (!BI.LiveThrough && IP.second <= BI.Def) {
605 // The interference doesn't reach the outgoing segment.
606 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
607 SE->useIntv(BI.Def, BI.Stop);
613 // No uses in block, avoid interference by reloading as late as possible.
614 DEBUG(dbgs() << ", no uses.\n");
615 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
616 assert(SegStart >= IP.second && "Couldn't avoid interference");
620 if (IP.second.getBoundaryIndex() < BI.LastUse) {
621 // There are interference-free uses at the end of the block.
622 // Find the first use that can get the live-out register.
623 SmallVectorImpl<SlotIndex>::const_iterator UI =
624 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
625 IP.second.getBoundaryIndex());
626 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
628 assert(Use <= BI.LastUse && "Couldn't find last use");
629 // Only attempt a split befroe the last split point.
630 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
631 DEBUG(dbgs() << ", free use at " << Use << ".\n");
632 SlotIndex SegStart = SE->enterIntvBefore(Use);
633 assert(SegStart >= IP.second && "Couldn't avoid interference");
634 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
635 SE->useIntv(SegStart, BI.Stop);
640 // Interference is after the last use.
641 DEBUG(dbgs() << " after last use.\n");
642 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
643 assert(SegStart >= IP.second && "Couldn't avoid interference");
646 // Now all defs leading to live bundles are handled, do everything else.
647 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
648 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
649 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
650 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
652 // Is the register live-in?
653 if (!BI.LiveIn || !RegIn)
656 // We have an incoming register. Check for interference.
657 IndexPair &IP = InterferenceRanges[i];
659 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
660 << " -> BB#" << BI.MBB->getNumber() << " [" << BI.Start << ';'
661 << BI.LastSplitPoint << '-' << BI.Stop << ')');
663 // Check interference entering the block.
664 if (!IP.first.isValid()) {
665 // Block is interference-free.
666 DEBUG(dbgs() << ", no interference");
668 assert(BI.LiveThrough && "No uses, but not live through block?");
669 // Block is live-through without interference.
671 DEBUG(dbgs() << ", no uses, live-through.\n");
672 SE->useIntv(BI.Start, BI.Stop);
674 DEBUG(dbgs() << ", no uses, stack-out.\n");
675 SE->leaveIntvAtTop(*BI.MBB);
679 if (!BI.LiveThrough) {
680 DEBUG(dbgs() << ", killed in block.\n");
681 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
685 // Block is live-through, but exit bundle is on the stack.
686 // Spill immediately after the last use.
687 if (BI.LastUse < BI.LastSplitPoint) {
688 DEBUG(dbgs() << ", uses, stack-out.\n");
689 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
692 // The last use is after the last split point, it is probably an
694 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
695 << BI.LastSplitPoint << ", stack-out.\n");
696 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
697 SE->useIntv(BI.Start, SegEnd);
698 // Run a double interval from the split to the last use.
699 // This makes it possible to spill the complement without affecting the
701 SE->overlapIntv(SegEnd, BI.LastUse);
704 // Register is live-through.
705 DEBUG(dbgs() << ", uses, live-through.\n");
706 SE->useIntv(BI.Start, BI.Stop);
710 // Block has interference.
711 DEBUG(dbgs() << ", interference from " << IP.first);
713 if (!BI.LiveThrough && IP.first >= BI.Kill) {
714 // The interference doesn't reach the outgoing segment.
715 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
716 SE->useIntv(BI.Start, BI.Kill);
721 // No uses in block, avoid interference by spilling as soon as possible.
722 DEBUG(dbgs() << ", no uses.\n");
723 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
724 assert(SegEnd <= IP.first && "Couldn't avoid interference");
727 if (IP.first.getBaseIndex() > BI.FirstUse) {
728 // There are interference-free uses at the beginning of the block.
729 // Find the last use that can get the register.
730 SmallVectorImpl<SlotIndex>::const_iterator UI =
731 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
732 IP.first.getBaseIndex());
733 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
734 SlotIndex Use = (--UI)->getBoundaryIndex();
735 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
736 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
737 assert(SegEnd <= IP.first && "Couldn't avoid interference");
738 SE->useIntv(BI.Start, SegEnd);
742 // Interference is before the first use.
743 DEBUG(dbgs() << " before first use.\n");
744 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
745 assert(SegEnd <= IP.first && "Couldn't avoid interference");
750 // FIXME: Should we be more aggressive about splitting the stack region into
751 // per-block segments? The current approach allows the stack region to
752 // separate into connected components. Some components may be allocatable.
757 MF->verify(this, "After splitting live range around region");
760 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
761 SmallVectorImpl<LiveInterval*> &NewVRegs) {
762 BitVector LiveBundles, BestBundles;
764 unsigned BestReg = 0;
767 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
768 if (GlobalCand.size() <= Cand)
769 GlobalCand.resize(Cand+1);
770 GlobalCand[Cand].PhysReg = PhysReg;
772 mapGlobalInterference(PhysReg, GlobalCand[Cand].Interference);
773 float Cost = calcSplitConstraints(GlobalCand[Cand].Interference);
774 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
775 if (BestReg && Cost >= BestCost) {
776 DEBUG(dbgs() << " higher.\n");
780 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
781 // No live bundles, defer to splitSingleBlocks().
782 if (!LiveBundles.any()) {
783 DEBUG(dbgs() << " no bundles.\n");
787 Cost += calcGlobalSplitCost(LiveBundles);
789 dbgs() << ", total = " << Cost << " with bundles";
790 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
791 dbgs() << " EB#" << i;
794 if (!BestReg || Cost < BestCost) {
796 BestCost = 0.98f * Cost; // Prevent rounding effects.
797 BestBundles.swap(LiveBundles);
804 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
805 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
810 //===----------------------------------------------------------------------===//
812 //===----------------------------------------------------------------------===//
815 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
816 /// in order to use PhysReg between two entries in SA->UseSlots.
818 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
820 void RAGreedy::calcGapWeights(unsigned PhysReg,
821 SmallVectorImpl<float> &GapWeight) {
822 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
823 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
824 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
825 const unsigned NumGaps = Uses.size()-1;
827 // Start and end points for the interference check.
828 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
829 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
831 GapWeight.assign(NumGaps, 0.0f);
833 // Add interference from each overlapping register.
834 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
835 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
836 .checkInterference())
839 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
840 // so we don't need InterferenceQuery.
842 // Interference that overlaps an instruction is counted in both gaps
843 // surrounding the instruction. The exception is interference before
844 // StartIdx and after StopIdx.
846 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
847 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
848 // Skip the gaps before IntI.
849 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
850 if (++Gap == NumGaps)
855 // Update the gaps covered by IntI.
856 const float weight = IntI.value()->weight;
857 for (; Gap != NumGaps; ++Gap) {
858 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
859 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
868 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
869 /// before MI that has a slot index. If MI is the first mapped instruction in
870 /// its block, return the block start index instead.
872 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
873 assert(MI && "Missing MachineInstr");
874 const MachineBasicBlock *MBB = MI->getParent();
875 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
877 if (!(--I)->isDebugValue() && !I->isCopy())
878 return Indexes->getInstructionIndex(I);
879 return Indexes->getMBBStartIdx(MBB);
882 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
883 /// real non-copy instruction for each instruction in SA->UseSlots.
885 void RAGreedy::calcPrevSlots() {
886 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
888 PrevSlot.reserve(Uses.size());
889 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
890 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
891 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
895 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
896 /// be beneficial to split before UseSlots[i].
898 /// 0 is always a valid split point
899 unsigned RAGreedy::nextSplitPoint(unsigned i) {
900 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
901 const unsigned Size = Uses.size();
902 assert(i != Size && "No split points after the end");
903 // Allow split before i when Uses[i] is not adjacent to the previous use.
904 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
909 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
912 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
913 SmallVectorImpl<LiveInterval*> &NewVRegs) {
914 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
915 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
917 // Note that it is possible to have an interval that is live-in or live-out
918 // while only covering a single block - A phi-def can use undef values from
919 // predecessors, and the block could be a single-block loop.
920 // We don't bother doing anything clever about such a case, we simply assume
921 // that the interval is continuous from FirstUse to LastUse. We should make
922 // sure that we don't do anything illegal to such an interval, though.
924 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
925 if (Uses.size() <= 2)
927 const unsigned NumGaps = Uses.size()-1;
930 dbgs() << "tryLocalSplit: ";
931 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
932 dbgs() << ' ' << SA->UseSlots[i];
936 // For every use, find the previous mapped non-copy instruction.
937 // We use this to detect valid split points, and to estimate new interval
941 unsigned BestBefore = NumGaps;
942 unsigned BestAfter = 0;
945 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
946 SmallVector<float, 8> GapWeight;
949 while (unsigned PhysReg = Order.next()) {
950 // Keep track of the largest spill weight that would need to be evicted in
951 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
952 calcGapWeights(PhysReg, GapWeight);
954 // Try to find the best sequence of gaps to close.
955 // The new spill weight must be larger than any gap interference.
957 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
958 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
960 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
961 // It is the spill weight that needs to be evicted.
962 float MaxGap = GapWeight[0];
963 for (unsigned i = 1; i != SplitAfter; ++i)
964 MaxGap = std::max(MaxGap, GapWeight[i]);
967 // Live before/after split?
968 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
969 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
971 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
972 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
975 // Stop before the interval gets so big we wouldn't be making progress.
976 if (!LiveBefore && !LiveAfter) {
977 DEBUG(dbgs() << " all\n");
980 // Should the interval be extended or shrunk?
982 if (MaxGap < HUGE_VALF) {
983 // Estimate the new spill weight.
985 // Each instruction reads and writes the register, except the first
986 // instr doesn't read when !FirstLive, and the last instr doesn't write
989 // We will be inserting copies before and after, so the total number of
990 // reads and writes is 2 * EstUses.
992 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
993 2*(LiveBefore + LiveAfter);
995 // Try to guess the size of the new interval. This should be trivial,
996 // but the slot index of an inserted copy can be a lot smaller than the
997 // instruction it is inserted before if there are many dead indexes
1000 // We measure the distance from the instruction before SplitBefore to
1001 // get a conservative estimate.
1003 // The final distance can still be different if inserting copies
1004 // triggers a slot index renumbering.
1006 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1007 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1008 // Would this split be possible to allocate?
1009 // Never allocate all gaps, we wouldn't be making progress.
1010 float Diff = EstWeight - MaxGap;
1011 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1014 if (Diff > BestDiff) {
1015 DEBUG(dbgs() << " (best)");
1017 BestBefore = SplitBefore;
1018 BestAfter = SplitAfter;
1025 SplitBefore = nextSplitPoint(SplitBefore);
1026 if (SplitBefore < SplitAfter) {
1027 DEBUG(dbgs() << " shrink\n");
1028 // Recompute the max when necessary.
1029 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1030 MaxGap = GapWeight[SplitBefore];
1031 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1032 MaxGap = std::max(MaxGap, GapWeight[i]);
1039 // Try to extend the interval.
1040 if (SplitAfter >= NumGaps) {
1041 DEBUG(dbgs() << " end\n");
1045 DEBUG(dbgs() << " extend\n");
1046 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1047 SplitAfter != e; ++SplitAfter)
1048 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1053 // Didn't find any candidates?
1054 if (BestBefore == NumGaps)
1057 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1058 << '-' << Uses[BestAfter] << ", " << BestDiff
1059 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1061 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1065 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1066 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1067 SE->useIntv(SegStart, SegStop);
1070 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
1076 //===----------------------------------------------------------------------===//
1077 // Live Range Splitting
1078 //===----------------------------------------------------------------------===//
1080 /// trySplit - Try to split VirtReg or one of its interferences, making it
1082 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1083 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1084 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1085 // Local intervals are handled separately.
1086 if (LIS->intervalIsInOneMBB(VirtReg)) {
1087 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1088 SA->analyze(&VirtReg);
1089 return tryLocalSplit(VirtReg, Order, NewVRegs);
1092 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1094 // Don't iterate global splitting.
1095 // Move straight to spilling if this range was produced by a global split.
1096 LiveRangeStage Stage = getStage(VirtReg);
1097 if (Stage >= RS_Block)
1100 SA->analyze(&VirtReg);
1102 // First try to split around a region spanning multiple blocks.
1103 if (Stage < RS_Region) {
1104 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1105 if (PhysReg || !NewVRegs.empty())
1109 // Then isolate blocks with multiple uses.
1110 if (Stage < RS_Block) {
1111 SplitAnalysis::BlockPtrSet Blocks;
1112 if (SA->getMultiUseBlocks(Blocks)) {
1113 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1115 SE->splitSingleBlocks(Blocks);
1116 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1118 MF->verify(this, "After splitting live range around basic blocks");
1122 // Don't assign any physregs.
1127 //===----------------------------------------------------------------------===//
1129 //===----------------------------------------------------------------------===//
1131 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1132 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1133 // First try assigning a free register.
1134 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1135 while (unsigned PhysReg = Order.next()) {
1136 if (!checkPhysRegInterference(VirtReg, PhysReg))
1140 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1143 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1145 // The first time we see a live range, don't try to split or spill.
1146 // Wait until the second time, when all smaller ranges have been allocated.
1147 // This gives a better picture of the interference to split around.
1148 LiveRangeStage Stage = getStage(VirtReg);
1149 if (Stage == RS_Original) {
1150 LRStage[VirtReg.reg] = RS_Second;
1151 DEBUG(dbgs() << "wait for second round\n");
1152 NewVRegs.push_back(&VirtReg);
1156 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1158 // Try splitting VirtReg or interferences.
1159 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1160 if (PhysReg || !NewVRegs.empty())
1163 // Finally spill VirtReg itself.
1164 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1165 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1166 spiller().spill(LRE);
1169 MF->verify(this, "After spilling");
1171 // The live virtual register requesting allocation was spilled, so tell
1172 // the caller not to allocate anything during this round.
1176 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1177 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1178 << "********** Function: "
1179 << ((Value*)mf.getFunction())->getName() << '\n');
1183 MF->verify(this, "Before greedy register allocator");
1185 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1186 Indexes = &getAnalysis<SlotIndexes>();
1187 DomTree = &getAnalysis<MachineDominatorTree>();
1188 ReservedRegs = TRI->getReservedRegs(*MF);
1189 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1190 Loops = &getAnalysis<MachineLoopInfo>();
1191 LoopRanges = &getAnalysis<MachineLoopRanges>();
1192 Bundles = &getAnalysis<EdgeBundles>();
1193 SpillPlacer = &getAnalysis<SpillPlacement>();
1195 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1196 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1198 LRStage.resize(MRI->getNumVirtRegs());
1202 LIS->addKillFlags();
1206 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1207 VRM->rewrite(Indexes);
1210 // The pass output is in VirtRegMap. Release all the transient data.