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.
124 static const char *const StageName[];
127 // RegInfo - Keep additional information about each live range.
129 LiveRangeStage Stage;
131 // Cascade - Eviction loop prevention. See canEvictInterference().
134 RegInfo() : Stage(RS_New), Cascade(0) {}
137 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
139 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
140 return ExtraRegInfo[VirtReg.reg].Stage;
143 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
144 ExtraRegInfo.resize(MRI->getNumVirtRegs());
145 ExtraRegInfo[VirtReg.reg].Stage = Stage;
148 template<typename Iterator>
149 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
151 for (;Begin != End; ++Begin) {
152 unsigned Reg = *Begin;
153 if (ExtraRegInfo[Reg].Stage == RS_New)
154 ExtraRegInfo[Reg].Stage = NewStage;
158 /// Cost of evicting interference.
159 struct EvictionCost {
160 unsigned BrokenHints; ///< Total number of broken hints.
161 float MaxWeight; ///< Maximum spill weight evicted.
163 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
165 bool isMax() const { return BrokenHints == ~0u; }
167 void setMax() { BrokenHints = ~0u; }
169 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
179 OwningPtr<SplitAnalysis> SA;
180 OwningPtr<SplitEditor> SE;
182 /// Cached per-block interference maps
183 InterferenceCache IntfCache;
185 /// All basic blocks where the current register has uses.
186 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
188 /// Global live range splitting candidate info.
189 struct GlobalSplitCandidate {
190 // Register intended for assignment, or 0.
193 // SplitKit interval index for this candidate.
196 // Interference for PhysReg.
197 InterferenceCache::Cursor Intf;
199 // Bundles where this candidate should be live.
200 BitVector LiveBundles;
201 SmallVector<unsigned, 8> ActiveBlocks;
203 void reset(InterferenceCache &Cache, unsigned Reg) {
206 Intf.setPhysReg(Cache, Reg);
208 ActiveBlocks.clear();
211 // Set B[i] = C for every live bundle where B[i] was NoCand.
212 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
214 for (int i = LiveBundles.find_first(); i >= 0;
215 i = LiveBundles.find_next(i))
216 if (B[i] == NoCand) {
224 /// Candidate info for each PhysReg in AllocationOrder.
225 /// This vector never shrinks, but grows to the size of the largest register
227 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
229 enum LLVM_ENUM_INT_TYPE(unsigned) { NoCand = ~0u };
231 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
232 /// NoCand which indicates the stack interval.
233 SmallVector<unsigned, 32> BundleCand;
238 /// Return the pass name.
239 virtual const char* getPassName() const {
240 return "Greedy Register Allocator";
243 /// RAGreedy analysis usage.
244 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
245 virtual void releaseMemory();
246 virtual Spiller &spiller() { return *SpillerInstance; }
247 virtual void enqueue(LiveInterval *LI);
248 virtual LiveInterval *dequeue();
249 virtual unsigned selectOrSplit(LiveInterval&,
250 SmallVectorImpl<unsigned>&);
252 /// Perform register allocation.
253 virtual bool runOnMachineFunction(MachineFunction &mf);
258 bool LRE_CanEraseVirtReg(unsigned);
259 void LRE_WillShrinkVirtReg(unsigned);
260 void LRE_DidCloneVirtReg(unsigned, unsigned);
262 BlockFrequency calcSpillCost();
263 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
264 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
265 void growRegion(GlobalSplitCandidate &Cand);
266 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
267 bool calcCompactRegion(GlobalSplitCandidate&);
268 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
269 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
270 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
271 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
272 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
273 void evictInterference(LiveInterval&, unsigned,
274 SmallVectorImpl<unsigned>&);
276 unsigned tryAssign(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<unsigned>&);
278 unsigned tryEvict(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<unsigned>&, unsigned = ~0u);
280 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
281 SmallVectorImpl<unsigned>&);
282 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
283 SmallVectorImpl<unsigned>&);
284 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
285 SmallVectorImpl<unsigned>&);
286 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
287 SmallVectorImpl<unsigned>&);
288 unsigned trySplit(LiveInterval&, AllocationOrder&,
289 SmallVectorImpl<unsigned>&);
291 } // end anonymous namespace
293 char RAGreedy::ID = 0;
296 const char *const RAGreedy::StageName[] = {
306 // Hysteresis to use when comparing floats.
307 // This helps stabilize decisions based on float comparisons.
308 const float Hysteresis = 0.98f;
311 FunctionPass* llvm::createGreedyRegisterAllocator() {
312 return new RAGreedy();
315 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
316 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
317 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
318 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
319 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
320 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
321 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
322 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
323 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
324 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
325 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
326 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
327 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
328 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
331 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
332 AU.setPreservesCFG();
333 AU.addRequired<MachineBlockFrequencyInfo>();
334 AU.addPreserved<MachineBlockFrequencyInfo>();
335 AU.addRequired<AliasAnalysis>();
336 AU.addPreserved<AliasAnalysis>();
337 AU.addRequired<LiveIntervals>();
338 AU.addPreserved<LiveIntervals>();
339 AU.addRequired<SlotIndexes>();
340 AU.addPreserved<SlotIndexes>();
341 AU.addRequired<LiveDebugVariables>();
342 AU.addPreserved<LiveDebugVariables>();
343 AU.addRequired<LiveStacks>();
344 AU.addPreserved<LiveStacks>();
345 AU.addRequired<MachineDominatorTree>();
346 AU.addPreserved<MachineDominatorTree>();
347 AU.addRequired<MachineLoopInfo>();
348 AU.addPreserved<MachineLoopInfo>();
349 AU.addRequired<VirtRegMap>();
350 AU.addPreserved<VirtRegMap>();
351 AU.addRequired<LiveRegMatrix>();
352 AU.addPreserved<LiveRegMatrix>();
353 AU.addRequired<EdgeBundles>();
354 AU.addRequired<SpillPlacement>();
355 MachineFunctionPass::getAnalysisUsage(AU);
359 //===----------------------------------------------------------------------===//
360 // LiveRangeEdit delegate methods
361 //===----------------------------------------------------------------------===//
363 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
364 if (VRM->hasPhys(VirtReg)) {
365 Matrix->unassign(LIS->getInterval(VirtReg));
368 // Unassigned virtreg is probably in the priority queue.
369 // RegAllocBase will erase it after dequeueing.
373 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
374 if (!VRM->hasPhys(VirtReg))
377 // Register is assigned, put it back on the queue for reassignment.
378 LiveInterval &LI = LIS->getInterval(VirtReg);
379 Matrix->unassign(LI);
383 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
384 // Cloning a register we haven't even heard about yet? Just ignore it.
385 if (!ExtraRegInfo.inBounds(Old))
388 // LRE may clone a virtual register because dead code elimination causes it to
389 // be split into connected components. The new components are much smaller
390 // than the original, so they should get a new chance at being assigned.
391 // same stage as the parent.
392 ExtraRegInfo[Old].Stage = RS_Assign;
393 ExtraRegInfo.grow(New);
394 ExtraRegInfo[New] = ExtraRegInfo[Old];
397 void RAGreedy::releaseMemory() {
398 SpillerInstance.reset(0);
399 ExtraRegInfo.clear();
403 void RAGreedy::enqueue(LiveInterval *LI) {
404 // Prioritize live ranges by size, assigning larger ranges first.
405 // The queue holds (size, reg) pairs.
406 const unsigned Size = LI->getSize();
407 const unsigned Reg = LI->reg;
408 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
409 "Can only enqueue virtual registers");
412 ExtraRegInfo.grow(Reg);
413 if (ExtraRegInfo[Reg].Stage == RS_New)
414 ExtraRegInfo[Reg].Stage = RS_Assign;
416 if (ExtraRegInfo[Reg].Stage == RS_Split) {
417 // Unsplit ranges that couldn't be allocated immediately are deferred until
418 // everything else has been allocated.
421 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
422 LIS->intervalIsInOneMBB(*LI)) {
423 // Allocate original local ranges in linear instruction order. Since they
424 // are singly defined, this produces optimal coloring in the absence of
425 // global interference and other constraints.
426 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
429 // Allocate global and split ranges in long->short order. Long ranges that
430 // don't fit should be spilled (or split) ASAP so they don't create
431 // interference. Mark a bit to prioritize global above local ranges.
432 Prio = (1u << 29) + Size;
434 // Mark a higher bit to prioritize global and local above RS_Split.
437 // Boost ranges that have a physical register hint.
438 if (VRM->hasKnownPreference(Reg))
441 // The virtual register number is a tie breaker for same-sized ranges.
442 // Give lower vreg numbers higher priority to assign them first.
443 Queue.push(std::make_pair(Prio, ~Reg));
446 LiveInterval *RAGreedy::dequeue() {
449 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
455 //===----------------------------------------------------------------------===//
457 //===----------------------------------------------------------------------===//
459 /// tryAssign - Try to assign VirtReg to an available register.
460 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
461 AllocationOrder &Order,
462 SmallVectorImpl<unsigned> &NewVRegs) {
465 while ((PhysReg = Order.next()))
466 if (!Matrix->checkInterference(VirtReg, PhysReg))
468 if (!PhysReg || Order.isHint())
471 // PhysReg is available, but there may be a better choice.
473 // If we missed a simple hint, try to cheaply evict interference from the
474 // preferred register.
475 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
476 if (Order.isHint(Hint)) {
477 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
478 EvictionCost MaxCost;
479 MaxCost.setBrokenHints(1);
480 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
481 evictInterference(VirtReg, Hint, NewVRegs);
486 // Try to evict interference from a cheaper alternative.
487 unsigned Cost = TRI->getCostPerUse(PhysReg);
489 // Most registers have 0 additional cost.
493 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
495 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
496 return CheapReg ? CheapReg : PhysReg;
500 //===----------------------------------------------------------------------===//
501 // Interference eviction
502 //===----------------------------------------------------------------------===//
504 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
505 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
507 while ((PhysReg = Order.next())) {
508 if (PhysReg == PrevReg)
511 MCRegUnitIterator Units(PhysReg, TRI);
512 for (; Units.isValid(); ++Units) {
513 // Instantiate a "subquery", not to be confused with the Queries array.
514 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
515 if (subQ.checkInterference())
518 // If no units have interference, break out with the current PhysReg.
519 if (!Units.isValid())
523 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
524 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
529 /// shouldEvict - determine if A should evict the assigned live range B. The
530 /// eviction policy defined by this function together with the allocation order
531 /// defined by enqueue() decides which registers ultimately end up being split
534 /// Cascade numbers are used to prevent infinite loops if this function is a
537 /// @param A The live range to be assigned.
538 /// @param IsHint True when A is about to be assigned to its preferred
540 /// @param B The live range to be evicted.
541 /// @param BreaksHint True when B is already assigned to its preferred register.
542 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
543 LiveInterval &B, bool BreaksHint) {
544 bool CanSplit = getStage(B) < RS_Spill;
546 // Be fairly aggressive about following hints as long as the evictee can be
548 if (CanSplit && IsHint && !BreaksHint)
551 return A.weight > B.weight;
554 /// canEvictInterference - Return true if all interferences between VirtReg and
555 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
557 /// @param VirtReg Live range that is about to be assigned.
558 /// @param PhysReg Desired register for assignment.
559 /// @param IsHint True when PhysReg is VirtReg's preferred register.
560 /// @param MaxCost Only look for cheaper candidates and update with new cost
561 /// when returning true.
562 /// @returns True when interference can be evicted cheaper than MaxCost.
563 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
564 bool IsHint, EvictionCost &MaxCost) {
565 // It is only possible to evict virtual register interference.
566 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
569 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
571 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
572 // involved in an eviction before. If a cascade number was assigned, deny
573 // evicting anything with the same or a newer cascade number. This prevents
574 // infinite eviction loops.
576 // This works out so a register without a cascade number is allowed to evict
577 // anything, and it can be evicted by anything.
578 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
580 Cascade = NextCascade;
583 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
584 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
585 // If there is 10 or more interferences, chances are one is heavier.
586 if (Q.collectInterferingVRegs(10) >= 10)
589 // Check if any interfering live range is heavier than MaxWeight.
590 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
591 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
592 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
593 "Only expecting virtual register interference from query");
594 // Never evict spill products. They cannot split or spill.
595 if (getStage(*Intf) == RS_Done)
597 // Once a live range becomes small enough, it is urgent that we find a
598 // register for it. This is indicated by an infinite spill weight. These
599 // urgent live ranges get to evict almost anything.
601 // Also allow urgent evictions of unspillable ranges from a strictly
602 // larger allocation order.
603 bool Urgent = !VirtReg.isSpillable() &&
604 (Intf->isSpillable() ||
605 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
606 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
607 // Only evict older cascades or live ranges without a cascade.
608 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
609 if (Cascade <= IntfCascade) {
612 // We permit breaking cascades for urgent evictions. It should be the
613 // last resort, though, so make it really expensive.
614 Cost.BrokenHints += 10;
616 // Would this break a satisfied hint?
617 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
618 // Update eviction cost.
619 Cost.BrokenHints += BreaksHint;
620 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
621 // Abort if this would be too expensive.
622 if (!(Cost < MaxCost))
626 // If !MaxCost.isMax(), then we're just looking for a cheap register.
627 // Evicting another local live range in this case could lead to suboptimal
629 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
630 !canReassign(*Intf, PhysReg)) {
633 // Finally, apply the eviction policy for non-urgent evictions.
634 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
642 /// evictInterference - Evict any interferring registers that prevent VirtReg
643 /// from being assigned to Physreg. This assumes that canEvictInterference
645 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
646 SmallVectorImpl<unsigned> &NewVRegs) {
647 // Make sure that VirtReg has a cascade number, and assign that cascade
648 // number to every evicted register. These live ranges than then only be
649 // evicted by a newer cascade, preventing infinite loops.
650 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
652 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
654 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
655 << " interference: Cascade " << Cascade << '\n');
657 // Collect all interfering virtregs first.
658 SmallVector<LiveInterval*, 8> Intfs;
659 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
660 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
661 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
662 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
663 Intfs.append(IVR.begin(), IVR.end());
666 // Evict them second. This will invalidate the queries.
667 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
668 LiveInterval *Intf = Intfs[i];
669 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
670 if (!VRM->hasPhys(Intf->reg))
672 Matrix->unassign(*Intf);
673 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
674 VirtReg.isSpillable() < Intf->isSpillable()) &&
675 "Cannot decrease cascade number, illegal eviction");
676 ExtraRegInfo[Intf->reg].Cascade = Cascade;
678 NewVRegs.push_back(Intf->reg);
682 /// tryEvict - Try to evict all interferences for a physreg.
683 /// @param VirtReg Currently unassigned virtual register.
684 /// @param Order Physregs to try.
685 /// @return Physreg to assign VirtReg, or 0.
686 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
687 AllocationOrder &Order,
688 SmallVectorImpl<unsigned> &NewVRegs,
689 unsigned CostPerUseLimit) {
690 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
692 // Keep track of the cheapest interference seen so far.
693 EvictionCost BestCost;
695 unsigned BestPhys = 0;
696 unsigned OrderLimit = Order.getOrder().size();
698 // When we are just looking for a reduced cost per use, don't break any
699 // hints, and only evict smaller spill weights.
700 if (CostPerUseLimit < ~0u) {
701 BestCost.BrokenHints = 0;
702 BestCost.MaxWeight = VirtReg.weight;
704 // Check of any registers in RC are below CostPerUseLimit.
705 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
706 unsigned MinCost = RegClassInfo.getMinCost(RC);
707 if (MinCost >= CostPerUseLimit) {
708 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
709 << ", no cheaper registers to be found.\n");
713 // It is normal for register classes to have a long tail of registers with
714 // the same cost. We don't need to look at them if they're too expensive.
715 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
716 OrderLimit = RegClassInfo.getLastCostChange(RC);
717 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
722 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
723 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
725 // The first use of a callee-saved register in a function has cost 1.
726 // Don't start using a CSR when the CostPerUseLimit is low.
727 if (CostPerUseLimit == 1)
728 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
729 if (!MRI->isPhysRegUsed(CSR)) {
730 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
731 << PrintReg(CSR, TRI) << '\n');
735 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
741 // Stop if the hint can be used.
749 evictInterference(VirtReg, BestPhys, NewVRegs);
754 //===----------------------------------------------------------------------===//
756 //===----------------------------------------------------------------------===//
758 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
759 /// interference pattern in Physreg and its aliases. Add the constraints to
760 /// SpillPlacement and return the static cost of this split in Cost, assuming
761 /// that all preferences in SplitConstraints are met.
762 /// Return false if there are no bundles with positive bias.
763 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
764 BlockFrequency &Cost) {
765 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
767 // Reset interference dependent info.
768 SplitConstraints.resize(UseBlocks.size());
769 BlockFrequency StaticCost = 0;
770 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
771 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
772 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
774 BC.Number = BI.MBB->getNumber();
775 Intf.moveToBlock(BC.Number);
776 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
777 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
778 BC.ChangesValue = BI.FirstDef.isValid();
780 if (!Intf.hasInterference())
783 // Number of spill code instructions to insert.
786 // Interference for the live-in value.
788 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
789 BC.Entry = SpillPlacement::MustSpill, ++Ins;
790 else if (Intf.first() < BI.FirstInstr)
791 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
792 else if (Intf.first() < BI.LastInstr)
796 // Interference for the live-out value.
798 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
799 BC.Exit = SpillPlacement::MustSpill, ++Ins;
800 else if (Intf.last() > BI.LastInstr)
801 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
802 else if (Intf.last() > BI.FirstInstr)
806 // Accumulate the total frequency of inserted spill code.
808 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
812 // Add constraints for use-blocks. Note that these are the only constraints
813 // that may add a positive bias, it is downhill from here.
814 SpillPlacer->addConstraints(SplitConstraints);
815 return SpillPlacer->scanActiveBundles();
819 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
820 /// live-through blocks in Blocks.
821 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
822 ArrayRef<unsigned> Blocks) {
823 const unsigned GroupSize = 8;
824 SpillPlacement::BlockConstraint BCS[GroupSize];
825 unsigned TBS[GroupSize];
826 unsigned B = 0, T = 0;
828 for (unsigned i = 0; i != Blocks.size(); ++i) {
829 unsigned Number = Blocks[i];
830 Intf.moveToBlock(Number);
832 if (!Intf.hasInterference()) {
833 assert(T < GroupSize && "Array overflow");
835 if (++T == GroupSize) {
836 SpillPlacer->addLinks(makeArrayRef(TBS, T));
842 assert(B < GroupSize && "Array overflow");
843 BCS[B].Number = Number;
845 // Interference for the live-in value.
846 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
847 BCS[B].Entry = SpillPlacement::MustSpill;
849 BCS[B].Entry = SpillPlacement::PrefSpill;
851 // Interference for the live-out value.
852 if (Intf.last() >= SA->getLastSplitPoint(Number))
853 BCS[B].Exit = SpillPlacement::MustSpill;
855 BCS[B].Exit = SpillPlacement::PrefSpill;
857 if (++B == GroupSize) {
858 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
859 SpillPlacer->addConstraints(Array);
864 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
865 SpillPlacer->addConstraints(Array);
866 SpillPlacer->addLinks(makeArrayRef(TBS, T));
869 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
870 // Keep track of through blocks that have not been added to SpillPlacer.
871 BitVector Todo = SA->getThroughBlocks();
872 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
873 unsigned AddedTo = 0;
875 unsigned Visited = 0;
879 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
880 // Find new through blocks in the periphery of PrefRegBundles.
881 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
882 unsigned Bundle = NewBundles[i];
883 // Look at all blocks connected to Bundle in the full graph.
884 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
885 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
888 if (!Todo.test(Block))
891 // This is a new through block. Add it to SpillPlacer later.
892 ActiveBlocks.push_back(Block);
898 // Any new blocks to add?
899 if (ActiveBlocks.size() == AddedTo)
902 // Compute through constraints from the interference, or assume that all
903 // through blocks prefer spilling when forming compact regions.
904 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
906 addThroughConstraints(Cand.Intf, NewBlocks);
908 // Provide a strong negative bias on through blocks to prevent unwanted
909 // liveness on loop backedges.
910 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
911 AddedTo = ActiveBlocks.size();
913 // Perhaps iterating can enable more bundles?
914 SpillPlacer->iterate();
916 DEBUG(dbgs() << ", v=" << Visited);
919 /// calcCompactRegion - Compute the set of edge bundles that should be live
920 /// when splitting the current live range into compact regions. Compact
921 /// regions can be computed without looking at interference. They are the
922 /// regions formed by removing all the live-through blocks from the live range.
924 /// Returns false if the current live range is already compact, or if the
925 /// compact regions would form single block regions anyway.
926 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
927 // Without any through blocks, the live range is already compact.
928 if (!SA->getNumThroughBlocks())
931 // Compact regions don't correspond to any physreg.
932 Cand.reset(IntfCache, 0);
934 DEBUG(dbgs() << "Compact region bundles");
936 // Use the spill placer to determine the live bundles. GrowRegion pretends
937 // that all the through blocks have interference when PhysReg is unset.
938 SpillPlacer->prepare(Cand.LiveBundles);
940 // The static split cost will be zero since Cand.Intf reports no interference.
942 if (!addSplitConstraints(Cand.Intf, Cost)) {
943 DEBUG(dbgs() << ", none.\n");
948 SpillPlacer->finish();
950 if (!Cand.LiveBundles.any()) {
951 DEBUG(dbgs() << ", none.\n");
956 for (int i = Cand.LiveBundles.find_first(); i>=0;
957 i = Cand.LiveBundles.find_next(i))
958 dbgs() << " EB#" << i;
964 /// calcSpillCost - Compute how expensive it would be to split the live range in
965 /// SA around all use blocks instead of forming bundle regions.
966 BlockFrequency RAGreedy::calcSpillCost() {
967 BlockFrequency Cost = 0;
968 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
969 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
970 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
971 unsigned Number = BI.MBB->getNumber();
972 // We normally only need one spill instruction - a load or a store.
973 Cost += SpillPlacer->getBlockFrequency(Number);
975 // Unless the value is redefined in the block.
976 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
977 Cost += SpillPlacer->getBlockFrequency(Number);
982 /// calcGlobalSplitCost - Return the global split cost of following the split
983 /// pattern in LiveBundles. This cost should be added to the local cost of the
984 /// interference pattern in SplitConstraints.
986 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
987 BlockFrequency GlobalCost = 0;
988 const BitVector &LiveBundles = Cand.LiveBundles;
989 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
990 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
991 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
992 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
993 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
994 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
998 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1000 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1002 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1005 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1006 unsigned Number = Cand.ActiveBlocks[i];
1007 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1008 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1009 if (!RegIn && !RegOut)
1011 if (RegIn && RegOut) {
1012 // We need double spill code if this block has interference.
1013 Cand.Intf.moveToBlock(Number);
1014 if (Cand.Intf.hasInterference()) {
1015 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1016 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1020 // live-in / stack-out or stack-in live-out.
1021 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1026 /// splitAroundRegion - Split the current live range around the regions
1027 /// determined by BundleCand and GlobalCand.
1029 /// Before calling this function, GlobalCand and BundleCand must be initialized
1030 /// so each bundle is assigned to a valid candidate, or NoCand for the
1031 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1032 /// objects must be initialized for the current live range, and intervals
1033 /// created for the used candidates.
1035 /// @param LREdit The LiveRangeEdit object handling the current split.
1036 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1037 /// must appear in this list.
1038 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1039 ArrayRef<unsigned> UsedCands) {
1040 // These are the intervals created for new global ranges. We may create more
1041 // intervals for local ranges.
1042 const unsigned NumGlobalIntvs = LREdit.size();
1043 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1044 assert(NumGlobalIntvs && "No global intervals configured");
1046 // Isolate even single instructions when dealing with a proper sub-class.
1047 // That guarantees register class inflation for the stack interval because it
1049 unsigned Reg = SA->getParent().reg;
1050 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1052 // First handle all the blocks with uses.
1053 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1054 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1055 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1056 unsigned Number = BI.MBB->getNumber();
1057 unsigned IntvIn = 0, IntvOut = 0;
1058 SlotIndex IntfIn, IntfOut;
1060 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1061 if (CandIn != NoCand) {
1062 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1063 IntvIn = Cand.IntvIdx;
1064 Cand.Intf.moveToBlock(Number);
1065 IntfIn = Cand.Intf.first();
1069 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1070 if (CandOut != NoCand) {
1071 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1072 IntvOut = Cand.IntvIdx;
1073 Cand.Intf.moveToBlock(Number);
1074 IntfOut = Cand.Intf.last();
1078 // Create separate intervals for isolated blocks with multiple uses.
1079 if (!IntvIn && !IntvOut) {
1080 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1081 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1082 SE->splitSingleBlock(BI);
1086 if (IntvIn && IntvOut)
1087 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1089 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1091 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1094 // Handle live-through blocks. The relevant live-through blocks are stored in
1095 // the ActiveBlocks list with each candidate. We need to filter out
1097 BitVector Todo = SA->getThroughBlocks();
1098 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1099 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1100 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1101 unsigned Number = Blocks[i];
1102 if (!Todo.test(Number))
1106 unsigned IntvIn = 0, IntvOut = 0;
1107 SlotIndex IntfIn, IntfOut;
1109 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1110 if (CandIn != NoCand) {
1111 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1112 IntvIn = Cand.IntvIdx;
1113 Cand.Intf.moveToBlock(Number);
1114 IntfIn = Cand.Intf.first();
1117 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1118 if (CandOut != NoCand) {
1119 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1120 IntvOut = Cand.IntvIdx;
1121 Cand.Intf.moveToBlock(Number);
1122 IntfOut = Cand.Intf.last();
1124 if (!IntvIn && !IntvOut)
1126 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1132 SmallVector<unsigned, 8> IntvMap;
1133 SE->finish(&IntvMap);
1134 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1136 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1137 unsigned OrigBlocks = SA->getNumLiveBlocks();
1139 // Sort out the new intervals created by splitting. We get four kinds:
1140 // - Remainder intervals should not be split again.
1141 // - Candidate intervals can be assigned to Cand.PhysReg.
1142 // - Block-local splits are candidates for local splitting.
1143 // - DCE leftovers should go back on the queue.
1144 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1145 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1147 // Ignore old intervals from DCE.
1148 if (getStage(Reg) != RS_New)
1151 // Remainder interval. Don't try splitting again, spill if it doesn't
1153 if (IntvMap[i] == 0) {
1154 setStage(Reg, RS_Spill);
1158 // Global intervals. Allow repeated splitting as long as the number of live
1159 // blocks is strictly decreasing.
1160 if (IntvMap[i] < NumGlobalIntvs) {
1161 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1162 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1163 << " blocks as original.\n");
1164 // Don't allow repeated splitting as a safe guard against looping.
1165 setStage(Reg, RS_Split2);
1170 // Other intervals are treated as new. This includes local intervals created
1171 // for blocks with multiple uses, and anything created by DCE.
1175 MF->verify(this, "After splitting live range around region");
1178 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1179 SmallVectorImpl<unsigned> &NewVRegs) {
1180 unsigned NumCands = 0;
1181 unsigned BestCand = NoCand;
1182 BlockFrequency BestCost;
1183 SmallVector<unsigned, 8> UsedCands;
1185 // Check if we can split this live range around a compact region.
1186 bool HasCompact = calcCompactRegion(GlobalCand.front());
1188 // Yes, keep GlobalCand[0] as the compact region candidate.
1190 BestCost = BlockFrequency::getMaxFrequency();
1192 // No benefit from the compact region, our fallback will be per-block
1193 // splitting. Make sure we find a solution that is cheaper than spilling.
1194 BestCost = calcSpillCost();
1195 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1199 while (unsigned PhysReg = Order.next()) {
1200 // Discard bad candidates before we run out of interference cache cursors.
1201 // This will only affect register classes with a lot of registers (>32).
1202 if (NumCands == IntfCache.getMaxCursors()) {
1203 unsigned WorstCount = ~0u;
1205 for (unsigned i = 0; i != NumCands; ++i) {
1206 if (i == BestCand || !GlobalCand[i].PhysReg)
1208 unsigned Count = GlobalCand[i].LiveBundles.count();
1209 if (Count < WorstCount)
1210 Worst = i, WorstCount = Count;
1213 GlobalCand[Worst] = GlobalCand[NumCands];
1214 if (BestCand == NumCands)
1218 if (GlobalCand.size() <= NumCands)
1219 GlobalCand.resize(NumCands+1);
1220 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1221 Cand.reset(IntfCache, PhysReg);
1223 SpillPlacer->prepare(Cand.LiveBundles);
1224 BlockFrequency Cost;
1225 if (!addSplitConstraints(Cand.Intf, Cost)) {
1226 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1229 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1230 if (Cost >= BestCost) {
1232 if (BestCand == NoCand)
1233 dbgs() << " worse than no bundles\n";
1235 dbgs() << " worse than "
1236 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1242 SpillPlacer->finish();
1244 // No live bundles, defer to splitSingleBlocks().
1245 if (!Cand.LiveBundles.any()) {
1246 DEBUG(dbgs() << " no bundles.\n");
1250 Cost += calcGlobalSplitCost(Cand);
1252 dbgs() << ", total = " << Cost << " with bundles";
1253 for (int i = Cand.LiveBundles.find_first(); i>=0;
1254 i = Cand.LiveBundles.find_next(i))
1255 dbgs() << " EB#" << i;
1258 if (Cost < BestCost) {
1259 BestCand = NumCands;
1265 // No solutions found, fall back to single block splitting.
1266 if (!HasCompact && BestCand == NoCand)
1269 // Prepare split editor.
1270 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1271 SE->reset(LREdit, SplitSpillMode);
1273 // Assign all edge bundles to the preferred candidate, or NoCand.
1274 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1276 // Assign bundles for the best candidate region.
1277 if (BestCand != NoCand) {
1278 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1279 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1280 UsedCands.push_back(BestCand);
1281 Cand.IntvIdx = SE->openIntv();
1282 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1283 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1288 // Assign bundles for the compact region.
1290 GlobalSplitCandidate &Cand = GlobalCand.front();
1291 assert(!Cand.PhysReg && "Compact region has no physreg");
1292 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1293 UsedCands.push_back(0);
1294 Cand.IntvIdx = SE->openIntv();
1295 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1296 << Cand.IntvIdx << ".\n");
1301 splitAroundRegion(LREdit, UsedCands);
1306 //===----------------------------------------------------------------------===//
1307 // Per-Block Splitting
1308 //===----------------------------------------------------------------------===//
1310 /// tryBlockSplit - Split a global live range around every block with uses. This
1311 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1312 /// they don't allocate.
1313 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1314 SmallVectorImpl<unsigned> &NewVRegs) {
1315 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1316 unsigned Reg = VirtReg.reg;
1317 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1318 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1319 SE->reset(LREdit, SplitSpillMode);
1320 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1321 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1322 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1323 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1324 SE->splitSingleBlock(BI);
1326 // No blocks were split.
1330 // We did split for some blocks.
1331 SmallVector<unsigned, 8> IntvMap;
1332 SE->finish(&IntvMap);
1334 // Tell LiveDebugVariables about the new ranges.
1335 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1337 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1339 // Sort out the new intervals created by splitting. The remainder interval
1340 // goes straight to spilling, the new local ranges get to stay RS_New.
1341 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1342 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
1343 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1344 setStage(LI, RS_Spill);
1348 MF->verify(this, "After splitting live range around basic blocks");
1353 //===----------------------------------------------------------------------===//
1354 // Per-Instruction Splitting
1355 //===----------------------------------------------------------------------===//
1357 /// tryInstructionSplit - Split a live range around individual instructions.
1358 /// This is normally not worthwhile since the spiller is doing essentially the
1359 /// same thing. However, when the live range is in a constrained register
1360 /// class, it may help to insert copies such that parts of the live range can
1361 /// be moved to a larger register class.
1363 /// This is similar to spilling to a larger register class.
1365 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1366 SmallVectorImpl<unsigned> &NewVRegs) {
1367 // There is no point to this if there are no larger sub-classes.
1368 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1371 // Always enable split spill mode, since we're effectively spilling to a
1373 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1374 SE->reset(LREdit, SplitEditor::SM_Size);
1376 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1377 if (Uses.size() <= 1)
1380 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1382 // Split around every non-copy instruction.
1383 for (unsigned i = 0; i != Uses.size(); ++i) {
1384 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1385 if (MI->isFullCopy()) {
1386 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1390 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1391 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1392 SE->useIntv(SegStart, SegStop);
1395 if (LREdit.empty()) {
1396 DEBUG(dbgs() << "All uses were copies.\n");
1400 SmallVector<unsigned, 8> IntvMap;
1401 SE->finish(&IntvMap);
1402 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1403 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1405 // Assign all new registers to RS_Spill. This was the last chance.
1406 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1411 //===----------------------------------------------------------------------===//
1413 //===----------------------------------------------------------------------===//
1416 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1417 /// in order to use PhysReg between two entries in SA->UseSlots.
1419 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1421 void RAGreedy::calcGapWeights(unsigned PhysReg,
1422 SmallVectorImpl<float> &GapWeight) {
1423 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1424 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1425 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1426 const unsigned NumGaps = Uses.size()-1;
1428 // Start and end points for the interference check.
1429 SlotIndex StartIdx =
1430 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1432 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1434 GapWeight.assign(NumGaps, 0.0f);
1436 // Add interference from each overlapping register.
1437 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1438 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1439 .checkInterference())
1442 // We know that VirtReg is a continuous interval from FirstInstr to
1443 // LastInstr, so we don't need InterferenceQuery.
1445 // Interference that overlaps an instruction is counted in both gaps
1446 // surrounding the instruction. The exception is interference before
1447 // StartIdx and after StopIdx.
1449 LiveIntervalUnion::SegmentIter IntI =
1450 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1451 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1452 // Skip the gaps before IntI.
1453 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1454 if (++Gap == NumGaps)
1459 // Update the gaps covered by IntI.
1460 const float weight = IntI.value()->weight;
1461 for (; Gap != NumGaps; ++Gap) {
1462 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1463 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1471 // Add fixed interference.
1472 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1473 const LiveRange &LR = LIS->getRegUnit(*Units);
1474 LiveRange::const_iterator I = LR.find(StartIdx);
1475 LiveRange::const_iterator E = LR.end();
1477 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1478 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1479 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1480 if (++Gap == NumGaps)
1485 for (; Gap != NumGaps; ++Gap) {
1486 GapWeight[Gap] = llvm::huge_valf;
1487 if (Uses[Gap+1].getBaseIndex() >= I->end)
1496 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1499 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1500 SmallVectorImpl<unsigned> &NewVRegs) {
1501 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1502 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1504 // Note that it is possible to have an interval that is live-in or live-out
1505 // while only covering a single block - A phi-def can use undef values from
1506 // predecessors, and the block could be a single-block loop.
1507 // We don't bother doing anything clever about such a case, we simply assume
1508 // that the interval is continuous from FirstInstr to LastInstr. We should
1509 // make sure that we don't do anything illegal to such an interval, though.
1511 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1512 if (Uses.size() <= 2)
1514 const unsigned NumGaps = Uses.size()-1;
1517 dbgs() << "tryLocalSplit: ";
1518 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1519 dbgs() << ' ' << Uses[i];
1523 // If VirtReg is live across any register mask operands, compute a list of
1524 // gaps with register masks.
1525 SmallVector<unsigned, 8> RegMaskGaps;
1526 if (Matrix->checkRegMaskInterference(VirtReg)) {
1527 // Get regmask slots for the whole block.
1528 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1529 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1530 // Constrain to VirtReg's live range.
1531 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1532 Uses.front().getRegSlot()) - RMS.begin();
1533 unsigned re = RMS.size();
1534 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1535 // Look for Uses[i] <= RMS <= Uses[i+1].
1536 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1537 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1539 // Skip a regmask on the same instruction as the last use. It doesn't
1540 // overlap the live range.
1541 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1543 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1544 RegMaskGaps.push_back(i);
1545 // Advance ri to the next gap. A regmask on one of the uses counts in
1547 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1550 DEBUG(dbgs() << '\n');
1553 // Since we allow local split results to be split again, there is a risk of
1554 // creating infinite loops. It is tempting to require that the new live
1555 // ranges have less instructions than the original. That would guarantee
1556 // convergence, but it is too strict. A live range with 3 instructions can be
1557 // split 2+3 (including the COPY), and we want to allow that.
1559 // Instead we use these rules:
1561 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1562 // noop split, of course).
1563 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1564 // the new ranges must have fewer instructions than before the split.
1565 // 3. New ranges with the same number of instructions are marked RS_Split2,
1566 // smaller ranges are marked RS_New.
1568 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1569 // excessive splitting and infinite loops.
1571 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1573 // Best split candidate.
1574 unsigned BestBefore = NumGaps;
1575 unsigned BestAfter = 0;
1578 const float blockFreq =
1579 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1580 (1.0f / BlockFrequency::getEntryFrequency());
1581 SmallVector<float, 8> GapWeight;
1584 while (unsigned PhysReg = Order.next()) {
1585 // Keep track of the largest spill weight that would need to be evicted in
1586 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1587 calcGapWeights(PhysReg, GapWeight);
1589 // Remove any gaps with regmask clobbers.
1590 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1591 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1592 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
1594 // Try to find the best sequence of gaps to close.
1595 // The new spill weight must be larger than any gap interference.
1597 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1598 unsigned SplitBefore = 0, SplitAfter = 1;
1600 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1601 // It is the spill weight that needs to be evicted.
1602 float MaxGap = GapWeight[0];
1605 // Live before/after split?
1606 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1607 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1609 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1610 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1611 << " i=" << MaxGap);
1613 // Stop before the interval gets so big we wouldn't be making progress.
1614 if (!LiveBefore && !LiveAfter) {
1615 DEBUG(dbgs() << " all\n");
1618 // Should the interval be extended or shrunk?
1621 // How many gaps would the new range have?
1622 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1624 // Legally, without causing looping?
1625 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1627 if (Legal && MaxGap < llvm::huge_valf) {
1628 // Estimate the new spill weight. Each instruction reads or writes the
1629 // register. Conservatively assume there are no read-modify-write
1632 // Try to guess the size of the new interval.
1633 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1634 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1635 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1636 // Would this split be possible to allocate?
1637 // Never allocate all gaps, we wouldn't be making progress.
1638 DEBUG(dbgs() << " w=" << EstWeight);
1639 if (EstWeight * Hysteresis >= MaxGap) {
1641 float Diff = EstWeight - MaxGap;
1642 if (Diff > BestDiff) {
1643 DEBUG(dbgs() << " (best)");
1644 BestDiff = Hysteresis * Diff;
1645 BestBefore = SplitBefore;
1646 BestAfter = SplitAfter;
1653 if (++SplitBefore < SplitAfter) {
1654 DEBUG(dbgs() << " shrink\n");
1655 // Recompute the max when necessary.
1656 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1657 MaxGap = GapWeight[SplitBefore];
1658 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1659 MaxGap = std::max(MaxGap, GapWeight[i]);
1666 // Try to extend the interval.
1667 if (SplitAfter >= NumGaps) {
1668 DEBUG(dbgs() << " end\n");
1672 DEBUG(dbgs() << " extend\n");
1673 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1677 // Didn't find any candidates?
1678 if (BestBefore == NumGaps)
1681 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1682 << '-' << Uses[BestAfter] << ", " << BestDiff
1683 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1685 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1689 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1690 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1691 SE->useIntv(SegStart, SegStop);
1692 SmallVector<unsigned, 8> IntvMap;
1693 SE->finish(&IntvMap);
1694 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1696 // If the new range has the same number of instructions as before, mark it as
1697 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1698 // leave the new intervals as RS_New so they can compete.
1699 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1700 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1701 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1702 if (NewGaps >= NumGaps) {
1703 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1704 assert(!ProgressRequired && "Didn't make progress when it was required.");
1705 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1706 if (IntvMap[i] == 1) {
1707 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1708 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
1710 DEBUG(dbgs() << '\n');
1717 //===----------------------------------------------------------------------===//
1718 // Live Range Splitting
1719 //===----------------------------------------------------------------------===//
1721 /// trySplit - Try to split VirtReg or one of its interferences, making it
1723 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1724 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1725 SmallVectorImpl<unsigned>&NewVRegs) {
1726 // Ranges must be Split2 or less.
1727 if (getStage(VirtReg) >= RS_Spill)
1730 // Local intervals are handled separately.
1731 if (LIS->intervalIsInOneMBB(VirtReg)) {
1732 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1733 SA->analyze(&VirtReg);
1734 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1735 if (PhysReg || !NewVRegs.empty())
1737 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1740 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1742 SA->analyze(&VirtReg);
1744 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1745 // coalescer. That may cause the range to become allocatable which means that
1746 // tryRegionSplit won't be making progress. This check should be replaced with
1747 // an assertion when the coalescer is fixed.
1748 if (SA->didRepairRange()) {
1749 // VirtReg has changed, so all cached queries are invalid.
1750 Matrix->invalidateVirtRegs();
1751 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1755 // First try to split around a region spanning multiple blocks. RS_Split2
1756 // ranges already made dubious progress with region splitting, so they go
1757 // straight to single block splitting.
1758 if (getStage(VirtReg) < RS_Split2) {
1759 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1760 if (PhysReg || !NewVRegs.empty())
1764 // Then isolate blocks.
1765 return tryBlockSplit(VirtReg, Order, NewVRegs);
1769 //===----------------------------------------------------------------------===//
1771 //===----------------------------------------------------------------------===//
1773 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1774 SmallVectorImpl<unsigned> &NewVRegs) {
1775 // First try assigning a free register.
1776 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1777 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1780 LiveRangeStage Stage = getStage(VirtReg);
1781 DEBUG(dbgs() << StageName[Stage]
1782 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1784 // Try to evict a less worthy live range, but only for ranges from the primary
1785 // queue. The RS_Split ranges already failed to do this, and they should not
1786 // get a second chance until they have been split.
1787 if (Stage != RS_Split)
1788 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1791 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1793 // The first time we see a live range, don't try to split or spill.
1794 // Wait until the second time, when all smaller ranges have been allocated.
1795 // This gives a better picture of the interference to split around.
1796 if (Stage < RS_Split) {
1797 setStage(VirtReg, RS_Split);
1798 DEBUG(dbgs() << "wait for second round\n");
1799 NewVRegs.push_back(VirtReg.reg);
1803 // If we couldn't allocate a register from spilling, there is probably some
1804 // invalid inline assembly. The base class wil report it.
1805 if (Stage >= RS_Done || !VirtReg.isSpillable())
1808 // Try splitting VirtReg or interferences.
1809 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1810 if (PhysReg || !NewVRegs.empty())
1813 // Finally spill VirtReg itself.
1814 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1815 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1816 spiller().spill(LRE);
1817 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1820 MF->verify(this, "After spilling");
1822 // The live virtual register requesting allocation was spilled, so tell
1823 // the caller not to allocate anything during this round.
1827 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1828 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1829 << "********** Function: " << mf.getName() << '\n');
1833 MF->verify(this, "Before greedy register allocator");
1835 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1836 getAnalysis<LiveIntervals>(),
1837 getAnalysis<LiveRegMatrix>());
1838 Indexes = &getAnalysis<SlotIndexes>();
1839 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1840 DomTree = &getAnalysis<MachineDominatorTree>();
1841 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1842 Loops = &getAnalysis<MachineLoopInfo>();
1843 Bundles = &getAnalysis<EdgeBundles>();
1844 SpillPlacer = &getAnalysis<SpillPlacement>();
1845 DebugVars = &getAnalysis<LiveDebugVariables>();
1847 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
1851 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1852 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1853 ExtraRegInfo.clear();
1854 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1856 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1857 GlobalCand.resize(32); // This will grow as needed.