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/RegisterClassInfo.h"
39 #include "llvm/CodeGen/VirtRegMap.h"
40 #include "llvm/PassAnalysisSupport.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/raw_ostream.h"
50 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51 STATISTIC(NumLocalSplits, "Number of split local live ranges");
52 STATISTIC(NumEvicted, "Number of interferences evicted");
54 static cl::opt<SplitEditor::ComplementSpillMode>
55 SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
61 cl::init(SplitEditor::SM_Partition));
63 static cl::opt<unsigned>
64 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
65 cl::desc("Last chance recoloring max depth"),
68 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
69 "lcr-max-interf", cl::Hidden,
70 cl::desc("Last chance recoloring maximum number of considered"
71 " interference at a time"),
74 // FIXME: Find a good default for this flag and remove the flag.
75 static cl::opt<unsigned>
76 CSRFirstTimeCost("regalloc-csr-first-time-cost",
77 cl::desc("Cost for first time use of callee-saved register."),
78 cl::init(0), cl::Hidden);
80 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
81 createGreedyRegisterAllocator);
84 class RAGreedy : public MachineFunctionPass,
86 private LiveRangeEdit::Delegate {
87 // Convenient shortcuts.
88 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
89 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
90 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
95 // Shortcuts to some useful interface.
96 const TargetInstrInfo *TII;
97 const TargetRegisterInfo *TRI;
98 RegisterClassInfo RCI;
101 SlotIndexes *Indexes;
102 MachineBlockFrequencyInfo *MBFI;
103 MachineDominatorTree *DomTree;
104 MachineLoopInfo *Loops;
105 EdgeBundles *Bundles;
106 SpillPlacement *SpillPlacer;
107 LiveDebugVariables *DebugVars;
110 std::unique_ptr<Spiller> SpillerInstance;
112 unsigned NextCascade;
114 // Live ranges pass through a number of stages as we try to allocate them.
115 // Some of the stages may also create new live ranges:
117 // - Region splitting.
118 // - Per-block splitting.
119 // - Local splitting.
122 // Ranges produced by one of the stages skip the previous stages when they are
123 // dequeued. This improves performance because we can skip interference checks
124 // that are unlikely to give any results. It also guarantees that the live
125 // range splitting algorithm terminates, something that is otherwise hard to
127 enum LiveRangeStage {
128 /// Newly created live range that has never been queued.
131 /// Only attempt assignment and eviction. Then requeue as RS_Split.
134 /// Attempt live range splitting if assignment is impossible.
137 /// Attempt more aggressive live range splitting that is guaranteed to make
138 /// progress. This is used for split products that may not be making
142 /// Live range will be spilled. No more splitting will be attempted.
145 /// There is nothing more we can do to this live range. Abort compilation
146 /// if it can't be assigned.
151 static const char *const StageName[];
154 // RegInfo - Keep additional information about each live range.
156 LiveRangeStage Stage;
158 // Cascade - Eviction loop prevention. See canEvictInterference().
161 RegInfo() : Stage(RS_New), Cascade(0) {}
164 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
166 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
167 return ExtraRegInfo[VirtReg.reg].Stage;
170 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
171 ExtraRegInfo.resize(MRI->getNumVirtRegs());
172 ExtraRegInfo[VirtReg.reg].Stage = Stage;
175 template<typename Iterator>
176 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
177 ExtraRegInfo.resize(MRI->getNumVirtRegs());
178 for (;Begin != End; ++Begin) {
179 unsigned Reg = *Begin;
180 if (ExtraRegInfo[Reg].Stage == RS_New)
181 ExtraRegInfo[Reg].Stage = NewStage;
185 /// Cost of evicting interference.
186 struct EvictionCost {
187 unsigned BrokenHints; ///< Total number of broken hints.
188 float MaxWeight; ///< Maximum spill weight evicted.
190 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
192 bool isMax() const { return BrokenHints == ~0u; }
194 void setMax() { BrokenHints = ~0u; }
196 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
198 bool operator<(const EvictionCost &O) const {
199 return std::tie(BrokenHints, MaxWeight) <
200 std::tie(O.BrokenHints, O.MaxWeight);
205 std::unique_ptr<SplitAnalysis> SA;
206 std::unique_ptr<SplitEditor> SE;
208 /// Cached per-block interference maps
209 InterferenceCache IntfCache;
211 /// All basic blocks where the current register has uses.
212 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
214 /// Global live range splitting candidate info.
215 struct GlobalSplitCandidate {
216 // Register intended for assignment, or 0.
219 // SplitKit interval index for this candidate.
222 // Interference for PhysReg.
223 InterferenceCache::Cursor Intf;
225 // Bundles where this candidate should be live.
226 BitVector LiveBundles;
227 SmallVector<unsigned, 8> ActiveBlocks;
229 void reset(InterferenceCache &Cache, unsigned Reg) {
232 Intf.setPhysReg(Cache, Reg);
234 ActiveBlocks.clear();
237 // Set B[i] = C for every live bundle where B[i] was NoCand.
238 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
240 for (int i = LiveBundles.find_first(); i >= 0;
241 i = LiveBundles.find_next(i))
242 if (B[i] == NoCand) {
250 /// Candidate info for each PhysReg in AllocationOrder.
251 /// This vector never shrinks, but grows to the size of the largest register
253 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
255 enum : unsigned { NoCand = ~0u };
257 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
258 /// NoCand which indicates the stack interval.
259 SmallVector<unsigned, 32> BundleCand;
264 /// Return the pass name.
265 const char* getPassName() const override {
266 return "Greedy Register Allocator";
269 /// RAGreedy analysis usage.
270 void getAnalysisUsage(AnalysisUsage &AU) const override;
271 void releaseMemory() override;
272 Spiller &spiller() override { return *SpillerInstance; }
273 void enqueue(LiveInterval *LI) override;
274 LiveInterval *dequeue() override;
275 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
277 /// Perform register allocation.
278 bool runOnMachineFunction(MachineFunction &mf) override;
283 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
284 SmallVirtRegSet &, unsigned = 0);
286 bool LRE_CanEraseVirtReg(unsigned) override;
287 void LRE_WillShrinkVirtReg(unsigned) override;
288 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
289 void enqueue(PQueue &CurQueue, LiveInterval *LI);
290 LiveInterval *dequeue(PQueue &CurQueue);
292 BlockFrequency calcSpillCost();
293 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
294 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
295 void growRegion(GlobalSplitCandidate &Cand);
296 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
297 bool calcCompactRegion(GlobalSplitCandidate&);
298 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
299 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
300 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
301 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
302 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
303 void evictInterference(LiveInterval&, unsigned,
304 SmallVectorImpl<unsigned>&);
305 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
306 SmallLISet &RecoloringCandidates,
307 const SmallVirtRegSet &FixedRegisters);
309 unsigned tryAssign(LiveInterval&, AllocationOrder&,
310 SmallVectorImpl<unsigned>&);
311 unsigned tryEvict(LiveInterval&, AllocationOrder&,
312 SmallVectorImpl<unsigned>&, unsigned = ~0u);
313 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
314 SmallVectorImpl<unsigned>&);
315 /// Calculate cost of region splitting.
316 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
317 AllocationOrder &Order,
318 BlockFrequency &BestCost,
319 unsigned &NumCands, bool IgnoreCSR);
320 /// Perform region splitting.
321 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
323 SmallVectorImpl<unsigned> &NewVRegs);
324 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
325 SmallVectorImpl<unsigned>&);
326 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
327 SmallVectorImpl<unsigned>&);
328 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
329 SmallVectorImpl<unsigned>&);
330 unsigned trySplit(LiveInterval&, AllocationOrder&,
331 SmallVectorImpl<unsigned>&);
332 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
333 SmallVectorImpl<unsigned> &,
334 SmallVirtRegSet &, unsigned);
335 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
336 SmallVirtRegSet &, unsigned);
338 } // end anonymous namespace
340 char RAGreedy::ID = 0;
343 const char *const RAGreedy::StageName[] = {
353 // Hysteresis to use when comparing floats.
354 // This helps stabilize decisions based on float comparisons.
355 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
358 FunctionPass* llvm::createGreedyRegisterAllocator() {
359 return new RAGreedy();
362 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
363 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
364 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
365 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
366 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
367 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
368 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
369 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
370 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
371 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
372 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
373 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
374 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
375 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
378 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
379 AU.setPreservesCFG();
380 AU.addRequired<MachineBlockFrequencyInfo>();
381 AU.addPreserved<MachineBlockFrequencyInfo>();
382 AU.addRequired<AliasAnalysis>();
383 AU.addPreserved<AliasAnalysis>();
384 AU.addRequired<LiveIntervals>();
385 AU.addPreserved<LiveIntervals>();
386 AU.addRequired<SlotIndexes>();
387 AU.addPreserved<SlotIndexes>();
388 AU.addRequired<LiveDebugVariables>();
389 AU.addPreserved<LiveDebugVariables>();
390 AU.addRequired<LiveStacks>();
391 AU.addPreserved<LiveStacks>();
392 AU.addRequired<MachineDominatorTree>();
393 AU.addPreserved<MachineDominatorTree>();
394 AU.addRequired<MachineLoopInfo>();
395 AU.addPreserved<MachineLoopInfo>();
396 AU.addRequired<VirtRegMap>();
397 AU.addPreserved<VirtRegMap>();
398 AU.addRequired<LiveRegMatrix>();
399 AU.addPreserved<LiveRegMatrix>();
400 AU.addRequired<EdgeBundles>();
401 AU.addRequired<SpillPlacement>();
402 MachineFunctionPass::getAnalysisUsage(AU);
406 //===----------------------------------------------------------------------===//
407 // LiveRangeEdit delegate methods
408 //===----------------------------------------------------------------------===//
410 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
411 if (VRM->hasPhys(VirtReg)) {
412 Matrix->unassign(LIS->getInterval(VirtReg));
415 // Unassigned virtreg is probably in the priority queue.
416 // RegAllocBase will erase it after dequeueing.
420 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
421 if (!VRM->hasPhys(VirtReg))
424 // Register is assigned, put it back on the queue for reassignment.
425 LiveInterval &LI = LIS->getInterval(VirtReg);
426 Matrix->unassign(LI);
430 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
431 // Cloning a register we haven't even heard about yet? Just ignore it.
432 if (!ExtraRegInfo.inBounds(Old))
435 // LRE may clone a virtual register because dead code elimination causes it to
436 // be split into connected components. The new components are much smaller
437 // than the original, so they should get a new chance at being assigned.
438 // same stage as the parent.
439 ExtraRegInfo[Old].Stage = RS_Assign;
440 ExtraRegInfo.grow(New);
441 ExtraRegInfo[New] = ExtraRegInfo[Old];
444 void RAGreedy::releaseMemory() {
445 SpillerInstance.reset(0);
446 ExtraRegInfo.clear();
450 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
452 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
453 // Prioritize live ranges by size, assigning larger ranges first.
454 // The queue holds (size, reg) pairs.
455 const unsigned Size = LI->getSize();
456 const unsigned Reg = LI->reg;
457 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
458 "Can only enqueue virtual registers");
461 ExtraRegInfo.grow(Reg);
462 if (ExtraRegInfo[Reg].Stage == RS_New)
463 ExtraRegInfo[Reg].Stage = RS_Assign;
465 if (ExtraRegInfo[Reg].Stage == RS_Split) {
466 // Unsplit ranges that couldn't be allocated immediately are deferred until
467 // everything else has been allocated.
470 // Giant live ranges fall back to the global assignment heuristic, which
471 // prevents excessive spilling in pathological cases.
472 bool ReverseLocal = TRI->reverseLocalAssignment();
473 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
474 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
476 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
477 LIS->intervalIsInOneMBB(*LI)) {
478 // Allocate original local ranges in linear instruction order. Since they
479 // are singly defined, this produces optimal coloring in the absence of
480 // global interference and other constraints.
482 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
484 // Allocating bottom up may allow many short LRGs to be assigned first
485 // to one of the cheap registers. This could be much faster for very
486 // large blocks on targets with many physical registers.
487 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
491 // Allocate global and split ranges in long->short order. Long ranges that
492 // don't fit should be spilled (or split) ASAP so they don't create
493 // interference. Mark a bit to prioritize global above local ranges.
494 Prio = (1u << 29) + Size;
496 // Mark a higher bit to prioritize global and local above RS_Split.
499 // Boost ranges that have a physical register hint.
500 if (VRM->hasKnownPreference(Reg))
503 // The virtual register number is a tie breaker for same-sized ranges.
504 // Give lower vreg numbers higher priority to assign them first.
505 CurQueue.push(std::make_pair(Prio, ~Reg));
508 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
510 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
511 if (CurQueue.empty())
513 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
519 //===----------------------------------------------------------------------===//
521 //===----------------------------------------------------------------------===//
523 /// tryAssign - Try to assign VirtReg to an available register.
524 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
525 AllocationOrder &Order,
526 SmallVectorImpl<unsigned> &NewVRegs) {
529 while ((PhysReg = Order.next()))
530 if (!Matrix->checkInterference(VirtReg, PhysReg))
532 if (!PhysReg || Order.isHint())
535 // PhysReg is available, but there may be a better choice.
537 // If we missed a simple hint, try to cheaply evict interference from the
538 // preferred register.
539 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
540 if (Order.isHint(Hint)) {
541 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
542 EvictionCost MaxCost;
543 MaxCost.setBrokenHints(1);
544 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
545 evictInterference(VirtReg, Hint, NewVRegs);
550 // Try to evict interference from a cheaper alternative.
551 unsigned Cost = TRI->getCostPerUse(PhysReg);
553 // Most registers have 0 additional cost.
557 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
559 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
560 return CheapReg ? CheapReg : PhysReg;
564 //===----------------------------------------------------------------------===//
565 // Interference eviction
566 //===----------------------------------------------------------------------===//
568 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
569 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
571 while ((PhysReg = Order.next())) {
572 if (PhysReg == PrevReg)
575 MCRegUnitIterator Units(PhysReg, TRI);
576 for (; Units.isValid(); ++Units) {
577 // Instantiate a "subquery", not to be confused with the Queries array.
578 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
579 if (subQ.checkInterference())
582 // If no units have interference, break out with the current PhysReg.
583 if (!Units.isValid())
587 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
588 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
593 /// shouldEvict - determine if A should evict the assigned live range B. The
594 /// eviction policy defined by this function together with the allocation order
595 /// defined by enqueue() decides which registers ultimately end up being split
598 /// Cascade numbers are used to prevent infinite loops if this function is a
601 /// @param A The live range to be assigned.
602 /// @param IsHint True when A is about to be assigned to its preferred
604 /// @param B The live range to be evicted.
605 /// @param BreaksHint True when B is already assigned to its preferred register.
606 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
607 LiveInterval &B, bool BreaksHint) {
608 bool CanSplit = getStage(B) < RS_Spill;
610 // Be fairly aggressive about following hints as long as the evictee can be
612 if (CanSplit && IsHint && !BreaksHint)
615 if (A.weight > B.weight) {
616 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
622 /// canEvictInterference - Return true if all interferences between VirtReg and
623 /// PhysReg can be evicted.
625 /// @param VirtReg Live range that is about to be assigned.
626 /// @param PhysReg Desired register for assignment.
627 /// @param IsHint True when PhysReg is VirtReg's preferred register.
628 /// @param MaxCost Only look for cheaper candidates and update with new cost
629 /// when returning true.
630 /// @returns True when interference can be evicted cheaper than MaxCost.
631 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
632 bool IsHint, EvictionCost &MaxCost) {
633 // It is only possible to evict virtual register interference.
634 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
637 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
639 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
640 // involved in an eviction before. If a cascade number was assigned, deny
641 // evicting anything with the same or a newer cascade number. This prevents
642 // infinite eviction loops.
644 // This works out so a register without a cascade number is allowed to evict
645 // anything, and it can be evicted by anything.
646 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
648 Cascade = NextCascade;
651 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
652 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
653 // If there is 10 or more interferences, chances are one is heavier.
654 if (Q.collectInterferingVRegs(10) >= 10)
657 // Check if any interfering live range is heavier than MaxWeight.
658 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
659 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
660 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
661 "Only expecting virtual register interference from query");
662 // Never evict spill products. They cannot split or spill.
663 if (getStage(*Intf) == RS_Done)
665 // Once a live range becomes small enough, it is urgent that we find a
666 // register for it. This is indicated by an infinite spill weight. These
667 // urgent live ranges get to evict almost anything.
669 // Also allow urgent evictions of unspillable ranges from a strictly
670 // larger allocation order.
671 bool Urgent = !VirtReg.isSpillable() &&
672 (Intf->isSpillable() ||
673 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
674 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
675 // Only evict older cascades or live ranges without a cascade.
676 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
677 if (Cascade <= IntfCascade) {
680 // We permit breaking cascades for urgent evictions. It should be the
681 // last resort, though, so make it really expensive.
682 Cost.BrokenHints += 10;
684 // Would this break a satisfied hint?
685 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
686 // Update eviction cost.
687 Cost.BrokenHints += BreaksHint;
688 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
689 // Abort if this would be too expensive.
690 if (!(Cost < MaxCost))
694 // Apply the eviction policy for non-urgent evictions.
695 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
697 // If !MaxCost.isMax(), then we're just looking for a cheap register.
698 // Evicting another local live range in this case could lead to suboptimal
700 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
701 !canReassign(*Intf, PhysReg)) {
710 /// evictInterference - Evict any interferring registers that prevent VirtReg
711 /// from being assigned to Physreg. This assumes that canEvictInterference
713 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
714 SmallVectorImpl<unsigned> &NewVRegs) {
715 // Make sure that VirtReg has a cascade number, and assign that cascade
716 // number to every evicted register. These live ranges than then only be
717 // evicted by a newer cascade, preventing infinite loops.
718 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
720 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
722 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
723 << " interference: Cascade " << Cascade << '\n');
725 // Collect all interfering virtregs first.
726 SmallVector<LiveInterval*, 8> Intfs;
727 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
728 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
729 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
730 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
731 Intfs.append(IVR.begin(), IVR.end());
734 // Evict them second. This will invalidate the queries.
735 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
736 LiveInterval *Intf = Intfs[i];
737 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
738 if (!VRM->hasPhys(Intf->reg))
740 Matrix->unassign(*Intf);
741 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
742 VirtReg.isSpillable() < Intf->isSpillable()) &&
743 "Cannot decrease cascade number, illegal eviction");
744 ExtraRegInfo[Intf->reg].Cascade = Cascade;
746 NewVRegs.push_back(Intf->reg);
750 /// tryEvict - Try to evict all interferences for a physreg.
751 /// @param VirtReg Currently unassigned virtual register.
752 /// @param Order Physregs to try.
753 /// @return Physreg to assign VirtReg, or 0.
754 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
755 AllocationOrder &Order,
756 SmallVectorImpl<unsigned> &NewVRegs,
757 unsigned CostPerUseLimit) {
758 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
760 // Keep track of the cheapest interference seen so far.
761 EvictionCost BestCost;
763 unsigned BestPhys = 0;
764 unsigned OrderLimit = Order.getOrder().size();
766 // When we are just looking for a reduced cost per use, don't break any
767 // hints, and only evict smaller spill weights.
768 if (CostPerUseLimit < ~0u) {
769 BestCost.BrokenHints = 0;
770 BestCost.MaxWeight = VirtReg.weight;
772 // Check of any registers in RC are below CostPerUseLimit.
773 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
774 unsigned MinCost = RegClassInfo.getMinCost(RC);
775 if (MinCost >= CostPerUseLimit) {
776 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
777 << ", no cheaper registers to be found.\n");
781 // It is normal for register classes to have a long tail of registers with
782 // the same cost. We don't need to look at them if they're too expensive.
783 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
784 OrderLimit = RegClassInfo.getLastCostChange(RC);
785 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
790 while (unsigned PhysReg = Order.next(OrderLimit)) {
791 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
793 // The first use of a callee-saved register in a function has cost 1.
794 // Don't start using a CSR when the CostPerUseLimit is low.
795 if (CostPerUseLimit == 1)
796 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
797 if (!MRI->isPhysRegUsed(CSR)) {
798 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
799 << PrintReg(CSR, TRI) << '\n');
803 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
809 // Stop if the hint can be used.
817 evictInterference(VirtReg, BestPhys, NewVRegs);
822 //===----------------------------------------------------------------------===//
824 //===----------------------------------------------------------------------===//
826 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
827 /// interference pattern in Physreg and its aliases. Add the constraints to
828 /// SpillPlacement and return the static cost of this split in Cost, assuming
829 /// that all preferences in SplitConstraints are met.
830 /// Return false if there are no bundles with positive bias.
831 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
832 BlockFrequency &Cost) {
833 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
835 // Reset interference dependent info.
836 SplitConstraints.resize(UseBlocks.size());
837 BlockFrequency StaticCost = 0;
838 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
839 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
840 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
842 BC.Number = BI.MBB->getNumber();
843 Intf.moveToBlock(BC.Number);
844 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
845 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
846 BC.ChangesValue = BI.FirstDef.isValid();
848 if (!Intf.hasInterference())
851 // Number of spill code instructions to insert.
854 // Interference for the live-in value.
856 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
857 BC.Entry = SpillPlacement::MustSpill, ++Ins;
858 else if (Intf.first() < BI.FirstInstr)
859 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
860 else if (Intf.first() < BI.LastInstr)
864 // Interference for the live-out value.
866 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
867 BC.Exit = SpillPlacement::MustSpill, ++Ins;
868 else if (Intf.last() > BI.LastInstr)
869 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
870 else if (Intf.last() > BI.FirstInstr)
874 // Accumulate the total frequency of inserted spill code.
876 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
880 // Add constraints for use-blocks. Note that these are the only constraints
881 // that may add a positive bias, it is downhill from here.
882 SpillPlacer->addConstraints(SplitConstraints);
883 return SpillPlacer->scanActiveBundles();
887 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
888 /// live-through blocks in Blocks.
889 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
890 ArrayRef<unsigned> Blocks) {
891 const unsigned GroupSize = 8;
892 SpillPlacement::BlockConstraint BCS[GroupSize];
893 unsigned TBS[GroupSize];
894 unsigned B = 0, T = 0;
896 for (unsigned i = 0; i != Blocks.size(); ++i) {
897 unsigned Number = Blocks[i];
898 Intf.moveToBlock(Number);
900 if (!Intf.hasInterference()) {
901 assert(T < GroupSize && "Array overflow");
903 if (++T == GroupSize) {
904 SpillPlacer->addLinks(makeArrayRef(TBS, T));
910 assert(B < GroupSize && "Array overflow");
911 BCS[B].Number = Number;
913 // Interference for the live-in value.
914 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
915 BCS[B].Entry = SpillPlacement::MustSpill;
917 BCS[B].Entry = SpillPlacement::PrefSpill;
919 // Interference for the live-out value.
920 if (Intf.last() >= SA->getLastSplitPoint(Number))
921 BCS[B].Exit = SpillPlacement::MustSpill;
923 BCS[B].Exit = SpillPlacement::PrefSpill;
925 if (++B == GroupSize) {
926 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
927 SpillPlacer->addConstraints(Array);
932 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
933 SpillPlacer->addConstraints(Array);
934 SpillPlacer->addLinks(makeArrayRef(TBS, T));
937 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
938 // Keep track of through blocks that have not been added to SpillPlacer.
939 BitVector Todo = SA->getThroughBlocks();
940 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
941 unsigned AddedTo = 0;
943 unsigned Visited = 0;
947 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
948 // Find new through blocks in the periphery of PrefRegBundles.
949 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
950 unsigned Bundle = NewBundles[i];
951 // Look at all blocks connected to Bundle in the full graph.
952 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
953 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
956 if (!Todo.test(Block))
959 // This is a new through block. Add it to SpillPlacer later.
960 ActiveBlocks.push_back(Block);
966 // Any new blocks to add?
967 if (ActiveBlocks.size() == AddedTo)
970 // Compute through constraints from the interference, or assume that all
971 // through blocks prefer spilling when forming compact regions.
972 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
974 addThroughConstraints(Cand.Intf, NewBlocks);
976 // Provide a strong negative bias on through blocks to prevent unwanted
977 // liveness on loop backedges.
978 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
979 AddedTo = ActiveBlocks.size();
981 // Perhaps iterating can enable more bundles?
982 SpillPlacer->iterate();
984 DEBUG(dbgs() << ", v=" << Visited);
987 /// calcCompactRegion - Compute the set of edge bundles that should be live
988 /// when splitting the current live range into compact regions. Compact
989 /// regions can be computed without looking at interference. They are the
990 /// regions formed by removing all the live-through blocks from the live range.
992 /// Returns false if the current live range is already compact, or if the
993 /// compact regions would form single block regions anyway.
994 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
995 // Without any through blocks, the live range is already compact.
996 if (!SA->getNumThroughBlocks())
999 // Compact regions don't correspond to any physreg.
1000 Cand.reset(IntfCache, 0);
1002 DEBUG(dbgs() << "Compact region bundles");
1004 // Use the spill placer to determine the live bundles. GrowRegion pretends
1005 // that all the through blocks have interference when PhysReg is unset.
1006 SpillPlacer->prepare(Cand.LiveBundles);
1008 // The static split cost will be zero since Cand.Intf reports no interference.
1009 BlockFrequency Cost;
1010 if (!addSplitConstraints(Cand.Intf, Cost)) {
1011 DEBUG(dbgs() << ", none.\n");
1016 SpillPlacer->finish();
1018 if (!Cand.LiveBundles.any()) {
1019 DEBUG(dbgs() << ", none.\n");
1024 for (int i = Cand.LiveBundles.find_first(); i>=0;
1025 i = Cand.LiveBundles.find_next(i))
1026 dbgs() << " EB#" << i;
1032 /// calcSpillCost - Compute how expensive it would be to split the live range in
1033 /// SA around all use blocks instead of forming bundle regions.
1034 BlockFrequency RAGreedy::calcSpillCost() {
1035 BlockFrequency Cost = 0;
1036 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1037 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1038 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1039 unsigned Number = BI.MBB->getNumber();
1040 // We normally only need one spill instruction - a load or a store.
1041 Cost += SpillPlacer->getBlockFrequency(Number);
1043 // Unless the value is redefined in the block.
1044 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1045 Cost += SpillPlacer->getBlockFrequency(Number);
1050 /// calcGlobalSplitCost - Return the global split cost of following the split
1051 /// pattern in LiveBundles. This cost should be added to the local cost of the
1052 /// interference pattern in SplitConstraints.
1054 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1055 BlockFrequency GlobalCost = 0;
1056 const BitVector &LiveBundles = Cand.LiveBundles;
1057 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1058 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1059 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1060 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1061 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1062 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1066 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1068 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1070 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1073 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1074 unsigned Number = Cand.ActiveBlocks[i];
1075 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1076 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1077 if (!RegIn && !RegOut)
1079 if (RegIn && RegOut) {
1080 // We need double spill code if this block has interference.
1081 Cand.Intf.moveToBlock(Number);
1082 if (Cand.Intf.hasInterference()) {
1083 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1084 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1088 // live-in / stack-out or stack-in live-out.
1089 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1094 /// splitAroundRegion - Split the current live range around the regions
1095 /// determined by BundleCand and GlobalCand.
1097 /// Before calling this function, GlobalCand and BundleCand must be initialized
1098 /// so each bundle is assigned to a valid candidate, or NoCand for the
1099 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1100 /// objects must be initialized for the current live range, and intervals
1101 /// created for the used candidates.
1103 /// @param LREdit The LiveRangeEdit object handling the current split.
1104 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1105 /// must appear in this list.
1106 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1107 ArrayRef<unsigned> UsedCands) {
1108 // These are the intervals created for new global ranges. We may create more
1109 // intervals for local ranges.
1110 const unsigned NumGlobalIntvs = LREdit.size();
1111 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1112 assert(NumGlobalIntvs && "No global intervals configured");
1114 // Isolate even single instructions when dealing with a proper sub-class.
1115 // That guarantees register class inflation for the stack interval because it
1117 unsigned Reg = SA->getParent().reg;
1118 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1120 // First handle all the blocks with uses.
1121 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1122 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1123 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1124 unsigned Number = BI.MBB->getNumber();
1125 unsigned IntvIn = 0, IntvOut = 0;
1126 SlotIndex IntfIn, IntfOut;
1128 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1129 if (CandIn != NoCand) {
1130 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1131 IntvIn = Cand.IntvIdx;
1132 Cand.Intf.moveToBlock(Number);
1133 IntfIn = Cand.Intf.first();
1137 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1138 if (CandOut != NoCand) {
1139 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1140 IntvOut = Cand.IntvIdx;
1141 Cand.Intf.moveToBlock(Number);
1142 IntfOut = Cand.Intf.last();
1146 // Create separate intervals for isolated blocks with multiple uses.
1147 if (!IntvIn && !IntvOut) {
1148 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1149 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1150 SE->splitSingleBlock(BI);
1154 if (IntvIn && IntvOut)
1155 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1157 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1159 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1162 // Handle live-through blocks. The relevant live-through blocks are stored in
1163 // the ActiveBlocks list with each candidate. We need to filter out
1165 BitVector Todo = SA->getThroughBlocks();
1166 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1167 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1168 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1169 unsigned Number = Blocks[i];
1170 if (!Todo.test(Number))
1174 unsigned IntvIn = 0, IntvOut = 0;
1175 SlotIndex IntfIn, IntfOut;
1177 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1178 if (CandIn != NoCand) {
1179 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1180 IntvIn = Cand.IntvIdx;
1181 Cand.Intf.moveToBlock(Number);
1182 IntfIn = Cand.Intf.first();
1185 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1186 if (CandOut != NoCand) {
1187 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1188 IntvOut = Cand.IntvIdx;
1189 Cand.Intf.moveToBlock(Number);
1190 IntfOut = Cand.Intf.last();
1192 if (!IntvIn && !IntvOut)
1194 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1200 SmallVector<unsigned, 8> IntvMap;
1201 SE->finish(&IntvMap);
1202 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1204 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1205 unsigned OrigBlocks = SA->getNumLiveBlocks();
1207 // Sort out the new intervals created by splitting. We get four kinds:
1208 // - Remainder intervals should not be split again.
1209 // - Candidate intervals can be assigned to Cand.PhysReg.
1210 // - Block-local splits are candidates for local splitting.
1211 // - DCE leftovers should go back on the queue.
1212 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1213 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1215 // Ignore old intervals from DCE.
1216 if (getStage(Reg) != RS_New)
1219 // Remainder interval. Don't try splitting again, spill if it doesn't
1221 if (IntvMap[i] == 0) {
1222 setStage(Reg, RS_Spill);
1226 // Global intervals. Allow repeated splitting as long as the number of live
1227 // blocks is strictly decreasing.
1228 if (IntvMap[i] < NumGlobalIntvs) {
1229 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1230 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1231 << " blocks as original.\n");
1232 // Don't allow repeated splitting as a safe guard against looping.
1233 setStage(Reg, RS_Split2);
1238 // Other intervals are treated as new. This includes local intervals created
1239 // for blocks with multiple uses, and anything created by DCE.
1243 MF->verify(this, "After splitting live range around region");
1246 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1247 SmallVectorImpl<unsigned> &NewVRegs) {
1248 unsigned NumCands = 0;
1249 BlockFrequency BestCost;
1251 // Check if we can split this live range around a compact region.
1252 bool HasCompact = calcCompactRegion(GlobalCand.front());
1254 // Yes, keep GlobalCand[0] as the compact region candidate.
1256 BestCost = BlockFrequency::getMaxFrequency();
1258 // No benefit from the compact region, our fallback will be per-block
1259 // splitting. Make sure we find a solution that is cheaper than spilling.
1260 BestCost = calcSpillCost();
1261 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1262 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1266 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1267 false/*IgnoreCSR*/);
1269 // No solutions found, fall back to single block splitting.
1270 if (!HasCompact && BestCand == NoCand)
1273 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1276 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1277 AllocationOrder &Order,
1278 BlockFrequency &BestCost,
1281 unsigned BestCand = NoCand;
1283 while (unsigned PhysReg = Order.next()) {
1284 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1285 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1288 // Discard bad candidates before we run out of interference cache cursors.
1289 // This will only affect register classes with a lot of registers (>32).
1290 if (NumCands == IntfCache.getMaxCursors()) {
1291 unsigned WorstCount = ~0u;
1293 for (unsigned i = 0; i != NumCands; ++i) {
1294 if (i == BestCand || !GlobalCand[i].PhysReg)
1296 unsigned Count = GlobalCand[i].LiveBundles.count();
1297 if (Count < WorstCount)
1298 Worst = i, WorstCount = Count;
1301 GlobalCand[Worst] = GlobalCand[NumCands];
1302 if (BestCand == NumCands)
1306 if (GlobalCand.size() <= NumCands)
1307 GlobalCand.resize(NumCands+1);
1308 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1309 Cand.reset(IntfCache, PhysReg);
1311 SpillPlacer->prepare(Cand.LiveBundles);
1312 BlockFrequency Cost;
1313 if (!addSplitConstraints(Cand.Intf, Cost)) {
1314 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1317 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1318 MBFI->printBlockFreq(dbgs(), Cost));
1319 if (Cost >= BestCost) {
1321 if (BestCand == NoCand)
1322 dbgs() << " worse than no bundles\n";
1324 dbgs() << " worse than "
1325 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1331 SpillPlacer->finish();
1333 // No live bundles, defer to splitSingleBlocks().
1334 if (!Cand.LiveBundles.any()) {
1335 DEBUG(dbgs() << " no bundles.\n");
1339 Cost += calcGlobalSplitCost(Cand);
1341 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1343 for (int i = Cand.LiveBundles.find_first(); i>=0;
1344 i = Cand.LiveBundles.find_next(i))
1345 dbgs() << " EB#" << i;
1348 if (Cost < BestCost) {
1349 BestCand = NumCands;
1357 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1359 SmallVectorImpl<unsigned> &NewVRegs) {
1360 SmallVector<unsigned, 8> UsedCands;
1361 // Prepare split editor.
1362 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1363 SE->reset(LREdit, SplitSpillMode);
1365 // Assign all edge bundles to the preferred candidate, or NoCand.
1366 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1368 // Assign bundles for the best candidate region.
1369 if (BestCand != NoCand) {
1370 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1371 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1372 UsedCands.push_back(BestCand);
1373 Cand.IntvIdx = SE->openIntv();
1374 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1375 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1380 // Assign bundles for the compact region.
1382 GlobalSplitCandidate &Cand = GlobalCand.front();
1383 assert(!Cand.PhysReg && "Compact region has no physreg");
1384 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1385 UsedCands.push_back(0);
1386 Cand.IntvIdx = SE->openIntv();
1387 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1388 << Cand.IntvIdx << ".\n");
1393 splitAroundRegion(LREdit, UsedCands);
1398 //===----------------------------------------------------------------------===//
1399 // Per-Block Splitting
1400 //===----------------------------------------------------------------------===//
1402 /// tryBlockSplit - Split a global live range around every block with uses. This
1403 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1404 /// they don't allocate.
1405 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1406 SmallVectorImpl<unsigned> &NewVRegs) {
1407 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1408 unsigned Reg = VirtReg.reg;
1409 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1410 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1411 SE->reset(LREdit, SplitSpillMode);
1412 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1413 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1414 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1415 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1416 SE->splitSingleBlock(BI);
1418 // No blocks were split.
1422 // We did split for some blocks.
1423 SmallVector<unsigned, 8> IntvMap;
1424 SE->finish(&IntvMap);
1426 // Tell LiveDebugVariables about the new ranges.
1427 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1429 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1431 // Sort out the new intervals created by splitting. The remainder interval
1432 // goes straight to spilling, the new local ranges get to stay RS_New.
1433 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1434 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
1435 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1436 setStage(LI, RS_Spill);
1440 MF->verify(this, "After splitting live range around basic blocks");
1445 //===----------------------------------------------------------------------===//
1446 // Per-Instruction Splitting
1447 //===----------------------------------------------------------------------===//
1449 /// Get the number of allocatable registers that match the constraints of \p Reg
1450 /// on \p MI and that are also in \p SuperRC.
1451 static unsigned getNumAllocatableRegsForConstraints(
1452 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1453 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1454 const RegisterClassInfo &RCI) {
1455 assert(SuperRC && "Invalid register class");
1457 const TargetRegisterClass *ConstrainedRC =
1458 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1459 /* ExploreBundle */ true);
1462 return RCI.getNumAllocatableRegs(ConstrainedRC);
1465 /// tryInstructionSplit - Split a live range around individual instructions.
1466 /// This is normally not worthwhile since the spiller is doing essentially the
1467 /// same thing. However, when the live range is in a constrained register
1468 /// class, it may help to insert copies such that parts of the live range can
1469 /// be moved to a larger register class.
1471 /// This is similar to spilling to a larger register class.
1473 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1474 SmallVectorImpl<unsigned> &NewVRegs) {
1475 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1476 // There is no point to this if there are no larger sub-classes.
1477 if (!RegClassInfo.isProperSubClass(CurRC))
1480 // Always enable split spill mode, since we're effectively spilling to a
1482 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1483 SE->reset(LREdit, SplitEditor::SM_Size);
1485 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1486 if (Uses.size() <= 1)
1489 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1491 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1492 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1493 // Split around every non-copy instruction if this split will relax
1494 // the constraints on the virtual register.
1495 // Otherwise, splitting just inserts uncoalescable copies that do not help
1497 for (unsigned i = 0; i != Uses.size(); ++i) {
1498 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1499 if (MI->isFullCopy() ||
1500 SuperRCNumAllocatableRegs ==
1501 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1503 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1507 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1508 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1509 SE->useIntv(SegStart, SegStop);
1512 if (LREdit.empty()) {
1513 DEBUG(dbgs() << "All uses were copies.\n");
1517 SmallVector<unsigned, 8> IntvMap;
1518 SE->finish(&IntvMap);
1519 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1520 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1522 // Assign all new registers to RS_Spill. This was the last chance.
1523 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1528 //===----------------------------------------------------------------------===//
1530 //===----------------------------------------------------------------------===//
1533 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1534 /// in order to use PhysReg between two entries in SA->UseSlots.
1536 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1538 void RAGreedy::calcGapWeights(unsigned PhysReg,
1539 SmallVectorImpl<float> &GapWeight) {
1540 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1541 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1542 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1543 const unsigned NumGaps = Uses.size()-1;
1545 // Start and end points for the interference check.
1546 SlotIndex StartIdx =
1547 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1549 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1551 GapWeight.assign(NumGaps, 0.0f);
1553 // Add interference from each overlapping register.
1554 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1555 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1556 .checkInterference())
1559 // We know that VirtReg is a continuous interval from FirstInstr to
1560 // LastInstr, so we don't need InterferenceQuery.
1562 // Interference that overlaps an instruction is counted in both gaps
1563 // surrounding the instruction. The exception is interference before
1564 // StartIdx and after StopIdx.
1566 LiveIntervalUnion::SegmentIter IntI =
1567 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1568 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1569 // Skip the gaps before IntI.
1570 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1571 if (++Gap == NumGaps)
1576 // Update the gaps covered by IntI.
1577 const float weight = IntI.value()->weight;
1578 for (; Gap != NumGaps; ++Gap) {
1579 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1580 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1588 // Add fixed interference.
1589 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1590 const LiveRange &LR = LIS->getRegUnit(*Units);
1591 LiveRange::const_iterator I = LR.find(StartIdx);
1592 LiveRange::const_iterator E = LR.end();
1594 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1595 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1596 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1597 if (++Gap == NumGaps)
1602 for (; Gap != NumGaps; ++Gap) {
1603 GapWeight[Gap] = llvm::huge_valf;
1604 if (Uses[Gap+1].getBaseIndex() >= I->end)
1613 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1616 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1617 SmallVectorImpl<unsigned> &NewVRegs) {
1618 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1619 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1621 // Note that it is possible to have an interval that is live-in or live-out
1622 // while only covering a single block - A phi-def can use undef values from
1623 // predecessors, and the block could be a single-block loop.
1624 // We don't bother doing anything clever about such a case, we simply assume
1625 // that the interval is continuous from FirstInstr to LastInstr. We should
1626 // make sure that we don't do anything illegal to such an interval, though.
1628 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1629 if (Uses.size() <= 2)
1631 const unsigned NumGaps = Uses.size()-1;
1634 dbgs() << "tryLocalSplit: ";
1635 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1636 dbgs() << ' ' << Uses[i];
1640 // If VirtReg is live across any register mask operands, compute a list of
1641 // gaps with register masks.
1642 SmallVector<unsigned, 8> RegMaskGaps;
1643 if (Matrix->checkRegMaskInterference(VirtReg)) {
1644 // Get regmask slots for the whole block.
1645 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1646 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1647 // Constrain to VirtReg's live range.
1648 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1649 Uses.front().getRegSlot()) - RMS.begin();
1650 unsigned re = RMS.size();
1651 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1652 // Look for Uses[i] <= RMS <= Uses[i+1].
1653 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1654 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1656 // Skip a regmask on the same instruction as the last use. It doesn't
1657 // overlap the live range.
1658 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1660 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1661 RegMaskGaps.push_back(i);
1662 // Advance ri to the next gap. A regmask on one of the uses counts in
1664 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1667 DEBUG(dbgs() << '\n');
1670 // Since we allow local split results to be split again, there is a risk of
1671 // creating infinite loops. It is tempting to require that the new live
1672 // ranges have less instructions than the original. That would guarantee
1673 // convergence, but it is too strict. A live range with 3 instructions can be
1674 // split 2+3 (including the COPY), and we want to allow that.
1676 // Instead we use these rules:
1678 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1679 // noop split, of course).
1680 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1681 // the new ranges must have fewer instructions than before the split.
1682 // 3. New ranges with the same number of instructions are marked RS_Split2,
1683 // smaller ranges are marked RS_New.
1685 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1686 // excessive splitting and infinite loops.
1688 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1690 // Best split candidate.
1691 unsigned BestBefore = NumGaps;
1692 unsigned BestAfter = 0;
1695 const float blockFreq =
1696 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1697 (1.0f / MBFI->getEntryFreq());
1698 SmallVector<float, 8> GapWeight;
1701 while (unsigned PhysReg = Order.next()) {
1702 // Keep track of the largest spill weight that would need to be evicted in
1703 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1704 calcGapWeights(PhysReg, GapWeight);
1706 // Remove any gaps with regmask clobbers.
1707 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1708 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1709 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
1711 // Try to find the best sequence of gaps to close.
1712 // The new spill weight must be larger than any gap interference.
1714 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1715 unsigned SplitBefore = 0, SplitAfter = 1;
1717 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1718 // It is the spill weight that needs to be evicted.
1719 float MaxGap = GapWeight[0];
1722 // Live before/after split?
1723 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1724 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1726 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1727 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1728 << " i=" << MaxGap);
1730 // Stop before the interval gets so big we wouldn't be making progress.
1731 if (!LiveBefore && !LiveAfter) {
1732 DEBUG(dbgs() << " all\n");
1735 // Should the interval be extended or shrunk?
1738 // How many gaps would the new range have?
1739 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1741 // Legally, without causing looping?
1742 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1744 if (Legal && MaxGap < llvm::huge_valf) {
1745 // Estimate the new spill weight. Each instruction reads or writes the
1746 // register. Conservatively assume there are no read-modify-write
1749 // Try to guess the size of the new interval.
1750 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1751 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1752 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1753 // Would this split be possible to allocate?
1754 // Never allocate all gaps, we wouldn't be making progress.
1755 DEBUG(dbgs() << " w=" << EstWeight);
1756 if (EstWeight * Hysteresis >= MaxGap) {
1758 float Diff = EstWeight - MaxGap;
1759 if (Diff > BestDiff) {
1760 DEBUG(dbgs() << " (best)");
1761 BestDiff = Hysteresis * Diff;
1762 BestBefore = SplitBefore;
1763 BestAfter = SplitAfter;
1770 if (++SplitBefore < SplitAfter) {
1771 DEBUG(dbgs() << " shrink\n");
1772 // Recompute the max when necessary.
1773 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1774 MaxGap = GapWeight[SplitBefore];
1775 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1776 MaxGap = std::max(MaxGap, GapWeight[i]);
1783 // Try to extend the interval.
1784 if (SplitAfter >= NumGaps) {
1785 DEBUG(dbgs() << " end\n");
1789 DEBUG(dbgs() << " extend\n");
1790 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1794 // Didn't find any candidates?
1795 if (BestBefore == NumGaps)
1798 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1799 << '-' << Uses[BestAfter] << ", " << BestDiff
1800 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1802 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1806 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1807 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1808 SE->useIntv(SegStart, SegStop);
1809 SmallVector<unsigned, 8> IntvMap;
1810 SE->finish(&IntvMap);
1811 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1813 // If the new range has the same number of instructions as before, mark it as
1814 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1815 // leave the new intervals as RS_New so they can compete.
1816 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1817 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1818 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1819 if (NewGaps >= NumGaps) {
1820 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1821 assert(!ProgressRequired && "Didn't make progress when it was required.");
1822 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1823 if (IntvMap[i] == 1) {
1824 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1825 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
1827 DEBUG(dbgs() << '\n');
1834 //===----------------------------------------------------------------------===//
1835 // Live Range Splitting
1836 //===----------------------------------------------------------------------===//
1838 /// trySplit - Try to split VirtReg or one of its interferences, making it
1840 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1841 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1842 SmallVectorImpl<unsigned>&NewVRegs) {
1843 // Ranges must be Split2 or less.
1844 if (getStage(VirtReg) >= RS_Spill)
1847 // Local intervals are handled separately.
1848 if (LIS->intervalIsInOneMBB(VirtReg)) {
1849 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1850 SA->analyze(&VirtReg);
1851 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1852 if (PhysReg || !NewVRegs.empty())
1854 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1857 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1859 SA->analyze(&VirtReg);
1861 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1862 // coalescer. That may cause the range to become allocatable which means that
1863 // tryRegionSplit won't be making progress. This check should be replaced with
1864 // an assertion when the coalescer is fixed.
1865 if (SA->didRepairRange()) {
1866 // VirtReg has changed, so all cached queries are invalid.
1867 Matrix->invalidateVirtRegs();
1868 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1872 // First try to split around a region spanning multiple blocks. RS_Split2
1873 // ranges already made dubious progress with region splitting, so they go
1874 // straight to single block splitting.
1875 if (getStage(VirtReg) < RS_Split2) {
1876 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1877 if (PhysReg || !NewVRegs.empty())
1881 // Then isolate blocks.
1882 return tryBlockSplit(VirtReg, Order, NewVRegs);
1885 //===----------------------------------------------------------------------===//
1886 // Last Chance Recoloring
1887 //===----------------------------------------------------------------------===//
1889 /// mayRecolorAllInterferences - Check if the virtual registers that
1890 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1891 /// recolored to free \p PhysReg.
1892 /// When true is returned, \p RecoloringCandidates has been augmented with all
1893 /// the live intervals that need to be recolored in order to free \p PhysReg
1895 /// \p FixedRegisters contains all the virtual registers that cannot be
1898 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1899 SmallLISet &RecoloringCandidates,
1900 const SmallVirtRegSet &FixedRegisters) {
1901 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1903 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1904 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1905 // If there is LastChanceRecoloringMaxInterference or more interferences,
1906 // chances are one would not be recolorable.
1907 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
1908 LastChanceRecoloringMaxInterference) {
1909 DEBUG(dbgs() << "Early abort: too many interferences.\n");
1912 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1913 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1914 // If Intf is done and sit on the same register class as VirtReg,
1915 // it would not be recolorable as it is in the same state as VirtReg.
1916 if ((getStage(*Intf) == RS_Done &&
1917 MRI->getRegClass(Intf->reg) == CurRC) ||
1918 FixedRegisters.count(Intf->reg)) {
1919 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1922 RecoloringCandidates.insert(Intf);
1928 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1929 /// its interferences.
1930 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
1931 /// virtual register that was using it. The recoloring process may recursively
1932 /// use the last chance recoloring. Therefore, when a virtual register has been
1933 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1934 /// be last-chance-recolored again during this recoloring "session".
1937 /// vA can use {R1, R2 }
1938 /// vB can use { R2, R3}
1939 /// vC can use {R1 }
1940 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
1941 /// instance) and they all interfere.
1943 /// vA is assigned R1
1944 /// vB is assigned R2
1945 /// vC tries to evict vA but vA is already done.
1946 /// Regular register allocation fails.
1948 /// Last chance recoloring kicks in:
1949 /// vC does as if vA was evicted => vC uses R1.
1950 /// vC is marked as fixed.
1951 /// vA needs to find a color.
1952 /// None are available.
1953 /// vA cannot evict vC: vC is a fixed virtual register now.
1954 /// vA does as if vB was evicted => vA uses R2.
1955 /// vB needs to find a color.
1956 /// R3 is available.
1957 /// Recoloring => vC = R1, vA = R2, vB = R3
1959 /// \p Order defines the preferred allocation order for \p VirtReg.
1960 /// \p NewRegs will contain any new virtual register that have been created
1961 /// (split, spill) during the process and that must be assigned.
1962 /// \p FixedRegisters contains all the virtual registers that cannot be
1964 /// \p Depth gives the current depth of the last chance recoloring.
1965 /// \return a physical register that can be used for VirtReg or ~0u if none
1967 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
1968 AllocationOrder &Order,
1969 SmallVectorImpl<unsigned> &NewVRegs,
1970 SmallVirtRegSet &FixedRegisters,
1972 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
1973 // Ranges must be Done.
1974 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
1975 "Last chance recoloring should really be last chance");
1976 // Set the max depth to LastChanceRecoloringMaxDepth.
1977 // We may want to reconsider that if we end up with a too large search space
1978 // for target with hundreds of registers.
1979 // Indeed, in that case we may want to cut the search space earlier.
1980 if (Depth >= LastChanceRecoloringMaxDepth) {
1981 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
1985 // Set of Live intervals that will need to be recolored.
1986 SmallLISet RecoloringCandidates;
1987 // Record the original mapping virtual register to physical register in case
1988 // the recoloring fails.
1989 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
1990 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
1991 // this recoloring "session".
1992 FixedRegisters.insert(VirtReg.reg);
1995 while (unsigned PhysReg = Order.next()) {
1996 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
1997 << PrintReg(PhysReg, TRI) << '\n');
1998 RecoloringCandidates.clear();
1999 VirtRegToPhysReg.clear();
2001 // It is only possible to recolor virtual register interference.
2002 if (Matrix->checkInterference(VirtReg, PhysReg) >
2003 LiveRegMatrix::IK_VirtReg) {
2004 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2009 // Early give up on this PhysReg if it is obvious we cannot recolor all
2010 // the interferences.
2011 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2013 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2017 // RecoloringCandidates contains all the virtual registers that interfer
2018 // with VirtReg on PhysReg (or one of its aliases).
2019 // Enqueue them for recoloring and perform the actual recoloring.
2020 PQueue RecoloringQueue;
2021 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2022 EndIt = RecoloringCandidates.end();
2023 It != EndIt; ++It) {
2024 unsigned ItVirtReg = (*It)->reg;
2025 enqueue(RecoloringQueue, *It);
2026 assert(VRM->hasPhys(ItVirtReg) &&
2027 "Interferences are supposed to be with allocated vairables");
2029 // Record the current allocation.
2030 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2031 // unset the related struct.
2032 Matrix->unassign(**It);
2035 // Do as if VirtReg was assigned to PhysReg so that the underlying
2036 // recoloring has the right information about the interferes and
2037 // available colors.
2038 Matrix->assign(VirtReg, PhysReg);
2040 // Save the current recoloring state.
2041 // If we cannot recolor all the interferences, we will have to start again
2042 // at this point for the next physical register.
2043 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2044 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2046 // Do not mess up with the global assignment process.
2047 // I.e., VirtReg must be unassigned.
2048 Matrix->unassign(VirtReg);
2052 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2053 << PrintReg(PhysReg, TRI) << '\n');
2055 // The recoloring attempt failed, undo the changes.
2056 FixedRegisters = SaveFixedRegisters;
2057 Matrix->unassign(VirtReg);
2059 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2060 EndIt = RecoloringCandidates.end();
2061 It != EndIt; ++It) {
2062 unsigned ItVirtReg = (*It)->reg;
2063 if (VRM->hasPhys(ItVirtReg))
2064 Matrix->unassign(**It);
2065 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2069 // Last chance recoloring did not worked either, give up.
2073 /// tryRecoloringCandidates - Try to assign a new color to every register
2074 /// in \RecoloringQueue.
2075 /// \p NewRegs will contain any new virtual register created during the
2076 /// recoloring process.
2077 /// \p FixedRegisters[in/out] contains all the registers that have been
2079 /// \return true if all virtual registers in RecoloringQueue were successfully
2080 /// recolored, false otherwise.
2081 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2082 SmallVectorImpl<unsigned> &NewVRegs,
2083 SmallVirtRegSet &FixedRegisters,
2085 while (!RecoloringQueue.empty()) {
2086 LiveInterval *LI = dequeue(RecoloringQueue);
2087 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2089 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2090 if (PhysReg == ~0u || !PhysReg)
2092 DEBUG(dbgs() << "Recoloring of " << *LI
2093 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2094 Matrix->assign(*LI, PhysReg);
2095 FixedRegisters.insert(LI->reg);
2100 //===----------------------------------------------------------------------===//
2102 //===----------------------------------------------------------------------===//
2104 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2105 SmallVectorImpl<unsigned> &NewVRegs) {
2106 SmallVirtRegSet FixedRegisters;
2107 return selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2110 unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2111 SmallVectorImpl<unsigned> &NewVRegs,
2112 SmallVirtRegSet &FixedRegisters,
2114 unsigned CostPerUseLimit = ~0u;
2115 // First try assigning a free register.
2116 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
2117 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2118 // We check other options if we are using a CSR for the first time.
2119 bool CSRFirstUse = false;
2120 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2121 if (!MRI->isPhysRegUsed(CSR))
2124 BlockFrequency CSRCost(CSRFirstTimeCost);
2125 // Using a CSR for the first time has a cost because it causes push|pop
2126 // to be added to prologue|epilogue. Splitting a cold section of the live
2127 // range can have lower cost than using the CSR for the first time;
2128 // Spilling a live range in the cold path can have lower cost than using
2129 // the CSR for the first time.
2130 if (getStage(VirtReg) == RS_Spill && CSRFirstUse && NewVRegs.empty() &&
2131 CSRFirstTimeCost > 0 && VirtReg.isSpillable()) {
2132 // We choose spill over using the CSR for the first time if the spill cost
2133 // is lower than CSRCost.
2134 SA->analyze(&VirtReg);
2135 if (calcSpillCost() >= CSRCost)
2138 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2139 // we will not use a callee-saved register in tryEvict.
2140 CostPerUseLimit = 1;
2142 else if (getStage(VirtReg) < RS_Split && CSRFirstUse &&
2143 NewVRegs.empty() && CSRFirstTimeCost > 0) {
2144 // We choose pre-splitting over using the CSR for the first time if
2145 // the cost of splitting is lower than CSRCost.
2146 SA->analyze(&VirtReg);
2147 unsigned NumCands = 0;
2149 calculateRegionSplitCost(VirtReg, Order, CSRCost, NumCands,
2151 if (BestCand == NoCand)
2152 // Use the CSR if we can't find a region split below CSRCost.
2155 // Perform the actual pre-splitting.
2156 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2157 if (!NewVRegs.empty())
2163 LiveRangeStage Stage = getStage(VirtReg);
2164 DEBUG(dbgs() << StageName[Stage]
2165 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
2167 // Try to evict a less worthy live range, but only for ranges from the primary
2168 // queue. The RS_Split ranges already failed to do this, and they should not
2169 // get a second chance until they have been split.
2170 if (Stage != RS_Split)
2171 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
2174 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2176 // The first time we see a live range, don't try to split or spill.
2177 // Wait until the second time, when all smaller ranges have been allocated.
2178 // This gives a better picture of the interference to split around.
2179 if (Stage < RS_Split) {
2180 setStage(VirtReg, RS_Split);
2181 DEBUG(dbgs() << "wait for second round\n");
2182 NewVRegs.push_back(VirtReg.reg);
2186 // If we couldn't allocate a register from spilling, there is probably some
2187 // invalid inline assembly. The base class wil report it.
2188 if (Stage >= RS_Done || !VirtReg.isSpillable())
2189 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2192 // Try splitting VirtReg or interferences.
2193 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2194 if (PhysReg || !NewVRegs.empty())
2197 // Finally spill VirtReg itself.
2198 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
2199 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
2200 spiller().spill(LRE);
2201 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2204 MF->verify(this, "After spilling");
2206 // The live virtual register requesting allocation was spilled, so tell
2207 // the caller not to allocate anything during this round.
2211 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2212 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2213 << "********** Function: " << mf.getName() << '\n');
2216 TRI = MF->getTarget().getRegisterInfo();
2217 TII = MF->getTarget().getInstrInfo();
2218 RCI.runOnMachineFunction(mf);
2220 MF->verify(this, "Before greedy register allocator");
2222 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2223 getAnalysis<LiveIntervals>(),
2224 getAnalysis<LiveRegMatrix>());
2225 Indexes = &getAnalysis<SlotIndexes>();
2226 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2227 DomTree = &getAnalysis<MachineDominatorTree>();
2228 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
2229 Loops = &getAnalysis<MachineLoopInfo>();
2230 Bundles = &getAnalysis<EdgeBundles>();
2231 SpillPlacer = &getAnalysis<SpillPlacement>();
2232 DebugVars = &getAnalysis<LiveDebugVariables>();
2234 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
2238 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2239 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
2240 ExtraRegInfo.clear();
2241 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2243 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2244 GlobalCand.resize(32); // This will grow as needed.