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(NumReassigned, "Number of interferences reassigned");
53 STATISTIC(NumEvicted, "Number of interferences evicted");
55 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
59 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
62 BitVector ReservedRegs;
67 MachineDominatorTree *DomTree;
68 MachineLoopInfo *Loops;
69 MachineLoopRanges *LoopRanges;
71 SpillPlacement *SpillPlacer;
74 std::auto_ptr<Spiller> SpillerInstance;
75 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
77 // Live ranges pass through a number of stages as we try to allocate them.
78 // Some of the stages may also create new live ranges:
80 // - Region splitting.
81 // - Per-block splitting.
85 // Ranges produced by one of the stages skip the previous stages when they are
86 // dequeued. This improves performance because we can skip interference checks
87 // that are unlikely to give any results. It also guarantees that the live
88 // range splitting algorithm terminates, something that is otherwise hard to
91 RS_Original, ///< Never seen before, never split.
92 RS_Second, ///< Second time in the queue.
93 RS_Region, ///< Produced by region splitting.
94 RS_Block, ///< Produced by per-block splitting.
95 RS_Local, ///< Produced by local splitting.
96 RS_Spill ///< Produced by spilling.
99 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
101 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
102 return LiveRangeStage(LRStage[VirtReg.reg]);
105 template<typename Iterator>
106 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
107 LRStage.resize(MRI->getNumVirtRegs());
108 for (;Begin != End; ++Begin)
109 LRStage[(*Begin)->reg] = NewStage;
113 std::auto_ptr<SplitAnalysis> SA;
114 std::auto_ptr<SplitEditor> SE;
116 /// All basic blocks where the current register is live.
117 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
119 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
121 /// Global live range splitting candidate info.
122 struct GlobalSplitCandidate {
124 SmallVector<IndexPair, 8> Interference;
125 BitVector LiveBundles;
128 /// Candidate info for for each PhysReg in AllocationOrder.
129 /// This vector never shrinks, but grows to the size of the largest register
131 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
133 /// For every instruction in SA->UseSlots, store the previous non-copy
135 SmallVector<SlotIndex, 8> PrevSlot;
140 /// Return the pass name.
141 virtual const char* getPassName() const {
142 return "Greedy Register Allocator";
145 /// RAGreedy analysis usage.
146 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
147 virtual void releaseMemory();
148 virtual Spiller &spiller() { return *SpillerInstance; }
149 virtual void enqueue(LiveInterval *LI);
150 virtual LiveInterval *dequeue();
151 virtual unsigned selectOrSplit(LiveInterval&,
152 SmallVectorImpl<LiveInterval*>&);
154 /// Perform register allocation.
155 virtual bool runOnMachineFunction(MachineFunction &mf);
160 bool checkUncachedInterference(LiveInterval&, unsigned);
161 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
162 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
164 void mapGlobalInterference(unsigned, SmallVectorImpl<IndexPair>&);
165 float calcSplitConstraints(const SmallVectorImpl<IndexPair>&);
167 float calcGlobalSplitCost(const BitVector&);
168 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
169 SmallVectorImpl<LiveInterval*>&);
170 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
171 SlotIndex getPrevMappedIndex(const MachineInstr*);
172 void calcPrevSlots();
173 unsigned nextSplitPoint(unsigned);
174 bool canEvictInterference(LiveInterval&, unsigned, float&);
176 unsigned tryReassign(LiveInterval&, AllocationOrder&,
177 SmallVectorImpl<LiveInterval*>&);
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);
237 void RAGreedy::releaseMemory() {
238 SpillerInstance.reset(0);
240 RegAllocBase::releaseMemory();
243 void RAGreedy::enqueue(LiveInterval *LI) {
244 // Prioritize live ranges by size, assigning larger ranges first.
245 // The queue holds (size, reg) pairs.
246 const unsigned Size = LI->getSize();
247 const unsigned Reg = LI->reg;
248 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
249 "Can only enqueue virtual registers");
253 if (LRStage[Reg] == RS_Original)
254 // 1st generation ranges are handled first, long -> short.
255 Prio = (1u << 31) + Size;
257 // Repeat offenders are handled second, short -> long
258 Prio = (1u << 30) - Size;
260 // Boost ranges that have a physical register hint.
261 const unsigned Hint = VRM->getRegAllocPref(Reg);
262 if (TargetRegisterInfo::isPhysicalRegister(Hint))
265 Queue.push(std::make_pair(Prio, Reg));
268 LiveInterval *RAGreedy::dequeue() {
271 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
276 //===----------------------------------------------------------------------===//
277 // Register Reassignment
278 //===----------------------------------------------------------------------===//
280 // Check interference without using the cache.
281 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
283 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
284 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
285 if (subQ.checkInterference())
291 /// getSingleInterference - Return the single interfering virtual register
292 /// assigned to PhysReg. Return 0 if more than one virtual register is
294 LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
296 // Check physreg and aliases.
297 LiveInterval *Interference = 0;
298 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
299 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
300 if (Q.checkInterference()) {
303 if (Q.collectInterferingVRegs(2) > 1)
305 Interference = Q.interferingVRegs().front();
311 // Attempt to reassign this virtual register to a different physical register.
313 // FIXME: we are not yet caching these "second-level" interferences discovered
314 // in the sub-queries. These interferences can change with each call to
315 // selectOrSplit. However, we could implement a "may-interfere" cache that
316 // could be conservatively dirtied when we reassign or split.
318 // FIXME: This may result in a lot of alias queries. We could summarize alias
319 // live intervals in their parent register's live union, but it's messy.
320 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
321 unsigned WantedPhysReg) {
322 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
323 "Can only reassign virtual registers");
324 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
325 "inconsistent phys reg assigment");
327 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
328 while (unsigned PhysReg = Order.next()) {
329 // Don't reassign to a WantedPhysReg alias.
330 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
333 if (checkUncachedInterference(InterferingVReg, PhysReg))
336 // Reassign the interfering virtual reg to this physical reg.
337 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
338 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
339 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
340 unassign(InterferingVReg, OldAssign);
341 assign(InterferingVReg, PhysReg);
348 /// tryReassign - Try to reassign a single interference to a different physreg.
349 /// @param VirtReg Currently unassigned virtual register.
350 /// @param Order Physregs to try.
351 /// @return Physreg to assign VirtReg, or 0.
352 unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order,
353 SmallVectorImpl<LiveInterval*> &NewVRegs){
354 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
357 while (unsigned PhysReg = Order.next()) {
358 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
359 if (!InterferingVReg)
361 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
363 if (reassignVReg(*InterferingVReg, PhysReg))
370 //===----------------------------------------------------------------------===//
371 // Interference eviction
372 //===----------------------------------------------------------------------===//
374 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
375 /// be evicted. Set maxWeight to the maximal spill weight of an interference.
376 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
379 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
380 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
381 // If there is 10 or more interferences, chances are one is smaller.
382 if (Q.collectInterferingVRegs(10) >= 10)
385 // Check if any interfering live range is heavier than VirtReg.
386 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
387 LiveInterval *Intf = Q.interferingVRegs()[i];
388 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
390 if (Intf->weight >= VirtReg.weight)
392 Weight = std::max(Weight, Intf->weight);
399 /// tryEvict - Try to evict all interferences for a physreg.
400 /// @param VirtReg Currently unassigned virtual register.
401 /// @param Order Physregs to try.
402 /// @return Physreg to assign VirtReg, or 0.
403 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
404 AllocationOrder &Order,
405 SmallVectorImpl<LiveInterval*> &NewVRegs){
406 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
408 // Keep track of the lightest single interference seen so far.
409 float BestWeight = 0;
410 unsigned BestPhys = 0;
413 while (unsigned PhysReg = Order.next()) {
415 if (!canEvictInterference(VirtReg, PhysReg, Weight))
418 // This is an eviction candidate.
419 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
421 if (BestPhys && Weight >= BestWeight)
427 // Stop if the hint can be used.
428 if (Order.isHint(PhysReg))
435 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
436 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
437 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
438 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
439 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
440 LiveInterval *Intf = Q.interferingVRegs()[i];
441 unassign(*Intf, VRM->getPhys(Intf->reg));
443 NewVRegs.push_back(Intf);
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// mapGlobalInterference - Compute a map of the interference from PhysReg and
455 /// its aliases in each block in SA->LiveBlocks.
456 /// If LiveBlocks[i] is live-in, Ranges[i].first is the first interference.
457 /// If LiveBlocks[i] is live-out, Ranges[i].second is the last interference.
458 void RAGreedy::mapGlobalInterference(unsigned PhysReg,
459 SmallVectorImpl<IndexPair> &Ranges) {
460 Ranges.assign(SA->LiveBlocks.size(), IndexPair());
461 LiveInterval &VirtReg = const_cast<LiveInterval&>(SA->getParent());
462 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
463 if (!query(VirtReg, *AI).checkInterference())
465 LiveIntervalUnion::SegmentIter IntI =
466 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
469 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
470 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
471 IndexPair &IP = Ranges[i];
473 // Skip interference-free blocks.
474 if (IntI.start() >= BI.Stop)
477 // First interference in block.
479 IntI.advanceTo(BI.Start);
482 if (IntI.start() >= BI.Stop)
484 if (!IP.first.isValid() || IntI.start() < IP.first)
485 IP.first = IntI.start();
488 // Last interference in block.
490 IntI.advanceTo(BI.Stop);
491 if (!IntI.valid() || IntI.start() >= BI.Stop)
493 if (IntI.stop() <= BI.Start)
495 if (!IP.second.isValid() || IntI.stop() > IP.second)
496 IP.second = IntI.stop();
502 /// calcSplitConstraints - Fill out the SplitConstraints vector based on the
503 /// interference pattern in Intf. Return the static cost of this split,
504 /// assuming that all preferences in SplitConstraints are met.
505 float RAGreedy::calcSplitConstraints(const SmallVectorImpl<IndexPair> &Intf) {
506 // Reset interference dependent info.
507 SplitConstraints.resize(SA->LiveBlocks.size());
508 float StaticCost = 0;
509 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
510 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
511 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
512 IndexPair IP = Intf[i];
514 BC.Number = BI.MBB->getNumber();
515 BC.Entry = (BI.Uses && BI.LiveIn) ?
516 SpillPlacement::PrefReg : SpillPlacement::DontCare;
517 BC.Exit = (BI.Uses && BI.LiveOut) ?
518 SpillPlacement::PrefReg : SpillPlacement::DontCare;
520 // Number of spill code instructions to insert.
523 // Interference for the live-in value.
524 if (IP.first.isValid()) {
525 if (IP.first <= BI.Start)
526 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
528 BC.Entry = SpillPlacement::PrefSpill;
529 else if (IP.first < BI.FirstUse)
530 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
531 else if (IP.first < (BI.LiveThrough ? BI.LastUse : BI.Kill))
535 // Interference for the live-out value.
536 if (IP.second.isValid()) {
537 if (IP.second >= BI.LastSplitPoint)
538 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
540 BC.Exit = SpillPlacement::PrefSpill;
541 else if (IP.second > BI.LastUse)
542 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
543 else if (IP.second > (BI.LiveThrough ? BI.FirstUse : BI.Def))
547 // Accumulate the total frequency of inserted spill code.
549 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
555 /// calcGlobalSplitCost - Return the global split cost of following the split
556 /// pattern in LiveBundles. This cost should be added to the local cost of the
557 /// interference pattern in SplitConstraints.
559 float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
560 float GlobalCost = 0;
561 for (unsigned i = 0, e = SplitConstraints.size(); i != e; ++i) {
562 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
563 unsigned Inserts = 0;
564 // Broken entry preference?
565 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
566 (BC.Entry == SpillPlacement::PrefReg);
567 // Broken exit preference?
568 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
569 (BC.Exit == SpillPlacement::PrefReg);
571 GlobalCost += Inserts * SpillPlacer->getBlockFrequency(BC.Number);
574 dbgs() << "Global cost = " << GlobalCost << " with bundles";
575 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
576 dbgs() << " EB#" << i;
582 /// splitAroundRegion - Split VirtReg around the region determined by
583 /// LiveBundles. Make an effort to avoid interference from PhysReg.
585 /// The 'register' interval is going to contain as many uses as possible while
586 /// avoiding interference. The 'stack' interval is the complement constructed by
587 /// SplitEditor. It will contain the rest.
589 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
590 const BitVector &LiveBundles,
591 SmallVectorImpl<LiveInterval*> &NewVRegs) {
593 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
595 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
596 dbgs() << " EB#" << i;
600 // First compute interference ranges in the live blocks.
601 SmallVector<IndexPair, 8> InterferenceRanges;
602 mapGlobalInterference(PhysReg, InterferenceRanges);
604 SmallVector<LiveInterval*, 4> SpillRegs;
605 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
608 // Create the main cross-block interval.
611 // First add all defs that are live out of a block.
612 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
613 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
614 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
615 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
617 // Should the register be live out?
618 if (!BI.LiveOut || !RegOut)
621 IndexPair &IP = InterferenceRanges[i];
622 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
623 << Bundles->getBundle(BI.MBB->getNumber(), 1)
624 << " intf [" << IP.first << ';' << IP.second << ')');
626 // The interference interval should either be invalid or overlap MBB.
627 assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
628 assert((!IP.second.isValid() || IP.second > BI.Start)
629 && "Bad interference");
631 // Check interference leaving the block.
632 if (!IP.second.isValid()) {
633 // Block is interference-free.
634 DEBUG(dbgs() << ", no interference");
636 assert(BI.LiveThrough && "No uses, but not live through block?");
637 // Block is live-through without interference.
638 DEBUG(dbgs() << ", no uses"
639 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
641 SE->enterIntvAtEnd(*BI.MBB);
644 if (!BI.LiveThrough) {
645 DEBUG(dbgs() << ", not live-through.\n");
646 SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
650 // Block is live-through, but entry bundle is on the stack.
651 // Reload just before the first use.
652 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
653 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
656 DEBUG(dbgs() << ", live-through.\n");
660 // Block has interference.
661 DEBUG(dbgs() << ", interference to " << IP.second);
663 if (!BI.LiveThrough && IP.second <= BI.Def) {
664 // The interference doesn't reach the outgoing segment.
665 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
666 SE->useIntv(BI.Def, BI.Stop);
672 // No uses in block, avoid interference by reloading as late as possible.
673 DEBUG(dbgs() << ", no uses.\n");
674 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
675 assert(SegStart >= IP.second && "Couldn't avoid interference");
679 if (IP.second.getBoundaryIndex() < BI.LastUse) {
680 // There are interference-free uses at the end of the block.
681 // Find the first use that can get the live-out register.
682 SmallVectorImpl<SlotIndex>::const_iterator UI =
683 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
684 IP.second.getBoundaryIndex());
685 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
687 assert(Use <= BI.LastUse && "Couldn't find last use");
688 // Only attempt a split befroe the last split point.
689 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
690 DEBUG(dbgs() << ", free use at " << Use << ".\n");
691 SlotIndex SegStart = SE->enterIntvBefore(Use);
692 assert(SegStart >= IP.second && "Couldn't avoid interference");
693 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
694 SE->useIntv(SegStart, BI.Stop);
699 // Interference is after the last use.
700 DEBUG(dbgs() << " after last use.\n");
701 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
702 assert(SegStart >= IP.second && "Couldn't avoid interference");
705 // Now all defs leading to live bundles are handled, do everything else.
706 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
707 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
708 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
709 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
711 // Is the register live-in?
712 if (!BI.LiveIn || !RegIn)
715 // We have an incoming register. Check for interference.
716 IndexPair &IP = InterferenceRanges[i];
718 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
719 << " -> BB#" << BI.MBB->getNumber());
721 // Check interference entering the block.
722 if (!IP.first.isValid()) {
723 // Block is interference-free.
724 DEBUG(dbgs() << ", no interference");
726 assert(BI.LiveThrough && "No uses, but not live through block?");
727 // Block is live-through without interference.
729 DEBUG(dbgs() << ", no uses, live-through.\n");
730 SE->useIntv(BI.Start, BI.Stop);
732 DEBUG(dbgs() << ", no uses, stack-out.\n");
733 SE->leaveIntvAtTop(*BI.MBB);
737 if (!BI.LiveThrough) {
738 DEBUG(dbgs() << ", killed in block.\n");
739 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
743 // Block is live-through, but exit bundle is on the stack.
744 // Spill immediately after the last use.
745 if (BI.LastUse < BI.LastSplitPoint) {
746 DEBUG(dbgs() << ", uses, stack-out.\n");
747 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
750 // The last use is after the last split point, it is probably an
752 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
753 << BI.LastSplitPoint << ", stack-out.\n");
754 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
755 SE->useIntv(BI.Start, SegEnd);
756 // Run a double interval from the split to the last use.
757 // This makes it possible to spill the complement without affecting the
759 SE->overlapIntv(SegEnd, BI.LastUse);
762 // Register is live-through.
763 DEBUG(dbgs() << ", uses, live-through.\n");
764 SE->useIntv(BI.Start, BI.Stop);
768 // Block has interference.
769 DEBUG(dbgs() << ", interference from " << IP.first);
771 if (!BI.LiveThrough && IP.first >= BI.Kill) {
772 // The interference doesn't reach the outgoing segment.
773 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
774 SE->useIntv(BI.Start, BI.Kill);
779 // No uses in block, avoid interference by spilling as soon as possible.
780 DEBUG(dbgs() << ", no uses.\n");
781 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
782 assert(SegEnd <= IP.first && "Couldn't avoid interference");
785 if (IP.first.getBaseIndex() > BI.FirstUse) {
786 // There are interference-free uses at the beginning of the block.
787 // Find the last use that can get the register.
788 SmallVectorImpl<SlotIndex>::const_iterator UI =
789 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
790 IP.first.getBaseIndex());
791 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
792 SlotIndex Use = (--UI)->getBoundaryIndex();
793 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
794 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
795 assert(SegEnd <= IP.first && "Couldn't avoid interference");
796 SE->useIntv(BI.Start, SegEnd);
800 // Interference is before the first use.
801 DEBUG(dbgs() << " before first use.\n");
802 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
803 assert(SegEnd <= IP.first && "Couldn't avoid interference");
808 // FIXME: Should we be more aggressive about splitting the stack region into
809 // per-block segments? The current approach allows the stack region to
810 // separate into connected components. Some components may be allocatable.
815 MF->verify(this, "After splitting live range around region");
818 // Make sure that at least one of the new intervals can allocate to PhysReg.
819 // That was the whole point of splitting the live range.
821 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
823 if (!checkUncachedInterference(**I, PhysReg)) {
827 assert(found && "No allocatable intervals after pointless splitting");
832 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
833 SmallVectorImpl<LiveInterval*> &NewVRegs) {
834 BitVector LiveBundles, BestBundles;
836 unsigned BestReg = 0;
839 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
840 if (GlobalCand.size() <= Cand)
841 GlobalCand.resize(Cand+1);
842 GlobalCand[Cand].PhysReg = PhysReg;
844 mapGlobalInterference(PhysReg, GlobalCand[Cand].Interference);
845 float Cost = calcSplitConstraints(GlobalCand[Cand].Interference);
846 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " static split cost = " << Cost
848 if (BestReg && Cost >= BestCost)
851 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
852 // No live bundles, defer to splitSingleBlocks().
853 if (!LiveBundles.any())
856 Cost += calcGlobalSplitCost(LiveBundles);
857 if (!BestReg || Cost < BestCost) {
860 BestBundles.swap(LiveBundles);
867 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
868 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
873 //===----------------------------------------------------------------------===//
875 //===----------------------------------------------------------------------===//
878 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
879 /// in order to use PhysReg between two entries in SA->UseSlots.
881 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
883 void RAGreedy::calcGapWeights(unsigned PhysReg,
884 SmallVectorImpl<float> &GapWeight) {
885 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
886 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
887 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
888 const unsigned NumGaps = Uses.size()-1;
890 // Start and end points for the interference check.
891 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
892 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
894 GapWeight.assign(NumGaps, 0.0f);
896 // Add interference from each overlapping register.
897 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
898 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
899 .checkInterference())
902 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
903 // so we don't need InterferenceQuery.
905 // Interference that overlaps an instruction is counted in both gaps
906 // surrounding the instruction. The exception is interference before
907 // StartIdx and after StopIdx.
909 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
910 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
911 // Skip the gaps before IntI.
912 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
913 if (++Gap == NumGaps)
918 // Update the gaps covered by IntI.
919 const float weight = IntI.value()->weight;
920 for (; Gap != NumGaps; ++Gap) {
921 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
922 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
931 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
932 /// before MI that has a slot index. If MI is the first mapped instruction in
933 /// its block, return the block start index instead.
935 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
936 assert(MI && "Missing MachineInstr");
937 const MachineBasicBlock *MBB = MI->getParent();
938 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
940 if (!(--I)->isDebugValue() && !I->isCopy())
941 return Indexes->getInstructionIndex(I);
942 return Indexes->getMBBStartIdx(MBB);
945 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
946 /// real non-copy instruction for each instruction in SA->UseSlots.
948 void RAGreedy::calcPrevSlots() {
949 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
951 PrevSlot.reserve(Uses.size());
952 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
953 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
954 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
958 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
959 /// be beneficial to split before UseSlots[i].
961 /// 0 is always a valid split point
962 unsigned RAGreedy::nextSplitPoint(unsigned i) {
963 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
964 const unsigned Size = Uses.size();
965 assert(i != Size && "No split points after the end");
966 // Allow split before i when Uses[i] is not adjacent to the previous use.
967 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
972 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
975 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
976 SmallVectorImpl<LiveInterval*> &NewVRegs) {
977 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
978 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
980 // Note that it is possible to have an interval that is live-in or live-out
981 // while only covering a single block - A phi-def can use undef values from
982 // predecessors, and the block could be a single-block loop.
983 // We don't bother doing anything clever about such a case, we simply assume
984 // that the interval is continuous from FirstUse to LastUse. We should make
985 // sure that we don't do anything illegal to such an interval, though.
987 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
988 if (Uses.size() <= 2)
990 const unsigned NumGaps = Uses.size()-1;
993 dbgs() << "tryLocalSplit: ";
994 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
995 dbgs() << ' ' << SA->UseSlots[i];
999 // For every use, find the previous mapped non-copy instruction.
1000 // We use this to detect valid split points, and to estimate new interval
1004 unsigned BestBefore = NumGaps;
1005 unsigned BestAfter = 0;
1008 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1009 SmallVector<float, 8> GapWeight;
1012 while (unsigned PhysReg = Order.next()) {
1013 // Keep track of the largest spill weight that would need to be evicted in
1014 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1015 calcGapWeights(PhysReg, GapWeight);
1017 // Try to find the best sequence of gaps to close.
1018 // The new spill weight must be larger than any gap interference.
1020 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1021 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1023 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1024 // It is the spill weight that needs to be evicted.
1025 float MaxGap = GapWeight[0];
1026 for (unsigned i = 1; i != SplitAfter; ++i)
1027 MaxGap = std::max(MaxGap, GapWeight[i]);
1030 // Live before/after split?
1031 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1032 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1034 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1035 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1036 << " i=" << MaxGap);
1038 // Stop before the interval gets so big we wouldn't be making progress.
1039 if (!LiveBefore && !LiveAfter) {
1040 DEBUG(dbgs() << " all\n");
1043 // Should the interval be extended or shrunk?
1045 if (MaxGap < HUGE_VALF) {
1046 // Estimate the new spill weight.
1048 // Each instruction reads and writes the register, except the first
1049 // instr doesn't read when !FirstLive, and the last instr doesn't write
1052 // We will be inserting copies before and after, so the total number of
1053 // reads and writes is 2 * EstUses.
1055 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1056 2*(LiveBefore + LiveAfter);
1058 // Try to guess the size of the new interval. This should be trivial,
1059 // but the slot index of an inserted copy can be a lot smaller than the
1060 // instruction it is inserted before if there are many dead indexes
1063 // We measure the distance from the instruction before SplitBefore to
1064 // get a conservative estimate.
1066 // The final distance can still be different if inserting copies
1067 // triggers a slot index renumbering.
1069 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1070 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1071 // Would this split be possible to allocate?
1072 // Never allocate all gaps, we wouldn't be making progress.
1073 float Diff = EstWeight - MaxGap;
1074 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1077 if (Diff > BestDiff) {
1078 DEBUG(dbgs() << " (best)");
1080 BestBefore = SplitBefore;
1081 BestAfter = SplitAfter;
1088 SplitBefore = nextSplitPoint(SplitBefore);
1089 if (SplitBefore < SplitAfter) {
1090 DEBUG(dbgs() << " shrink\n");
1091 // Recompute the max when necessary.
1092 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1093 MaxGap = GapWeight[SplitBefore];
1094 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1095 MaxGap = std::max(MaxGap, GapWeight[i]);
1102 // Try to extend the interval.
1103 if (SplitAfter >= NumGaps) {
1104 DEBUG(dbgs() << " end\n");
1108 DEBUG(dbgs() << " extend\n");
1109 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1110 SplitAfter != e; ++SplitAfter)
1111 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1116 // Didn't find any candidates?
1117 if (BestBefore == NumGaps)
1120 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1121 << '-' << Uses[BestAfter] << ", " << BestDiff
1122 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1124 SmallVector<LiveInterval*, 4> SpillRegs;
1125 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1129 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1130 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1131 SE->useIntv(SegStart, SegStop);
1134 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
1140 //===----------------------------------------------------------------------===//
1141 // Live Range Splitting
1142 //===----------------------------------------------------------------------===//
1144 /// trySplit - Try to split VirtReg or one of its interferences, making it
1146 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1147 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1148 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1149 // Local intervals are handled separately.
1150 if (LIS->intervalIsInOneMBB(VirtReg)) {
1151 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1152 SA->analyze(&VirtReg);
1153 return tryLocalSplit(VirtReg, Order, NewVRegs);
1156 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1158 // Don't iterate global splitting.
1159 // Move straight to spilling if this range was produced by a global split.
1160 LiveRangeStage Stage = getStage(VirtReg);
1161 if (Stage >= RS_Block)
1164 SA->analyze(&VirtReg);
1166 // First try to split around a region spanning multiple blocks.
1167 if (Stage < RS_Region) {
1168 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1169 if (PhysReg || !NewVRegs.empty())
1173 // Then isolate blocks with multiple uses.
1174 if (Stage < RS_Block) {
1175 SplitAnalysis::BlockPtrSet Blocks;
1176 if (SA->getMultiUseBlocks(Blocks)) {
1177 SmallVector<LiveInterval*, 4> SpillRegs;
1178 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1180 SE->splitSingleBlocks(Blocks);
1181 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1183 MF->verify(this, "After splitting live range around basic blocks");
1187 // Don't assign any physregs.
1192 //===----------------------------------------------------------------------===//
1194 //===----------------------------------------------------------------------===//
1196 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1197 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1198 LiveRangeStage Stage = getStage(VirtReg);
1199 if (Stage == RS_Original)
1200 LRStage[VirtReg.reg] = RS_Second;
1202 // First try assigning a free register.
1203 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1204 while (unsigned PhysReg = Order.next()) {
1205 if (!checkPhysRegInterference(VirtReg, PhysReg))
1209 if (unsigned PhysReg = tryReassign(VirtReg, Order, NewVRegs))
1212 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1215 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1217 // The first time we see a live range, don't try to split or spill.
1218 // Wait until the second time, when all smaller ranges have been allocated.
1219 // This gives a better picture of the interference to split around.
1220 if (Stage == RS_Original) {
1221 NewVRegs.push_back(&VirtReg);
1225 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1227 // Try splitting VirtReg or interferences.
1228 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1229 if (PhysReg || !NewVRegs.empty())
1232 // Finally spill VirtReg itself.
1233 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1234 SmallVector<LiveInterval*, 1> pendingSpills;
1235 spiller().spill(&VirtReg, NewVRegs, pendingSpills);
1237 // The live virtual register requesting allocation was spilled, so tell
1238 // the caller not to allocate anything during this round.
1242 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1243 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1244 << "********** Function: "
1245 << ((Value*)mf.getFunction())->getName() << '\n');
1249 MF->verify(this, "Before greedy register allocator");
1251 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1252 Indexes = &getAnalysis<SlotIndexes>();
1253 DomTree = &getAnalysis<MachineDominatorTree>();
1254 ReservedRegs = TRI->getReservedRegs(*MF);
1255 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1256 Loops = &getAnalysis<MachineLoopInfo>();
1257 LoopRanges = &getAnalysis<MachineLoopRanges>();
1258 Bundles = &getAnalysis<EdgeBundles>();
1259 SpillPlacer = &getAnalysis<SpillPlacement>();
1261 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1262 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1264 LRStage.resize(MRI->getNumVirtRegs());
1268 LIS->addKillFlags();
1272 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1273 VRM->rewrite(Indexes);
1276 // The pass output is in VirtRegMap. Release all the transient data.