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 "VirtRegMap.h"
17 #include "VirtRegRewriter.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/CalcSpillWeights.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterCoalescer.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/ADT/EquivalenceClasses.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #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);
69 static RegisterRegAlloc
70 linearscanRegAlloc("linearscan", "linear scan register allocator",
71 createLinearScanRegisterAllocator);
74 // When we allocate a register, add it to a fixed-size queue of
75 // registers to skip in subsequent allocations. This trades a small
76 // amount of register pressure and increased spills for flexibility in
77 // the post-pass scheduler.
79 // Note that in a the number of registers used for reloading spills
80 // will be one greater than the value of this option.
82 // One big limitation of this is that it doesn't differentiate between
83 // different register classes. So on x86-64, if there is xmm register
84 // pressure, it can caused fewer GPRs to be held in the queue.
85 static cl::opt<unsigned>
86 NumRecentlyUsedRegs("linearscan-skip-count",
87 cl::desc("Number of registers for linearscan to remember"
92 struct RALinScan : public MachineFunctionPass {
94 RALinScan() : MachineFunctionPass(ID) {
95 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
97 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
98 initializeRegisterCoalescerAnalysisGroup(
99 *PassRegistry::getPassRegistry());
100 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
101 initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
102 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
103 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
104 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
105 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
106 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
108 // Initialize the queue to record recently-used registers.
109 if (NumRecentlyUsedRegs > 0)
110 RecentRegs.resize(NumRecentlyUsedRegs, 0);
111 RecentNext = RecentRegs.begin();
114 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
115 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
117 /// RelatedRegClasses - This structure is built the first time a function is
118 /// compiled, and keeps track of which register classes have registers that
119 /// belong to multiple classes or have aliases that are in other classes.
120 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
121 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
123 // NextReloadMap - For each register in the map, it maps to the another
124 // register which is defined by a reload from the same stack slot and
125 // both reloads are in the same basic block.
126 DenseMap<unsigned, unsigned> NextReloadMap;
128 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
129 // un-favored for allocation.
130 SmallSet<unsigned, 8> DowngradedRegs;
132 // DowngradeMap - A map from virtual registers to physical registers being
133 // downgraded for the virtual registers.
134 DenseMap<unsigned, unsigned> DowngradeMap;
136 MachineFunction* mf_;
137 MachineRegisterInfo* mri_;
138 const TargetMachine* tm_;
139 const TargetRegisterInfo* tri_;
140 const TargetInstrInfo* tii_;
141 BitVector allocatableRegs_;
142 BitVector reservedRegs_;
144 MachineLoopInfo *loopInfo;
146 /// handled_ - Intervals are added to the handled_ set in the order of their
147 /// start value. This is uses for backtracking.
148 std::vector<LiveInterval*> handled_;
150 /// fixed_ - Intervals that correspond to machine registers.
154 /// active_ - Intervals that are currently being processed, and which have a
155 /// live range active for the current point.
156 IntervalPtrs active_;
158 /// inactive_ - Intervals that are currently being processed, but which have
159 /// a hold at the current point.
160 IntervalPtrs inactive_;
162 typedef std::priority_queue<LiveInterval*,
163 SmallVector<LiveInterval*, 64>,
164 greater_ptr<LiveInterval> > IntervalHeap;
165 IntervalHeap unhandled_;
167 /// regUse_ - Tracks register usage.
168 SmallVector<unsigned, 32> regUse_;
169 SmallVector<unsigned, 32> regUseBackUp_;
171 /// vrm_ - Tracks register assignments.
174 std::auto_ptr<VirtRegRewriter> rewriter_;
176 std::auto_ptr<Spiller> spiller_;
178 // The queue of recently-used registers.
179 SmallVector<unsigned, 4> RecentRegs;
180 SmallVector<unsigned, 4>::iterator RecentNext;
182 // Record that we just picked this register.
183 void recordRecentlyUsed(unsigned reg) {
184 assert(reg != 0 && "Recently used register is NOREG!");
185 if (!RecentRegs.empty()) {
187 if (RecentNext == RecentRegs.end())
188 RecentNext = RecentRegs.begin();
193 virtual const char* getPassName() const {
194 return "Linear Scan Register Allocator";
197 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198 AU.setPreservesCFG();
199 AU.addRequired<AliasAnalysis>();
200 AU.addPreserved<AliasAnalysis>();
201 AU.addRequired<LiveIntervals>();
202 AU.addPreserved<SlotIndexes>();
204 AU.addRequiredID(StrongPHIEliminationID);
205 // Make sure PassManager knows which analyses to make available
206 // to coalescing and which analyses coalescing invalidates.
207 AU.addRequiredTransitive<RegisterCoalescer>();
208 AU.addRequired<CalculateSpillWeights>();
209 if (PreSplitIntervals)
210 AU.addRequiredID(PreAllocSplittingID);
211 AU.addRequiredID(LiveStacksID);
212 AU.addPreservedID(LiveStacksID);
213 AU.addRequired<MachineLoopInfo>();
214 AU.addPreserved<MachineLoopInfo>();
215 AU.addRequired<VirtRegMap>();
216 AU.addPreserved<VirtRegMap>();
217 AU.addRequired<LiveDebugVariables>();
218 AU.addPreserved<LiveDebugVariables>();
219 AU.addRequiredID(MachineDominatorsID);
220 AU.addPreservedID(MachineDominatorsID);
221 MachineFunctionPass::getAnalysisUsage(AU);
224 /// runOnMachineFunction - register allocate the whole function
225 bool runOnMachineFunction(MachineFunction&);
227 // Determine if we skip this register due to its being recently used.
228 bool isRecentlyUsed(unsigned reg) const {
229 return std::find(RecentRegs.begin(), RecentRegs.end(), reg) !=
234 /// linearScan - the linear scan algorithm
237 /// initIntervalSets - initialize the interval sets.
239 void initIntervalSets();
241 /// processActiveIntervals - expire old intervals and move non-overlapping
242 /// ones to the inactive list.
243 void processActiveIntervals(SlotIndex CurPoint);
245 /// processInactiveIntervals - expire old intervals and move overlapping
246 /// ones to the active list.
247 void processInactiveIntervals(SlotIndex CurPoint);
249 /// hasNextReloadInterval - Return the next liveinterval that's being
250 /// defined by a reload from the same SS as the specified one.
251 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
253 /// DowngradeRegister - Downgrade a register for allocation.
254 void DowngradeRegister(LiveInterval *li, unsigned Reg);
256 /// UpgradeRegister - Upgrade a register for allocation.
257 void UpgradeRegister(unsigned Reg);
259 /// assignRegOrStackSlotAtInterval - assign a register if one
260 /// is available, or spill.
261 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
263 void updateSpillWeights(std::vector<float> &Weights,
264 unsigned reg, float weight,
265 const TargetRegisterClass *RC);
267 /// findIntervalsToSpill - Determine the intervals to spill for the
268 /// specified interval. It's passed the physical registers whose spill
269 /// weight is the lowest among all the registers whose live intervals
270 /// conflict with the interval.
271 void findIntervalsToSpill(LiveInterval *cur,
272 std::vector<std::pair<unsigned,float> > &Candidates,
274 SmallVector<LiveInterval*, 8> &SpillIntervals);
276 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
277 /// try to allocate the definition to the same register as the source,
278 /// if the register is not defined during the life time of the interval.
279 /// This eliminates a copy, and is used to coalesce copies which were not
280 /// coalesced away before allocation either due to dest and src being in
281 /// different register classes or because the coalescer was overly
283 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
286 /// Register usage / availability tracking helpers.
290 regUse_.resize(tri_->getNumRegs(), 0);
291 regUseBackUp_.resize(tri_->getNumRegs(), 0);
294 void finalizeRegUses() {
296 // Verify all the registers are "freed".
298 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
299 if (regUse_[i] != 0) {
300 dbgs() << tri_->getName(i) << " is still in use!\n";
308 regUseBackUp_.clear();
311 void addRegUse(unsigned physReg) {
312 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
313 "should be physical register!");
315 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
319 void delRegUse(unsigned physReg) {
320 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
321 "should be physical register!");
322 assert(regUse_[physReg] != 0);
324 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
325 assert(regUse_[*as] != 0);
330 bool isRegAvail(unsigned physReg) const {
331 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
332 "should be physical register!");
333 return regUse_[physReg] == 0;
336 void backUpRegUses() {
337 regUseBackUp_ = regUse_;
340 void restoreRegUses() {
341 regUse_ = regUseBackUp_;
345 /// Register handling helpers.
348 /// getFreePhysReg - return a free physical register for this virtual
349 /// register interval if we have one, otherwise return 0.
350 unsigned getFreePhysReg(LiveInterval* cur);
351 unsigned getFreePhysReg(LiveInterval* cur,
352 const TargetRegisterClass *RC,
353 unsigned MaxInactiveCount,
354 SmallVector<unsigned, 256> &inactiveCounts,
357 /// getFirstNonReservedPhysReg - return the first non-reserved physical
358 /// register in the register class.
359 unsigned getFirstNonReservedPhysReg(const TargetRegisterClass *RC) {
360 TargetRegisterClass::iterator aoe = RC->allocation_order_end(*mf_);
361 TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_);
362 while (i != aoe && reservedRegs_.test(*i))
364 assert(i != aoe && "All registers reserved?!");
368 void ComputeRelatedRegClasses();
370 template <typename ItTy>
371 void printIntervals(const char* const str, ItTy i, ItTy e) const {
374 dbgs() << str << " intervals:\n";
376 for (; i != e; ++i) {
377 dbgs() << "\t" << *i->first << " -> ";
379 unsigned reg = i->first->reg;
380 if (TargetRegisterInfo::isVirtualRegister(reg))
381 reg = vrm_->getPhys(reg);
383 dbgs() << tri_->getName(reg) << '\n';
388 char RALinScan::ID = 0;
391 INITIALIZE_PASS_BEGIN(RALinScan, "linearscan-regalloc",
392 "Linear Scan Register Allocator", false, false)
393 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
394 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
395 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
396 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting)
397 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
398 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
399 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
400 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
401 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
402 INITIALIZE_PASS_END(RALinScan, "linearscan-regalloc",
403 "Linear Scan Register Allocator", false, false)
405 void RALinScan::ComputeRelatedRegClasses() {
406 // First pass, add all reg classes to the union, and determine at least one
407 // reg class that each register is in.
408 bool HasAliases = false;
409 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
410 E = tri_->regclass_end(); RCI != E; ++RCI) {
411 RelatedRegClasses.insert(*RCI);
412 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
414 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
416 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
418 // Already processed this register. Just make sure we know that
419 // multiple register classes share a register.
420 RelatedRegClasses.unionSets(PRC, *RCI);
427 // Second pass, now that we know conservatively what register classes each reg
428 // belongs to, add info about aliases. We don't need to do this for targets
429 // without register aliases.
431 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
432 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
434 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
435 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
438 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
439 /// allocate the definition the same register as the source register if the
440 /// register is not defined during live time of the interval. If the interval is
441 /// killed by a copy, try to use the destination register. This eliminates a
442 /// copy. This is used to coalesce copies which were not coalesced away before
443 /// allocation either due to dest and src being in different register classes or
444 /// because the coalescer was overly conservative.
445 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
446 unsigned Preference = vrm_->getRegAllocPref(cur.reg);
447 if ((Preference && Preference == Reg) || !cur.containsOneValue())
450 // We cannot handle complicated live ranges. Simple linear stuff only.
451 if (cur.ranges.size() != 1)
454 const LiveRange &range = cur.ranges.front();
456 VNInfo *vni = range.valno;
462 MachineInstr *CopyMI;
463 if ((CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
464 // Defined by a copy, try to extend SrcReg forward
465 CandReg = CopyMI->getOperand(1).getReg();
466 else if (TrivCoalesceEnds &&
467 (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
468 CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
469 // Only used by a copy, try to extend DstReg backwards
470 CandReg = CopyMI->getOperand(0).getReg();
474 // If the target of the copy is a sub-register then don't coalesce.
475 if(CopyMI->getOperand(0).getSubReg())
479 if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
480 if (!vrm_->isAssignedReg(CandReg))
482 CandReg = vrm_->getPhys(CandReg);
487 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
488 if (!RC->contains(CandReg))
491 if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
495 DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
497 vrm_->clearVirt(cur.reg);
498 vrm_->assignVirt2Phys(cur.reg, CandReg);
504 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
506 mri_ = &fn.getRegInfo();
507 tm_ = &fn.getTarget();
508 tri_ = tm_->getRegisterInfo();
509 tii_ = tm_->getInstrInfo();
510 allocatableRegs_ = tri_->getAllocatableSet(fn);
511 reservedRegs_ = tri_->getReservedRegs(fn);
512 li_ = &getAnalysis<LiveIntervals>();
513 loopInfo = &getAnalysis<MachineLoopInfo>();
515 // We don't run the coalescer here because we have no reason to
516 // interact with it. If the coalescer requires interaction, it
517 // won't do anything. If it doesn't require interaction, we assume
518 // it was run as a separate pass.
520 // If this is the first function compiled, compute the related reg classes.
521 if (RelatedRegClasses.empty())
522 ComputeRelatedRegClasses();
524 // Also resize register usage trackers.
527 vrm_ = &getAnalysis<VirtRegMap>();
528 if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
530 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
536 // Rewrite spill code and update the PhysRegsUsed set.
537 rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
539 // Write out new DBG_VALUE instructions.
540 getAnalysis<LiveDebugVariables>().emitDebugValues(vrm_);
542 assert(unhandled_.empty() && "Unhandled live intervals remain!");
550 NextReloadMap.clear();
551 DowngradedRegs.clear();
552 DowngradeMap.clear();
558 /// initIntervalSets - initialize the interval sets.
560 void RALinScan::initIntervalSets()
562 assert(unhandled_.empty() && fixed_.empty() &&
563 active_.empty() && inactive_.empty() &&
564 "interval sets should be empty on initialization");
566 handled_.reserve(li_->getNumIntervals());
568 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
569 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
570 if (!i->second->empty()) {
571 mri_->setPhysRegUsed(i->second->reg);
572 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
575 if (i->second->empty()) {
576 assignRegOrStackSlotAtInterval(i->second);
579 unhandled_.push(i->second);
584 void RALinScan::linearScan() {
585 // linear scan algorithm
587 dbgs() << "********** LINEAR SCAN **********\n"
588 << "********** Function: "
589 << mf_->getFunction()->getName() << '\n';
590 printIntervals("fixed", fixed_.begin(), fixed_.end());
593 while (!unhandled_.empty()) {
594 // pick the interval with the earliest start point
595 LiveInterval* cur = unhandled_.top();
598 DEBUG(dbgs() << "\n*** CURRENT ***: " << *cur << '\n');
600 assert(!cur->empty() && "Empty interval in unhandled set.");
602 processActiveIntervals(cur->beginIndex());
603 processInactiveIntervals(cur->beginIndex());
605 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
606 "Can only allocate virtual registers!");
608 // Allocating a virtual register. try to find a free
609 // physical register or spill an interval (possibly this one) in order to
611 assignRegOrStackSlotAtInterval(cur);
614 printIntervals("active", active_.begin(), active_.end());
615 printIntervals("inactive", inactive_.begin(), inactive_.end());
619 // Expire any remaining active intervals
620 while (!active_.empty()) {
621 IntervalPtr &IP = active_.back();
622 unsigned reg = IP.first->reg;
623 DEBUG(dbgs() << "\tinterval " << *IP.first << " expired\n");
624 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
625 "Can only allocate virtual registers!");
626 reg = vrm_->getPhys(reg);
631 // Expire any remaining inactive intervals
633 for (IntervalPtrs::reverse_iterator
634 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
635 dbgs() << "\tinterval " << *i->first << " expired\n";
639 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
640 MachineFunction::iterator EntryMBB = mf_->begin();
641 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
642 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
643 LiveInterval &cur = *i->second;
645 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
648 else if (vrm_->isAssignedReg(cur.reg))
649 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
652 // Ignore splited live intervals.
653 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
656 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
658 const LiveRange &LR = *I;
659 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
660 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
661 if (LiveInMBBs[i] != EntryMBB) {
662 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
663 "Adding a virtual register to livein set?");
664 LiveInMBBs[i]->addLiveIn(Reg);
671 DEBUG(dbgs() << *vrm_);
673 // Look for physical registers that end up not being allocated even though
674 // register allocator had to spill other registers in its register class.
675 if (!vrm_->FindUnusedRegisters(li_))
679 /// processActiveIntervals - expire old intervals and move non-overlapping ones
680 /// to the inactive list.
681 void RALinScan::processActiveIntervals(SlotIndex CurPoint)
683 DEBUG(dbgs() << "\tprocessing active intervals:\n");
685 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
686 LiveInterval *Interval = active_[i].first;
687 LiveInterval::iterator IntervalPos = active_[i].second;
688 unsigned reg = Interval->reg;
690 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
692 if (IntervalPos == Interval->end()) { // Remove expired intervals.
693 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
694 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
695 "Can only allocate virtual registers!");
696 reg = vrm_->getPhys(reg);
699 // Pop off the end of the list.
700 active_[i] = active_.back();
704 } else if (IntervalPos->start > CurPoint) {
705 // Move inactive intervals to inactive list.
706 DEBUG(dbgs() << "\t\tinterval " << *Interval << " inactive\n");
707 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
708 "Can only allocate virtual registers!");
709 reg = vrm_->getPhys(reg);
712 inactive_.push_back(std::make_pair(Interval, IntervalPos));
714 // Pop off the end of the list.
715 active_[i] = active_.back();
719 // Otherwise, just update the iterator position.
720 active_[i].second = IntervalPos;
725 /// processInactiveIntervals - expire old intervals and move overlapping
726 /// ones to the active list.
727 void RALinScan::processInactiveIntervals(SlotIndex CurPoint)
729 DEBUG(dbgs() << "\tprocessing inactive intervals:\n");
731 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
732 LiveInterval *Interval = inactive_[i].first;
733 LiveInterval::iterator IntervalPos = inactive_[i].second;
734 unsigned reg = Interval->reg;
736 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
738 if (IntervalPos == Interval->end()) { // remove expired intervals.
739 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
741 // Pop off the end of the list.
742 inactive_[i] = inactive_.back();
743 inactive_.pop_back();
745 } else if (IntervalPos->start <= CurPoint) {
746 // move re-activated intervals in active list
747 DEBUG(dbgs() << "\t\tinterval " << *Interval << " active\n");
748 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
749 "Can only allocate virtual registers!");
750 reg = vrm_->getPhys(reg);
753 active_.push_back(std::make_pair(Interval, IntervalPos));
755 // Pop off the end of the list.
756 inactive_[i] = inactive_.back();
757 inactive_.pop_back();
760 // Otherwise, just update the iterator position.
761 inactive_[i].second = IntervalPos;
766 /// updateSpillWeights - updates the spill weights of the specifed physical
767 /// register and its weight.
768 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
769 unsigned reg, float weight,
770 const TargetRegisterClass *RC) {
771 SmallSet<unsigned, 4> Processed;
772 SmallSet<unsigned, 4> SuperAdded;
773 SmallVector<unsigned, 4> Supers;
774 Weights[reg] += weight;
775 Processed.insert(reg);
776 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
777 Weights[*as] += weight;
778 Processed.insert(*as);
779 if (tri_->isSubRegister(*as, reg) &&
780 SuperAdded.insert(*as) &&
782 Supers.push_back(*as);
786 // If the alias is a super-register, and the super-register is in the
787 // register class we are trying to allocate. Then add the weight to all
788 // sub-registers of the super-register even if they are not aliases.
789 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
790 // bl should get the same spill weight otherwise it will be choosen
791 // as a spill candidate since spilling bh doesn't make ebx available.
792 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
793 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
794 if (!Processed.count(*sr))
795 Weights[*sr] += weight;
800 RALinScan::IntervalPtrs::iterator
801 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
802 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
804 if (I->first == LI) return I;
808 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V,
810 for (unsigned i = 0, e = V.size(); i != e; ++i) {
811 RALinScan::IntervalPtr &IP = V[i];
812 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
814 if (I != IP.first->begin()) --I;
819 /// getConflictWeight - Return the number of conflicts between cur
820 /// live interval and defs and uses of Reg weighted by loop depthes.
822 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
823 MachineRegisterInfo *mri_,
824 MachineLoopInfo *loopInfo) {
826 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
827 E = mri_->reg_end(); I != E; ++I) {
828 MachineInstr *MI = &*I;
829 if (cur->liveAt(li_->getInstructionIndex(MI))) {
830 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
831 Conflicts += std::pow(10.0f, (float)loopDepth);
837 /// findIntervalsToSpill - Determine the intervals to spill for the
838 /// specified interval. It's passed the physical registers whose spill
839 /// weight is the lowest among all the registers whose live intervals
840 /// conflict with the interval.
841 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
842 std::vector<std::pair<unsigned,float> > &Candidates,
844 SmallVector<LiveInterval*, 8> &SpillIntervals) {
845 // We have figured out the *best* register to spill. But there are other
846 // registers that are pretty good as well (spill weight within 3%). Spill
847 // the one that has fewest defs and uses that conflict with cur.
848 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
849 SmallVector<LiveInterval*, 8> SLIs[3];
852 dbgs() << "\tConsidering " << NumCands << " candidates: ";
853 for (unsigned i = 0; i != NumCands; ++i)
854 dbgs() << tri_->getName(Candidates[i].first) << " ";
858 // Calculate the number of conflicts of each candidate.
859 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
860 unsigned Reg = i->first->reg;
861 unsigned PhysReg = vrm_->getPhys(Reg);
862 if (!cur->overlapsFrom(*i->first, i->second))
864 for (unsigned j = 0; j < NumCands; ++j) {
865 unsigned Candidate = Candidates[j].first;
866 if (tri_->regsOverlap(PhysReg, Candidate)) {
868 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
869 SLIs[j].push_back(i->first);
874 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
875 unsigned Reg = i->first->reg;
876 unsigned PhysReg = vrm_->getPhys(Reg);
877 if (!cur->overlapsFrom(*i->first, i->second-1))
879 for (unsigned j = 0; j < NumCands; ++j) {
880 unsigned Candidate = Candidates[j].first;
881 if (tri_->regsOverlap(PhysReg, Candidate)) {
883 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
884 SLIs[j].push_back(i->first);
889 // Which is the best candidate?
890 unsigned BestCandidate = 0;
891 float MinConflicts = Conflicts[0];
892 for (unsigned i = 1; i != NumCands; ++i) {
893 if (Conflicts[i] < MinConflicts) {
895 MinConflicts = Conflicts[i];
899 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
900 std::back_inserter(SpillIntervals));
904 struct WeightCompare {
906 const RALinScan &Allocator;
909 WeightCompare(const RALinScan &Alloc) : Allocator(Alloc) {}
911 typedef std::pair<unsigned, float> RegWeightPair;
912 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
913 return LHS.second < RHS.second && !Allocator.isRecentlyUsed(LHS.first);
918 static bool weightsAreClose(float w1, float w2) {
922 float diff = w1 - w2;
923 if (diff <= 0.02f) // Within 0.02f
925 return (diff / w2) <= 0.05f; // Within 5%.
928 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
929 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
930 if (I == NextReloadMap.end())
932 return &li_->getInterval(I->second);
935 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
936 for (const unsigned *AS = tri_->getOverlaps(Reg); *AS; ++AS) {
937 bool isNew = DowngradedRegs.insert(*AS);
938 (void)isNew; // Silence compiler warning.
939 assert(isNew && "Multiple reloads holding the same register?");
940 DowngradeMap.insert(std::make_pair(li->reg, *AS));
945 void RALinScan::UpgradeRegister(unsigned Reg) {
947 DowngradedRegs.erase(Reg);
948 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
949 DowngradedRegs.erase(*AS);
955 bool operator()(LiveInterval* A, LiveInterval* B) {
956 return A->beginIndex() < B->beginIndex();
961 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
963 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
964 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
965 DEBUG(dbgs() << "\tallocating current interval from "
966 << RC->getName() << ": ");
968 // This is an implicitly defined live interval, just assign any register.
970 unsigned physReg = vrm_->getRegAllocPref(cur->reg);
972 physReg = getFirstNonReservedPhysReg(RC);
973 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
974 // Note the register is not really in use.
975 vrm_->assignVirt2Phys(cur->reg, physReg);
981 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
982 SlotIndex StartPosition = cur->beginIndex();
983 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
985 // If start of this live interval is defined by a move instruction and its
986 // source is assigned a physical register that is compatible with the target
987 // register class, then we should try to assign it the same register.
988 // This can happen when the move is from a larger register class to a smaller
989 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
990 if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
991 VNInfo *vni = cur->begin()->valno;
992 if (!vni->isUnused()) {
993 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
994 if (CopyMI && CopyMI->isCopy()) {
995 unsigned DstSubReg = CopyMI->getOperand(0).getSubReg();
996 unsigned SrcReg = CopyMI->getOperand(1).getReg();
997 unsigned SrcSubReg = CopyMI->getOperand(1).getSubReg();
999 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1001 else if (vrm_->isAssignedReg(SrcReg))
1002 Reg = vrm_->getPhys(SrcReg);
1005 Reg = tri_->getSubReg(Reg, SrcSubReg);
1007 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1008 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1009 mri_->setRegAllocationHint(cur->reg, 0, Reg);
1015 // For every interval in inactive we overlap with, mark the
1016 // register as not free and update spill weights.
1017 for (IntervalPtrs::const_iterator i = inactive_.begin(),
1018 e = inactive_.end(); i != e; ++i) {
1019 unsigned Reg = i->first->reg;
1020 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1021 "Can only allocate virtual registers!");
1022 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1023 // If this is not in a related reg class to the register we're allocating,
1025 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1026 cur->overlapsFrom(*i->first, i->second-1)) {
1027 Reg = vrm_->getPhys(Reg);
1029 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1033 // Speculatively check to see if we can get a register right now. If not,
1034 // we know we won't be able to by adding more constraints. If so, we can
1035 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1036 // is very bad (it contains all callee clobbered registers for any functions
1037 // with a call), so we want to avoid doing that if possible.
1038 unsigned physReg = getFreePhysReg(cur);
1039 unsigned BestPhysReg = physReg;
1041 // We got a register. However, if it's in the fixed_ list, we might
1042 // conflict with it. Check to see if we conflict with it or any of its
1044 SmallSet<unsigned, 8> RegAliases;
1045 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1046 RegAliases.insert(*AS);
1048 bool ConflictsWithFixed = false;
1049 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1050 IntervalPtr &IP = fixed_[i];
1051 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1052 // Okay, this reg is on the fixed list. Check to see if we actually
1054 LiveInterval *I = IP.first;
1055 if (I->endIndex() > StartPosition) {
1056 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1058 if (II != I->begin() && II->start > StartPosition)
1060 if (cur->overlapsFrom(*I, II)) {
1061 ConflictsWithFixed = true;
1068 // Okay, the register picked by our speculative getFreePhysReg call turned
1069 // out to be in use. Actually add all of the conflicting fixed registers to
1070 // regUse_ so we can do an accurate query.
1071 if (ConflictsWithFixed) {
1072 // For every interval in fixed we overlap with, mark the register as not
1073 // free and update spill weights.
1074 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1075 IntervalPtr &IP = fixed_[i];
1076 LiveInterval *I = IP.first;
1078 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1079 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1080 I->endIndex() > StartPosition) {
1081 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1083 if (II != I->begin() && II->start > StartPosition)
1085 if (cur->overlapsFrom(*I, II)) {
1086 unsigned reg = I->reg;
1088 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1093 // Using the newly updated regUse_ object, which includes conflicts in the
1094 // future, see if there are any registers available.
1095 physReg = getFreePhysReg(cur);
1099 // Restore the physical register tracker, removing information about the
1103 // If we find a free register, we are done: assign this virtual to
1104 // the free physical register and add this interval to the active
1107 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
1108 vrm_->assignVirt2Phys(cur->reg, physReg);
1110 active_.push_back(std::make_pair(cur, cur->begin()));
1111 handled_.push_back(cur);
1113 // "Upgrade" the physical register since it has been allocated.
1114 UpgradeRegister(physReg);
1115 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1116 // "Downgrade" physReg to try to keep physReg from being allocated until
1117 // the next reload from the same SS is allocated.
1118 mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1119 DowngradeRegister(cur, physReg);
1123 DEBUG(dbgs() << "no free registers\n");
1125 // Compile the spill weights into an array that is better for scanning.
1126 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1127 for (std::vector<std::pair<unsigned, float> >::iterator
1128 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1129 updateSpillWeights(SpillWeights, I->first, I->second, RC);
1131 // for each interval in active, update spill weights.
1132 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1134 unsigned reg = i->first->reg;
1135 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1136 "Can only allocate virtual registers!");
1137 reg = vrm_->getPhys(reg);
1138 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1141 DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1143 // Find a register to spill.
1144 float minWeight = HUGE_VALF;
1145 unsigned minReg = 0;
1148 std::vector<std::pair<unsigned,float> > RegsWeights;
1149 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1150 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1151 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1153 float regWeight = SpillWeights[reg];
1154 // Don't even consider reserved regs.
1155 if (reservedRegs_.test(reg))
1157 // Skip recently allocated registers and reserved registers.
1158 if (minWeight > regWeight && !isRecentlyUsed(reg))
1160 RegsWeights.push_back(std::make_pair(reg, regWeight));
1163 // If we didn't find a register that is spillable, try aliases?
1165 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1166 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1168 if (reservedRegs_.test(reg))
1170 // No need to worry about if the alias register size < regsize of RC.
1171 // We are going to spill all registers that alias it anyway.
1172 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1173 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1177 // Sort all potential spill candidates by weight.
1178 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1179 minReg = RegsWeights[0].first;
1180 minWeight = RegsWeights[0].second;
1181 if (minWeight == HUGE_VALF) {
1182 // All registers must have inf weight. Just grab one!
1183 minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1184 if (cur->weight == HUGE_VALF ||
1185 li_->getApproximateInstructionCount(*cur) == 0) {
1186 // Spill a physical register around defs and uses.
1187 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1188 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1189 // in fixed_. Reset them.
1190 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1191 IntervalPtr &IP = fixed_[i];
1192 LiveInterval *I = IP.first;
1193 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1194 IP.second = I->advanceTo(I->begin(), StartPosition);
1197 DowngradedRegs.clear();
1198 assignRegOrStackSlotAtInterval(cur);
1200 assert(false && "Ran out of registers during register allocation!");
1201 report_fatal_error("Ran out of registers during register allocation!");
1207 // Find up to 3 registers to consider as spill candidates.
1208 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1209 while (LastCandidate > 1) {
1210 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1216 dbgs() << "\t\tregister(s) with min weight(s): ";
1218 for (unsigned i = 0; i != LastCandidate; ++i)
1219 dbgs() << tri_->getName(RegsWeights[i].first)
1220 << " (" << RegsWeights[i].second << ")\n";
1223 // If the current has the minimum weight, we need to spill it and
1224 // add any added intervals back to unhandled, and restart
1226 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1227 DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1228 SmallVector<LiveInterval*, 8> spillIs, added;
1229 spiller_->spill(cur, added, spillIs);
1231 std::sort(added.begin(), added.end(), LISorter());
1233 return; // Early exit if all spills were folded.
1235 // Merge added with unhandled. Note that we have already sorted
1236 // intervals returned by addIntervalsForSpills by their starting
1238 // This also update the NextReloadMap. That is, it adds mapping from a
1239 // register defined by a reload from SS to the next reload from SS in the
1240 // same basic block.
1241 MachineBasicBlock *LastReloadMBB = 0;
1242 LiveInterval *LastReload = 0;
1243 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1244 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1245 LiveInterval *ReloadLi = added[i];
1246 if (ReloadLi->weight == HUGE_VALF &&
1247 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1248 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1249 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1250 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1251 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1252 // Last reload of same SS is in the same MBB. We want to try to
1253 // allocate both reloads the same register and make sure the reg
1254 // isn't clobbered in between if at all possible.
1255 assert(LastReload->beginIndex() < ReloadIdx);
1256 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1258 LastReloadMBB = ReloadMBB;
1259 LastReload = ReloadLi;
1260 LastReloadSS = ReloadSS;
1262 unhandled_.push(ReloadLi);
1269 // Push the current interval back to unhandled since we are going
1270 // to re-run at least this iteration. Since we didn't modify it it
1271 // should go back right in the front of the list
1272 unhandled_.push(cur);
1274 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1275 "did not choose a register to spill?");
1277 // We spill all intervals aliasing the register with
1278 // minimum weight, rollback to the interval with the earliest
1279 // start point and let the linear scan algorithm run again
1280 SmallVector<LiveInterval*, 8> spillIs;
1282 // Determine which intervals have to be spilled.
1283 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1285 // Set of spilled vregs (used later to rollback properly)
1286 SmallSet<unsigned, 8> spilled;
1288 // The earliest start of a Spilled interval indicates up to where
1289 // in handled we need to roll back
1290 assert(!spillIs.empty() && "No spill intervals?");
1291 SlotIndex earliestStart = spillIs[0]->beginIndex();
1293 // Spill live intervals of virtual regs mapped to the physical register we
1294 // want to clear (and its aliases). We only spill those that overlap with the
1295 // current interval as the rest do not affect its allocation. we also keep
1296 // track of the earliest start of all spilled live intervals since this will
1297 // mark our rollback point.
1298 SmallVector<LiveInterval*, 8> added;
1299 while (!spillIs.empty()) {
1300 LiveInterval *sli = spillIs.back();
1302 DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1303 if (sli->beginIndex() < earliestStart)
1304 earliestStart = sli->beginIndex();
1305 spiller_->spill(sli, added, spillIs);
1306 spilled.insert(sli->reg);
1309 // Include any added intervals in earliestStart.
1310 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1311 SlotIndex SI = added[i]->beginIndex();
1312 if (SI < earliestStart)
1316 DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1318 // Scan handled in reverse order up to the earliest start of a
1319 // spilled live interval and undo each one, restoring the state of
1321 while (!handled_.empty()) {
1322 LiveInterval* i = handled_.back();
1323 // If this interval starts before t we are done.
1324 if (!i->empty() && i->beginIndex() < earliestStart)
1326 DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1327 handled_.pop_back();
1329 // When undoing a live interval allocation we must know if it is active or
1330 // inactive to properly update regUse_ and the VirtRegMap.
1331 IntervalPtrs::iterator it;
1332 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1334 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1335 if (!spilled.count(i->reg))
1337 delRegUse(vrm_->getPhys(i->reg));
1338 vrm_->clearVirt(i->reg);
1339 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1340 inactive_.erase(it);
1341 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1342 if (!spilled.count(i->reg))
1344 vrm_->clearVirt(i->reg);
1346 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1347 "Can only allocate virtual registers!");
1348 vrm_->clearVirt(i->reg);
1352 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1353 if (ii == DowngradeMap.end())
1354 // It interval has a preference, it must be defined by a copy. Clear the
1355 // preference now since the source interval allocation may have been
1357 mri_->setRegAllocationHint(i->reg, 0, 0);
1359 UpgradeRegister(ii->second);
1363 // Rewind the iterators in the active, inactive, and fixed lists back to the
1364 // point we reverted to.
1365 RevertVectorIteratorsTo(active_, earliestStart);
1366 RevertVectorIteratorsTo(inactive_, earliestStart);
1367 RevertVectorIteratorsTo(fixed_, earliestStart);
1369 // Scan the rest and undo each interval that expired after t and
1370 // insert it in active (the next iteration of the algorithm will
1371 // put it in inactive if required)
1372 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1373 LiveInterval *HI = handled_[i];
1374 if (!HI->expiredAt(earliestStart) &&
1375 HI->expiredAt(cur->beginIndex())) {
1376 DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1377 active_.push_back(std::make_pair(HI, HI->begin()));
1378 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1379 addRegUse(vrm_->getPhys(HI->reg));
1383 // Merge added with unhandled.
1384 // This also update the NextReloadMap. That is, it adds mapping from a
1385 // register defined by a reload from SS to the next reload from SS in the
1386 // same basic block.
1387 MachineBasicBlock *LastReloadMBB = 0;
1388 LiveInterval *LastReload = 0;
1389 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1390 std::sort(added.begin(), added.end(), LISorter());
1391 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1392 LiveInterval *ReloadLi = added[i];
1393 if (ReloadLi->weight == HUGE_VALF &&
1394 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1395 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1396 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1397 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1398 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1399 // Last reload of same SS is in the same MBB. We want to try to
1400 // allocate both reloads the same register and make sure the reg
1401 // isn't clobbered in between if at all possible.
1402 assert(LastReload->beginIndex() < ReloadIdx);
1403 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1405 LastReloadMBB = ReloadMBB;
1406 LastReload = ReloadLi;
1407 LastReloadSS = ReloadSS;
1409 unhandled_.push(ReloadLi);
1413 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1414 const TargetRegisterClass *RC,
1415 unsigned MaxInactiveCount,
1416 SmallVector<unsigned, 256> &inactiveCounts,
1418 unsigned FreeReg = 0;
1419 unsigned FreeRegInactiveCount = 0;
1421 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1422 // Resolve second part of the hint (if possible) given the current allocation.
1423 unsigned physReg = Hint.second;
1424 if (TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1425 physReg = vrm_->getPhys(physReg);
1427 TargetRegisterClass::iterator I, E;
1428 tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1429 assert(I != E && "No allocatable register in this register class!");
1431 // Scan for the first available register.
1432 for (; I != E; ++I) {
1434 // Ignore "downgraded" registers.
1435 if (SkipDGRegs && DowngradedRegs.count(Reg))
1437 // Skip reserved registers.
1438 if (reservedRegs_.test(Reg))
1440 // Skip recently allocated registers.
1441 if (isRegAvail(Reg) && !isRecentlyUsed(Reg)) {
1443 if (FreeReg < inactiveCounts.size())
1444 FreeRegInactiveCount = inactiveCounts[FreeReg];
1446 FreeRegInactiveCount = 0;
1451 // If there are no free regs, or if this reg has the max inactive count,
1452 // return this register.
1453 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1454 // Remember what register we picked so we can skip it next time.
1455 if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1459 // Continue scanning the registers, looking for the one with the highest
1460 // inactive count. Alkis found that this reduced register pressure very
1461 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1463 for (; I != E; ++I) {
1465 // Ignore "downgraded" registers.
1466 if (SkipDGRegs && DowngradedRegs.count(Reg))
1468 // Skip reserved registers.
1469 if (reservedRegs_.test(Reg))
1471 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1472 FreeRegInactiveCount < inactiveCounts[Reg] && !isRecentlyUsed(Reg)) {
1474 FreeRegInactiveCount = inactiveCounts[Reg];
1475 if (FreeRegInactiveCount == MaxInactiveCount)
1476 break; // We found the one with the max inactive count.
1480 // Remember what register we picked so we can skip it next time.
1481 recordRecentlyUsed(FreeReg);
1486 /// getFreePhysReg - return a free physical register for this virtual register
1487 /// interval if we have one, otherwise return 0.
1488 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1489 SmallVector<unsigned, 256> inactiveCounts;
1490 unsigned MaxInactiveCount = 0;
1492 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1493 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1495 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1497 unsigned reg = i->first->reg;
1498 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1499 "Can only allocate virtual registers!");
1501 // If this is not in a related reg class to the register we're allocating,
1503 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1504 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1505 reg = vrm_->getPhys(reg);
1506 if (inactiveCounts.size() <= reg)
1507 inactiveCounts.resize(reg+1);
1508 ++inactiveCounts[reg];
1509 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1513 // If copy coalescer has assigned a "preferred" register, check if it's
1515 unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1517 DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1518 if (isRegAvail(Preference) &&
1519 RC->contains(Preference))
1523 if (!DowngradedRegs.empty()) {
1524 unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1529 return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1532 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1533 return new RALinScan();