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"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/CalcSpillWeights.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/RegisterCoalescer.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/ADT/EquivalenceClasses.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
49 STATISTIC(NumIters , "Number of iterations performed");
50 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
51 STATISTIC(NumCoalesce, "Number of copies coalesced");
52 STATISTIC(NumDowngrade, "Number of registers downgraded");
55 NewHeuristic("new-spilling-heuristic",
56 cl::desc("Use new spilling heuristic"),
57 cl::init(false), cl::Hidden);
60 PreSplitIntervals("pre-alloc-split",
61 cl::desc("Pre-register allocation live interval splitting"),
62 cl::init(false), cl::Hidden);
65 TrivCoalesceEnds("trivial-coalesce-ends",
66 cl::desc("Attempt trivial coalescing of interval ends"),
67 cl::init(false), cl::Hidden);
70 AvoidWAWHazard("avoid-waw-hazard",
71 cl::desc("Avoid write-write hazards for some register classes"),
72 cl::init(false), cl::Hidden);
74 static RegisterRegAlloc
75 linearscanRegAlloc("linearscan", "linear scan register allocator",
76 createLinearScanRegisterAllocator);
79 // When we allocate a register, add it to a fixed-size queue of
80 // registers to skip in subsequent allocations. This trades a small
81 // amount of register pressure and increased spills for flexibility in
82 // the post-pass scheduler.
84 // Note that in a the number of registers used for reloading spills
85 // will be one greater than the value of this option.
87 // One big limitation of this is that it doesn't differentiate between
88 // different register classes. So on x86-64, if there is xmm register
89 // pressure, it can caused fewer GPRs to be held in the queue.
90 static cl::opt<unsigned>
91 NumRecentlyUsedRegs("linearscan-skip-count",
92 cl::desc("Number of registers for linearscan to remember"
97 struct RALinScan : public MachineFunctionPass {
99 RALinScan() : MachineFunctionPass(ID) {
100 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
101 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
102 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
103 initializeRegisterCoalescerAnalysisGroup(
104 *PassRegistry::getPassRegistry());
105 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
106 initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
107 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
108 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
109 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
110 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
111 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
113 // Initialize the queue to record recently-used registers.
114 if (NumRecentlyUsedRegs > 0)
115 RecentRegs.resize(NumRecentlyUsedRegs, 0);
116 RecentNext = RecentRegs.begin();
120 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
121 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
123 /// RelatedRegClasses - This structure is built the first time a function is
124 /// compiled, and keeps track of which register classes have registers that
125 /// belong to multiple classes or have aliases that are in other classes.
126 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
127 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
129 // NextReloadMap - For each register in the map, it maps to the another
130 // register which is defined by a reload from the same stack slot and
131 // both reloads are in the same basic block.
132 DenseMap<unsigned, unsigned> NextReloadMap;
134 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
135 // un-favored for allocation.
136 SmallSet<unsigned, 8> DowngradedRegs;
138 // DowngradeMap - A map from virtual registers to physical registers being
139 // downgraded for the virtual registers.
140 DenseMap<unsigned, unsigned> DowngradeMap;
142 MachineFunction* mf_;
143 MachineRegisterInfo* mri_;
144 const TargetMachine* tm_;
145 const TargetRegisterInfo* tri_;
146 const TargetInstrInfo* tii_;
147 BitVector allocatableRegs_;
148 BitVector reservedRegs_;
150 MachineLoopInfo *loopInfo;
152 /// handled_ - Intervals are added to the handled_ set in the order of their
153 /// start value. This is uses for backtracking.
154 std::vector<LiveInterval*> handled_;
156 /// fixed_ - Intervals that correspond to machine registers.
160 /// active_ - Intervals that are currently being processed, and which have a
161 /// live range active for the current point.
162 IntervalPtrs active_;
164 /// inactive_ - Intervals that are currently being processed, but which have
165 /// a hold at the current point.
166 IntervalPtrs inactive_;
168 typedef std::priority_queue<LiveInterval*,
169 SmallVector<LiveInterval*, 64>,
170 greater_ptr<LiveInterval> > IntervalHeap;
171 IntervalHeap unhandled_;
173 /// regUse_ - Tracks register usage.
174 SmallVector<unsigned, 32> regUse_;
175 SmallVector<unsigned, 32> regUseBackUp_;
177 /// vrm_ - Tracks register assignments.
180 std::auto_ptr<VirtRegRewriter> rewriter_;
182 std::auto_ptr<Spiller> spiller_;
184 // The queue of recently-used registers.
185 SmallVector<unsigned, 4> RecentRegs;
186 SmallVector<unsigned, 4>::iterator RecentNext;
188 // Last write-after-write register written.
191 // Record that we just picked this register.
192 void recordRecentlyUsed(unsigned reg) {
193 assert(reg != 0 && "Recently used register is NOREG!");
194 if (!RecentRegs.empty()) {
196 if (RecentNext == RecentRegs.end())
197 RecentNext = RecentRegs.begin();
202 virtual const char* getPassName() const {
203 return "Linear Scan Register Allocator";
206 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207 AU.setPreservesCFG();
208 AU.addRequired<AliasAnalysis>();
209 AU.addPreserved<AliasAnalysis>();
210 AU.addRequired<LiveIntervals>();
211 AU.addPreserved<SlotIndexes>();
213 AU.addRequiredID(StrongPHIEliminationID);
214 // Make sure PassManager knows which analyses to make available
215 // to coalescing and which analyses coalescing invalidates.
216 AU.addRequiredTransitive<RegisterCoalescer>();
217 AU.addRequired<CalculateSpillWeights>();
218 if (PreSplitIntervals)
219 AU.addRequiredID(PreAllocSplittingID);
220 AU.addRequiredID(LiveStacksID);
221 AU.addPreservedID(LiveStacksID);
222 AU.addRequired<MachineLoopInfo>();
223 AU.addPreserved<MachineLoopInfo>();
224 AU.addRequired<VirtRegMap>();
225 AU.addPreserved<VirtRegMap>();
226 AU.addRequired<LiveDebugVariables>();
227 AU.addPreserved<LiveDebugVariables>();
228 AU.addRequiredID(MachineDominatorsID);
229 AU.addPreservedID(MachineDominatorsID);
230 MachineFunctionPass::getAnalysisUsage(AU);
233 /// runOnMachineFunction - register allocate the whole function
234 bool runOnMachineFunction(MachineFunction&);
236 // Determine if we skip this register due to its being recently used.
237 bool isRecentlyUsed(unsigned reg) const {
238 return reg == avoidWAW_ ||
239 std::find(RecentRegs.begin(), RecentRegs.end(), reg) != RecentRegs.end();
243 /// linearScan - the linear scan algorithm
246 /// initIntervalSets - initialize the interval sets.
248 void initIntervalSets();
250 /// processActiveIntervals - expire old intervals and move non-overlapping
251 /// ones to the inactive list.
252 void processActiveIntervals(SlotIndex CurPoint);
254 /// processInactiveIntervals - expire old intervals and move overlapping
255 /// ones to the active list.
256 void processInactiveIntervals(SlotIndex CurPoint);
258 /// hasNextReloadInterval - Return the next liveinterval that's being
259 /// defined by a reload from the same SS as the specified one.
260 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
262 /// DowngradeRegister - Downgrade a register for allocation.
263 void DowngradeRegister(LiveInterval *li, unsigned Reg);
265 /// UpgradeRegister - Upgrade a register for allocation.
266 void UpgradeRegister(unsigned Reg);
268 /// assignRegOrStackSlotAtInterval - assign a register if one
269 /// is available, or spill.
270 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
272 void updateSpillWeights(std::vector<float> &Weights,
273 unsigned reg, float weight,
274 const TargetRegisterClass *RC);
276 /// findIntervalsToSpill - Determine the intervals to spill for the
277 /// specified interval. It's passed the physical registers whose spill
278 /// weight is the lowest among all the registers whose live intervals
279 /// conflict with the interval.
280 void findIntervalsToSpill(LiveInterval *cur,
281 std::vector<std::pair<unsigned,float> > &Candidates,
283 SmallVector<LiveInterval*, 8> &SpillIntervals);
285 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
286 /// try to allocate the definition to the same register as the source,
287 /// if the register is not defined during the life time of the interval.
288 /// This eliminates a copy, and is used to coalesce copies which were not
289 /// coalesced away before allocation either due to dest and src being in
290 /// different register classes or because the coalescer was overly
292 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
295 /// Register usage / availability tracking helpers.
299 regUse_.resize(tri_->getNumRegs(), 0);
300 regUseBackUp_.resize(tri_->getNumRegs(), 0);
303 void finalizeRegUses() {
305 // Verify all the registers are "freed".
307 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
308 if (regUse_[i] != 0) {
309 dbgs() << tri_->getName(i) << " is still in use!\n";
317 regUseBackUp_.clear();
320 void addRegUse(unsigned physReg) {
321 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
322 "should be physical register!");
324 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
328 void delRegUse(unsigned physReg) {
329 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
330 "should be physical register!");
331 assert(regUse_[physReg] != 0);
333 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
334 assert(regUse_[*as] != 0);
339 bool isRegAvail(unsigned physReg) const {
340 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
341 "should be physical register!");
342 return regUse_[physReg] == 0;
345 void backUpRegUses() {
346 regUseBackUp_ = regUse_;
349 void restoreRegUses() {
350 regUse_ = regUseBackUp_;
354 /// Register handling helpers.
357 /// getFreePhysReg - return a free physical register for this virtual
358 /// register interval if we have one, otherwise return 0.
359 unsigned getFreePhysReg(LiveInterval* cur);
360 unsigned getFreePhysReg(LiveInterval* cur,
361 const TargetRegisterClass *RC,
362 unsigned MaxInactiveCount,
363 SmallVector<unsigned, 256> &inactiveCounts,
366 /// getFirstNonReservedPhysReg - return the first non-reserved physical
367 /// register in the register class.
368 unsigned getFirstNonReservedPhysReg(const TargetRegisterClass *RC) {
369 TargetRegisterClass::iterator aoe = RC->allocation_order_end(*mf_);
370 TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_);
371 while (i != aoe && reservedRegs_.test(*i))
373 assert(i != aoe && "All registers reserved?!");
377 void ComputeRelatedRegClasses();
379 template <typename ItTy>
380 void printIntervals(const char* const str, ItTy i, ItTy e) const {
383 dbgs() << str << " intervals:\n";
385 for (; i != e; ++i) {
386 dbgs() << '\t' << *i->first << " -> ";
388 unsigned reg = i->first->reg;
389 if (TargetRegisterInfo::isVirtualRegister(reg))
390 reg = vrm_->getPhys(reg);
392 dbgs() << tri_->getName(reg) << '\n';
397 char RALinScan::ID = 0;
400 INITIALIZE_PASS_BEGIN(RALinScan, "linearscan-regalloc",
401 "Linear Scan Register Allocator", false, false)
402 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
403 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
404 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
405 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting)
406 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
407 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
408 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
409 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
410 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
411 INITIALIZE_PASS_END(RALinScan, "linearscan-regalloc",
412 "Linear Scan Register Allocator", false, false)
414 void RALinScan::ComputeRelatedRegClasses() {
415 // First pass, add all reg classes to the union, and determine at least one
416 // reg class that each register is in.
417 bool HasAliases = false;
418 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
419 E = tri_->regclass_end(); RCI != E; ++RCI) {
420 RelatedRegClasses.insert(*RCI);
421 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
423 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
425 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
427 // Already processed this register. Just make sure we know that
428 // multiple register classes share a register.
429 RelatedRegClasses.unionSets(PRC, *RCI);
436 // Second pass, now that we know conservatively what register classes each reg
437 // belongs to, add info about aliases. We don't need to do this for targets
438 // without register aliases.
440 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
441 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
443 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS) {
444 const TargetRegisterClass *AliasClass =
445 OneClassForEachPhysReg.lookup(*AS);
447 RelatedRegClasses.unionSets(I->second, AliasClass);
451 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
452 /// allocate the definition the same register as the source register if the
453 /// register is not defined during live time of the interval. If the interval is
454 /// killed by a copy, try to use the destination register. This eliminates a
455 /// copy. This is used to coalesce copies which were not coalesced away before
456 /// allocation either due to dest and src being in different register classes or
457 /// because the coalescer was overly conservative.
458 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
459 unsigned Preference = vrm_->getRegAllocPref(cur.reg);
460 if ((Preference && Preference == Reg) || !cur.containsOneValue())
463 // We cannot handle complicated live ranges. Simple linear stuff only.
464 if (cur.ranges.size() != 1)
467 const LiveRange &range = cur.ranges.front();
469 VNInfo *vni = range.valno;
470 if (vni->isUnused() || !vni->def.isValid())
475 MachineInstr *CopyMI;
476 if ((CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
477 // Defined by a copy, try to extend SrcReg forward
478 CandReg = CopyMI->getOperand(1).getReg();
479 else if (TrivCoalesceEnds &&
480 (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
481 CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
482 // Only used by a copy, try to extend DstReg backwards
483 CandReg = CopyMI->getOperand(0).getReg();
487 // If the target of the copy is a sub-register then don't coalesce.
488 if(CopyMI->getOperand(0).getSubReg())
492 if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
493 if (!vrm_->isAssignedReg(CandReg))
495 CandReg = vrm_->getPhys(CandReg);
500 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
501 if (!RC->contains(CandReg))
504 if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
508 DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
510 vrm_->clearVirt(cur.reg);
511 vrm_->assignVirt2Phys(cur.reg, CandReg);
517 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
519 mri_ = &fn.getRegInfo();
520 tm_ = &fn.getTarget();
521 tri_ = tm_->getRegisterInfo();
522 tii_ = tm_->getInstrInfo();
523 allocatableRegs_ = tri_->getAllocatableSet(fn);
524 reservedRegs_ = tri_->getReservedRegs(fn);
525 li_ = &getAnalysis<LiveIntervals>();
526 loopInfo = &getAnalysis<MachineLoopInfo>();
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 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1170 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1171 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1173 float regWeight = SpillWeights[reg];
1174 // Don't even consider reserved regs.
1175 if (reservedRegs_.test(reg))
1177 // Skip recently allocated registers and reserved registers.
1178 if (minWeight > regWeight && !isRecentlyUsed(reg))
1180 RegsWeights.push_back(std::make_pair(reg, regWeight));
1183 // If we didn't find a register that is spillable, try aliases?
1185 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1186 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1188 if (reservedRegs_.test(reg))
1190 // No need to worry about if the alias register size < regsize of RC.
1191 // We are going to spill all registers that alias it anyway.
1192 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1193 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1197 // Sort all potential spill candidates by weight.
1198 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1199 minReg = RegsWeights[0].first;
1200 minWeight = RegsWeights[0].second;
1201 if (minWeight == HUGE_VALF) {
1202 // All registers must have inf weight. Just grab one!
1203 minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1204 if (cur->weight == HUGE_VALF ||
1205 li_->getApproximateInstructionCount(*cur) == 0) {
1206 // Spill a physical register around defs and uses.
1207 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1208 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1209 // in fixed_. Reset them.
1210 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1211 IntervalPtr &IP = fixed_[i];
1212 LiveInterval *I = IP.first;
1213 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1214 IP.second = I->advanceTo(I->begin(), StartPosition);
1217 DowngradedRegs.clear();
1218 assignRegOrStackSlotAtInterval(cur);
1220 assert(false && "Ran out of registers during register allocation!");
1221 report_fatal_error("Ran out of registers during register allocation!");
1227 // Find up to 3 registers to consider as spill candidates.
1228 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1229 while (LastCandidate > 1) {
1230 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1236 dbgs() << "\t\tregister(s) with min weight(s): ";
1238 for (unsigned i = 0; i != LastCandidate; ++i)
1239 dbgs() << tri_->getName(RegsWeights[i].first)
1240 << " (" << RegsWeights[i].second << ")\n";
1243 // If the current has the minimum weight, we need to spill it and
1244 // add any added intervals back to unhandled, and restart
1246 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1247 DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1248 SmallVector<LiveInterval*, 8> added;
1249 LiveRangeEdit LRE(*cur, added);
1250 spiller_->spill(LRE);
1252 std::sort(added.begin(), added.end(), LISorter());
1254 return; // Early exit if all spills were folded.
1256 // Merge added with unhandled. Note that we have already sorted
1257 // intervals returned by addIntervalsForSpills by their starting
1259 // This also update the NextReloadMap. That is, it adds mapping from a
1260 // register defined by a reload from SS to the next reload from SS in the
1261 // same basic block.
1262 MachineBasicBlock *LastReloadMBB = 0;
1263 LiveInterval *LastReload = 0;
1264 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1265 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1266 LiveInterval *ReloadLi = added[i];
1267 if (ReloadLi->weight == HUGE_VALF &&
1268 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1269 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1270 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1271 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1272 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1273 // Last reload of same SS is in the same MBB. We want to try to
1274 // allocate both reloads the same register and make sure the reg
1275 // isn't clobbered in between if at all possible.
1276 assert(LastReload->beginIndex() < ReloadIdx);
1277 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1279 LastReloadMBB = ReloadMBB;
1280 LastReload = ReloadLi;
1281 LastReloadSS = ReloadSS;
1283 unhandled_.push(ReloadLi);
1290 // Push the current interval back to unhandled since we are going
1291 // to re-run at least this iteration. Since we didn't modify it it
1292 // should go back right in the front of the list
1293 unhandled_.push(cur);
1295 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1296 "did not choose a register to spill?");
1298 // We spill all intervals aliasing the register with
1299 // minimum weight, rollback to the interval with the earliest
1300 // start point and let the linear scan algorithm run again
1301 SmallVector<LiveInterval*, 8> spillIs;
1303 // Determine which intervals have to be spilled.
1304 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1306 // Set of spilled vregs (used later to rollback properly)
1307 SmallSet<unsigned, 8> spilled;
1309 // The earliest start of a Spilled interval indicates up to where
1310 // in handled we need to roll back
1311 assert(!spillIs.empty() && "No spill intervals?");
1312 SlotIndex earliestStart = spillIs[0]->beginIndex();
1314 // Spill live intervals of virtual regs mapped to the physical register we
1315 // want to clear (and its aliases). We only spill those that overlap with the
1316 // current interval as the rest do not affect its allocation. we also keep
1317 // track of the earliest start of all spilled live intervals since this will
1318 // mark our rollback point.
1319 SmallVector<LiveInterval*, 8> added;
1320 while (!spillIs.empty()) {
1321 LiveInterval *sli = spillIs.back();
1323 DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1324 if (sli->beginIndex() < earliestStart)
1325 earliestStart = sli->beginIndex();
1326 LiveRangeEdit LRE(*sli, added, 0, &spillIs);
1327 spiller_->spill(LRE);
1328 spilled.insert(sli->reg);
1331 // Include any added intervals in earliestStart.
1332 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1333 SlotIndex SI = added[i]->beginIndex();
1334 if (SI < earliestStart)
1338 DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1340 // Scan handled in reverse order up to the earliest start of a
1341 // spilled live interval and undo each one, restoring the state of
1343 while (!handled_.empty()) {
1344 LiveInterval* i = handled_.back();
1345 // If this interval starts before t we are done.
1346 if (!i->empty() && i->beginIndex() < earliestStart)
1348 DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1349 handled_.pop_back();
1351 // When undoing a live interval allocation we must know if it is active or
1352 // inactive to properly update regUse_ and the VirtRegMap.
1353 IntervalPtrs::iterator it;
1354 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1356 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1357 if (!spilled.count(i->reg))
1359 delRegUse(vrm_->getPhys(i->reg));
1360 vrm_->clearVirt(i->reg);
1361 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1362 inactive_.erase(it);
1363 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1364 if (!spilled.count(i->reg))
1366 vrm_->clearVirt(i->reg);
1368 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1369 "Can only allocate virtual registers!");
1370 vrm_->clearVirt(i->reg);
1374 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1375 if (ii == DowngradeMap.end())
1376 // It interval has a preference, it must be defined by a copy. Clear the
1377 // preference now since the source interval allocation may have been
1379 mri_->setRegAllocationHint(i->reg, 0, 0);
1381 UpgradeRegister(ii->second);
1385 // Rewind the iterators in the active, inactive, and fixed lists back to the
1386 // point we reverted to.
1387 RevertVectorIteratorsTo(active_, earliestStart);
1388 RevertVectorIteratorsTo(inactive_, earliestStart);
1389 RevertVectorIteratorsTo(fixed_, earliestStart);
1391 // Scan the rest and undo each interval that expired after t and
1392 // insert it in active (the next iteration of the algorithm will
1393 // put it in inactive if required)
1394 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1395 LiveInterval *HI = handled_[i];
1396 if (!HI->expiredAt(earliestStart) &&
1397 HI->expiredAt(cur->beginIndex())) {
1398 DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1399 active_.push_back(std::make_pair(HI, HI->begin()));
1400 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1401 addRegUse(vrm_->getPhys(HI->reg));
1405 // Merge added with unhandled.
1406 // This also update the NextReloadMap. That is, it adds mapping from a
1407 // register defined by a reload from SS to the next reload from SS in the
1408 // same basic block.
1409 MachineBasicBlock *LastReloadMBB = 0;
1410 LiveInterval *LastReload = 0;
1411 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1412 std::sort(added.begin(), added.end(), LISorter());
1413 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1414 LiveInterval *ReloadLi = added[i];
1415 if (ReloadLi->weight == HUGE_VALF &&
1416 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1417 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1418 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1419 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1420 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1421 // Last reload of same SS is in the same MBB. We want to try to
1422 // allocate both reloads the same register and make sure the reg
1423 // isn't clobbered in between if at all possible.
1424 assert(LastReload->beginIndex() < ReloadIdx);
1425 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1427 LastReloadMBB = ReloadMBB;
1428 LastReload = ReloadLi;
1429 LastReloadSS = ReloadSS;
1431 unhandled_.push(ReloadLi);
1435 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1436 const TargetRegisterClass *RC,
1437 unsigned MaxInactiveCount,
1438 SmallVector<unsigned, 256> &inactiveCounts,
1440 unsigned FreeReg = 0;
1441 unsigned FreeRegInactiveCount = 0;
1443 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1444 // Resolve second part of the hint (if possible) given the current allocation.
1445 unsigned physReg = Hint.second;
1446 if (TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1447 physReg = vrm_->getPhys(physReg);
1449 TargetRegisterClass::iterator I, E;
1450 tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1451 assert(I != E && "No allocatable register in this register class!");
1453 // Scan for the first available register.
1454 for (; I != E; ++I) {
1456 // Ignore "downgraded" registers.
1457 if (SkipDGRegs && DowngradedRegs.count(Reg))
1459 // Skip reserved registers.
1460 if (reservedRegs_.test(Reg))
1462 // Skip recently allocated registers.
1463 if (isRegAvail(Reg) && (!SkipDGRegs || !isRecentlyUsed(Reg))) {
1465 if (FreeReg < inactiveCounts.size())
1466 FreeRegInactiveCount = inactiveCounts[FreeReg];
1468 FreeRegInactiveCount = 0;
1473 // If there are no free regs, or if this reg has the max inactive count,
1474 // return this register.
1475 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1476 // Remember what register we picked so we can skip it next time.
1477 if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1481 // Continue scanning the registers, looking for the one with the highest
1482 // inactive count. Alkis found that this reduced register pressure very
1483 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1485 for (; I != E; ++I) {
1487 // Ignore "downgraded" registers.
1488 if (SkipDGRegs && DowngradedRegs.count(Reg))
1490 // Skip reserved registers.
1491 if (reservedRegs_.test(Reg))
1493 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1494 FreeRegInactiveCount < inactiveCounts[Reg] &&
1495 (!SkipDGRegs || !isRecentlyUsed(Reg))) {
1497 FreeRegInactiveCount = inactiveCounts[Reg];
1498 if (FreeRegInactiveCount == MaxInactiveCount)
1499 break; // We found the one with the max inactive count.
1503 // Remember what register we picked so we can skip it next time.
1504 recordRecentlyUsed(FreeReg);
1509 /// getFreePhysReg - return a free physical register for this virtual register
1510 /// interval if we have one, otherwise return 0.
1511 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1512 SmallVector<unsigned, 256> inactiveCounts;
1513 unsigned MaxInactiveCount = 0;
1515 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1516 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1518 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1520 unsigned reg = i->first->reg;
1521 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1522 "Can only allocate virtual registers!");
1524 // If this is not in a related reg class to the register we're allocating,
1526 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1527 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1528 reg = vrm_->getPhys(reg);
1529 if (inactiveCounts.size() <= reg)
1530 inactiveCounts.resize(reg+1);
1531 ++inactiveCounts[reg];
1532 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1536 // If copy coalescer has assigned a "preferred" register, check if it's
1538 unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1540 DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1541 if (isRegAvail(Preference) &&
1542 RC->contains(Preference))
1546 unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1550 return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1553 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1554 return new RALinScan();