1 //===-- RegAllocLinearScan.cpp - Linear Scan 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 implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "LiveDebugVariables.h"
16 #include "LiveRangeEdit.h"
17 #include "VirtRegMap.h"
18 #include "VirtRegRewriter.h"
19 #include "RegisterClassInfo.h"
21 #include "RegisterCoalescer.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Function.h"
24 #include "llvm/CodeGen/CalcSpillWeights.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegAllocRegistry.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/ADT/EquivalenceClasses.h"
37 #include "llvm/ADT/SmallSet.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
50 STATISTIC(NumIters
, "Number of iterations performed");
51 STATISTIC(NumBacktracks
, "Number of times we had to backtrack");
52 STATISTIC(NumCoalesce
, "Number of copies coalesced");
53 STATISTIC(NumDowngrade
, "Number of registers downgraded");
56 NewHeuristic("new-spilling-heuristic",
57 cl::desc("Use new spilling heuristic"),
58 cl::init(false), cl::Hidden
);
61 PreSplitIntervals("pre-alloc-split",
62 cl::desc("Pre-register allocation live interval splitting"),
63 cl::init(false), cl::Hidden
);
66 TrivCoalesceEnds("trivial-coalesce-ends",
67 cl::desc("Attempt trivial coalescing of interval ends"),
68 cl::init(false), cl::Hidden
);
71 AvoidWAWHazard("avoid-waw-hazard",
72 cl::desc("Avoid write-write hazards for some register classes"),
73 cl::init(false), cl::Hidden
);
75 static RegisterRegAlloc
76 linearscanRegAlloc("linearscan", "linear scan register allocator",
77 createLinearScanRegisterAllocator
);
80 // When we allocate a register, add it to a fixed-size queue of
81 // registers to skip in subsequent allocations. This trades a small
82 // amount of register pressure and increased spills for flexibility in
83 // the post-pass scheduler.
85 // Note that in a the number of registers used for reloading spills
86 // will be one greater than the value of this option.
88 // One big limitation of this is that it doesn't differentiate between
89 // different register classes. So on x86-64, if there is xmm register
90 // pressure, it can caused fewer GPRs to be held in the queue.
91 static cl::opt
<unsigned>
92 NumRecentlyUsedRegs("linearscan-skip-count",
93 cl::desc("Number of registers for linearscan to remember"
98 struct RALinScan
: public MachineFunctionPass
{
100 RALinScan() : MachineFunctionPass(ID
) {
101 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
102 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
103 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
104 initializeRegisterCoalescerAnalysisGroup(
105 *PassRegistry::getPassRegistry());
106 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
107 initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
108 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
109 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
110 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
111 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
112 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
114 // Initialize the queue to record recently-used registers.
115 if (NumRecentlyUsedRegs
> 0)
116 RecentRegs
.resize(NumRecentlyUsedRegs
, 0);
117 RecentNext
= RecentRegs
.begin();
121 typedef std::pair
<LiveInterval
*, LiveInterval::iterator
> IntervalPtr
;
122 typedef SmallVector
<IntervalPtr
, 32> IntervalPtrs
;
124 /// RelatedRegClasses - This structure is built the first time a function is
125 /// compiled, and keeps track of which register classes have registers that
126 /// belong to multiple classes or have aliases that are in other classes.
127 EquivalenceClasses
<const TargetRegisterClass
*> RelatedRegClasses
;
128 DenseMap
<unsigned, const TargetRegisterClass
*> OneClassForEachPhysReg
;
130 // NextReloadMap - For each register in the map, it maps to the another
131 // register which is defined by a reload from the same stack slot and
132 // both reloads are in the same basic block.
133 DenseMap
<unsigned, unsigned> NextReloadMap
;
135 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
136 // un-favored for allocation.
137 SmallSet
<unsigned, 8> DowngradedRegs
;
139 // DowngradeMap - A map from virtual registers to physical registers being
140 // downgraded for the virtual registers.
141 DenseMap
<unsigned, unsigned> DowngradeMap
;
143 MachineFunction
* mf_
;
144 MachineRegisterInfo
* mri_
;
145 const TargetMachine
* tm_
;
146 const TargetRegisterInfo
* tri_
;
147 const TargetInstrInfo
* tii_
;
148 BitVector allocatableRegs_
;
149 BitVector reservedRegs_
;
151 MachineLoopInfo
*loopInfo
;
152 RegisterClassInfo RegClassInfo
;
154 /// handled_ - Intervals are added to the handled_ set in the order of their
155 /// start value. This is uses for backtracking.
156 std::vector
<LiveInterval
*> handled_
;
158 /// fixed_ - Intervals that correspond to machine registers.
162 /// active_ - Intervals that are currently being processed, and which have a
163 /// live range active for the current point.
164 IntervalPtrs active_
;
166 /// inactive_ - Intervals that are currently being processed, but which have
167 /// a hold at the current point.
168 IntervalPtrs inactive_
;
170 typedef std::priority_queue
<LiveInterval
*,
171 SmallVector
<LiveInterval
*, 64>,
172 greater_ptr
<LiveInterval
> > IntervalHeap
;
173 IntervalHeap unhandled_
;
175 /// regUse_ - Tracks register usage.
176 SmallVector
<unsigned, 32> regUse_
;
177 SmallVector
<unsigned, 32> regUseBackUp_
;
179 /// vrm_ - Tracks register assignments.
182 std::auto_ptr
<VirtRegRewriter
> rewriter_
;
184 std::auto_ptr
<Spiller
> spiller_
;
186 // The queue of recently-used registers.
187 SmallVector
<unsigned, 4> RecentRegs
;
188 SmallVector
<unsigned, 4>::iterator RecentNext
;
190 // Last write-after-write register written.
193 // Record that we just picked this register.
194 void recordRecentlyUsed(unsigned reg
) {
195 assert(reg
!= 0 && "Recently used register is NOREG!");
196 if (!RecentRegs
.empty()) {
198 if (RecentNext
== RecentRegs
.end())
199 RecentNext
= RecentRegs
.begin();
204 virtual const char* getPassName() const {
205 return "Linear Scan Register Allocator";
208 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
209 AU
.setPreservesCFG();
210 AU
.addRequired
<AliasAnalysis
>();
211 AU
.addPreserved
<AliasAnalysis
>();
212 AU
.addRequired
<LiveIntervals
>();
213 AU
.addPreserved
<SlotIndexes
>();
215 AU
.addRequiredID(StrongPHIEliminationID
);
216 // Make sure PassManager knows which analyses to make available
217 // to coalescing and which analyses coalescing invalidates.
218 AU
.addRequiredTransitive
<RegisterCoalescer
>();
219 AU
.addRequired
<CalculateSpillWeights
>();
220 if (PreSplitIntervals
)
221 AU
.addRequiredID(PreAllocSplittingID
);
222 AU
.addRequiredID(LiveStacksID
);
223 AU
.addPreservedID(LiveStacksID
);
224 AU
.addRequired
<MachineLoopInfo
>();
225 AU
.addPreserved
<MachineLoopInfo
>();
226 AU
.addRequired
<VirtRegMap
>();
227 AU
.addPreserved
<VirtRegMap
>();
228 AU
.addRequired
<LiveDebugVariables
>();
229 AU
.addPreserved
<LiveDebugVariables
>();
230 AU
.addRequiredID(MachineDominatorsID
);
231 AU
.addPreservedID(MachineDominatorsID
);
232 MachineFunctionPass::getAnalysisUsage(AU
);
235 /// runOnMachineFunction - register allocate the whole function
236 bool runOnMachineFunction(MachineFunction
&);
238 // Determine if we skip this register due to its being recently used.
239 bool isRecentlyUsed(unsigned reg
) const {
240 return reg
== avoidWAW_
||
241 std::find(RecentRegs
.begin(), RecentRegs
.end(), reg
) != RecentRegs
.end();
245 /// linearScan - the linear scan algorithm
248 /// initIntervalSets - initialize the interval sets.
250 void initIntervalSets();
252 /// processActiveIntervals - expire old intervals and move non-overlapping
253 /// ones to the inactive list.
254 void processActiveIntervals(SlotIndex CurPoint
);
256 /// processInactiveIntervals - expire old intervals and move overlapping
257 /// ones to the active list.
258 void processInactiveIntervals(SlotIndex CurPoint
);
260 /// hasNextReloadInterval - Return the next liveinterval that's being
261 /// defined by a reload from the same SS as the specified one.
262 LiveInterval
*hasNextReloadInterval(LiveInterval
*cur
);
264 /// DowngradeRegister - Downgrade a register for allocation.
265 void DowngradeRegister(LiveInterval
*li
, unsigned Reg
);
267 /// UpgradeRegister - Upgrade a register for allocation.
268 void UpgradeRegister(unsigned Reg
);
270 /// assignRegOrStackSlotAtInterval - assign a register if one
271 /// is available, or spill.
272 void assignRegOrStackSlotAtInterval(LiveInterval
* cur
);
274 void updateSpillWeights(std::vector
<float> &Weights
,
275 unsigned reg
, float weight
,
276 const TargetRegisterClass
*RC
);
278 /// findIntervalsToSpill - Determine the intervals to spill for the
279 /// specified interval. It's passed the physical registers whose spill
280 /// weight is the lowest among all the registers whose live intervals
281 /// conflict with the interval.
282 void findIntervalsToSpill(LiveInterval
*cur
,
283 std::vector
<std::pair
<unsigned,float> > &Candidates
,
285 SmallVector
<LiveInterval
*, 8> &SpillIntervals
);
287 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
288 /// try to allocate the definition to the same register as the source,
289 /// if the register is not defined during the life time of the interval.
290 /// This eliminates a copy, and is used to coalesce copies which were not
291 /// coalesced away before allocation either due to dest and src being in
292 /// different register classes or because the coalescer was overly
294 unsigned attemptTrivialCoalescing(LiveInterval
&cur
, unsigned Reg
);
297 /// Register usage / availability tracking helpers.
301 regUse_
.resize(tri_
->getNumRegs(), 0);
302 regUseBackUp_
.resize(tri_
->getNumRegs(), 0);
305 void finalizeRegUses() {
307 // Verify all the registers are "freed".
309 for (unsigned i
= 0, e
= tri_
->getNumRegs(); i
!= e
; ++i
) {
310 if (regUse_
[i
] != 0) {
311 dbgs() << tri_
->getName(i
) << " is still in use!\n";
319 regUseBackUp_
.clear();
322 void addRegUse(unsigned physReg
) {
323 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
324 "should be physical register!");
326 for (const unsigned* as
= tri_
->getAliasSet(physReg
); *as
; ++as
)
330 void delRegUse(unsigned physReg
) {
331 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
332 "should be physical register!");
333 assert(regUse_
[physReg
] != 0);
335 for (const unsigned* as
= tri_
->getAliasSet(physReg
); *as
; ++as
) {
336 assert(regUse_
[*as
] != 0);
341 bool isRegAvail(unsigned physReg
) const {
342 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
343 "should be physical register!");
344 return regUse_
[physReg
] == 0;
347 void backUpRegUses() {
348 regUseBackUp_
= regUse_
;
351 void restoreRegUses() {
352 regUse_
= regUseBackUp_
;
356 /// Register handling helpers.
359 /// getFreePhysReg - return a free physical register for this virtual
360 /// register interval if we have one, otherwise return 0.
361 unsigned getFreePhysReg(LiveInterval
* cur
);
362 unsigned getFreePhysReg(LiveInterval
* cur
,
363 const TargetRegisterClass
*RC
,
364 unsigned MaxInactiveCount
,
365 SmallVector
<unsigned, 256> &inactiveCounts
,
368 /// getFirstNonReservedPhysReg - return the first non-reserved physical
369 /// register in the register class.
370 unsigned getFirstNonReservedPhysReg(const TargetRegisterClass
*RC
) {
371 ArrayRef
<unsigned> O
= RegClassInfo
.getOrder(RC
);
372 assert(!O
.empty() && "All registers reserved?!");
376 void ComputeRelatedRegClasses();
378 template <typename ItTy
>
379 void printIntervals(const char* const str
, ItTy i
, ItTy e
) const {
382 dbgs() << str
<< " intervals:\n";
384 for (; i
!= e
; ++i
) {
385 dbgs() << '\t' << *i
->first
<< " -> ";
387 unsigned reg
= i
->first
->reg
;
388 if (TargetRegisterInfo::isVirtualRegister(reg
))
389 reg
= vrm_
->getPhys(reg
);
391 dbgs() << tri_
->getName(reg
) << '\n';
396 char RALinScan::ID
= 0;
399 INITIALIZE_PASS_BEGIN(RALinScan
, "linearscan-regalloc",
400 "Linear Scan Register Allocator", false, false)
401 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
402 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination
)
403 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights
)
404 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting
)
405 INITIALIZE_PASS_DEPENDENCY(LiveStacks
)
406 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
407 INITIALIZE_PASS_DEPENDENCY(VirtRegMap
)
408 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer
)
409 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
410 INITIALIZE_PASS_END(RALinScan
, "linearscan-regalloc",
411 "Linear Scan Register Allocator", false, false)
413 void RALinScan::ComputeRelatedRegClasses() {
414 // First pass, add all reg classes to the union, and determine at least one
415 // reg class that each register is in.
416 bool HasAliases
= false;
417 for (TargetRegisterInfo::regclass_iterator RCI
= tri_
->regclass_begin(),
418 E
= tri_
->regclass_end(); RCI
!= E
; ++RCI
) {
419 RelatedRegClasses
.insert(*RCI
);
420 for (TargetRegisterClass::iterator I
= (*RCI
)->begin(), E
= (*RCI
)->end();
422 HasAliases
= HasAliases
|| *tri_
->getAliasSet(*I
) != 0;
424 const TargetRegisterClass
*&PRC
= OneClassForEachPhysReg
[*I
];
426 // Already processed this register. Just make sure we know that
427 // multiple register classes share a register.
428 RelatedRegClasses
.unionSets(PRC
, *RCI
);
435 // Second pass, now that we know conservatively what register classes each reg
436 // belongs to, add info about aliases. We don't need to do this for targets
437 // without register aliases.
439 for (DenseMap
<unsigned, const TargetRegisterClass
*>::iterator
440 I
= OneClassForEachPhysReg
.begin(), E
= OneClassForEachPhysReg
.end();
442 for (const unsigned *AS
= tri_
->getAliasSet(I
->first
); *AS
; ++AS
) {
443 const TargetRegisterClass
*AliasClass
=
444 OneClassForEachPhysReg
.lookup(*AS
);
446 RelatedRegClasses
.unionSets(I
->second
, AliasClass
);
450 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
451 /// allocate the definition the same register as the source register if the
452 /// register is not defined during live time of the interval. If the interval is
453 /// killed by a copy, try to use the destination register. This eliminates a
454 /// copy. This is used to coalesce copies which were not coalesced away before
455 /// allocation either due to dest and src being in different register classes or
456 /// because the coalescer was overly conservative.
457 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval
&cur
, unsigned Reg
) {
458 unsigned Preference
= vrm_
->getRegAllocPref(cur
.reg
);
459 if ((Preference
&& Preference
== Reg
) || !cur
.containsOneValue())
462 // We cannot handle complicated live ranges. Simple linear stuff only.
463 if (cur
.ranges
.size() != 1)
466 const LiveRange
&range
= cur
.ranges
.front();
468 VNInfo
*vni
= range
.valno
;
469 if (vni
->isUnused() || !vni
->def
.isValid())
474 MachineInstr
*CopyMI
;
475 if ((CopyMI
= li_
->getInstructionFromIndex(vni
->def
)) && CopyMI
->isCopy())
476 // Defined by a copy, try to extend SrcReg forward
477 CandReg
= CopyMI
->getOperand(1).getReg();
478 else if (TrivCoalesceEnds
&&
479 (CopyMI
= li_
->getInstructionFromIndex(range
.end
.getBaseIndex())) &&
480 CopyMI
->isCopy() && cur
.reg
== CopyMI
->getOperand(1).getReg())
481 // Only used by a copy, try to extend DstReg backwards
482 CandReg
= CopyMI
->getOperand(0).getReg();
486 // If the target of the copy is a sub-register then don't coalesce.
487 if(CopyMI
->getOperand(0).getSubReg())
491 if (TargetRegisterInfo::isVirtualRegister(CandReg
)) {
492 if (!vrm_
->isAssignedReg(CandReg
))
494 CandReg
= vrm_
->getPhys(CandReg
);
499 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
.reg
);
500 if (!RC
->contains(CandReg
))
503 if (li_
->conflictsWithPhysReg(cur
, *vrm_
, CandReg
))
507 DEBUG(dbgs() << "Coalescing: " << cur
<< " -> " << tri_
->getName(CandReg
)
509 vrm_
->clearVirt(cur
.reg
);
510 vrm_
->assignVirt2Phys(cur
.reg
, CandReg
);
516 bool RALinScan::runOnMachineFunction(MachineFunction
&fn
) {
518 mri_
= &fn
.getRegInfo();
519 tm_
= &fn
.getTarget();
520 tri_
= tm_
->getRegisterInfo();
521 tii_
= tm_
->getInstrInfo();
522 allocatableRegs_
= tri_
->getAllocatableSet(fn
);
523 reservedRegs_
= tri_
->getReservedRegs(fn
);
524 li_
= &getAnalysis
<LiveIntervals
>();
525 loopInfo
= &getAnalysis
<MachineLoopInfo
>();
526 RegClassInfo
.runOnMachineFunction(fn
);
528 // We don't run the coalescer here because we have no reason to
529 // interact with it. If the coalescer requires interaction, it
530 // won't do anything. If it doesn't require interaction, we assume
531 // it was run as a separate pass.
533 // If this is the first function compiled, compute the related reg classes.
534 if (RelatedRegClasses
.empty())
535 ComputeRelatedRegClasses();
537 // Also resize register usage trackers.
540 vrm_
= &getAnalysis
<VirtRegMap
>();
541 if (!rewriter_
.get()) rewriter_
.reset(createVirtRegRewriter());
543 spiller_
.reset(createSpiller(*this, *mf_
, *vrm_
));
549 // Rewrite spill code and update the PhysRegsUsed set.
550 rewriter_
->runOnMachineFunction(*mf_
, *vrm_
, li_
);
552 // Write out new DBG_VALUE instructions.
553 getAnalysis
<LiveDebugVariables
>().emitDebugValues(vrm_
);
555 assert(unhandled_
.empty() && "Unhandled live intervals remain!");
563 NextReloadMap
.clear();
564 DowngradedRegs
.clear();
565 DowngradeMap
.clear();
571 /// initIntervalSets - initialize the interval sets.
573 void RALinScan::initIntervalSets()
575 assert(unhandled_
.empty() && fixed_
.empty() &&
576 active_
.empty() && inactive_
.empty() &&
577 "interval sets should be empty on initialization");
579 handled_
.reserve(li_
->getNumIntervals());
581 for (LiveIntervals::iterator i
= li_
->begin(), e
= li_
->end(); i
!= e
; ++i
) {
582 if (TargetRegisterInfo::isPhysicalRegister(i
->second
->reg
)) {
583 if (!i
->second
->empty() && allocatableRegs_
.test(i
->second
->reg
)) {
584 mri_
->setPhysRegUsed(i
->second
->reg
);
585 fixed_
.push_back(std::make_pair(i
->second
, i
->second
->begin()));
588 if (i
->second
->empty()) {
589 assignRegOrStackSlotAtInterval(i
->second
);
592 unhandled_
.push(i
->second
);
597 void RALinScan::linearScan() {
598 // linear scan algorithm
600 dbgs() << "********** LINEAR SCAN **********\n"
601 << "********** Function: "
602 << mf_
->getFunction()->getName() << '\n';
603 printIntervals("fixed", fixed_
.begin(), fixed_
.end());
606 while (!unhandled_
.empty()) {
607 // pick the interval with the earliest start point
608 LiveInterval
* cur
= unhandled_
.top();
611 DEBUG(dbgs() << "\n*** CURRENT ***: " << *cur
<< '\n');
613 assert(!cur
->empty() && "Empty interval in unhandled set.");
615 processActiveIntervals(cur
->beginIndex());
616 processInactiveIntervals(cur
->beginIndex());
618 assert(TargetRegisterInfo::isVirtualRegister(cur
->reg
) &&
619 "Can only allocate virtual registers!");
621 // Allocating a virtual register. try to find a free
622 // physical register or spill an interval (possibly this one) in order to
624 assignRegOrStackSlotAtInterval(cur
);
627 printIntervals("active", active_
.begin(), active_
.end());
628 printIntervals("inactive", inactive_
.begin(), inactive_
.end());
632 // Expire any remaining active intervals
633 while (!active_
.empty()) {
634 IntervalPtr
&IP
= active_
.back();
635 unsigned reg
= IP
.first
->reg
;
636 DEBUG(dbgs() << "\tinterval " << *IP
.first
<< " expired\n");
637 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
638 "Can only allocate virtual registers!");
639 reg
= vrm_
->getPhys(reg
);
644 // Expire any remaining inactive intervals
646 for (IntervalPtrs::reverse_iterator
647 i
= inactive_
.rbegin(); i
!= inactive_
.rend(); ++i
)
648 dbgs() << "\tinterval " << *i
->first
<< " expired\n";
652 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
653 MachineFunction::iterator EntryMBB
= mf_
->begin();
654 SmallVector
<MachineBasicBlock
*, 8> LiveInMBBs
;
655 for (LiveIntervals::iterator i
= li_
->begin(), e
= li_
->end(); i
!= e
; ++i
) {
656 LiveInterval
&cur
= *i
->second
;
658 bool isPhys
= TargetRegisterInfo::isPhysicalRegister(cur
.reg
);
661 else if (vrm_
->isAssignedReg(cur
.reg
))
662 Reg
= attemptTrivialCoalescing(cur
, vrm_
->getPhys(cur
.reg
));
665 // Ignore splited live intervals.
666 if (!isPhys
&& vrm_
->getPreSplitReg(cur
.reg
))
669 for (LiveInterval::Ranges::const_iterator I
= cur
.begin(), E
= cur
.end();
671 const LiveRange
&LR
= *I
;
672 if (li_
->findLiveInMBBs(LR
.start
, LR
.end
, LiveInMBBs
)) {
673 for (unsigned i
= 0, e
= LiveInMBBs
.size(); i
!= e
; ++i
)
674 if (LiveInMBBs
[i
] != EntryMBB
) {
675 assert(TargetRegisterInfo::isPhysicalRegister(Reg
) &&
676 "Adding a virtual register to livein set?");
677 LiveInMBBs
[i
]->addLiveIn(Reg
);
684 DEBUG(dbgs() << *vrm_
);
686 // Look for physical registers that end up not being allocated even though
687 // register allocator had to spill other registers in its register class.
688 if (!vrm_
->FindUnusedRegisters(li_
))
692 /// processActiveIntervals - expire old intervals and move non-overlapping ones
693 /// to the inactive list.
694 void RALinScan::processActiveIntervals(SlotIndex CurPoint
)
696 DEBUG(dbgs() << "\tprocessing active intervals:\n");
698 for (unsigned i
= 0, e
= active_
.size(); i
!= e
; ++i
) {
699 LiveInterval
*Interval
= active_
[i
].first
;
700 LiveInterval::iterator IntervalPos
= active_
[i
].second
;
701 unsigned reg
= Interval
->reg
;
703 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
705 if (IntervalPos
== Interval
->end()) { // Remove expired intervals.
706 DEBUG(dbgs() << "\t\tinterval " << *Interval
<< " expired\n");
707 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
708 "Can only allocate virtual registers!");
709 reg
= vrm_
->getPhys(reg
);
712 // Pop off the end of the list.
713 active_
[i
] = active_
.back();
717 } else if (IntervalPos
->start
> CurPoint
) {
718 // Move inactive intervals to inactive list.
719 DEBUG(dbgs() << "\t\tinterval " << *Interval
<< " inactive\n");
720 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
721 "Can only allocate virtual registers!");
722 reg
= vrm_
->getPhys(reg
);
725 inactive_
.push_back(std::make_pair(Interval
, IntervalPos
));
727 // Pop off the end of the list.
728 active_
[i
] = active_
.back();
732 // Otherwise, just update the iterator position.
733 active_
[i
].second
= IntervalPos
;
738 /// processInactiveIntervals - expire old intervals and move overlapping
739 /// ones to the active list.
740 void RALinScan::processInactiveIntervals(SlotIndex CurPoint
)
742 DEBUG(dbgs() << "\tprocessing inactive intervals:\n");
744 for (unsigned i
= 0, e
= inactive_
.size(); i
!= e
; ++i
) {
745 LiveInterval
*Interval
= inactive_
[i
].first
;
746 LiveInterval::iterator IntervalPos
= inactive_
[i
].second
;
747 unsigned reg
= Interval
->reg
;
749 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
751 if (IntervalPos
== Interval
->end()) { // remove expired intervals.
752 DEBUG(dbgs() << "\t\tinterval " << *Interval
<< " expired\n");
754 // Pop off the end of the list.
755 inactive_
[i
] = inactive_
.back();
756 inactive_
.pop_back();
758 } else if (IntervalPos
->start
<= CurPoint
) {
759 // move re-activated intervals in active list
760 DEBUG(dbgs() << "\t\tinterval " << *Interval
<< " active\n");
761 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
762 "Can only allocate virtual registers!");
763 reg
= vrm_
->getPhys(reg
);
766 active_
.push_back(std::make_pair(Interval
, IntervalPos
));
768 // Pop off the end of the list.
769 inactive_
[i
] = inactive_
.back();
770 inactive_
.pop_back();
773 // Otherwise, just update the iterator position.
774 inactive_
[i
].second
= IntervalPos
;
779 /// updateSpillWeights - updates the spill weights of the specifed physical
780 /// register and its weight.
781 void RALinScan::updateSpillWeights(std::vector
<float> &Weights
,
782 unsigned reg
, float weight
,
783 const TargetRegisterClass
*RC
) {
784 SmallSet
<unsigned, 4> Processed
;
785 SmallSet
<unsigned, 4> SuperAdded
;
786 SmallVector
<unsigned, 4> Supers
;
787 Weights
[reg
] += weight
;
788 Processed
.insert(reg
);
789 for (const unsigned* as
= tri_
->getAliasSet(reg
); *as
; ++as
) {
790 Weights
[*as
] += weight
;
791 Processed
.insert(*as
);
792 if (tri_
->isSubRegister(*as
, reg
) &&
793 SuperAdded
.insert(*as
) &&
795 Supers
.push_back(*as
);
799 // If the alias is a super-register, and the super-register is in the
800 // register class we are trying to allocate. Then add the weight to all
801 // sub-registers of the super-register even if they are not aliases.
802 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
803 // bl should get the same spill weight otherwise it will be chosen
804 // as a spill candidate since spilling bh doesn't make ebx available.
805 for (unsigned i
= 0, e
= Supers
.size(); i
!= e
; ++i
) {
806 for (const unsigned *sr
= tri_
->getSubRegisters(Supers
[i
]); *sr
; ++sr
)
807 if (!Processed
.count(*sr
))
808 Weights
[*sr
] += weight
;
813 RALinScan::IntervalPtrs::iterator
814 FindIntervalInVector(RALinScan::IntervalPtrs
&IP
, LiveInterval
*LI
) {
815 for (RALinScan::IntervalPtrs::iterator I
= IP
.begin(), E
= IP
.end();
817 if (I
->first
== LI
) return I
;
821 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs
&V
,
823 for (unsigned i
= 0, e
= V
.size(); i
!= e
; ++i
) {
824 RALinScan::IntervalPtr
&IP
= V
[i
];
825 LiveInterval::iterator I
= std::upper_bound(IP
.first
->begin(),
827 if (I
!= IP
.first
->begin()) --I
;
832 /// getConflictWeight - Return the number of conflicts between cur
833 /// live interval and defs and uses of Reg weighted by loop depthes.
835 float getConflictWeight(LiveInterval
*cur
, unsigned Reg
, LiveIntervals
*li_
,
836 MachineRegisterInfo
*mri_
,
837 MachineLoopInfo
*loopInfo
) {
839 for (MachineRegisterInfo::reg_iterator I
= mri_
->reg_begin(Reg
),
840 E
= mri_
->reg_end(); I
!= E
; ++I
) {
841 MachineInstr
*MI
= &*I
;
842 if (cur
->liveAt(li_
->getInstructionIndex(MI
))) {
843 unsigned loopDepth
= loopInfo
->getLoopDepth(MI
->getParent());
844 Conflicts
+= std::pow(10.0f
, (float)loopDepth
);
850 /// findIntervalsToSpill - Determine the intervals to spill for the
851 /// specified interval. It's passed the physical registers whose spill
852 /// weight is the lowest among all the registers whose live intervals
853 /// conflict with the interval.
854 void RALinScan::findIntervalsToSpill(LiveInterval
*cur
,
855 std::vector
<std::pair
<unsigned,float> > &Candidates
,
857 SmallVector
<LiveInterval
*, 8> &SpillIntervals
) {
858 // We have figured out the *best* register to spill. But there are other
859 // registers that are pretty good as well (spill weight within 3%). Spill
860 // the one that has fewest defs and uses that conflict with cur.
861 float Conflicts
[3] = { 0.0f
, 0.0f
, 0.0f
};
862 SmallVector
<LiveInterval
*, 8> SLIs
[3];
865 dbgs() << "\tConsidering " << NumCands
<< " candidates: ";
866 for (unsigned i
= 0; i
!= NumCands
; ++i
)
867 dbgs() << tri_
->getName(Candidates
[i
].first
) << " ";
871 // Calculate the number of conflicts of each candidate.
872 for (IntervalPtrs::iterator i
= active_
.begin(); i
!= active_
.end(); ++i
) {
873 unsigned Reg
= i
->first
->reg
;
874 unsigned PhysReg
= vrm_
->getPhys(Reg
);
875 if (!cur
->overlapsFrom(*i
->first
, i
->second
))
877 for (unsigned j
= 0; j
< NumCands
; ++j
) {
878 unsigned Candidate
= Candidates
[j
].first
;
879 if (tri_
->regsOverlap(PhysReg
, Candidate
)) {
881 Conflicts
[j
] += getConflictWeight(cur
, Reg
, li_
, mri_
, loopInfo
);
882 SLIs
[j
].push_back(i
->first
);
887 for (IntervalPtrs::iterator i
= inactive_
.begin(); i
!= inactive_
.end(); ++i
){
888 unsigned Reg
= i
->first
->reg
;
889 unsigned PhysReg
= vrm_
->getPhys(Reg
);
890 if (!cur
->overlapsFrom(*i
->first
, i
->second
-1))
892 for (unsigned j
= 0; j
< NumCands
; ++j
) {
893 unsigned Candidate
= Candidates
[j
].first
;
894 if (tri_
->regsOverlap(PhysReg
, Candidate
)) {
896 Conflicts
[j
] += getConflictWeight(cur
, Reg
, li_
, mri_
, loopInfo
);
897 SLIs
[j
].push_back(i
->first
);
902 // Which is the best candidate?
903 unsigned BestCandidate
= 0;
904 float MinConflicts
= Conflicts
[0];
905 for (unsigned i
= 1; i
!= NumCands
; ++i
) {
906 if (Conflicts
[i
] < MinConflicts
) {
908 MinConflicts
= Conflicts
[i
];
912 std::copy(SLIs
[BestCandidate
].begin(), SLIs
[BestCandidate
].end(),
913 std::back_inserter(SpillIntervals
));
917 struct WeightCompare
{
919 const RALinScan
&Allocator
;
922 WeightCompare(const RALinScan
&Alloc
) : Allocator(Alloc
) {}
924 typedef std::pair
<unsigned, float> RegWeightPair
;
925 bool operator()(const RegWeightPair
&LHS
, const RegWeightPair
&RHS
) const {
926 return LHS
.second
< RHS
.second
&& !Allocator
.isRecentlyUsed(LHS
.first
);
931 static bool weightsAreClose(float w1
, float w2
) {
935 float diff
= w1
- w2
;
936 if (diff
<= 0.02f
) // Within 0.02f
938 return (diff
/ w2
) <= 0.05f
; // Within 5%.
941 LiveInterval
*RALinScan::hasNextReloadInterval(LiveInterval
*cur
) {
942 DenseMap
<unsigned, unsigned>::iterator I
= NextReloadMap
.find(cur
->reg
);
943 if (I
== NextReloadMap
.end())
945 return &li_
->getInterval(I
->second
);
948 void RALinScan::DowngradeRegister(LiveInterval
*li
, unsigned Reg
) {
949 for (const unsigned *AS
= tri_
->getOverlaps(Reg
); *AS
; ++AS
) {
950 bool isNew
= DowngradedRegs
.insert(*AS
);
951 (void)isNew
; // Silence compiler warning.
952 assert(isNew
&& "Multiple reloads holding the same register?");
953 DowngradeMap
.insert(std::make_pair(li
->reg
, *AS
));
958 void RALinScan::UpgradeRegister(unsigned Reg
) {
960 DowngradedRegs
.erase(Reg
);
961 for (const unsigned *AS
= tri_
->getAliasSet(Reg
); *AS
; ++AS
)
962 DowngradedRegs
.erase(*AS
);
968 bool operator()(LiveInterval
* A
, LiveInterval
* B
) {
969 return A
->beginIndex() < B
->beginIndex();
974 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
976 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval
* cur
) {
977 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
->reg
);
978 DEBUG(dbgs() << "\tallocating current interval from "
979 << RC
->getName() << ": ");
981 // This is an implicitly defined live interval, just assign any register.
983 unsigned physReg
= vrm_
->getRegAllocPref(cur
->reg
);
985 physReg
= getFirstNonReservedPhysReg(RC
);
986 DEBUG(dbgs() << tri_
->getName(physReg
) << '\n');
987 // Note the register is not really in use.
988 vrm_
->assignVirt2Phys(cur
->reg
, physReg
);
994 std::vector
<std::pair
<unsigned, float> > SpillWeightsToAdd
;
995 SlotIndex StartPosition
= cur
->beginIndex();
996 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
998 // If start of this live interval is defined by a move instruction and its
999 // source is assigned a physical register that is compatible with the target
1000 // register class, then we should try to assign it the same register.
1001 // This can happen when the move is from a larger register class to a smaller
1002 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
1003 if (!vrm_
->getRegAllocPref(cur
->reg
) && cur
->hasAtLeastOneValue()) {
1004 VNInfo
*vni
= cur
->begin()->valno
;
1005 if (!vni
->isUnused() && vni
->def
.isValid()) {
1006 MachineInstr
*CopyMI
= li_
->getInstructionFromIndex(vni
->def
);
1007 if (CopyMI
&& CopyMI
->isCopy()) {
1008 unsigned DstSubReg
= CopyMI
->getOperand(0).getSubReg();
1009 unsigned SrcReg
= CopyMI
->getOperand(1).getReg();
1010 unsigned SrcSubReg
= CopyMI
->getOperand(1).getSubReg();
1012 if (TargetRegisterInfo::isPhysicalRegister(SrcReg
))
1014 else if (vrm_
->isAssignedReg(SrcReg
))
1015 Reg
= vrm_
->getPhys(SrcReg
);
1018 Reg
= tri_
->getSubReg(Reg
, SrcSubReg
);
1020 Reg
= tri_
->getMatchingSuperReg(Reg
, DstSubReg
, RC
);
1021 if (Reg
&& allocatableRegs_
[Reg
] && RC
->contains(Reg
))
1022 mri_
->setRegAllocationHint(cur
->reg
, 0, Reg
);
1028 // For every interval in inactive we overlap with, mark the
1029 // register as not free and update spill weights.
1030 for (IntervalPtrs::const_iterator i
= inactive_
.begin(),
1031 e
= inactive_
.end(); i
!= e
; ++i
) {
1032 unsigned Reg
= i
->first
->reg
;
1033 assert(TargetRegisterInfo::isVirtualRegister(Reg
) &&
1034 "Can only allocate virtual registers!");
1035 const TargetRegisterClass
*RegRC
= mri_
->getRegClass(Reg
);
1036 // If this is not in a related reg class to the register we're allocating,
1038 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
1039 cur
->overlapsFrom(*i
->first
, i
->second
-1)) {
1040 Reg
= vrm_
->getPhys(Reg
);
1042 SpillWeightsToAdd
.push_back(std::make_pair(Reg
, i
->first
->weight
));
1046 // Speculatively check to see if we can get a register right now. If not,
1047 // we know we won't be able to by adding more constraints. If so, we can
1048 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1049 // is very bad (it contains all callee clobbered registers for any functions
1050 // with a call), so we want to avoid doing that if possible.
1051 unsigned physReg
= getFreePhysReg(cur
);
1052 unsigned BestPhysReg
= physReg
;
1054 // We got a register. However, if it's in the fixed_ list, we might
1055 // conflict with it. Check to see if we conflict with it or any of its
1057 SmallSet
<unsigned, 8> RegAliases
;
1058 for (const unsigned *AS
= tri_
->getAliasSet(physReg
); *AS
; ++AS
)
1059 RegAliases
.insert(*AS
);
1061 bool ConflictsWithFixed
= false;
1062 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
1063 IntervalPtr
&IP
= fixed_
[i
];
1064 if (physReg
== IP
.first
->reg
|| RegAliases
.count(IP
.first
->reg
)) {
1065 // Okay, this reg is on the fixed list. Check to see if we actually
1067 LiveInterval
*I
= IP
.first
;
1068 if (I
->endIndex() > StartPosition
) {
1069 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
1071 if (II
!= I
->begin() && II
->start
> StartPosition
)
1073 if (cur
->overlapsFrom(*I
, II
)) {
1074 ConflictsWithFixed
= true;
1081 // Okay, the register picked by our speculative getFreePhysReg call turned
1082 // out to be in use. Actually add all of the conflicting fixed registers to
1083 // regUse_ so we can do an accurate query.
1084 if (ConflictsWithFixed
) {
1085 // For every interval in fixed we overlap with, mark the register as not
1086 // free and update spill weights.
1087 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
1088 IntervalPtr
&IP
= fixed_
[i
];
1089 LiveInterval
*I
= IP
.first
;
1091 const TargetRegisterClass
*RegRC
= OneClassForEachPhysReg
[I
->reg
];
1092 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
1093 I
->endIndex() > StartPosition
) {
1094 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
1096 if (II
!= I
->begin() && II
->start
> StartPosition
)
1098 if (cur
->overlapsFrom(*I
, II
)) {
1099 unsigned reg
= I
->reg
;
1101 SpillWeightsToAdd
.push_back(std::make_pair(reg
, I
->weight
));
1106 // Using the newly updated regUse_ object, which includes conflicts in the
1107 // future, see if there are any registers available.
1108 physReg
= getFreePhysReg(cur
);
1112 // Restore the physical register tracker, removing information about the
1116 // If we find a free register, we are done: assign this virtual to
1117 // the free physical register and add this interval to the active
1120 DEBUG(dbgs() << tri_
->getName(physReg
) << '\n');
1121 assert(RC
->contains(physReg
) && "Invalid candidate");
1122 vrm_
->assignVirt2Phys(cur
->reg
, physReg
);
1124 active_
.push_back(std::make_pair(cur
, cur
->begin()));
1125 handled_
.push_back(cur
);
1127 // Remember physReg for avoiding a write-after-write hazard in the next
1129 if (AvoidWAWHazard
&&
1130 tri_
->avoidWriteAfterWrite(mri_
->getRegClass(cur
->reg
)))
1131 avoidWAW_
= physReg
;
1133 // "Upgrade" the physical register since it has been allocated.
1134 UpgradeRegister(physReg
);
1135 if (LiveInterval
*NextReloadLI
= hasNextReloadInterval(cur
)) {
1136 // "Downgrade" physReg to try to keep physReg from being allocated until
1137 // the next reload from the same SS is allocated.
1138 mri_
->setRegAllocationHint(NextReloadLI
->reg
, 0, physReg
);
1139 DowngradeRegister(cur
, physReg
);
1143 DEBUG(dbgs() << "no free registers\n");
1145 // Compile the spill weights into an array that is better for scanning.
1146 std::vector
<float> SpillWeights(tri_
->getNumRegs(), 0.0f
);
1147 for (std::vector
<std::pair
<unsigned, float> >::iterator
1148 I
= SpillWeightsToAdd
.begin(), E
= SpillWeightsToAdd
.end(); I
!= E
; ++I
)
1149 updateSpillWeights(SpillWeights
, I
->first
, I
->second
, RC
);
1151 // for each interval in active, update spill weights.
1152 for (IntervalPtrs::const_iterator i
= active_
.begin(), e
= active_
.end();
1154 unsigned reg
= i
->first
->reg
;
1155 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
1156 "Can only allocate virtual registers!");
1157 reg
= vrm_
->getPhys(reg
);
1158 updateSpillWeights(SpillWeights
, reg
, i
->first
->weight
, RC
);
1161 DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur
<< ":\n");
1163 // Find a register to spill.
1164 float minWeight
= HUGE_VALF
;
1165 unsigned minReg
= 0;
1168 std::vector
<std::pair
<unsigned,float> > RegsWeights
;
1169 ArrayRef
<unsigned> Order
= RegClassInfo
.getOrder(RC
);
1170 if (!minReg
|| SpillWeights
[minReg
] == HUGE_VALF
)
1171 for (unsigned i
= 0; i
!= Order
.size(); ++i
) {
1172 unsigned reg
= Order
[i
];
1173 float regWeight
= SpillWeights
[reg
];
1174 // Skip recently allocated registers and reserved registers.
1175 if (minWeight
> regWeight
&& !isRecentlyUsed(reg
))
1177 RegsWeights
.push_back(std::make_pair(reg
, regWeight
));
1180 // If we didn't find a register that is spillable, try aliases?
1182 for (unsigned i
= 0; i
!= Order
.size(); ++i
) {
1183 unsigned reg
= Order
[i
];
1184 // No need to worry about if the alias register size < regsize of RC.
1185 // We are going to spill all registers that alias it anyway.
1186 for (const unsigned* as
= tri_
->getAliasSet(reg
); *as
; ++as
)
1187 RegsWeights
.push_back(std::make_pair(*as
, SpillWeights
[*as
]));
1191 // Sort all potential spill candidates by weight.
1192 std::sort(RegsWeights
.begin(), RegsWeights
.end(), WeightCompare(*this));
1193 minReg
= RegsWeights
[0].first
;
1194 minWeight
= RegsWeights
[0].second
;
1195 if (minWeight
== HUGE_VALF
) {
1196 // All registers must have inf weight. Just grab one!
1197 minReg
= BestPhysReg
? BestPhysReg
: getFirstNonReservedPhysReg(RC
);
1198 if (cur
->weight
== HUGE_VALF
||
1199 li_
->getApproximateInstructionCount(*cur
) == 0) {
1200 // Spill a physical register around defs and uses.
1201 if (li_
->spillPhysRegAroundRegDefsUses(*cur
, minReg
, *vrm_
)) {
1202 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1203 // in fixed_. Reset them.
1204 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
1205 IntervalPtr
&IP
= fixed_
[i
];
1206 LiveInterval
*I
= IP
.first
;
1207 if (I
->reg
== minReg
|| tri_
->isSubRegister(minReg
, I
->reg
))
1208 IP
.second
= I
->advanceTo(I
->begin(), StartPosition
);
1211 DowngradedRegs
.clear();
1212 assignRegOrStackSlotAtInterval(cur
);
1214 assert(false && "Ran out of registers during register allocation!");
1215 report_fatal_error("Ran out of registers during register allocation!");
1221 // Find up to 3 registers to consider as spill candidates.
1222 unsigned LastCandidate
= RegsWeights
.size() >= 3 ? 3 : 1;
1223 while (LastCandidate
> 1) {
1224 if (weightsAreClose(RegsWeights
[LastCandidate
-1].second
, minWeight
))
1230 dbgs() << "\t\tregister(s) with min weight(s): ";
1232 for (unsigned i
= 0; i
!= LastCandidate
; ++i
)
1233 dbgs() << tri_
->getName(RegsWeights
[i
].first
)
1234 << " (" << RegsWeights
[i
].second
<< ")\n";
1237 // If the current has the minimum weight, we need to spill it and
1238 // add any added intervals back to unhandled, and restart
1240 if (cur
->weight
!= HUGE_VALF
&& cur
->weight
<= minWeight
) {
1241 DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur
<< '\n');
1242 SmallVector
<LiveInterval
*, 8> added
;
1243 LiveRangeEdit
LRE(*cur
, added
);
1244 spiller_
->spill(LRE
);
1246 std::sort(added
.begin(), added
.end(), LISorter());
1248 return; // Early exit if all spills were folded.
1250 // Merge added with unhandled. Note that we have already sorted
1251 // intervals returned by addIntervalsForSpills by their starting
1253 // This also update the NextReloadMap. That is, it adds mapping from a
1254 // register defined by a reload from SS to the next reload from SS in the
1255 // same basic block.
1256 MachineBasicBlock
*LastReloadMBB
= 0;
1257 LiveInterval
*LastReload
= 0;
1258 int LastReloadSS
= VirtRegMap::NO_STACK_SLOT
;
1259 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
) {
1260 LiveInterval
*ReloadLi
= added
[i
];
1261 if (ReloadLi
->weight
== HUGE_VALF
&&
1262 li_
->getApproximateInstructionCount(*ReloadLi
) == 0) {
1263 SlotIndex ReloadIdx
= ReloadLi
->beginIndex();
1264 MachineBasicBlock
*ReloadMBB
= li_
->getMBBFromIndex(ReloadIdx
);
1265 int ReloadSS
= vrm_
->getStackSlot(ReloadLi
->reg
);
1266 if (LastReloadMBB
== ReloadMBB
&& LastReloadSS
== ReloadSS
) {
1267 // Last reload of same SS is in the same MBB. We want to try to
1268 // allocate both reloads the same register and make sure the reg
1269 // isn't clobbered in between if at all possible.
1270 assert(LastReload
->beginIndex() < ReloadIdx
);
1271 NextReloadMap
.insert(std::make_pair(LastReload
->reg
, ReloadLi
->reg
));
1273 LastReloadMBB
= ReloadMBB
;
1274 LastReload
= ReloadLi
;
1275 LastReloadSS
= ReloadSS
;
1277 unhandled_
.push(ReloadLi
);
1284 // Push the current interval back to unhandled since we are going
1285 // to re-run at least this iteration. Since we didn't modify it it
1286 // should go back right in the front of the list
1287 unhandled_
.push(cur
);
1289 assert(TargetRegisterInfo::isPhysicalRegister(minReg
) &&
1290 "did not choose a register to spill?");
1292 // We spill all intervals aliasing the register with
1293 // minimum weight, rollback to the interval with the earliest
1294 // start point and let the linear scan algorithm run again
1295 SmallVector
<LiveInterval
*, 8> spillIs
;
1297 // Determine which intervals have to be spilled.
1298 findIntervalsToSpill(cur
, RegsWeights
, LastCandidate
, spillIs
);
1300 // Set of spilled vregs (used later to rollback properly)
1301 SmallSet
<unsigned, 8> spilled
;
1303 // The earliest start of a Spilled interval indicates up to where
1304 // in handled we need to roll back
1305 assert(!spillIs
.empty() && "No spill intervals?");
1306 SlotIndex earliestStart
= spillIs
[0]->beginIndex();
1308 // Spill live intervals of virtual regs mapped to the physical register we
1309 // want to clear (and its aliases). We only spill those that overlap with the
1310 // current interval as the rest do not affect its allocation. we also keep
1311 // track of the earliest start of all spilled live intervals since this will
1312 // mark our rollback point.
1313 SmallVector
<LiveInterval
*, 8> added
;
1314 while (!spillIs
.empty()) {
1315 LiveInterval
*sli
= spillIs
.back();
1317 DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli
<< '\n');
1318 if (sli
->beginIndex() < earliestStart
)
1319 earliestStart
= sli
->beginIndex();
1320 LiveRangeEdit
LRE(*sli
, added
, 0, &spillIs
);
1321 spiller_
->spill(LRE
);
1322 spilled
.insert(sli
->reg
);
1325 // Include any added intervals in earliestStart.
1326 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
) {
1327 SlotIndex SI
= added
[i
]->beginIndex();
1328 if (SI
< earliestStart
)
1332 DEBUG(dbgs() << "\t\trolling back to: " << earliestStart
<< '\n');
1334 // Scan handled in reverse order up to the earliest start of a
1335 // spilled live interval and undo each one, restoring the state of
1337 while (!handled_
.empty()) {
1338 LiveInterval
* i
= handled_
.back();
1339 // If this interval starts before t we are done.
1340 if (!i
->empty() && i
->beginIndex() < earliestStart
)
1342 DEBUG(dbgs() << "\t\t\tundo changes for: " << *i
<< '\n');
1343 handled_
.pop_back();
1345 // When undoing a live interval allocation we must know if it is active or
1346 // inactive to properly update regUse_ and the VirtRegMap.
1347 IntervalPtrs::iterator it
;
1348 if ((it
= FindIntervalInVector(active_
, i
)) != active_
.end()) {
1350 assert(!TargetRegisterInfo::isPhysicalRegister(i
->reg
));
1351 if (!spilled
.count(i
->reg
))
1353 delRegUse(vrm_
->getPhys(i
->reg
));
1354 vrm_
->clearVirt(i
->reg
);
1355 } else if ((it
= FindIntervalInVector(inactive_
, i
)) != inactive_
.end()) {
1356 inactive_
.erase(it
);
1357 assert(!TargetRegisterInfo::isPhysicalRegister(i
->reg
));
1358 if (!spilled
.count(i
->reg
))
1360 vrm_
->clearVirt(i
->reg
);
1362 assert(TargetRegisterInfo::isVirtualRegister(i
->reg
) &&
1363 "Can only allocate virtual registers!");
1364 vrm_
->clearVirt(i
->reg
);
1368 DenseMap
<unsigned, unsigned>::iterator ii
= DowngradeMap
.find(i
->reg
);
1369 if (ii
== DowngradeMap
.end())
1370 // It interval has a preference, it must be defined by a copy. Clear the
1371 // preference now since the source interval allocation may have been
1373 mri_
->setRegAllocationHint(i
->reg
, 0, 0);
1375 UpgradeRegister(ii
->second
);
1379 // Rewind the iterators in the active, inactive, and fixed lists back to the
1380 // point we reverted to.
1381 RevertVectorIteratorsTo(active_
, earliestStart
);
1382 RevertVectorIteratorsTo(inactive_
, earliestStart
);
1383 RevertVectorIteratorsTo(fixed_
, earliestStart
);
1385 // Scan the rest and undo each interval that expired after t and
1386 // insert it in active (the next iteration of the algorithm will
1387 // put it in inactive if required)
1388 for (unsigned i
= 0, e
= handled_
.size(); i
!= e
; ++i
) {
1389 LiveInterval
*HI
= handled_
[i
];
1390 if (!HI
->expiredAt(earliestStart
) &&
1391 HI
->expiredAt(cur
->beginIndex())) {
1392 DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI
<< '\n');
1393 active_
.push_back(std::make_pair(HI
, HI
->begin()));
1394 assert(!TargetRegisterInfo::isPhysicalRegister(HI
->reg
));
1395 addRegUse(vrm_
->getPhys(HI
->reg
));
1399 // Merge added with unhandled.
1400 // This also update the NextReloadMap. That is, it adds mapping from a
1401 // register defined by a reload from SS to the next reload from SS in the
1402 // same basic block.
1403 MachineBasicBlock
*LastReloadMBB
= 0;
1404 LiveInterval
*LastReload
= 0;
1405 int LastReloadSS
= VirtRegMap::NO_STACK_SLOT
;
1406 std::sort(added
.begin(), added
.end(), LISorter());
1407 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
) {
1408 LiveInterval
*ReloadLi
= added
[i
];
1409 if (ReloadLi
->weight
== HUGE_VALF
&&
1410 li_
->getApproximateInstructionCount(*ReloadLi
) == 0) {
1411 SlotIndex ReloadIdx
= ReloadLi
->beginIndex();
1412 MachineBasicBlock
*ReloadMBB
= li_
->getMBBFromIndex(ReloadIdx
);
1413 int ReloadSS
= vrm_
->getStackSlot(ReloadLi
->reg
);
1414 if (LastReloadMBB
== ReloadMBB
&& LastReloadSS
== ReloadSS
) {
1415 // Last reload of same SS is in the same MBB. We want to try to
1416 // allocate both reloads the same register and make sure the reg
1417 // isn't clobbered in between if at all possible.
1418 assert(LastReload
->beginIndex() < ReloadIdx
);
1419 NextReloadMap
.insert(std::make_pair(LastReload
->reg
, ReloadLi
->reg
));
1421 LastReloadMBB
= ReloadMBB
;
1422 LastReload
= ReloadLi
;
1423 LastReloadSS
= ReloadSS
;
1425 unhandled_
.push(ReloadLi
);
1429 unsigned RALinScan::getFreePhysReg(LiveInterval
* cur
,
1430 const TargetRegisterClass
*RC
,
1431 unsigned MaxInactiveCount
,
1432 SmallVector
<unsigned, 256> &inactiveCounts
,
1434 unsigned FreeReg
= 0;
1435 unsigned FreeRegInactiveCount
= 0;
1437 std::pair
<unsigned, unsigned> Hint
= mri_
->getRegAllocationHint(cur
->reg
);
1438 // Resolve second part of the hint (if possible) given the current allocation.
1439 unsigned physReg
= Hint
.second
;
1440 if (TargetRegisterInfo::isVirtualRegister(physReg
) && vrm_
->hasPhys(physReg
))
1441 physReg
= vrm_
->getPhys(physReg
);
1443 ArrayRef
<unsigned> Order
;
1445 Order
= tri_
->getRawAllocationOrder(RC
, Hint
.first
, physReg
, *mf_
);
1447 Order
= RegClassInfo
.getOrder(RC
);
1449 assert(!Order
.empty() && "No allocatable register in this register class!");
1451 // Scan for the first available register.
1452 for (unsigned i
= 0; i
!= Order
.size(); ++i
) {
1453 unsigned Reg
= Order
[i
];
1454 // Ignore "downgraded" registers.
1455 if (SkipDGRegs
&& DowngradedRegs
.count(Reg
))
1457 // Skip reserved registers.
1458 if (reservedRegs_
.test(Reg
))
1460 // Skip recently allocated registers.
1461 if (isRegAvail(Reg
) && (!SkipDGRegs
|| !isRecentlyUsed(Reg
))) {
1463 if (FreeReg
< inactiveCounts
.size())
1464 FreeRegInactiveCount
= inactiveCounts
[FreeReg
];
1466 FreeRegInactiveCount
= 0;
1471 // If there are no free regs, or if this reg has the max inactive count,
1472 // return this register.
1473 if (FreeReg
== 0 || FreeRegInactiveCount
== MaxInactiveCount
) {
1474 // Remember what register we picked so we can skip it next time.
1475 if (FreeReg
!= 0) recordRecentlyUsed(FreeReg
);
1479 // Continue scanning the registers, looking for the one with the highest
1480 // inactive count. Alkis found that this reduced register pressure very
1481 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1483 for (unsigned i
= 0; i
!= Order
.size(); ++i
) {
1484 unsigned Reg
= Order
[i
];
1485 // Ignore "downgraded" registers.
1486 if (SkipDGRegs
&& DowngradedRegs
.count(Reg
))
1488 // Skip reserved registers.
1489 if (reservedRegs_
.test(Reg
))
1491 if (isRegAvail(Reg
) && Reg
< inactiveCounts
.size() &&
1492 FreeRegInactiveCount
< inactiveCounts
[Reg
] &&
1493 (!SkipDGRegs
|| !isRecentlyUsed(Reg
))) {
1495 FreeRegInactiveCount
= inactiveCounts
[Reg
];
1496 if (FreeRegInactiveCount
== MaxInactiveCount
)
1497 break; // We found the one with the max inactive count.
1501 // Remember what register we picked so we can skip it next time.
1502 recordRecentlyUsed(FreeReg
);
1507 /// getFreePhysReg - return a free physical register for this virtual register
1508 /// interval if we have one, otherwise return 0.
1509 unsigned RALinScan::getFreePhysReg(LiveInterval
*cur
) {
1510 SmallVector
<unsigned, 256> inactiveCounts
;
1511 unsigned MaxInactiveCount
= 0;
1513 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
->reg
);
1514 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
1516 for (IntervalPtrs::iterator i
= inactive_
.begin(), e
= inactive_
.end();
1518 unsigned reg
= i
->first
->reg
;
1519 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
1520 "Can only allocate virtual registers!");
1522 // If this is not in a related reg class to the register we're allocating,
1524 const TargetRegisterClass
*RegRC
= mri_
->getRegClass(reg
);
1525 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
) {
1526 reg
= vrm_
->getPhys(reg
);
1527 if (inactiveCounts
.size() <= reg
)
1528 inactiveCounts
.resize(reg
+1);
1529 ++inactiveCounts
[reg
];
1530 MaxInactiveCount
= std::max(MaxInactiveCount
, inactiveCounts
[reg
]);
1534 // If copy coalescer has assigned a "preferred" register, check if it's
1536 unsigned Preference
= vrm_
->getRegAllocPref(cur
->reg
);
1538 DEBUG(dbgs() << "(preferred: " << tri_
->getName(Preference
) << ") ");
1539 if (isRegAvail(Preference
) &&
1540 RC
->contains(Preference
))
1544 unsigned FreeReg
= getFreePhysReg(cur
, RC
, MaxInactiveCount
, inactiveCounts
,
1548 return getFreePhysReg(cur
, RC
, MaxInactiveCount
, inactiveCounts
, false);
1551 FunctionPass
* llvm::createLinearScanRegisterAllocator() {
1552 return new RALinScan();