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/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Support/CommandLine.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 cl::opt<bool> CompactRegions("compact-regions", cl::init(true));
56 static cl::opt<SplitEditor::ComplementSpillMode>
57 SplitSpillMode("split-spill-mode", cl::Hidden,
58 cl::desc("Spill mode for splitting live ranges"),
59 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
60 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
61 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
63 cl::init(SplitEditor::SM_Partition));
65 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
66 createGreedyRegisterAllocator);
69 class RAGreedy : public MachineFunctionPass,
71 private LiveRangeEdit::Delegate {
79 MachineDominatorTree *DomTree;
80 MachineLoopInfo *Loops;
82 SpillPlacement *SpillPlacer;
83 LiveDebugVariables *DebugVars;
86 std::auto_ptr<Spiller> SpillerInstance;
87 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
90 // Live ranges pass through a number of stages as we try to allocate them.
91 // Some of the stages may also create new live ranges:
93 // - Region splitting.
94 // - Per-block splitting.
98 // Ranges produced by one of the stages skip the previous stages when they are
99 // dequeued. This improves performance because we can skip interference checks
100 // that are unlikely to give any results. It also guarantees that the live
101 // range splitting algorithm terminates, something that is otherwise hard to
103 enum LiveRangeStage {
104 /// Newly created live range that has never been queued.
107 /// Only attempt assignment and eviction. Then requeue as RS_Split.
110 /// Attempt live range splitting if assignment is impossible.
113 /// Attempt more aggressive live range splitting that is guaranteed to make
114 /// progress. This is used for split products that may not be making
118 /// Live range will be spilled. No more splitting will be attempted.
121 /// There is nothing more we can do to this live range. Abort compilation
122 /// if it can't be assigned.
126 static const char *const StageName[];
128 // RegInfo - Keep additional information about each live range.
130 LiveRangeStage Stage;
132 // Cascade - Eviction loop prevention. See canEvictInterference().
135 RegInfo() : Stage(RS_New), Cascade(0) {}
138 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
140 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
141 return ExtraRegInfo[VirtReg.reg].Stage;
144 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
145 ExtraRegInfo.resize(MRI->getNumVirtRegs());
146 ExtraRegInfo[VirtReg.reg].Stage = Stage;
149 template<typename Iterator>
150 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
151 ExtraRegInfo.resize(MRI->getNumVirtRegs());
152 for (;Begin != End; ++Begin) {
153 unsigned Reg = (*Begin)->reg;
154 if (ExtraRegInfo[Reg].Stage == RS_New)
155 ExtraRegInfo[Reg].Stage = NewStage;
159 /// Cost of evicting interference.
160 struct EvictionCost {
161 unsigned BrokenHints; ///< Total number of broken hints.
162 float MaxWeight; ///< Maximum spill weight evicted.
164 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
166 bool operator<(const EvictionCost &O) const {
167 if (BrokenHints != O.BrokenHints)
168 return BrokenHints < O.BrokenHints;
169 return MaxWeight < O.MaxWeight;
174 std::auto_ptr<SplitAnalysis> SA;
175 std::auto_ptr<SplitEditor> SE;
177 /// Cached per-block interference maps
178 InterferenceCache IntfCache;
180 /// All basic blocks where the current register has uses.
181 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
183 /// Global live range splitting candidate info.
184 struct GlobalSplitCandidate {
185 // Register intended for assignment, or 0.
188 // SplitKit interval index for this candidate.
191 // Interference for PhysReg.
192 InterferenceCache::Cursor Intf;
194 // Bundles where this candidate should be live.
195 BitVector LiveBundles;
196 SmallVector<unsigned, 8> ActiveBlocks;
198 void reset(InterferenceCache &Cache, unsigned Reg) {
201 Intf.setPhysReg(Cache, Reg);
203 ActiveBlocks.clear();
206 // Set B[i] = C for every live bundle where B[i] was NoCand.
207 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
209 for (int i = LiveBundles.find_first(); i >= 0;
210 i = LiveBundles.find_next(i))
211 if (B[i] == NoCand) {
219 /// Candidate info for for each PhysReg in AllocationOrder.
220 /// This vector never shrinks, but grows to the size of the largest register
222 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
224 enum { NoCand = ~0u };
226 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
227 /// NoCand which indicates the stack interval.
228 SmallVector<unsigned, 32> BundleCand;
233 /// Return the pass name.
234 virtual const char* getPassName() const {
235 return "Greedy Register Allocator";
238 /// RAGreedy analysis usage.
239 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
240 virtual void releaseMemory();
241 virtual Spiller &spiller() { return *SpillerInstance; }
242 virtual void enqueue(LiveInterval *LI);
243 virtual LiveInterval *dequeue();
244 virtual unsigned selectOrSplit(LiveInterval&,
245 SmallVectorImpl<LiveInterval*>&);
247 /// Perform register allocation.
248 virtual bool runOnMachineFunction(MachineFunction &mf);
253 void LRE_WillEraseInstruction(MachineInstr*);
254 bool LRE_CanEraseVirtReg(unsigned);
255 void LRE_WillShrinkVirtReg(unsigned);
256 void LRE_DidCloneVirtReg(unsigned, unsigned);
258 float calcSpillCost();
259 bool addSplitConstraints(InterferenceCache::Cursor, float&);
260 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
261 void growRegion(GlobalSplitCandidate &Cand);
262 float calcGlobalSplitCost(GlobalSplitCandidate&);
263 bool calcCompactRegion(GlobalSplitCandidate&);
264 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
265 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
266 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
267 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
268 void evictInterference(LiveInterval&, unsigned,
269 SmallVectorImpl<LiveInterval*>&);
271 unsigned tryAssign(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
273 unsigned tryEvict(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
275 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
279 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
281 unsigned trySplit(LiveInterval&, AllocationOrder&,
282 SmallVectorImpl<LiveInterval*>&);
284 } // end anonymous namespace
286 char RAGreedy::ID = 0;
289 const char *const RAGreedy::StageName[] = {
299 // Hysteresis to use when comparing floats.
300 // This helps stabilize decisions based on float comparisons.
301 const float Hysteresis = 0.98f;
304 FunctionPass* llvm::createGreedyRegisterAllocator() {
305 return new RAGreedy();
308 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
309 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
312 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
313 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
314 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
315 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
316 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
317 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
318 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
319 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
320 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
321 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
324 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
325 AU.setPreservesCFG();
326 AU.addRequired<AliasAnalysis>();
327 AU.addPreserved<AliasAnalysis>();
328 AU.addRequired<LiveIntervals>();
329 AU.addRequired<SlotIndexes>();
330 AU.addPreserved<SlotIndexes>();
331 AU.addRequired<LiveDebugVariables>();
332 AU.addPreserved<LiveDebugVariables>();
334 AU.addRequiredID(StrongPHIEliminationID);
335 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
336 AU.addRequired<CalculateSpillWeights>();
337 AU.addRequired<LiveStacks>();
338 AU.addPreserved<LiveStacks>();
339 AU.addRequired<MachineDominatorTree>();
340 AU.addPreserved<MachineDominatorTree>();
341 AU.addRequired<MachineLoopInfo>();
342 AU.addPreserved<MachineLoopInfo>();
343 AU.addRequired<VirtRegMap>();
344 AU.addPreserved<VirtRegMap>();
345 AU.addRequired<EdgeBundles>();
346 AU.addRequired<SpillPlacement>();
347 MachineFunctionPass::getAnalysisUsage(AU);
351 //===----------------------------------------------------------------------===//
352 // LiveRangeEdit delegate methods
353 //===----------------------------------------------------------------------===//
355 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
356 // LRE itself will remove from SlotIndexes and parent basic block.
357 VRM->RemoveMachineInstrFromMaps(MI);
360 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
361 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
362 unassign(LIS->getInterval(VirtReg), PhysReg);
365 // Unassigned virtreg is probably in the priority queue.
366 // RegAllocBase will erase it after dequeueing.
370 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
371 unsigned PhysReg = VRM->getPhys(VirtReg);
375 // Register is assigned, put it back on the queue for reassignment.
376 LiveInterval &LI = LIS->getInterval(VirtReg);
377 unassign(LI, PhysReg);
381 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
382 // LRE may clone a virtual register because dead code elimination causes it to
383 // be split into connected components. The new components are much smaller
384 // than the original, so they should get a new chance at being assigned.
385 // same stage as the parent.
386 ExtraRegInfo[Old].Stage = RS_Assign;
387 ExtraRegInfo.grow(New);
388 ExtraRegInfo[New] = ExtraRegInfo[Old];
391 void RAGreedy::releaseMemory() {
392 SpillerInstance.reset(0);
393 ExtraRegInfo.clear();
395 RegAllocBase::releaseMemory();
398 void RAGreedy::enqueue(LiveInterval *LI) {
399 // Prioritize live ranges by size, assigning larger ranges first.
400 // The queue holds (size, reg) pairs.
401 const unsigned Size = LI->getSize();
402 const unsigned Reg = LI->reg;
403 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
404 "Can only enqueue virtual registers");
407 ExtraRegInfo.grow(Reg);
408 if (ExtraRegInfo[Reg].Stage == RS_New)
409 ExtraRegInfo[Reg].Stage = RS_Assign;
411 if (ExtraRegInfo[Reg].Stage == RS_Split) {
412 // Unsplit ranges that couldn't be allocated immediately are deferred until
413 // everything else has been allocated. Long ranges are allocated last so
414 // they are split against realistic interference.
418 Prio = (1u << 31) - Size;
420 // Everything else is allocated in long->short order. Long ranges that don't
421 // fit should be spilled ASAP so they don't create interference.
422 Prio = (1u << 31) + Size;
424 // Boost ranges that have a physical register hint.
425 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
429 Queue.push(std::make_pair(Prio, Reg));
432 LiveInterval *RAGreedy::dequeue() {
435 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// tryAssign - Try to assign VirtReg to an available register.
446 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
447 AllocationOrder &Order,
448 SmallVectorImpl<LiveInterval*> &NewVRegs) {
451 while ((PhysReg = Order.next()))
452 if (!checkPhysRegInterference(VirtReg, PhysReg))
454 if (!PhysReg || Order.isHint(PhysReg))
457 // PhysReg is available, but there may be a better choice.
459 // If we missed a simple hint, try to cheaply evict interference from the
460 // preferred register.
461 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
462 if (Order.isHint(Hint)) {
463 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
464 EvictionCost MaxCost(1);
465 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
466 evictInterference(VirtReg, Hint, NewVRegs);
471 // Try to evict interference from a cheaper alternative.
472 unsigned Cost = TRI->getCostPerUse(PhysReg);
474 // Most registers have 0 additional cost.
478 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
480 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
481 return CheapReg ? CheapReg : PhysReg;
485 //===----------------------------------------------------------------------===//
486 // Interference eviction
487 //===----------------------------------------------------------------------===//
489 /// shouldEvict - determine if A should evict the assigned live range B. The
490 /// eviction policy defined by this function together with the allocation order
491 /// defined by enqueue() decides which registers ultimately end up being split
494 /// Cascade numbers are used to prevent infinite loops if this function is a
497 /// @param A The live range to be assigned.
498 /// @param IsHint True when A is about to be assigned to its preferred
500 /// @param B The live range to be evicted.
501 /// @param BreaksHint True when B is already assigned to its preferred register.
502 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
503 LiveInterval &B, bool BreaksHint) {
504 bool CanSplit = getStage(B) < RS_Spill;
506 // Be fairly aggressive about following hints as long as the evictee can be
508 if (CanSplit && IsHint && !BreaksHint)
511 return A.weight > B.weight;
514 /// canEvictInterference - Return true if all interferences between VirtReg and
515 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
517 /// @param VirtReg Live range that is about to be assigned.
518 /// @param PhysReg Desired register for assignment.
519 /// @prarm IsHint True when PhysReg is VirtReg's preferred register.
520 /// @param MaxCost Only look for cheaper candidates and update with new cost
521 /// when returning true.
522 /// @returns True when interference can be evicted cheaper than MaxCost.
523 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
524 bool IsHint, EvictionCost &MaxCost) {
525 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
526 // involved in an eviction before. If a cascade number was assigned, deny
527 // evicting anything with the same or a newer cascade number. This prevents
528 // infinite eviction loops.
530 // This works out so a register without a cascade number is allowed to evict
531 // anything, and it can be evicted by anything.
532 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
534 Cascade = NextCascade;
537 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
538 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
539 // If there is 10 or more interferences, chances are one is heavier.
540 if (Q.collectInterferingVRegs(10) >= 10)
543 // Check if any interfering live range is heavier than MaxWeight.
544 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
545 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
546 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
548 // Never evict spill products. They cannot split or spill.
549 if (getStage(*Intf) == RS_Done)
551 // Once a live range becomes small enough, it is urgent that we find a
552 // register for it. This is indicated by an infinite spill weight. These
553 // urgent live ranges get to evict almost anything.
554 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
555 // Only evict older cascades or live ranges without a cascade.
556 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
557 if (Cascade <= IntfCascade) {
560 // We permit breaking cascades for urgent evictions. It should be the
561 // last resort, though, so make it really expensive.
562 Cost.BrokenHints += 10;
564 // Would this break a satisfied hint?
565 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
566 // Update eviction cost.
567 Cost.BrokenHints += BreaksHint;
568 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
569 // Abort if this would be too expensive.
570 if (!(Cost < MaxCost))
572 // Finally, apply the eviction policy for non-urgent evictions.
573 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
581 /// evictInterference - Evict any interferring registers that prevent VirtReg
582 /// from being assigned to Physreg. This assumes that canEvictInterference
584 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
585 SmallVectorImpl<LiveInterval*> &NewVRegs) {
586 // Make sure that VirtReg has a cascade number, and assign that cascade
587 // number to every evicted register. These live ranges than then only be
588 // evicted by a newer cascade, preventing infinite loops.
589 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
591 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
593 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
594 << " interference: Cascade " << Cascade << '\n');
595 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
596 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
597 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
598 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
599 LiveInterval *Intf = Q.interferingVRegs()[i];
600 unassign(*Intf, VRM->getPhys(Intf->reg));
601 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
602 VirtReg.isSpillable() < Intf->isSpillable()) &&
603 "Cannot decrease cascade number, illegal eviction");
604 ExtraRegInfo[Intf->reg].Cascade = Cascade;
606 NewVRegs.push_back(Intf);
611 /// tryEvict - Try to evict all interferences for a physreg.
612 /// @param VirtReg Currently unassigned virtual register.
613 /// @param Order Physregs to try.
614 /// @return Physreg to assign VirtReg, or 0.
615 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
616 AllocationOrder &Order,
617 SmallVectorImpl<LiveInterval*> &NewVRegs,
618 unsigned CostPerUseLimit) {
619 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
621 // Keep track of the cheapest interference seen so far.
622 EvictionCost BestCost(~0u);
623 unsigned BestPhys = 0;
625 // When we are just looking for a reduced cost per use, don't break any
626 // hints, and only evict smaller spill weights.
627 if (CostPerUseLimit < ~0u) {
628 BestCost.BrokenHints = 0;
629 BestCost.MaxWeight = VirtReg.weight;
633 while (unsigned PhysReg = Order.next()) {
634 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
636 // The first use of a callee-saved register in a function has cost 1.
637 // Don't start using a CSR when the CostPerUseLimit is low.
638 if (CostPerUseLimit == 1)
639 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
640 if (!MRI->isPhysRegUsed(CSR)) {
641 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
642 << PrintReg(CSR, TRI) << '\n');
646 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
652 // Stop if the hint can be used.
653 if (Order.isHint(PhysReg))
660 evictInterference(VirtReg, BestPhys, NewVRegs);
665 //===----------------------------------------------------------------------===//
667 //===----------------------------------------------------------------------===//
669 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
670 /// interference pattern in Physreg and its aliases. Add the constraints to
671 /// SpillPlacement and return the static cost of this split in Cost, assuming
672 /// that all preferences in SplitConstraints are met.
673 /// Return false if there are no bundles with positive bias.
674 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
676 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
678 // Reset interference dependent info.
679 SplitConstraints.resize(UseBlocks.size());
680 float StaticCost = 0;
681 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
682 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
683 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
685 BC.Number = BI.MBB->getNumber();
686 Intf.moveToBlock(BC.Number);
687 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
688 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
689 BC.ChangesValue = BI.FirstDef;
691 if (!Intf.hasInterference())
694 // Number of spill code instructions to insert.
697 // Interference for the live-in value.
699 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
700 BC.Entry = SpillPlacement::MustSpill, ++Ins;
701 else if (Intf.first() < BI.FirstInstr)
702 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
703 else if (Intf.first() < BI.LastInstr)
707 // Interference for the live-out value.
709 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
710 BC.Exit = SpillPlacement::MustSpill, ++Ins;
711 else if (Intf.last() > BI.LastInstr)
712 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
713 else if (Intf.last() > BI.FirstInstr)
717 // Accumulate the total frequency of inserted spill code.
719 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
723 // Add constraints for use-blocks. Note that these are the only constraints
724 // that may add a positive bias, it is downhill from here.
725 SpillPlacer->addConstraints(SplitConstraints);
726 return SpillPlacer->scanActiveBundles();
730 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
731 /// live-through blocks in Blocks.
732 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
733 ArrayRef<unsigned> Blocks) {
734 const unsigned GroupSize = 8;
735 SpillPlacement::BlockConstraint BCS[GroupSize];
736 unsigned TBS[GroupSize];
737 unsigned B = 0, T = 0;
739 for (unsigned i = 0; i != Blocks.size(); ++i) {
740 unsigned Number = Blocks[i];
741 Intf.moveToBlock(Number);
743 if (!Intf.hasInterference()) {
744 assert(T < GroupSize && "Array overflow");
746 if (++T == GroupSize) {
747 SpillPlacer->addLinks(makeArrayRef(TBS, T));
753 assert(B < GroupSize && "Array overflow");
754 BCS[B].Number = Number;
756 // Interference for the live-in value.
757 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
758 BCS[B].Entry = SpillPlacement::MustSpill;
760 BCS[B].Entry = SpillPlacement::PrefSpill;
762 // Interference for the live-out value.
763 if (Intf.last() >= SA->getLastSplitPoint(Number))
764 BCS[B].Exit = SpillPlacement::MustSpill;
766 BCS[B].Exit = SpillPlacement::PrefSpill;
768 if (++B == GroupSize) {
769 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
770 SpillPlacer->addConstraints(Array);
775 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
776 SpillPlacer->addConstraints(Array);
777 SpillPlacer->addLinks(makeArrayRef(TBS, T));
780 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
781 // Keep track of through blocks that have not been added to SpillPlacer.
782 BitVector Todo = SA->getThroughBlocks();
783 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
784 unsigned AddedTo = 0;
786 unsigned Visited = 0;
790 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
791 // Find new through blocks in the periphery of PrefRegBundles.
792 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
793 unsigned Bundle = NewBundles[i];
794 // Look at all blocks connected to Bundle in the full graph.
795 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
796 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
799 if (!Todo.test(Block))
802 // This is a new through block. Add it to SpillPlacer later.
803 ActiveBlocks.push_back(Block);
809 // Any new blocks to add?
810 if (ActiveBlocks.size() == AddedTo)
813 // Compute through constraints from the interference, or assume that all
814 // through blocks prefer spilling when forming compact regions.
815 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
817 addThroughConstraints(Cand.Intf, NewBlocks);
819 // Provide a strong negative bias on through blocks to prevent unwanted
820 // liveness on loop backedges.
821 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
822 AddedTo = ActiveBlocks.size();
824 // Perhaps iterating can enable more bundles?
825 SpillPlacer->iterate();
827 DEBUG(dbgs() << ", v=" << Visited);
830 /// calcCompactRegion - Compute the set of edge bundles that should be live
831 /// when splitting the current live range into compact regions. Compact
832 /// regions can be computed without looking at interference. They are the
833 /// regions formed by removing all the live-through blocks from the live range.
835 /// Returns false if the current live range is already compact, or if the
836 /// compact regions would form single block regions anyway.
837 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
838 // Without any through blocks, the live range is already compact.
839 if (!SA->getNumThroughBlocks())
842 // Compact regions don't correspond to any physreg.
843 Cand.reset(IntfCache, 0);
845 DEBUG(dbgs() << "Compact region bundles");
847 // Use the spill placer to determine the live bundles. GrowRegion pretends
848 // that all the through blocks have interference when PhysReg is unset.
849 SpillPlacer->prepare(Cand.LiveBundles);
851 // The static split cost will be zero since Cand.Intf reports no interference.
853 if (!addSplitConstraints(Cand.Intf, Cost)) {
854 DEBUG(dbgs() << ", none.\n");
859 SpillPlacer->finish();
861 if (!Cand.LiveBundles.any()) {
862 DEBUG(dbgs() << ", none.\n");
867 for (int i = Cand.LiveBundles.find_first(); i>=0;
868 i = Cand.LiveBundles.find_next(i))
869 dbgs() << " EB#" << i;
875 /// calcSpillCost - Compute how expensive it would be to split the live range in
876 /// SA around all use blocks instead of forming bundle regions.
877 float RAGreedy::calcSpillCost() {
879 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
880 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
881 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
882 unsigned Number = BI.MBB->getNumber();
883 // We normally only need one spill instruction - a load or a store.
884 Cost += SpillPlacer->getBlockFrequency(Number);
886 // Unless the value is redefined in the block.
887 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
888 Cost += SpillPlacer->getBlockFrequency(Number);
893 /// calcGlobalSplitCost - Return the global split cost of following the split
894 /// pattern in LiveBundles. This cost should be added to the local cost of the
895 /// interference pattern in SplitConstraints.
897 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
898 float GlobalCost = 0;
899 const BitVector &LiveBundles = Cand.LiveBundles;
900 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
901 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
902 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
903 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
904 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
905 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
909 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
911 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
913 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
916 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
917 unsigned Number = Cand.ActiveBlocks[i];
918 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
919 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
920 if (!RegIn && !RegOut)
922 if (RegIn && RegOut) {
923 // We need double spill code if this block has interference.
924 Cand.Intf.moveToBlock(Number);
925 if (Cand.Intf.hasInterference())
926 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
929 // live-in / stack-out or stack-in live-out.
930 GlobalCost += SpillPlacer->getBlockFrequency(Number);
935 /// splitAroundRegion - Split the current live range around the regions
936 /// determined by BundleCand and GlobalCand.
938 /// Before calling this function, GlobalCand and BundleCand must be initialized
939 /// so each bundle is assigned to a valid candidate, or NoCand for the
940 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
941 /// objects must be initialized for the current live range, and intervals
942 /// created for the used candidates.
944 /// @param LREdit The LiveRangeEdit object handling the current split.
945 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
946 /// must appear in this list.
947 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
948 ArrayRef<unsigned> UsedCands) {
949 // These are the intervals created for new global ranges. We may create more
950 // intervals for local ranges.
951 const unsigned NumGlobalIntvs = LREdit.size();
952 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
953 assert(NumGlobalIntvs && "No global intervals configured");
955 // Isolate even single instructions when dealing with a proper sub-class.
956 // That guarantees register class inflation for the stack interval because it
958 unsigned Reg = SA->getParent().reg;
959 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
961 // First handle all the blocks with uses.
962 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
963 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
964 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
965 unsigned Number = BI.MBB->getNumber();
966 unsigned IntvIn = 0, IntvOut = 0;
967 SlotIndex IntfIn, IntfOut;
969 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
970 if (CandIn != NoCand) {
971 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
972 IntvIn = Cand.IntvIdx;
973 Cand.Intf.moveToBlock(Number);
974 IntfIn = Cand.Intf.first();
978 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
979 if (CandOut != NoCand) {
980 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
981 IntvOut = Cand.IntvIdx;
982 Cand.Intf.moveToBlock(Number);
983 IntfOut = Cand.Intf.last();
987 // Create separate intervals for isolated blocks with multiple uses.
988 if (!IntvIn && !IntvOut) {
989 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
990 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
991 SE->splitSingleBlock(BI);
995 if (IntvIn && IntvOut)
996 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
998 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1000 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1003 // Handle live-through blocks. The relevant live-through blocks are stored in
1004 // the ActiveBlocks list with each candidate. We need to filter out
1006 BitVector Todo = SA->getThroughBlocks();
1007 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1008 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1009 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1010 unsigned Number = Blocks[i];
1011 if (!Todo.test(Number))
1015 unsigned IntvIn = 0, IntvOut = 0;
1016 SlotIndex IntfIn, IntfOut;
1018 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1019 if (CandIn != NoCand) {
1020 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1021 IntvIn = Cand.IntvIdx;
1022 Cand.Intf.moveToBlock(Number);
1023 IntfIn = Cand.Intf.first();
1026 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1027 if (CandOut != NoCand) {
1028 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1029 IntvOut = Cand.IntvIdx;
1030 Cand.Intf.moveToBlock(Number);
1031 IntfOut = Cand.Intf.last();
1033 if (!IntvIn && !IntvOut)
1035 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1041 SmallVector<unsigned, 8> IntvMap;
1042 SE->finish(&IntvMap);
1043 DebugVars->splitRegister(Reg, LREdit.regs());
1045 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1046 unsigned OrigBlocks = SA->getNumLiveBlocks();
1048 // Sort out the new intervals created by splitting. We get four kinds:
1049 // - Remainder intervals should not be split again.
1050 // - Candidate intervals can be assigned to Cand.PhysReg.
1051 // - Block-local splits are candidates for local splitting.
1052 // - DCE leftovers should go back on the queue.
1053 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1054 LiveInterval &Reg = *LREdit.get(i);
1056 // Ignore old intervals from DCE.
1057 if (getStage(Reg) != RS_New)
1060 // Remainder interval. Don't try splitting again, spill if it doesn't
1062 if (IntvMap[i] == 0) {
1063 setStage(Reg, RS_Spill);
1067 // Global intervals. Allow repeated splitting as long as the number of live
1068 // blocks is strictly decreasing.
1069 if (IntvMap[i] < NumGlobalIntvs) {
1070 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1071 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1072 << " blocks as original.\n");
1073 // Don't allow repeated splitting as a safe guard against looping.
1074 setStage(Reg, RS_Split2);
1079 // Other intervals are treated as new. This includes local intervals created
1080 // for blocks with multiple uses, and anything created by DCE.
1084 MF->verify(this, "After splitting live range around region");
1087 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1088 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1089 unsigned NumCands = 0;
1090 unsigned BestCand = NoCand;
1092 SmallVector<unsigned, 8> UsedCands;
1094 // Check if we can split this live range around a compact region.
1095 bool HasCompact = CompactRegions && calcCompactRegion(GlobalCand.front());
1097 // Yes, keep GlobalCand[0] as the compact region candidate.
1099 BestCost = HUGE_VALF;
1101 // No benefit from the compact region, our fallback will be per-block
1102 // splitting. Make sure we find a solution that is cheaper than spilling.
1103 BestCost = Hysteresis * calcSpillCost();
1104 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1108 while (unsigned PhysReg = Order.next()) {
1109 // Discard bad candidates before we run out of interference cache cursors.
1110 // This will only affect register classes with a lot of registers (>32).
1111 if (NumCands == IntfCache.getMaxCursors()) {
1112 unsigned WorstCount = ~0u;
1114 for (unsigned i = 0; i != NumCands; ++i) {
1115 if (i == BestCand || !GlobalCand[i].PhysReg)
1117 unsigned Count = GlobalCand[i].LiveBundles.count();
1118 if (Count < WorstCount)
1119 Worst = i, WorstCount = Count;
1122 GlobalCand[Worst] = GlobalCand[NumCands];
1125 if (GlobalCand.size() <= NumCands)
1126 GlobalCand.resize(NumCands+1);
1127 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1128 Cand.reset(IntfCache, PhysReg);
1130 SpillPlacer->prepare(Cand.LiveBundles);
1132 if (!addSplitConstraints(Cand.Intf, Cost)) {
1133 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1136 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1137 if (Cost >= BestCost) {
1139 if (BestCand == NoCand)
1140 dbgs() << " worse than no bundles\n";
1142 dbgs() << " worse than "
1143 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1149 SpillPlacer->finish();
1151 // No live bundles, defer to splitSingleBlocks().
1152 if (!Cand.LiveBundles.any()) {
1153 DEBUG(dbgs() << " no bundles.\n");
1157 Cost += calcGlobalSplitCost(Cand);
1159 dbgs() << ", total = " << Cost << " with bundles";
1160 for (int i = Cand.LiveBundles.find_first(); i>=0;
1161 i = Cand.LiveBundles.find_next(i))
1162 dbgs() << " EB#" << i;
1165 if (Cost < BestCost) {
1166 BestCand = NumCands;
1167 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1172 // No solutions found, fall back to single block splitting.
1173 if (!HasCompact && BestCand == NoCand)
1176 // Prepare split editor.
1177 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1178 SE->reset(LREdit, SplitSpillMode);
1180 // Assign all edge bundles to the preferred candidate, or NoCand.
1181 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1183 // Assign bundles for the best candidate region.
1184 if (BestCand != NoCand) {
1185 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1186 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1187 UsedCands.push_back(BestCand);
1188 Cand.IntvIdx = SE->openIntv();
1189 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1190 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1195 // Assign bundles for the compact region.
1197 GlobalSplitCandidate &Cand = GlobalCand.front();
1198 assert(!Cand.PhysReg && "Compact region has no physreg");
1199 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1200 UsedCands.push_back(0);
1201 Cand.IntvIdx = SE->openIntv();
1202 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1203 << Cand.IntvIdx << ".\n");
1208 splitAroundRegion(LREdit, UsedCands);
1213 //===----------------------------------------------------------------------===//
1214 // Per-Block Splitting
1215 //===----------------------------------------------------------------------===//
1217 /// tryBlockSplit - Split a global live range around every block with uses. This
1218 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1219 /// they don't allocate.
1220 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1221 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1222 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1223 unsigned Reg = VirtReg.reg;
1224 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1225 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1226 SE->reset(LREdit, SplitSpillMode);
1227 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1228 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1229 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1230 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1231 SE->splitSingleBlock(BI);
1233 // No blocks were split.
1237 // We did split for some blocks.
1238 SmallVector<unsigned, 8> IntvMap;
1239 SE->finish(&IntvMap);
1241 // Tell LiveDebugVariables about the new ranges.
1242 DebugVars->splitRegister(Reg, LREdit.regs());
1244 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1246 // Sort out the new intervals created by splitting. The remainder interval
1247 // goes straight to spilling, the new local ranges get to stay RS_New.
1248 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1249 LiveInterval &LI = *LREdit.get(i);
1250 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1251 setStage(LI, RS_Spill);
1255 MF->verify(this, "After splitting live range around basic blocks");
1259 //===----------------------------------------------------------------------===//
1261 //===----------------------------------------------------------------------===//
1264 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1265 /// in order to use PhysReg between two entries in SA->UseSlots.
1267 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1269 void RAGreedy::calcGapWeights(unsigned PhysReg,
1270 SmallVectorImpl<float> &GapWeight) {
1271 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1272 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1273 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1274 const unsigned NumGaps = Uses.size()-1;
1276 // Start and end points for the interference check.
1277 SlotIndex StartIdx =
1278 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1280 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1282 GapWeight.assign(NumGaps, 0.0f);
1284 // Add interference from each overlapping register.
1285 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1286 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1287 .checkInterference())
1290 // We know that VirtReg is a continuous interval from FirstInstr to
1291 // LastInstr, so we don't need InterferenceQuery.
1293 // Interference that overlaps an instruction is counted in both gaps
1294 // surrounding the instruction. The exception is interference before
1295 // StartIdx and after StopIdx.
1297 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1298 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1299 // Skip the gaps before IntI.
1300 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1301 if (++Gap == NumGaps)
1306 // Update the gaps covered by IntI.
1307 const float weight = IntI.value()->weight;
1308 for (; Gap != NumGaps; ++Gap) {
1309 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1310 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1319 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1322 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1323 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1324 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1325 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1327 // Note that it is possible to have an interval that is live-in or live-out
1328 // while only covering a single block - A phi-def can use undef values from
1329 // predecessors, and the block could be a single-block loop.
1330 // We don't bother doing anything clever about such a case, we simply assume
1331 // that the interval is continuous from FirstInstr to LastInstr. We should
1332 // make sure that we don't do anything illegal to such an interval, though.
1334 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1335 if (Uses.size() <= 2)
1337 const unsigned NumGaps = Uses.size()-1;
1340 dbgs() << "tryLocalSplit: ";
1341 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1342 dbgs() << ' ' << SA->UseSlots[i];
1346 // Since we allow local split results to be split again, there is a risk of
1347 // creating infinite loops. It is tempting to require that the new live
1348 // ranges have less instructions than the original. That would guarantee
1349 // convergence, but it is too strict. A live range with 3 instructions can be
1350 // split 2+3 (including the COPY), and we want to allow that.
1352 // Instead we use these rules:
1354 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1355 // noop split, of course).
1356 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1357 // the new ranges must have fewer instructions than before the split.
1358 // 3. New ranges with the same number of instructions are marked RS_Split2,
1359 // smaller ranges are marked RS_New.
1361 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1362 // excessive splitting and infinite loops.
1364 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1366 // Best split candidate.
1367 unsigned BestBefore = NumGaps;
1368 unsigned BestAfter = 0;
1371 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1372 SmallVector<float, 8> GapWeight;
1375 while (unsigned PhysReg = Order.next()) {
1376 // Keep track of the largest spill weight that would need to be evicted in
1377 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1378 calcGapWeights(PhysReg, GapWeight);
1380 // Try to find the best sequence of gaps to close.
1381 // The new spill weight must be larger than any gap interference.
1383 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1384 unsigned SplitBefore = 0, SplitAfter = 1;
1386 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1387 // It is the spill weight that needs to be evicted.
1388 float MaxGap = GapWeight[0];
1391 // Live before/after split?
1392 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1393 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1395 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1396 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1397 << " i=" << MaxGap);
1399 // Stop before the interval gets so big we wouldn't be making progress.
1400 if (!LiveBefore && !LiveAfter) {
1401 DEBUG(dbgs() << " all\n");
1404 // Should the interval be extended or shrunk?
1407 // How many gaps would the new range have?
1408 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1410 // Legally, without causing looping?
1411 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1413 if (Legal && MaxGap < HUGE_VALF) {
1414 // Estimate the new spill weight. Each instruction reads or writes the
1415 // register. Conservatively assume there are no read-modify-write
1418 // Try to guess the size of the new interval.
1419 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1420 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1421 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1422 // Would this split be possible to allocate?
1423 // Never allocate all gaps, we wouldn't be making progress.
1424 DEBUG(dbgs() << " w=" << EstWeight);
1425 if (EstWeight * Hysteresis >= MaxGap) {
1427 float Diff = EstWeight - MaxGap;
1428 if (Diff > BestDiff) {
1429 DEBUG(dbgs() << " (best)");
1430 BestDiff = Hysteresis * Diff;
1431 BestBefore = SplitBefore;
1432 BestAfter = SplitAfter;
1439 if (++SplitBefore < SplitAfter) {
1440 DEBUG(dbgs() << " shrink\n");
1441 // Recompute the max when necessary.
1442 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1443 MaxGap = GapWeight[SplitBefore];
1444 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1445 MaxGap = std::max(MaxGap, GapWeight[i]);
1452 // Try to extend the interval.
1453 if (SplitAfter >= NumGaps) {
1454 DEBUG(dbgs() << " end\n");
1458 DEBUG(dbgs() << " extend\n");
1459 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1463 // Didn't find any candidates?
1464 if (BestBefore == NumGaps)
1467 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1468 << '-' << Uses[BestAfter] << ", " << BestDiff
1469 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1471 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1475 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1476 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1477 SE->useIntv(SegStart, SegStop);
1478 SmallVector<unsigned, 8> IntvMap;
1479 SE->finish(&IntvMap);
1480 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1482 // If the new range has the same number of instructions as before, mark it as
1483 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1484 // leave the new intervals as RS_New so they can compete.
1485 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1486 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1487 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1488 if (NewGaps >= NumGaps) {
1489 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1490 assert(!ProgressRequired && "Didn't make progress when it was required.");
1491 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1492 if (IntvMap[i] == 1) {
1493 setStage(*LREdit.get(i), RS_Split2);
1494 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1496 DEBUG(dbgs() << '\n');
1503 //===----------------------------------------------------------------------===//
1504 // Live Range Splitting
1505 //===----------------------------------------------------------------------===//
1507 /// trySplit - Try to split VirtReg or one of its interferences, making it
1509 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1510 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1511 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1512 // Ranges must be Split2 or less.
1513 if (getStage(VirtReg) >= RS_Spill)
1516 // Local intervals are handled separately.
1517 if (LIS->intervalIsInOneMBB(VirtReg)) {
1518 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1519 SA->analyze(&VirtReg);
1520 return tryLocalSplit(VirtReg, Order, NewVRegs);
1523 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1525 SA->analyze(&VirtReg);
1527 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1528 // coalescer. That may cause the range to become allocatable which means that
1529 // tryRegionSplit won't be making progress. This check should be replaced with
1530 // an assertion when the coalescer is fixed.
1531 if (SA->didRepairRange()) {
1532 // VirtReg has changed, so all cached queries are invalid.
1533 invalidateVirtRegs();
1534 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1538 // First try to split around a region spanning multiple blocks. RS_Split2
1539 // ranges already made dubious progress with region splitting, so they go
1540 // straight to single block splitting.
1541 if (getStage(VirtReg) < RS_Split2) {
1542 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1543 if (PhysReg || !NewVRegs.empty())
1547 // Then isolate blocks.
1548 return tryBlockSplit(VirtReg, Order, NewVRegs);
1552 //===----------------------------------------------------------------------===//
1554 //===----------------------------------------------------------------------===//
1556 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1557 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1558 // First try assigning a free register.
1559 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1560 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1563 LiveRangeStage Stage = getStage(VirtReg);
1564 DEBUG(dbgs() << StageName[Stage]
1565 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1567 // Try to evict a less worthy live range, but only for ranges from the primary
1568 // queue. The RS_Split ranges already failed to do this, and they should not
1569 // get a second chance until they have been split.
1570 if (Stage != RS_Split)
1571 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1574 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1576 // The first time we see a live range, don't try to split or spill.
1577 // Wait until the second time, when all smaller ranges have been allocated.
1578 // This gives a better picture of the interference to split around.
1579 if (Stage < RS_Split) {
1580 setStage(VirtReg, RS_Split);
1581 DEBUG(dbgs() << "wait for second round\n");
1582 NewVRegs.push_back(&VirtReg);
1586 // If we couldn't allocate a register from spilling, there is probably some
1587 // invalid inline assembly. The base class wil report it.
1588 if (Stage >= RS_Done || !VirtReg.isSpillable())
1591 // Try splitting VirtReg or interferences.
1592 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1593 if (PhysReg || !NewVRegs.empty())
1596 // Finally spill VirtReg itself.
1597 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1598 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1599 spiller().spill(LRE);
1600 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1603 MF->verify(this, "After spilling");
1605 // The live virtual register requesting allocation was spilled, so tell
1606 // the caller not to allocate anything during this round.
1610 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1611 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1612 << "********** Function: "
1613 << ((Value*)mf.getFunction())->getName() << '\n');
1617 MF->verify(this, "Before greedy register allocator");
1619 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1620 Indexes = &getAnalysis<SlotIndexes>();
1621 DomTree = &getAnalysis<MachineDominatorTree>();
1622 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1623 Loops = &getAnalysis<MachineLoopInfo>();
1624 Bundles = &getAnalysis<EdgeBundles>();
1625 SpillPlacer = &getAnalysis<SpillPlacement>();
1626 DebugVars = &getAnalysis<LiveDebugVariables>();
1628 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1629 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1630 ExtraRegInfo.clear();
1631 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1633 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1634 GlobalCand.resize(32); // This will grow as needed.
1638 LIS->addKillFlags();
1642 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1643 VRM->rewrite(Indexes);
1646 // Write out new DBG_VALUE instructions.
1648 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1649 DebugVars->emitDebugValues(VRM);
1652 // The pass output is in VirtRegMap. Release all the transient data.