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 "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.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/RegAllocRegistry.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/PassAnalysisSupport.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
49 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50 STATISTIC(NumLocalSplits, "Number of split local live ranges");
51 STATISTIC(NumEvicted, "Number of interferences evicted");
53 static cl::opt<SplitEditor::ComplementSpillMode>
54 SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 cl::init(SplitEditor::SM_Partition));
62 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
66 class RAGreedy : public MachineFunctionPass,
68 private LiveRangeEdit::Delegate {
75 MachineBlockFrequencyInfo *MBFI;
76 MachineDominatorTree *DomTree;
77 MachineLoopInfo *Loops;
79 SpillPlacement *SpillPlacer;
80 LiveDebugVariables *DebugVars;
83 OwningPtr<Spiller> SpillerInstance;
84 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
90 // - Region splitting.
91 // - Per-block splitting.
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
100 enum LiveRangeStage {
101 /// Newly created live range that has never been queued.
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
107 /// Attempt live range splitting if assignment is impossible.
110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
115 /// Live range will be spilled. No more splitting will be attempted.
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
123 static const char *const StageName[];
125 // RegInfo - Keep additional information about each live range.
127 LiveRangeStage Stage;
129 // Cascade - Eviction loop prevention. See canEvictInterference().
132 RegInfo() : Stage(RS_New), Cascade(0) {}
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
138 return ExtraRegInfo[VirtReg.reg].Stage;
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163 bool operator<(const EvictionCost &O) const {
164 if (BrokenHints != O.BrokenHints)
165 return BrokenHints < O.BrokenHints;
166 return MaxWeight < O.MaxWeight;
171 OwningPtr<SplitAnalysis> SA;
172 OwningPtr<SplitEditor> SE;
174 /// Cached per-block interference maps
175 InterferenceCache IntfCache;
177 /// All basic blocks where the current register has uses.
178 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
180 /// Global live range splitting candidate info.
181 struct GlobalSplitCandidate {
182 // Register intended for assignment, or 0.
185 // SplitKit interval index for this candidate.
188 // Interference for PhysReg.
189 InterferenceCache::Cursor Intf;
191 // Bundles where this candidate should be live.
192 BitVector LiveBundles;
193 SmallVector<unsigned, 8> ActiveBlocks;
195 void reset(InterferenceCache &Cache, unsigned Reg) {
198 Intf.setPhysReg(Cache, Reg);
200 ActiveBlocks.clear();
203 // Set B[i] = C for every live bundle where B[i] was NoCand.
204 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
206 for (int i = LiveBundles.find_first(); i >= 0;
207 i = LiveBundles.find_next(i))
208 if (B[i] == NoCand) {
216 /// Candidate info for for each PhysReg in AllocationOrder.
217 /// This vector never shrinks, but grows to the size of the largest register
219 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
221 enum { NoCand = ~0u };
223 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
224 /// NoCand which indicates the stack interval.
225 SmallVector<unsigned, 32> BundleCand;
230 /// Return the pass name.
231 virtual const char* getPassName() const {
232 return "Greedy Register Allocator";
235 /// RAGreedy analysis usage.
236 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
237 virtual void releaseMemory();
238 virtual Spiller &spiller() { return *SpillerInstance; }
239 virtual void enqueue(LiveInterval *LI);
240 virtual LiveInterval *dequeue();
241 virtual unsigned selectOrSplit(LiveInterval&,
242 SmallVectorImpl<LiveInterval*>&);
244 /// Perform register allocation.
245 virtual bool runOnMachineFunction(MachineFunction &mf);
250 bool LRE_CanEraseVirtReg(unsigned);
251 void LRE_WillShrinkVirtReg(unsigned);
252 void LRE_DidCloneVirtReg(unsigned, unsigned);
254 float calcSpillCost();
255 bool addSplitConstraints(InterferenceCache::Cursor, float&);
256 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
257 void growRegion(GlobalSplitCandidate &Cand);
258 float calcGlobalSplitCost(GlobalSplitCandidate&);
259 bool calcCompactRegion(GlobalSplitCandidate&);
260 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
261 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
262 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
263 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
264 void evictInterference(LiveInterval&, unsigned,
265 SmallVectorImpl<LiveInterval*>&);
267 unsigned tryAssign(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
269 unsigned tryEvict(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
271 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
273 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
275 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
279 unsigned trySplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
282 } // end anonymous namespace
284 char RAGreedy::ID = 0;
287 const char *const RAGreedy::StageName[] = {
297 // Hysteresis to use when comparing floats.
298 // This helps stabilize decisions based on float comparisons.
299 const float Hysteresis = 0.98f;
302 FunctionPass* llvm::createGreedyRegisterAllocator() {
303 return new RAGreedy();
306 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
307 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
309 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
312 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
313 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
314 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
315 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
316 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
317 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
318 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
319 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
320 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
323 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
324 AU.setPreservesCFG();
325 AU.addRequired<MachineBlockFrequencyInfo>();
326 AU.addPreserved<MachineBlockFrequencyInfo>();
327 AU.addRequired<AliasAnalysis>();
328 AU.addPreserved<AliasAnalysis>();
329 AU.addRequired<LiveIntervals>();
330 AU.addPreserved<LiveIntervals>();
331 AU.addRequired<SlotIndexes>();
332 AU.addPreserved<SlotIndexes>();
333 AU.addRequired<LiveDebugVariables>();
334 AU.addPreserved<LiveDebugVariables>();
335 AU.addRequired<LiveStacks>();
336 AU.addPreserved<LiveStacks>();
337 AU.addRequired<CalculateSpillWeights>();
338 AU.addRequired<MachineDominatorTree>();
339 AU.addPreserved<MachineDominatorTree>();
340 AU.addRequired<MachineLoopInfo>();
341 AU.addPreserved<MachineLoopInfo>();
342 AU.addRequired<VirtRegMap>();
343 AU.addPreserved<VirtRegMap>();
344 AU.addRequired<LiveRegMatrix>();
345 AU.addPreserved<LiveRegMatrix>();
346 AU.addRequired<EdgeBundles>();
347 AU.addRequired<SpillPlacement>();
348 MachineFunctionPass::getAnalysisUsage(AU);
352 //===----------------------------------------------------------------------===//
353 // LiveRangeEdit delegate methods
354 //===----------------------------------------------------------------------===//
356 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
357 if (VRM->hasPhys(VirtReg)) {
358 Matrix->unassign(LIS->getInterval(VirtReg));
361 // Unassigned virtreg is probably in the priority queue.
362 // RegAllocBase will erase it after dequeueing.
366 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
367 if (!VRM->hasPhys(VirtReg))
370 // Register is assigned, put it back on the queue for reassignment.
371 LiveInterval &LI = LIS->getInterval(VirtReg);
372 Matrix->unassign(LI);
376 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
377 // Cloning a register we haven't even heard about yet? Just ignore it.
378 if (!ExtraRegInfo.inBounds(Old))
381 // LRE may clone a virtual register because dead code elimination causes it to
382 // be split into connected components. The new components are much smaller
383 // than the original, so they should get a new chance at being assigned.
384 // same stage as the parent.
385 ExtraRegInfo[Old].Stage = RS_Assign;
386 ExtraRegInfo.grow(New);
387 ExtraRegInfo[New] = ExtraRegInfo[Old];
390 void RAGreedy::releaseMemory() {
391 SpillerInstance.reset(0);
392 ExtraRegInfo.clear();
396 void RAGreedy::enqueue(LiveInterval *LI) {
397 // Prioritize live ranges by size, assigning larger ranges first.
398 // The queue holds (size, reg) pairs.
399 const unsigned Size = LI->getSize();
400 const unsigned Reg = LI->reg;
401 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
402 "Can only enqueue virtual registers");
405 ExtraRegInfo.grow(Reg);
406 if (ExtraRegInfo[Reg].Stage == RS_New)
407 ExtraRegInfo[Reg].Stage = RS_Assign;
409 if (ExtraRegInfo[Reg].Stage == RS_Split) {
410 // Unsplit ranges that couldn't be allocated immediately are deferred until
411 // everything else has been allocated.
414 // Everything is allocated in long->short order. Long ranges that don't fit
415 // should be spilled (or split) ASAP so they don't create interference.
416 Prio = (1u << 31) + Size;
418 // Boost ranges that have a physical register hint.
419 if (VRM->hasKnownPreference(Reg))
423 Queue.push(std::make_pair(Prio, ~Reg));
426 LiveInterval *RAGreedy::dequeue() {
429 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
435 //===----------------------------------------------------------------------===//
437 //===----------------------------------------------------------------------===//
439 /// tryAssign - Try to assign VirtReg to an available register.
440 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
441 AllocationOrder &Order,
442 SmallVectorImpl<LiveInterval*> &NewVRegs) {
445 while ((PhysReg = Order.next()))
446 if (!Matrix->checkInterference(VirtReg, PhysReg))
448 if (!PhysReg || Order.isHint())
451 // PhysReg is available, but there may be a better choice.
453 // If we missed a simple hint, try to cheaply evict interference from the
454 // preferred register.
455 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
456 if (Order.isHint(Hint)) {
457 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
458 EvictionCost MaxCost(1);
459 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
460 evictInterference(VirtReg, Hint, NewVRegs);
465 // Try to evict interference from a cheaper alternative.
466 unsigned Cost = TRI->getCostPerUse(PhysReg);
468 // Most registers have 0 additional cost.
472 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
474 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
475 return CheapReg ? CheapReg : PhysReg;
479 //===----------------------------------------------------------------------===//
480 // Interference eviction
481 //===----------------------------------------------------------------------===//
483 /// shouldEvict - determine if A should evict the assigned live range B. The
484 /// eviction policy defined by this function together with the allocation order
485 /// defined by enqueue() decides which registers ultimately end up being split
488 /// Cascade numbers are used to prevent infinite loops if this function is a
491 /// @param A The live range to be assigned.
492 /// @param IsHint True when A is about to be assigned to its preferred
494 /// @param B The live range to be evicted.
495 /// @param BreaksHint True when B is already assigned to its preferred register.
496 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
497 LiveInterval &B, bool BreaksHint) {
498 bool CanSplit = getStage(B) < RS_Spill;
500 // Be fairly aggressive about following hints as long as the evictee can be
502 if (CanSplit && IsHint && !BreaksHint)
505 return A.weight > B.weight;
508 /// canEvictInterference - Return true if all interferences between VirtReg and
509 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
511 /// @param VirtReg Live range that is about to be assigned.
512 /// @param PhysReg Desired register for assignment.
513 /// @param IsHint True when PhysReg is VirtReg's preferred register.
514 /// @param MaxCost Only look for cheaper candidates and update with new cost
515 /// when returning true.
516 /// @returns True when interference can be evicted cheaper than MaxCost.
517 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
518 bool IsHint, EvictionCost &MaxCost) {
519 // It is only possible to evict virtual register interference.
520 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
523 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
524 // involved in an eviction before. If a cascade number was assigned, deny
525 // evicting anything with the same or a newer cascade number. This prevents
526 // infinite eviction loops.
528 // This works out so a register without a cascade number is allowed to evict
529 // anything, and it can be evicted by anything.
530 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
532 Cascade = NextCascade;
535 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
536 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
537 // If there is 10 or more interferences, chances are one is heavier.
538 if (Q.collectInterferingVRegs(10) >= 10)
541 // Check if any interfering live range is heavier than MaxWeight.
542 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
543 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
544 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
545 "Only expecting virtual register interference from query");
546 // Never evict spill products. They cannot split or spill.
547 if (getStage(*Intf) == RS_Done)
549 // Once a live range becomes small enough, it is urgent that we find a
550 // register for it. This is indicated by an infinite spill weight. These
551 // urgent live ranges get to evict almost anything.
553 // Also allow urgent evictions of unspillable ranges from a strictly
554 // larger allocation order.
555 bool Urgent = !VirtReg.isSpillable() &&
556 (Intf->isSpillable() ||
557 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
558 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
559 // Only evict older cascades or live ranges without a cascade.
560 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
561 if (Cascade <= IntfCascade) {
564 // We permit breaking cascades for urgent evictions. It should be the
565 // last resort, though, so make it really expensive.
566 Cost.BrokenHints += 10;
568 // Would this break a satisfied hint?
569 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
570 // Update eviction cost.
571 Cost.BrokenHints += BreaksHint;
572 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
573 // Abort if this would be too expensive.
574 if (!(Cost < MaxCost))
576 // Finally, apply the eviction policy for non-urgent evictions.
577 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
585 /// evictInterference - Evict any interferring registers that prevent VirtReg
586 /// from being assigned to Physreg. This assumes that canEvictInterference
588 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
589 SmallVectorImpl<LiveInterval*> &NewVRegs) {
590 // Make sure that VirtReg has a cascade number, and assign that cascade
591 // number to every evicted register. These live ranges than then only be
592 // evicted by a newer cascade, preventing infinite loops.
593 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
595 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
597 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
598 << " interference: Cascade " << Cascade << '\n');
600 // Collect all interfering virtregs first.
601 SmallVector<LiveInterval*, 8> Intfs;
602 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
603 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
604 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
605 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
606 Intfs.append(IVR.begin(), IVR.end());
609 // Evict them second. This will invalidate the queries.
610 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
611 LiveInterval *Intf = Intfs[i];
612 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
613 if (!VRM->hasPhys(Intf->reg))
615 Matrix->unassign(*Intf);
616 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
617 VirtReg.isSpillable() < Intf->isSpillable()) &&
618 "Cannot decrease cascade number, illegal eviction");
619 ExtraRegInfo[Intf->reg].Cascade = Cascade;
621 NewVRegs.push_back(Intf);
625 /// tryEvict - Try to evict all interferences for a physreg.
626 /// @param VirtReg Currently unassigned virtual register.
627 /// @param Order Physregs to try.
628 /// @return Physreg to assign VirtReg, or 0.
629 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
630 AllocationOrder &Order,
631 SmallVectorImpl<LiveInterval*> &NewVRegs,
632 unsigned CostPerUseLimit) {
633 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
635 // Keep track of the cheapest interference seen so far.
636 EvictionCost BestCost(~0u);
637 unsigned BestPhys = 0;
638 unsigned OrderLimit = Order.getOrder().size();
640 // When we are just looking for a reduced cost per use, don't break any
641 // hints, and only evict smaller spill weights.
642 if (CostPerUseLimit < ~0u) {
643 BestCost.BrokenHints = 0;
644 BestCost.MaxWeight = VirtReg.weight;
646 // Check of any registers in RC are below CostPerUseLimit.
647 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
648 unsigned MinCost = RegClassInfo.getMinCost(RC);
649 if (MinCost >= CostPerUseLimit) {
650 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
651 << ", no cheaper registers to be found.\n");
655 // It is normal for register classes to have a long tail of registers with
656 // the same cost. We don't need to look at them if they're too expensive.
657 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
658 OrderLimit = RegClassInfo.getLastCostChange(RC);
659 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
664 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
665 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
667 // The first use of a callee-saved register in a function has cost 1.
668 // Don't start using a CSR when the CostPerUseLimit is low.
669 if (CostPerUseLimit == 1)
670 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
671 if (!MRI->isPhysRegUsed(CSR)) {
672 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
673 << PrintReg(CSR, TRI) << '\n');
677 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
683 // Stop if the hint can be used.
691 evictInterference(VirtReg, BestPhys, NewVRegs);
696 //===----------------------------------------------------------------------===//
698 //===----------------------------------------------------------------------===//
700 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
701 /// interference pattern in Physreg and its aliases. Add the constraints to
702 /// SpillPlacement and return the static cost of this split in Cost, assuming
703 /// that all preferences in SplitConstraints are met.
704 /// Return false if there are no bundles with positive bias.
705 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
707 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
709 // Reset interference dependent info.
710 SplitConstraints.resize(UseBlocks.size());
711 float StaticCost = 0;
712 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
713 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
714 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
716 BC.Number = BI.MBB->getNumber();
717 Intf.moveToBlock(BC.Number);
718 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
719 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
720 BC.ChangesValue = BI.FirstDef.isValid();
722 if (!Intf.hasInterference())
725 // Number of spill code instructions to insert.
728 // Interference for the live-in value.
730 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
731 BC.Entry = SpillPlacement::MustSpill, ++Ins;
732 else if (Intf.first() < BI.FirstInstr)
733 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
734 else if (Intf.first() < BI.LastInstr)
738 // Interference for the live-out value.
740 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
741 BC.Exit = SpillPlacement::MustSpill, ++Ins;
742 else if (Intf.last() > BI.LastInstr)
743 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
744 else if (Intf.last() > BI.FirstInstr)
748 // Accumulate the total frequency of inserted spill code.
750 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
754 // Add constraints for use-blocks. Note that these are the only constraints
755 // that may add a positive bias, it is downhill from here.
756 SpillPlacer->addConstraints(SplitConstraints);
757 return SpillPlacer->scanActiveBundles();
761 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
762 /// live-through blocks in Blocks.
763 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
764 ArrayRef<unsigned> Blocks) {
765 const unsigned GroupSize = 8;
766 SpillPlacement::BlockConstraint BCS[GroupSize];
767 unsigned TBS[GroupSize];
768 unsigned B = 0, T = 0;
770 for (unsigned i = 0; i != Blocks.size(); ++i) {
771 unsigned Number = Blocks[i];
772 Intf.moveToBlock(Number);
774 if (!Intf.hasInterference()) {
775 assert(T < GroupSize && "Array overflow");
777 if (++T == GroupSize) {
778 SpillPlacer->addLinks(makeArrayRef(TBS, T));
784 assert(B < GroupSize && "Array overflow");
785 BCS[B].Number = Number;
787 // Interference for the live-in value.
788 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
789 BCS[B].Entry = SpillPlacement::MustSpill;
791 BCS[B].Entry = SpillPlacement::PrefSpill;
793 // Interference for the live-out value.
794 if (Intf.last() >= SA->getLastSplitPoint(Number))
795 BCS[B].Exit = SpillPlacement::MustSpill;
797 BCS[B].Exit = SpillPlacement::PrefSpill;
799 if (++B == GroupSize) {
800 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
801 SpillPlacer->addConstraints(Array);
806 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
807 SpillPlacer->addConstraints(Array);
808 SpillPlacer->addLinks(makeArrayRef(TBS, T));
811 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
812 // Keep track of through blocks that have not been added to SpillPlacer.
813 BitVector Todo = SA->getThroughBlocks();
814 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
815 unsigned AddedTo = 0;
817 unsigned Visited = 0;
821 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
822 // Find new through blocks in the periphery of PrefRegBundles.
823 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
824 unsigned Bundle = NewBundles[i];
825 // Look at all blocks connected to Bundle in the full graph.
826 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
827 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
830 if (!Todo.test(Block))
833 // This is a new through block. Add it to SpillPlacer later.
834 ActiveBlocks.push_back(Block);
840 // Any new blocks to add?
841 if (ActiveBlocks.size() == AddedTo)
844 // Compute through constraints from the interference, or assume that all
845 // through blocks prefer spilling when forming compact regions.
846 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
848 addThroughConstraints(Cand.Intf, NewBlocks);
850 // Provide a strong negative bias on through blocks to prevent unwanted
851 // liveness on loop backedges.
852 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
853 AddedTo = ActiveBlocks.size();
855 // Perhaps iterating can enable more bundles?
856 SpillPlacer->iterate();
858 DEBUG(dbgs() << ", v=" << Visited);
861 /// calcCompactRegion - Compute the set of edge bundles that should be live
862 /// when splitting the current live range into compact regions. Compact
863 /// regions can be computed without looking at interference. They are the
864 /// regions formed by removing all the live-through blocks from the live range.
866 /// Returns false if the current live range is already compact, or if the
867 /// compact regions would form single block regions anyway.
868 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
869 // Without any through blocks, the live range is already compact.
870 if (!SA->getNumThroughBlocks())
873 // Compact regions don't correspond to any physreg.
874 Cand.reset(IntfCache, 0);
876 DEBUG(dbgs() << "Compact region bundles");
878 // Use the spill placer to determine the live bundles. GrowRegion pretends
879 // that all the through blocks have interference when PhysReg is unset.
880 SpillPlacer->prepare(Cand.LiveBundles);
882 // The static split cost will be zero since Cand.Intf reports no interference.
884 if (!addSplitConstraints(Cand.Intf, Cost)) {
885 DEBUG(dbgs() << ", none.\n");
890 SpillPlacer->finish();
892 if (!Cand.LiveBundles.any()) {
893 DEBUG(dbgs() << ", none.\n");
898 for (int i = Cand.LiveBundles.find_first(); i>=0;
899 i = Cand.LiveBundles.find_next(i))
900 dbgs() << " EB#" << i;
906 /// calcSpillCost - Compute how expensive it would be to split the live range in
907 /// SA around all use blocks instead of forming bundle regions.
908 float RAGreedy::calcSpillCost() {
910 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
911 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
912 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
913 unsigned Number = BI.MBB->getNumber();
914 // We normally only need one spill instruction - a load or a store.
915 Cost += SpillPlacer->getBlockFrequency(Number);
917 // Unless the value is redefined in the block.
918 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
919 Cost += SpillPlacer->getBlockFrequency(Number);
924 /// calcGlobalSplitCost - Return the global split cost of following the split
925 /// pattern in LiveBundles. This cost should be added to the local cost of the
926 /// interference pattern in SplitConstraints.
928 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
929 float GlobalCost = 0;
930 const BitVector &LiveBundles = Cand.LiveBundles;
931 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
932 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
933 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
934 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
935 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
936 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
940 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
942 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
944 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
947 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
948 unsigned Number = Cand.ActiveBlocks[i];
949 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
950 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
951 if (!RegIn && !RegOut)
953 if (RegIn && RegOut) {
954 // We need double spill code if this block has interference.
955 Cand.Intf.moveToBlock(Number);
956 if (Cand.Intf.hasInterference())
957 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
960 // live-in / stack-out or stack-in live-out.
961 GlobalCost += SpillPlacer->getBlockFrequency(Number);
966 /// splitAroundRegion - Split the current live range around the regions
967 /// determined by BundleCand and GlobalCand.
969 /// Before calling this function, GlobalCand and BundleCand must be initialized
970 /// so each bundle is assigned to a valid candidate, or NoCand for the
971 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
972 /// objects must be initialized for the current live range, and intervals
973 /// created for the used candidates.
975 /// @param LREdit The LiveRangeEdit object handling the current split.
976 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
977 /// must appear in this list.
978 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
979 ArrayRef<unsigned> UsedCands) {
980 // These are the intervals created for new global ranges. We may create more
981 // intervals for local ranges.
982 const unsigned NumGlobalIntvs = LREdit.size();
983 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
984 assert(NumGlobalIntvs && "No global intervals configured");
986 // Isolate even single instructions when dealing with a proper sub-class.
987 // That guarantees register class inflation for the stack interval because it
989 unsigned Reg = SA->getParent().reg;
990 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
992 // First handle all the blocks with uses.
993 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
994 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
995 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
996 unsigned Number = BI.MBB->getNumber();
997 unsigned IntvIn = 0, IntvOut = 0;
998 SlotIndex IntfIn, IntfOut;
1000 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1001 if (CandIn != NoCand) {
1002 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1003 IntvIn = Cand.IntvIdx;
1004 Cand.Intf.moveToBlock(Number);
1005 IntfIn = Cand.Intf.first();
1009 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1010 if (CandOut != NoCand) {
1011 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1012 IntvOut = Cand.IntvIdx;
1013 Cand.Intf.moveToBlock(Number);
1014 IntfOut = Cand.Intf.last();
1018 // Create separate intervals for isolated blocks with multiple uses.
1019 if (!IntvIn && !IntvOut) {
1020 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1021 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1022 SE->splitSingleBlock(BI);
1026 if (IntvIn && IntvOut)
1027 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1029 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1031 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1034 // Handle live-through blocks. The relevant live-through blocks are stored in
1035 // the ActiveBlocks list with each candidate. We need to filter out
1037 BitVector Todo = SA->getThroughBlocks();
1038 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1039 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1040 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1041 unsigned Number = Blocks[i];
1042 if (!Todo.test(Number))
1046 unsigned IntvIn = 0, IntvOut = 0;
1047 SlotIndex IntfIn, IntfOut;
1049 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1050 if (CandIn != NoCand) {
1051 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1052 IntvIn = Cand.IntvIdx;
1053 Cand.Intf.moveToBlock(Number);
1054 IntfIn = Cand.Intf.first();
1057 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1058 if (CandOut != NoCand) {
1059 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1060 IntvOut = Cand.IntvIdx;
1061 Cand.Intf.moveToBlock(Number);
1062 IntfOut = Cand.Intf.last();
1064 if (!IntvIn && !IntvOut)
1066 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1072 SmallVector<unsigned, 8> IntvMap;
1073 SE->finish(&IntvMap);
1074 DebugVars->splitRegister(Reg, LREdit.regs());
1076 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1077 unsigned OrigBlocks = SA->getNumLiveBlocks();
1079 // Sort out the new intervals created by splitting. We get four kinds:
1080 // - Remainder intervals should not be split again.
1081 // - Candidate intervals can be assigned to Cand.PhysReg.
1082 // - Block-local splits are candidates for local splitting.
1083 // - DCE leftovers should go back on the queue.
1084 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1085 LiveInterval &Reg = *LREdit.get(i);
1087 // Ignore old intervals from DCE.
1088 if (getStage(Reg) != RS_New)
1091 // Remainder interval. Don't try splitting again, spill if it doesn't
1093 if (IntvMap[i] == 0) {
1094 setStage(Reg, RS_Spill);
1098 // Global intervals. Allow repeated splitting as long as the number of live
1099 // blocks is strictly decreasing.
1100 if (IntvMap[i] < NumGlobalIntvs) {
1101 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1102 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1103 << " blocks as original.\n");
1104 // Don't allow repeated splitting as a safe guard against looping.
1105 setStage(Reg, RS_Split2);
1110 // Other intervals are treated as new. This includes local intervals created
1111 // for blocks with multiple uses, and anything created by DCE.
1115 MF->verify(this, "After splitting live range around region");
1118 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1119 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1120 unsigned NumCands = 0;
1121 unsigned BestCand = NoCand;
1123 SmallVector<unsigned, 8> UsedCands;
1125 // Check if we can split this live range around a compact region.
1126 bool HasCompact = calcCompactRegion(GlobalCand.front());
1128 // Yes, keep GlobalCand[0] as the compact region candidate.
1130 BestCost = HUGE_VALF;
1132 // No benefit from the compact region, our fallback will be per-block
1133 // splitting. Make sure we find a solution that is cheaper than spilling.
1134 BestCost = Hysteresis * calcSpillCost();
1135 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1139 while (unsigned PhysReg = Order.next()) {
1140 // Discard bad candidates before we run out of interference cache cursors.
1141 // This will only affect register classes with a lot of registers (>32).
1142 if (NumCands == IntfCache.getMaxCursors()) {
1143 unsigned WorstCount = ~0u;
1145 for (unsigned i = 0; i != NumCands; ++i) {
1146 if (i == BestCand || !GlobalCand[i].PhysReg)
1148 unsigned Count = GlobalCand[i].LiveBundles.count();
1149 if (Count < WorstCount)
1150 Worst = i, WorstCount = Count;
1153 GlobalCand[Worst] = GlobalCand[NumCands];
1154 if (BestCand == NumCands)
1158 if (GlobalCand.size() <= NumCands)
1159 GlobalCand.resize(NumCands+1);
1160 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1161 Cand.reset(IntfCache, PhysReg);
1163 SpillPlacer->prepare(Cand.LiveBundles);
1165 if (!addSplitConstraints(Cand.Intf, Cost)) {
1166 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1169 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1170 if (Cost >= BestCost) {
1172 if (BestCand == NoCand)
1173 dbgs() << " worse than no bundles\n";
1175 dbgs() << " worse than "
1176 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1182 SpillPlacer->finish();
1184 // No live bundles, defer to splitSingleBlocks().
1185 if (!Cand.LiveBundles.any()) {
1186 DEBUG(dbgs() << " no bundles.\n");
1190 Cost += calcGlobalSplitCost(Cand);
1192 dbgs() << ", total = " << Cost << " with bundles";
1193 for (int i = Cand.LiveBundles.find_first(); i>=0;
1194 i = Cand.LiveBundles.find_next(i))
1195 dbgs() << " EB#" << i;
1198 if (Cost < BestCost) {
1199 BestCand = NumCands;
1200 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1205 // No solutions found, fall back to single block splitting.
1206 if (!HasCompact && BestCand == NoCand)
1209 // Prepare split editor.
1210 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1211 SE->reset(LREdit, SplitSpillMode);
1213 // Assign all edge bundles to the preferred candidate, or NoCand.
1214 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1216 // Assign bundles for the best candidate region.
1217 if (BestCand != NoCand) {
1218 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1219 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1220 UsedCands.push_back(BestCand);
1221 Cand.IntvIdx = SE->openIntv();
1222 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1223 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1228 // Assign bundles for the compact region.
1230 GlobalSplitCandidate &Cand = GlobalCand.front();
1231 assert(!Cand.PhysReg && "Compact region has no physreg");
1232 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1233 UsedCands.push_back(0);
1234 Cand.IntvIdx = SE->openIntv();
1235 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1236 << Cand.IntvIdx << ".\n");
1241 splitAroundRegion(LREdit, UsedCands);
1246 //===----------------------------------------------------------------------===//
1247 // Per-Block Splitting
1248 //===----------------------------------------------------------------------===//
1250 /// tryBlockSplit - Split a global live range around every block with uses. This
1251 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1252 /// they don't allocate.
1253 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1254 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1255 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1256 unsigned Reg = VirtReg.reg;
1257 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1258 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1259 SE->reset(LREdit, SplitSpillMode);
1260 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1261 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1262 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1263 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1264 SE->splitSingleBlock(BI);
1266 // No blocks were split.
1270 // We did split for some blocks.
1271 SmallVector<unsigned, 8> IntvMap;
1272 SE->finish(&IntvMap);
1274 // Tell LiveDebugVariables about the new ranges.
1275 DebugVars->splitRegister(Reg, LREdit.regs());
1277 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1279 // Sort out the new intervals created by splitting. The remainder interval
1280 // goes straight to spilling, the new local ranges get to stay RS_New.
1281 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1282 LiveInterval &LI = *LREdit.get(i);
1283 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1284 setStage(LI, RS_Spill);
1288 MF->verify(this, "After splitting live range around basic blocks");
1293 //===----------------------------------------------------------------------===//
1294 // Per-Instruction Splitting
1295 //===----------------------------------------------------------------------===//
1297 /// tryInstructionSplit - Split a live range around individual instructions.
1298 /// This is normally not worthwhile since the spiller is doing essentially the
1299 /// same thing. However, when the live range is in a constrained register
1300 /// class, it may help to insert copies such that parts of the live range can
1301 /// be moved to a larger register class.
1303 /// This is similar to spilling to a larger register class.
1305 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1306 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1307 // There is no point to this if there are no larger sub-classes.
1308 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1311 // Always enable split spill mode, since we're effectively spilling to a
1313 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1314 SE->reset(LREdit, SplitEditor::SM_Size);
1316 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1317 if (Uses.size() <= 1)
1320 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1322 // Split around every non-copy instruction.
1323 for (unsigned i = 0; i != Uses.size(); ++i) {
1324 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1325 if (MI->isFullCopy()) {
1326 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1330 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1331 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1332 SE->useIntv(SegStart, SegStop);
1335 if (LREdit.empty()) {
1336 DEBUG(dbgs() << "All uses were copies.\n");
1340 SmallVector<unsigned, 8> IntvMap;
1341 SE->finish(&IntvMap);
1342 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1343 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1345 // Assign all new registers to RS_Spill. This was the last chance.
1346 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1351 //===----------------------------------------------------------------------===//
1353 //===----------------------------------------------------------------------===//
1356 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1357 /// in order to use PhysReg between two entries in SA->UseSlots.
1359 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1361 void RAGreedy::calcGapWeights(unsigned PhysReg,
1362 SmallVectorImpl<float> &GapWeight) {
1363 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1364 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1365 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1366 const unsigned NumGaps = Uses.size()-1;
1368 // Start and end points for the interference check.
1369 SlotIndex StartIdx =
1370 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1372 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1374 GapWeight.assign(NumGaps, 0.0f);
1376 // Add interference from each overlapping register.
1377 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1378 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1379 .checkInterference())
1382 // We know that VirtReg is a continuous interval from FirstInstr to
1383 // LastInstr, so we don't need InterferenceQuery.
1385 // Interference that overlaps an instruction is counted in both gaps
1386 // surrounding the instruction. The exception is interference before
1387 // StartIdx and after StopIdx.
1389 LiveIntervalUnion::SegmentIter IntI =
1390 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1391 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1392 // Skip the gaps before IntI.
1393 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1394 if (++Gap == NumGaps)
1399 // Update the gaps covered by IntI.
1400 const float weight = IntI.value()->weight;
1401 for (; Gap != NumGaps; ++Gap) {
1402 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1403 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1411 // Add fixed interference.
1412 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1413 const LiveInterval &LI = LIS->getRegUnit(*Units);
1414 LiveInterval::const_iterator I = LI.find(StartIdx);
1415 LiveInterval::const_iterator E = LI.end();
1417 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1418 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1419 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1420 if (++Gap == NumGaps)
1425 for (; Gap != NumGaps; ++Gap) {
1426 GapWeight[Gap] = HUGE_VALF;
1427 if (Uses[Gap+1].getBaseIndex() >= I->end)
1436 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1439 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1440 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1441 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1442 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1444 // Note that it is possible to have an interval that is live-in or live-out
1445 // while only covering a single block - A phi-def can use undef values from
1446 // predecessors, and the block could be a single-block loop.
1447 // We don't bother doing anything clever about such a case, we simply assume
1448 // that the interval is continuous from FirstInstr to LastInstr. We should
1449 // make sure that we don't do anything illegal to such an interval, though.
1451 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1452 if (Uses.size() <= 2)
1454 const unsigned NumGaps = Uses.size()-1;
1457 dbgs() << "tryLocalSplit: ";
1458 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1459 dbgs() << ' ' << Uses[i];
1463 // If VirtReg is live across any register mask operands, compute a list of
1464 // gaps with register masks.
1465 SmallVector<unsigned, 8> RegMaskGaps;
1466 if (Matrix->checkRegMaskInterference(VirtReg)) {
1467 // Get regmask slots for the whole block.
1468 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1469 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1470 // Constrain to VirtReg's live range.
1471 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1472 Uses.front().getRegSlot()) - RMS.begin();
1473 unsigned re = RMS.size();
1474 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1475 // Look for Uses[i] <= RMS <= Uses[i+1].
1476 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1477 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1479 // Skip a regmask on the same instruction as the last use. It doesn't
1480 // overlap the live range.
1481 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1483 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1484 RegMaskGaps.push_back(i);
1485 // Advance ri to the next gap. A regmask on one of the uses counts in
1487 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1490 DEBUG(dbgs() << '\n');
1493 // Since we allow local split results to be split again, there is a risk of
1494 // creating infinite loops. It is tempting to require that the new live
1495 // ranges have less instructions than the original. That would guarantee
1496 // convergence, but it is too strict. A live range with 3 instructions can be
1497 // split 2+3 (including the COPY), and we want to allow that.
1499 // Instead we use these rules:
1501 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1502 // noop split, of course).
1503 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1504 // the new ranges must have fewer instructions than before the split.
1505 // 3. New ranges with the same number of instructions are marked RS_Split2,
1506 // smaller ranges are marked RS_New.
1508 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1509 // excessive splitting and infinite loops.
1511 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1513 // Best split candidate.
1514 unsigned BestBefore = NumGaps;
1515 unsigned BestAfter = 0;
1518 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1519 SmallVector<float, 8> GapWeight;
1522 while (unsigned PhysReg = Order.next()) {
1523 // Keep track of the largest spill weight that would need to be evicted in
1524 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1525 calcGapWeights(PhysReg, GapWeight);
1527 // Remove any gaps with regmask clobbers.
1528 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1529 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1530 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1532 // Try to find the best sequence of gaps to close.
1533 // The new spill weight must be larger than any gap interference.
1535 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1536 unsigned SplitBefore = 0, SplitAfter = 1;
1538 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1539 // It is the spill weight that needs to be evicted.
1540 float MaxGap = GapWeight[0];
1543 // Live before/after split?
1544 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1545 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1547 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1548 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1549 << " i=" << MaxGap);
1551 // Stop before the interval gets so big we wouldn't be making progress.
1552 if (!LiveBefore && !LiveAfter) {
1553 DEBUG(dbgs() << " all\n");
1556 // Should the interval be extended or shrunk?
1559 // How many gaps would the new range have?
1560 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1562 // Legally, without causing looping?
1563 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1565 if (Legal && MaxGap < HUGE_VALF) {
1566 // Estimate the new spill weight. Each instruction reads or writes the
1567 // register. Conservatively assume there are no read-modify-write
1570 // Try to guess the size of the new interval.
1571 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1572 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1573 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1574 // Would this split be possible to allocate?
1575 // Never allocate all gaps, we wouldn't be making progress.
1576 DEBUG(dbgs() << " w=" << EstWeight);
1577 if (EstWeight * Hysteresis >= MaxGap) {
1579 float Diff = EstWeight - MaxGap;
1580 if (Diff > BestDiff) {
1581 DEBUG(dbgs() << " (best)");
1582 BestDiff = Hysteresis * Diff;
1583 BestBefore = SplitBefore;
1584 BestAfter = SplitAfter;
1591 if (++SplitBefore < SplitAfter) {
1592 DEBUG(dbgs() << " shrink\n");
1593 // Recompute the max when necessary.
1594 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1595 MaxGap = GapWeight[SplitBefore];
1596 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1597 MaxGap = std::max(MaxGap, GapWeight[i]);
1604 // Try to extend the interval.
1605 if (SplitAfter >= NumGaps) {
1606 DEBUG(dbgs() << " end\n");
1610 DEBUG(dbgs() << " extend\n");
1611 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1615 // Didn't find any candidates?
1616 if (BestBefore == NumGaps)
1619 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1620 << '-' << Uses[BestAfter] << ", " << BestDiff
1621 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1623 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1627 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1628 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1629 SE->useIntv(SegStart, SegStop);
1630 SmallVector<unsigned, 8> IntvMap;
1631 SE->finish(&IntvMap);
1632 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1634 // If the new range has the same number of instructions as before, mark it as
1635 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1636 // leave the new intervals as RS_New so they can compete.
1637 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1638 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1639 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1640 if (NewGaps >= NumGaps) {
1641 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1642 assert(!ProgressRequired && "Didn't make progress when it was required.");
1643 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1644 if (IntvMap[i] == 1) {
1645 setStage(*LREdit.get(i), RS_Split2);
1646 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1648 DEBUG(dbgs() << '\n');
1655 //===----------------------------------------------------------------------===//
1656 // Live Range Splitting
1657 //===----------------------------------------------------------------------===//
1659 /// trySplit - Try to split VirtReg or one of its interferences, making it
1661 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1662 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1663 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1664 // Ranges must be Split2 or less.
1665 if (getStage(VirtReg) >= RS_Spill)
1668 // Local intervals are handled separately.
1669 if (LIS->intervalIsInOneMBB(VirtReg)) {
1670 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1671 SA->analyze(&VirtReg);
1672 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1673 if (PhysReg || !NewVRegs.empty())
1675 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1678 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1680 SA->analyze(&VirtReg);
1682 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1683 // coalescer. That may cause the range to become allocatable which means that
1684 // tryRegionSplit won't be making progress. This check should be replaced with
1685 // an assertion when the coalescer is fixed.
1686 if (SA->didRepairRange()) {
1687 // VirtReg has changed, so all cached queries are invalid.
1688 Matrix->invalidateVirtRegs();
1689 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1693 // First try to split around a region spanning multiple blocks. RS_Split2
1694 // ranges already made dubious progress with region splitting, so they go
1695 // straight to single block splitting.
1696 if (getStage(VirtReg) < RS_Split2) {
1697 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1698 if (PhysReg || !NewVRegs.empty())
1702 // Then isolate blocks.
1703 return tryBlockSplit(VirtReg, Order, NewVRegs);
1707 //===----------------------------------------------------------------------===//
1709 //===----------------------------------------------------------------------===//
1711 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1712 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1713 // First try assigning a free register.
1714 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1715 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1718 LiveRangeStage Stage = getStage(VirtReg);
1719 DEBUG(dbgs() << StageName[Stage]
1720 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1722 // Try to evict a less worthy live range, but only for ranges from the primary
1723 // queue. The RS_Split ranges already failed to do this, and they should not
1724 // get a second chance until they have been split.
1725 if (Stage != RS_Split)
1726 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1729 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1731 // The first time we see a live range, don't try to split or spill.
1732 // Wait until the second time, when all smaller ranges have been allocated.
1733 // This gives a better picture of the interference to split around.
1734 if (Stage < RS_Split) {
1735 setStage(VirtReg, RS_Split);
1736 DEBUG(dbgs() << "wait for second round\n");
1737 NewVRegs.push_back(&VirtReg);
1741 // If we couldn't allocate a register from spilling, there is probably some
1742 // invalid inline assembly. The base class wil report it.
1743 if (Stage >= RS_Done || !VirtReg.isSpillable())
1746 // Try splitting VirtReg or interferences.
1747 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1748 if (PhysReg || !NewVRegs.empty())
1751 // Finally spill VirtReg itself.
1752 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1753 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1754 spiller().spill(LRE);
1755 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1758 MF->verify(this, "After spilling");
1760 // The live virtual register requesting allocation was spilled, so tell
1761 // the caller not to allocate anything during this round.
1765 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1766 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1767 << "********** Function: " << mf.getName() << '\n');
1771 MF->verify(this, "Before greedy register allocator");
1773 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1774 getAnalysis<LiveIntervals>(),
1775 getAnalysis<LiveRegMatrix>());
1776 Indexes = &getAnalysis<SlotIndexes>();
1777 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1778 DomTree = &getAnalysis<MachineDominatorTree>();
1779 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1780 Loops = &getAnalysis<MachineLoopInfo>();
1781 Bundles = &getAnalysis<EdgeBundles>();
1782 SpillPlacer = &getAnalysis<SpillPlacement>();
1783 DebugVars = &getAnalysis<LiveDebugVariables>();
1785 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1786 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1787 ExtraRegInfo.clear();
1788 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1790 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1791 GlobalCand.resize(32); // This will grow as needed.