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 "VirtRegMap.h"
16 #include "VirtRegRewriter.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/CalcSpillWeights.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/RegisterCoalescer.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/ADT/EquivalenceClasses.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
48 STATISTIC(NumIters , "Number of iterations performed");
49 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
50 STATISTIC(NumCoalesce, "Number of copies coalesced");
51 STATISTIC(NumDowngrade, "Number of registers downgraded");
54 NewHeuristic("new-spilling-heuristic",
55 cl::desc("Use new spilling heuristic"),
56 cl::init(false), cl::Hidden);
59 PreSplitIntervals("pre-alloc-split",
60 cl::desc("Pre-register allocation live interval splitting"),
61 cl::init(false), cl::Hidden);
64 TrivCoalesceEnds("trivial-coalesce-ends",
65 cl::desc("Attempt trivial coalescing of interval ends"),
66 cl::init(false), cl::Hidden);
68 static RegisterRegAlloc
69 linearscanRegAlloc("linearscan", "linear scan register allocator",
70 createLinearScanRegisterAllocator);
73 // When we allocate a register, add it to a fixed-size queue of
74 // registers to skip in subsequent allocations. This trades a small
75 // amount of register pressure and increased spills for flexibility in
76 // the post-pass scheduler.
78 // Note that in a the number of registers used for reloading spills
79 // will be one greater than the value of this option.
81 // One big limitation of this is that it doesn't differentiate between
82 // different register classes. So on x86-64, if there is xmm register
83 // pressure, it can caused fewer GPRs to be held in the queue.
84 static cl::opt<unsigned>
85 NumRecentlyUsedRegs("linearscan-skip-count",
86 cl::desc("Number of registers for linearscan to remember"
91 struct RALinScan : public MachineFunctionPass {
93 RALinScan() : MachineFunctionPass(ID) {
94 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
95 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
96 initializeRegisterCoalescerAnalysisGroup(
97 *PassRegistry::getPassRegistry());
98 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
99 initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
100 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
101 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
102 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
103 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
104 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
106 // Initialize the queue to record recently-used registers.
107 if (NumRecentlyUsedRegs > 0)
108 RecentRegs.resize(NumRecentlyUsedRegs, 0);
109 RecentNext = RecentRegs.begin();
112 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
113 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
115 /// RelatedRegClasses - This structure is built the first time a function is
116 /// compiled, and keeps track of which register classes have registers that
117 /// belong to multiple classes or have aliases that are in other classes.
118 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
119 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
121 // NextReloadMap - For each register in the map, it maps to the another
122 // register which is defined by a reload from the same stack slot and
123 // both reloads are in the same basic block.
124 DenseMap<unsigned, unsigned> NextReloadMap;
126 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
127 // un-favored for allocation.
128 SmallSet<unsigned, 8> DowngradedRegs;
130 // DowngradeMap - A map from virtual registers to physical registers being
131 // downgraded for the virtual registers.
132 DenseMap<unsigned, unsigned> DowngradeMap;
134 MachineFunction* mf_;
135 MachineRegisterInfo* mri_;
136 const TargetMachine* tm_;
137 const TargetRegisterInfo* tri_;
138 const TargetInstrInfo* tii_;
139 BitVector allocatableRegs_;
140 BitVector reservedRegs_;
142 MachineLoopInfo *loopInfo;
144 /// handled_ - Intervals are added to the handled_ set in the order of their
145 /// start value. This is uses for backtracking.
146 std::vector<LiveInterval*> handled_;
148 /// fixed_ - Intervals that correspond to machine registers.
152 /// active_ - Intervals that are currently being processed, and which have a
153 /// live range active for the current point.
154 IntervalPtrs active_;
156 /// inactive_ - Intervals that are currently being processed, but which have
157 /// a hold at the current point.
158 IntervalPtrs inactive_;
160 typedef std::priority_queue<LiveInterval*,
161 SmallVector<LiveInterval*, 64>,
162 greater_ptr<LiveInterval> > IntervalHeap;
163 IntervalHeap unhandled_;
165 /// regUse_ - Tracks register usage.
166 SmallVector<unsigned, 32> regUse_;
167 SmallVector<unsigned, 32> regUseBackUp_;
169 /// vrm_ - Tracks register assignments.
172 std::auto_ptr<VirtRegRewriter> rewriter_;
174 std::auto_ptr<Spiller> spiller_;
176 // The queue of recently-used registers.
177 SmallVector<unsigned, 4> RecentRegs;
178 SmallVector<unsigned, 4>::iterator RecentNext;
180 // Record that we just picked this register.
181 void recordRecentlyUsed(unsigned reg) {
182 assert(reg != 0 && "Recently used register is NOREG!");
183 if (!RecentRegs.empty()) {
185 if (RecentNext == RecentRegs.end())
186 RecentNext = RecentRegs.begin();
191 virtual const char* getPassName() const {
192 return "Linear Scan Register Allocator";
195 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
196 AU.setPreservesCFG();
197 AU.addRequired<AliasAnalysis>();
198 AU.addPreserved<AliasAnalysis>();
199 AU.addRequired<LiveIntervals>();
200 AU.addPreserved<SlotIndexes>();
202 AU.addRequiredID(StrongPHIEliminationID);
203 // Make sure PassManager knows which analyses to make available
204 // to coalescing and which analyses coalescing invalidates.
205 AU.addRequiredTransitive<RegisterCoalescer>();
206 AU.addRequired<CalculateSpillWeights>();
207 if (PreSplitIntervals)
208 AU.addRequiredID(PreAllocSplittingID);
209 AU.addRequiredID(LiveStacksID);
210 AU.addPreservedID(LiveStacksID);
211 AU.addRequired<MachineLoopInfo>();
212 AU.addPreserved<MachineLoopInfo>();
213 AU.addRequired<VirtRegMap>();
214 AU.addPreserved<VirtRegMap>();
215 AU.addRequiredID(MachineDominatorsID);
216 AU.addPreservedID(MachineDominatorsID);
217 MachineFunctionPass::getAnalysisUsage(AU);
220 /// runOnMachineFunction - register allocate the whole function
221 bool runOnMachineFunction(MachineFunction&);
223 // Determine if we skip this register due to its being recently used.
224 bool isRecentlyUsed(unsigned reg) const {
225 return std::find(RecentRegs.begin(), RecentRegs.end(), reg) !=
230 /// linearScan - the linear scan algorithm
233 /// initIntervalSets - initialize the interval sets.
235 void initIntervalSets();
237 /// processActiveIntervals - expire old intervals and move non-overlapping
238 /// ones to the inactive list.
239 void processActiveIntervals(SlotIndex CurPoint);
241 /// processInactiveIntervals - expire old intervals and move overlapping
242 /// ones to the active list.
243 void processInactiveIntervals(SlotIndex CurPoint);
245 /// hasNextReloadInterval - Return the next liveinterval that's being
246 /// defined by a reload from the same SS as the specified one.
247 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
249 /// DowngradeRegister - Downgrade a register for allocation.
250 void DowngradeRegister(LiveInterval *li, unsigned Reg);
252 /// UpgradeRegister - Upgrade a register for allocation.
253 void UpgradeRegister(unsigned Reg);
255 /// assignRegOrStackSlotAtInterval - assign a register if one
256 /// is available, or spill.
257 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
259 void updateSpillWeights(std::vector<float> &Weights,
260 unsigned reg, float weight,
261 const TargetRegisterClass *RC);
263 /// findIntervalsToSpill - Determine the intervals to spill for the
264 /// specified interval. It's passed the physical registers whose spill
265 /// weight is the lowest among all the registers whose live intervals
266 /// conflict with the interval.
267 void findIntervalsToSpill(LiveInterval *cur,
268 std::vector<std::pair<unsigned,float> > &Candidates,
270 SmallVector<LiveInterval*, 8> &SpillIntervals);
272 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
273 /// try to allocate the definition to the same register as the source,
274 /// if the register is not defined during the life time of the interval.
275 /// This eliminates a copy, and is used to coalesce copies which were not
276 /// coalesced away before allocation either due to dest and src being in
277 /// different register classes or because the coalescer was overly
279 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
282 /// Register usage / availability tracking helpers.
286 regUse_.resize(tri_->getNumRegs(), 0);
287 regUseBackUp_.resize(tri_->getNumRegs(), 0);
290 void finalizeRegUses() {
292 // Verify all the registers are "freed".
294 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
295 if (regUse_[i] != 0) {
296 dbgs() << tri_->getName(i) << " is still in use!\n";
304 regUseBackUp_.clear();
307 void addRegUse(unsigned physReg) {
308 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
309 "should be physical register!");
311 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
315 void delRegUse(unsigned physReg) {
316 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
317 "should be physical register!");
318 assert(regUse_[physReg] != 0);
320 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
321 assert(regUse_[*as] != 0);
326 bool isRegAvail(unsigned physReg) const {
327 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
328 "should be physical register!");
329 return regUse_[physReg] == 0;
332 void backUpRegUses() {
333 regUseBackUp_ = regUse_;
336 void restoreRegUses() {
337 regUse_ = regUseBackUp_;
341 /// Register handling helpers.
344 /// getFreePhysReg - return a free physical register for this virtual
345 /// register interval if we have one, otherwise return 0.
346 unsigned getFreePhysReg(LiveInterval* cur);
347 unsigned getFreePhysReg(LiveInterval* cur,
348 const TargetRegisterClass *RC,
349 unsigned MaxInactiveCount,
350 SmallVector<unsigned, 256> &inactiveCounts,
353 /// getFirstNonReservedPhysReg - return the first non-reserved physical
354 /// register in the register class.
355 unsigned getFirstNonReservedPhysReg(const TargetRegisterClass *RC) {
356 TargetRegisterClass::iterator aoe = RC->allocation_order_end(*mf_);
357 TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_);
358 while (i != aoe && reservedRegs_.test(*i))
360 assert(i != aoe && "All registers reserved?!");
364 void ComputeRelatedRegClasses();
366 template <typename ItTy>
367 void printIntervals(const char* const str, ItTy i, ItTy e) const {
370 dbgs() << str << " intervals:\n";
372 for (; i != e; ++i) {
373 dbgs() << "\t" << *i->first << " -> ";
375 unsigned reg = i->first->reg;
376 if (TargetRegisterInfo::isVirtualRegister(reg))
377 reg = vrm_->getPhys(reg);
379 dbgs() << tri_->getName(reg) << '\n';
384 char RALinScan::ID = 0;
387 INITIALIZE_PASS_BEGIN(RALinScan, "linearscan-regalloc",
388 "Linear Scan Register Allocator", false, false)
389 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
390 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
391 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
392 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting)
393 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
394 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
395 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
396 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
397 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
398 INITIALIZE_PASS_END(RALinScan, "linearscan-regalloc",
399 "Linear Scan Register Allocator", false, false)
401 void RALinScan::ComputeRelatedRegClasses() {
402 // First pass, add all reg classes to the union, and determine at least one
403 // reg class that each register is in.
404 bool HasAliases = false;
405 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
406 E = tri_->regclass_end(); RCI != E; ++RCI) {
407 RelatedRegClasses.insert(*RCI);
408 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
410 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
412 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
414 // Already processed this register. Just make sure we know that
415 // multiple register classes share a register.
416 RelatedRegClasses.unionSets(PRC, *RCI);
423 // Second pass, now that we know conservatively what register classes each reg
424 // belongs to, add info about aliases. We don't need to do this for targets
425 // without register aliases.
427 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
428 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
430 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
431 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
434 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
435 /// allocate the definition the same register as the source register if the
436 /// register is not defined during live time of the interval. If the interval is
437 /// killed by a copy, try to use the destination register. This eliminates a
438 /// copy. This is used to coalesce copies which were not coalesced away before
439 /// allocation either due to dest and src being in different register classes or
440 /// because the coalescer was overly conservative.
441 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
442 unsigned Preference = vrm_->getRegAllocPref(cur.reg);
443 if ((Preference && Preference == Reg) || !cur.containsOneValue())
446 // We cannot handle complicated live ranges. Simple linear stuff only.
447 if (cur.ranges.size() != 1)
450 const LiveRange &range = cur.ranges.front();
452 VNInfo *vni = range.valno;
458 MachineInstr *CopyMI;
459 if ((CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
460 // Defined by a copy, try to extend SrcReg forward
461 CandReg = CopyMI->getOperand(1).getReg();
462 else if (TrivCoalesceEnds &&
463 (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
464 CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
465 // Only used by a copy, try to extend DstReg backwards
466 CandReg = CopyMI->getOperand(0).getReg();
471 if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
472 if (!vrm_->isAssignedReg(CandReg))
474 CandReg = vrm_->getPhys(CandReg);
479 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
480 if (!RC->contains(CandReg))
483 if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
487 DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
489 vrm_->clearVirt(cur.reg);
490 vrm_->assignVirt2Phys(cur.reg, CandReg);
496 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
498 mri_ = &fn.getRegInfo();
499 tm_ = &fn.getTarget();
500 tri_ = tm_->getRegisterInfo();
501 tii_ = tm_->getInstrInfo();
502 allocatableRegs_ = tri_->getAllocatableSet(fn);
503 reservedRegs_ = tri_->getReservedRegs(fn);
504 li_ = &getAnalysis<LiveIntervals>();
505 loopInfo = &getAnalysis<MachineLoopInfo>();
507 // We don't run the coalescer here because we have no reason to
508 // interact with it. If the coalescer requires interaction, it
509 // won't do anything. If it doesn't require interaction, we assume
510 // it was run as a separate pass.
512 // If this is the first function compiled, compute the related reg classes.
513 if (RelatedRegClasses.empty())
514 ComputeRelatedRegClasses();
516 // Also resize register usage trackers.
519 vrm_ = &getAnalysis<VirtRegMap>();
520 if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
522 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
528 // Rewrite spill code and update the PhysRegsUsed set.
529 rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
531 assert(unhandled_.empty() && "Unhandled live intervals remain!");
539 NextReloadMap.clear();
540 DowngradedRegs.clear();
541 DowngradeMap.clear();
547 /// initIntervalSets - initialize the interval sets.
549 void RALinScan::initIntervalSets()
551 assert(unhandled_.empty() && fixed_.empty() &&
552 active_.empty() && inactive_.empty() &&
553 "interval sets should be empty on initialization");
555 handled_.reserve(li_->getNumIntervals());
557 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
558 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
559 if (!i->second->empty()) {
560 mri_->setPhysRegUsed(i->second->reg);
561 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
564 if (i->second->empty()) {
565 assignRegOrStackSlotAtInterval(i->second);
568 unhandled_.push(i->second);
573 void RALinScan::linearScan() {
574 // linear scan algorithm
576 dbgs() << "********** LINEAR SCAN **********\n"
577 << "********** Function: "
578 << mf_->getFunction()->getName() << '\n';
579 printIntervals("fixed", fixed_.begin(), fixed_.end());
582 while (!unhandled_.empty()) {
583 // pick the interval with the earliest start point
584 LiveInterval* cur = unhandled_.top();
587 DEBUG(dbgs() << "\n*** CURRENT ***: " << *cur << '\n');
589 assert(!cur->empty() && "Empty interval in unhandled set.");
591 processActiveIntervals(cur->beginIndex());
592 processInactiveIntervals(cur->beginIndex());
594 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
595 "Can only allocate virtual registers!");
597 // Allocating a virtual register. try to find a free
598 // physical register or spill an interval (possibly this one) in order to
600 assignRegOrStackSlotAtInterval(cur);
603 printIntervals("active", active_.begin(), active_.end());
604 printIntervals("inactive", inactive_.begin(), inactive_.end());
608 // Expire any remaining active intervals
609 while (!active_.empty()) {
610 IntervalPtr &IP = active_.back();
611 unsigned reg = IP.first->reg;
612 DEBUG(dbgs() << "\tinterval " << *IP.first << " expired\n");
613 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
614 "Can only allocate virtual registers!");
615 reg = vrm_->getPhys(reg);
620 // Expire any remaining inactive intervals
622 for (IntervalPtrs::reverse_iterator
623 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
624 dbgs() << "\tinterval " << *i->first << " expired\n";
628 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
629 MachineFunction::iterator EntryMBB = mf_->begin();
630 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
631 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
632 LiveInterval &cur = *i->second;
634 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
637 else if (vrm_->isAssignedReg(cur.reg))
638 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
641 // Ignore splited live intervals.
642 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
645 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
647 const LiveRange &LR = *I;
648 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
649 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
650 if (LiveInMBBs[i] != EntryMBB) {
651 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
652 "Adding a virtual register to livein set?");
653 LiveInMBBs[i]->addLiveIn(Reg);
660 DEBUG(dbgs() << *vrm_);
662 // Look for physical registers that end up not being allocated even though
663 // register allocator had to spill other registers in its register class.
664 if (!vrm_->FindUnusedRegisters(li_))
668 /// processActiveIntervals - expire old intervals and move non-overlapping ones
669 /// to the inactive list.
670 void RALinScan::processActiveIntervals(SlotIndex CurPoint)
672 DEBUG(dbgs() << "\tprocessing active intervals:\n");
674 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
675 LiveInterval *Interval = active_[i].first;
676 LiveInterval::iterator IntervalPos = active_[i].second;
677 unsigned reg = Interval->reg;
679 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
681 if (IntervalPos == Interval->end()) { // Remove expired intervals.
682 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
683 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
684 "Can only allocate virtual registers!");
685 reg = vrm_->getPhys(reg);
688 // Pop off the end of the list.
689 active_[i] = active_.back();
693 } else if (IntervalPos->start > CurPoint) {
694 // Move inactive intervals to inactive list.
695 DEBUG(dbgs() << "\t\tinterval " << *Interval << " inactive\n");
696 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
697 "Can only allocate virtual registers!");
698 reg = vrm_->getPhys(reg);
701 inactive_.push_back(std::make_pair(Interval, IntervalPos));
703 // Pop off the end of the list.
704 active_[i] = active_.back();
708 // Otherwise, just update the iterator position.
709 active_[i].second = IntervalPos;
714 /// processInactiveIntervals - expire old intervals and move overlapping
715 /// ones to the active list.
716 void RALinScan::processInactiveIntervals(SlotIndex CurPoint)
718 DEBUG(dbgs() << "\tprocessing inactive intervals:\n");
720 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
721 LiveInterval *Interval = inactive_[i].first;
722 LiveInterval::iterator IntervalPos = inactive_[i].second;
723 unsigned reg = Interval->reg;
725 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
727 if (IntervalPos == Interval->end()) { // remove expired intervals.
728 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
730 // Pop off the end of the list.
731 inactive_[i] = inactive_.back();
732 inactive_.pop_back();
734 } else if (IntervalPos->start <= CurPoint) {
735 // move re-activated intervals in active list
736 DEBUG(dbgs() << "\t\tinterval " << *Interval << " active\n");
737 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
738 "Can only allocate virtual registers!");
739 reg = vrm_->getPhys(reg);
742 active_.push_back(std::make_pair(Interval, IntervalPos));
744 // Pop off the end of the list.
745 inactive_[i] = inactive_.back();
746 inactive_.pop_back();
749 // Otherwise, just update the iterator position.
750 inactive_[i].second = IntervalPos;
755 /// updateSpillWeights - updates the spill weights of the specifed physical
756 /// register and its weight.
757 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
758 unsigned reg, float weight,
759 const TargetRegisterClass *RC) {
760 SmallSet<unsigned, 4> Processed;
761 SmallSet<unsigned, 4> SuperAdded;
762 SmallVector<unsigned, 4> Supers;
763 Weights[reg] += weight;
764 Processed.insert(reg);
765 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
766 Weights[*as] += weight;
767 Processed.insert(*as);
768 if (tri_->isSubRegister(*as, reg) &&
769 SuperAdded.insert(*as) &&
771 Supers.push_back(*as);
775 // If the alias is a super-register, and the super-register is in the
776 // register class we are trying to allocate. Then add the weight to all
777 // sub-registers of the super-register even if they are not aliases.
778 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
779 // bl should get the same spill weight otherwise it will be choosen
780 // as a spill candidate since spilling bh doesn't make ebx available.
781 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
782 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
783 if (!Processed.count(*sr))
784 Weights[*sr] += weight;
789 RALinScan::IntervalPtrs::iterator
790 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
791 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
793 if (I->first == LI) return I;
797 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V,
799 for (unsigned i = 0, e = V.size(); i != e; ++i) {
800 RALinScan::IntervalPtr &IP = V[i];
801 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
803 if (I != IP.first->begin()) --I;
808 /// getConflictWeight - Return the number of conflicts between cur
809 /// live interval and defs and uses of Reg weighted by loop depthes.
811 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
812 MachineRegisterInfo *mri_,
813 MachineLoopInfo *loopInfo) {
815 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
816 E = mri_->reg_end(); I != E; ++I) {
817 MachineInstr *MI = &*I;
818 if (cur->liveAt(li_->getInstructionIndex(MI))) {
819 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
820 Conflicts += std::pow(10.0f, (float)loopDepth);
826 /// findIntervalsToSpill - Determine the intervals to spill for the
827 /// specified interval. It's passed the physical registers whose spill
828 /// weight is the lowest among all the registers whose live intervals
829 /// conflict with the interval.
830 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
831 std::vector<std::pair<unsigned,float> > &Candidates,
833 SmallVector<LiveInterval*, 8> &SpillIntervals) {
834 // We have figured out the *best* register to spill. But there are other
835 // registers that are pretty good as well (spill weight within 3%). Spill
836 // the one that has fewest defs and uses that conflict with cur.
837 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
838 SmallVector<LiveInterval*, 8> SLIs[3];
841 dbgs() << "\tConsidering " << NumCands << " candidates: ";
842 for (unsigned i = 0; i != NumCands; ++i)
843 dbgs() << tri_->getName(Candidates[i].first) << " ";
847 // Calculate the number of conflicts of each candidate.
848 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
849 unsigned Reg = i->first->reg;
850 unsigned PhysReg = vrm_->getPhys(Reg);
851 if (!cur->overlapsFrom(*i->first, i->second))
853 for (unsigned j = 0; j < NumCands; ++j) {
854 unsigned Candidate = Candidates[j].first;
855 if (tri_->regsOverlap(PhysReg, Candidate)) {
857 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
858 SLIs[j].push_back(i->first);
863 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
864 unsigned Reg = i->first->reg;
865 unsigned PhysReg = vrm_->getPhys(Reg);
866 if (!cur->overlapsFrom(*i->first, i->second-1))
868 for (unsigned j = 0; j < NumCands; ++j) {
869 unsigned Candidate = Candidates[j].first;
870 if (tri_->regsOverlap(PhysReg, Candidate)) {
872 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
873 SLIs[j].push_back(i->first);
878 // Which is the best candidate?
879 unsigned BestCandidate = 0;
880 float MinConflicts = Conflicts[0];
881 for (unsigned i = 1; i != NumCands; ++i) {
882 if (Conflicts[i] < MinConflicts) {
884 MinConflicts = Conflicts[i];
888 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
889 std::back_inserter(SpillIntervals));
893 struct WeightCompare {
895 const RALinScan &Allocator;
898 WeightCompare(const RALinScan &Alloc) : Allocator(Alloc) {}
900 typedef std::pair<unsigned, float> RegWeightPair;
901 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
902 return LHS.second < RHS.second && !Allocator.isRecentlyUsed(LHS.first);
907 static bool weightsAreClose(float w1, float w2) {
911 float diff = w1 - w2;
912 if (diff <= 0.02f) // Within 0.02f
914 return (diff / w2) <= 0.05f; // Within 5%.
917 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
918 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
919 if (I == NextReloadMap.end())
921 return &li_->getInterval(I->second);
924 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
925 bool isNew = DowngradedRegs.insert(Reg);
926 isNew = isNew; // Silence compiler warning.
927 assert(isNew && "Multiple reloads holding the same register?");
928 DowngradeMap.insert(std::make_pair(li->reg, Reg));
929 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
930 isNew = DowngradedRegs.insert(*AS);
931 isNew = isNew; // Silence compiler warning.
932 assert(isNew && "Multiple reloads holding the same register?");
933 DowngradeMap.insert(std::make_pair(li->reg, *AS));
938 void RALinScan::UpgradeRegister(unsigned Reg) {
940 DowngradedRegs.erase(Reg);
941 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
942 DowngradedRegs.erase(*AS);
948 bool operator()(LiveInterval* A, LiveInterval* B) {
949 return A->beginIndex() < B->beginIndex();
954 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
956 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
957 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
958 DEBUG(dbgs() << "\tallocating current interval from "
959 << RC->getName() << ": ");
961 // This is an implicitly defined live interval, just assign any register.
963 unsigned physReg = vrm_->getRegAllocPref(cur->reg);
965 physReg = getFirstNonReservedPhysReg(RC);
966 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
967 // Note the register is not really in use.
968 vrm_->assignVirt2Phys(cur->reg, physReg);
974 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
975 SlotIndex StartPosition = cur->beginIndex();
976 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
978 // If start of this live interval is defined by a move instruction and its
979 // source is assigned a physical register that is compatible with the target
980 // register class, then we should try to assign it the same register.
981 // This can happen when the move is from a larger register class to a smaller
982 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
983 if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
984 VNInfo *vni = cur->begin()->valno;
985 if (!vni->isUnused()) {
986 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
987 if (CopyMI && CopyMI->isCopy()) {
988 unsigned DstSubReg = CopyMI->getOperand(0).getSubReg();
989 unsigned SrcReg = CopyMI->getOperand(1).getReg();
990 unsigned SrcSubReg = CopyMI->getOperand(1).getSubReg();
992 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
994 else if (vrm_->isAssignedReg(SrcReg))
995 Reg = vrm_->getPhys(SrcReg);
998 Reg = tri_->getSubReg(Reg, SrcSubReg);
1000 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1001 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1002 mri_->setRegAllocationHint(cur->reg, 0, Reg);
1008 // For every interval in inactive we overlap with, mark the
1009 // register as not free and update spill weights.
1010 for (IntervalPtrs::const_iterator i = inactive_.begin(),
1011 e = inactive_.end(); i != e; ++i) {
1012 unsigned Reg = i->first->reg;
1013 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1014 "Can only allocate virtual registers!");
1015 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1016 // If this is not in a related reg class to the register we're allocating,
1018 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1019 cur->overlapsFrom(*i->first, i->second-1)) {
1020 Reg = vrm_->getPhys(Reg);
1022 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1026 // Speculatively check to see if we can get a register right now. If not,
1027 // we know we won't be able to by adding more constraints. If so, we can
1028 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1029 // is very bad (it contains all callee clobbered registers for any functions
1030 // with a call), so we want to avoid doing that if possible.
1031 unsigned physReg = getFreePhysReg(cur);
1032 unsigned BestPhysReg = physReg;
1034 // We got a register. However, if it's in the fixed_ list, we might
1035 // conflict with it. Check to see if we conflict with it or any of its
1037 SmallSet<unsigned, 8> RegAliases;
1038 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1039 RegAliases.insert(*AS);
1041 bool ConflictsWithFixed = false;
1042 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1043 IntervalPtr &IP = fixed_[i];
1044 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1045 // Okay, this reg is on the fixed list. Check to see if we actually
1047 LiveInterval *I = IP.first;
1048 if (I->endIndex() > StartPosition) {
1049 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1051 if (II != I->begin() && II->start > StartPosition)
1053 if (cur->overlapsFrom(*I, II)) {
1054 ConflictsWithFixed = true;
1061 // Okay, the register picked by our speculative getFreePhysReg call turned
1062 // out to be in use. Actually add all of the conflicting fixed registers to
1063 // regUse_ so we can do an accurate query.
1064 if (ConflictsWithFixed) {
1065 // For every interval in fixed we overlap with, mark the register as not
1066 // free and update spill weights.
1067 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1068 IntervalPtr &IP = fixed_[i];
1069 LiveInterval *I = IP.first;
1071 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1072 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1073 I->endIndex() > StartPosition) {
1074 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1076 if (II != I->begin() && II->start > StartPosition)
1078 if (cur->overlapsFrom(*I, II)) {
1079 unsigned reg = I->reg;
1081 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1086 // Using the newly updated regUse_ object, which includes conflicts in the
1087 // future, see if there are any registers available.
1088 physReg = getFreePhysReg(cur);
1092 // Restore the physical register tracker, removing information about the
1096 // If we find a free register, we are done: assign this virtual to
1097 // the free physical register and add this interval to the active
1100 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
1101 vrm_->assignVirt2Phys(cur->reg, physReg);
1103 active_.push_back(std::make_pair(cur, cur->begin()));
1104 handled_.push_back(cur);
1106 // "Upgrade" the physical register since it has been allocated.
1107 UpgradeRegister(physReg);
1108 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1109 // "Downgrade" physReg to try to keep physReg from being allocated until
1110 // the next reload from the same SS is allocated.
1111 mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1112 DowngradeRegister(cur, physReg);
1116 DEBUG(dbgs() << "no free registers\n");
1118 // Compile the spill weights into an array that is better for scanning.
1119 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1120 for (std::vector<std::pair<unsigned, float> >::iterator
1121 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1122 updateSpillWeights(SpillWeights, I->first, I->second, RC);
1124 // for each interval in active, update spill weights.
1125 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1127 unsigned reg = i->first->reg;
1128 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1129 "Can only allocate virtual registers!");
1130 reg = vrm_->getPhys(reg);
1131 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1134 DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1136 // Find a register to spill.
1137 float minWeight = HUGE_VALF;
1138 unsigned minReg = 0;
1141 std::vector<std::pair<unsigned,float> > RegsWeights;
1142 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1143 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1144 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1146 float regWeight = SpillWeights[reg];
1147 // Don't even consider reserved regs.
1148 if (reservedRegs_.test(reg))
1150 // Skip recently allocated registers and reserved registers.
1151 if (minWeight > regWeight && !isRecentlyUsed(reg))
1153 RegsWeights.push_back(std::make_pair(reg, regWeight));
1156 // If we didn't find a register that is spillable, try aliases?
1158 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1159 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1161 if (reservedRegs_.test(reg))
1163 // No need to worry about if the alias register size < regsize of RC.
1164 // We are going to spill all registers that alias it anyway.
1165 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1166 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1170 // Sort all potential spill candidates by weight.
1171 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1172 minReg = RegsWeights[0].first;
1173 minWeight = RegsWeights[0].second;
1174 if (minWeight == HUGE_VALF) {
1175 // All registers must have inf weight. Just grab one!
1176 minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1177 if (cur->weight == HUGE_VALF ||
1178 li_->getApproximateInstructionCount(*cur) == 0) {
1179 // Spill a physical register around defs and uses.
1180 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1181 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1182 // in fixed_. Reset them.
1183 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1184 IntervalPtr &IP = fixed_[i];
1185 LiveInterval *I = IP.first;
1186 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1187 IP.second = I->advanceTo(I->begin(), StartPosition);
1190 DowngradedRegs.clear();
1191 assignRegOrStackSlotAtInterval(cur);
1193 assert(false && "Ran out of registers during register allocation!");
1194 report_fatal_error("Ran out of registers during register allocation!");
1200 // Find up to 3 registers to consider as spill candidates.
1201 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1202 while (LastCandidate > 1) {
1203 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1209 dbgs() << "\t\tregister(s) with min weight(s): ";
1211 for (unsigned i = 0; i != LastCandidate; ++i)
1212 dbgs() << tri_->getName(RegsWeights[i].first)
1213 << " (" << RegsWeights[i].second << ")\n";
1216 // If the current has the minimum weight, we need to spill it and
1217 // add any added intervals back to unhandled, and restart
1219 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1220 DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1221 SmallVector<LiveInterval*, 8> spillIs, added;
1222 spiller_->spill(cur, added, spillIs);
1224 std::sort(added.begin(), added.end(), LISorter());
1226 return; // Early exit if all spills were folded.
1228 // Merge added with unhandled. Note that we have already sorted
1229 // intervals returned by addIntervalsForSpills by their starting
1231 // This also update the NextReloadMap. That is, it adds mapping from a
1232 // register defined by a reload from SS to the next reload from SS in the
1233 // same basic block.
1234 MachineBasicBlock *LastReloadMBB = 0;
1235 LiveInterval *LastReload = 0;
1236 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1237 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1238 LiveInterval *ReloadLi = added[i];
1239 if (ReloadLi->weight == HUGE_VALF &&
1240 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1241 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1242 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1243 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1244 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1245 // Last reload of same SS is in the same MBB. We want to try to
1246 // allocate both reloads the same register and make sure the reg
1247 // isn't clobbered in between if at all possible.
1248 assert(LastReload->beginIndex() < ReloadIdx);
1249 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1251 LastReloadMBB = ReloadMBB;
1252 LastReload = ReloadLi;
1253 LastReloadSS = ReloadSS;
1255 unhandled_.push(ReloadLi);
1262 // Push the current interval back to unhandled since we are going
1263 // to re-run at least this iteration. Since we didn't modify it it
1264 // should go back right in the front of the list
1265 unhandled_.push(cur);
1267 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1268 "did not choose a register to spill?");
1270 // We spill all intervals aliasing the register with
1271 // minimum weight, rollback to the interval with the earliest
1272 // start point and let the linear scan algorithm run again
1273 SmallVector<LiveInterval*, 8> spillIs;
1275 // Determine which intervals have to be spilled.
1276 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1278 // Set of spilled vregs (used later to rollback properly)
1279 SmallSet<unsigned, 8> spilled;
1281 // The earliest start of a Spilled interval indicates up to where
1282 // in handled we need to roll back
1283 assert(!spillIs.empty() && "No spill intervals?");
1284 SlotIndex earliestStart = spillIs[0]->beginIndex();
1286 // Spill live intervals of virtual regs mapped to the physical register we
1287 // want to clear (and its aliases). We only spill those that overlap with the
1288 // current interval as the rest do not affect its allocation. we also keep
1289 // track of the earliest start of all spilled live intervals since this will
1290 // mark our rollback point.
1291 SmallVector<LiveInterval*, 8> added;
1292 while (!spillIs.empty()) {
1293 LiveInterval *sli = spillIs.back();
1295 DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1296 if (sli->beginIndex() < earliestStart)
1297 earliestStart = sli->beginIndex();
1298 spiller_->spill(sli, added, spillIs);
1299 spilled.insert(sli->reg);
1302 // Include any added intervals in earliestStart.
1303 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1304 SlotIndex SI = added[i]->beginIndex();
1305 if (SI < earliestStart)
1309 DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1311 // Scan handled in reverse order up to the earliest start of a
1312 // spilled live interval and undo each one, restoring the state of
1314 while (!handled_.empty()) {
1315 LiveInterval* i = handled_.back();
1316 // If this interval starts before t we are done.
1317 if (!i->empty() && i->beginIndex() < earliestStart)
1319 DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1320 handled_.pop_back();
1322 // When undoing a live interval allocation we must know if it is active or
1323 // inactive to properly update regUse_ and the VirtRegMap.
1324 IntervalPtrs::iterator it;
1325 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1327 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1328 if (!spilled.count(i->reg))
1330 delRegUse(vrm_->getPhys(i->reg));
1331 vrm_->clearVirt(i->reg);
1332 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1333 inactive_.erase(it);
1334 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1335 if (!spilled.count(i->reg))
1337 vrm_->clearVirt(i->reg);
1339 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1340 "Can only allocate virtual registers!");
1341 vrm_->clearVirt(i->reg);
1345 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1346 if (ii == DowngradeMap.end())
1347 // It interval has a preference, it must be defined by a copy. Clear the
1348 // preference now since the source interval allocation may have been
1350 mri_->setRegAllocationHint(i->reg, 0, 0);
1352 UpgradeRegister(ii->second);
1356 // Rewind the iterators in the active, inactive, and fixed lists back to the
1357 // point we reverted to.
1358 RevertVectorIteratorsTo(active_, earliestStart);
1359 RevertVectorIteratorsTo(inactive_, earliestStart);
1360 RevertVectorIteratorsTo(fixed_, earliestStart);
1362 // Scan the rest and undo each interval that expired after t and
1363 // insert it in active (the next iteration of the algorithm will
1364 // put it in inactive if required)
1365 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1366 LiveInterval *HI = handled_[i];
1367 if (!HI->expiredAt(earliestStart) &&
1368 HI->expiredAt(cur->beginIndex())) {
1369 DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1370 active_.push_back(std::make_pair(HI, HI->begin()));
1371 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1372 addRegUse(vrm_->getPhys(HI->reg));
1376 // Merge added with unhandled.
1377 // This also update the NextReloadMap. That is, it adds mapping from a
1378 // register defined by a reload from SS to the next reload from SS in the
1379 // same basic block.
1380 MachineBasicBlock *LastReloadMBB = 0;
1381 LiveInterval *LastReload = 0;
1382 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1383 std::sort(added.begin(), added.end(), LISorter());
1384 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1385 LiveInterval *ReloadLi = added[i];
1386 if (ReloadLi->weight == HUGE_VALF &&
1387 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1388 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1389 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1390 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1391 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1392 // Last reload of same SS is in the same MBB. We want to try to
1393 // allocate both reloads the same register and make sure the reg
1394 // isn't clobbered in between if at all possible.
1395 assert(LastReload->beginIndex() < ReloadIdx);
1396 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1398 LastReloadMBB = ReloadMBB;
1399 LastReload = ReloadLi;
1400 LastReloadSS = ReloadSS;
1402 unhandled_.push(ReloadLi);
1406 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1407 const TargetRegisterClass *RC,
1408 unsigned MaxInactiveCount,
1409 SmallVector<unsigned, 256> &inactiveCounts,
1411 unsigned FreeReg = 0;
1412 unsigned FreeRegInactiveCount = 0;
1414 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1415 // Resolve second part of the hint (if possible) given the current allocation.
1416 unsigned physReg = Hint.second;
1418 TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1419 physReg = vrm_->getPhys(physReg);
1421 TargetRegisterClass::iterator I, E;
1422 tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1423 assert(I != E && "No allocatable register in this register class!");
1425 // Scan for the first available register.
1426 for (; I != E; ++I) {
1428 // Ignore "downgraded" registers.
1429 if (SkipDGRegs && DowngradedRegs.count(Reg))
1431 // Skip reserved registers.
1432 if (reservedRegs_.test(Reg))
1434 // Skip recently allocated registers.
1435 if (isRegAvail(Reg) && !isRecentlyUsed(Reg)) {
1437 if (FreeReg < inactiveCounts.size())
1438 FreeRegInactiveCount = inactiveCounts[FreeReg];
1440 FreeRegInactiveCount = 0;
1445 // If there are no free regs, or if this reg has the max inactive count,
1446 // return this register.
1447 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1448 // Remember what register we picked so we can skip it next time.
1449 if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1453 // Continue scanning the registers, looking for the one with the highest
1454 // inactive count. Alkis found that this reduced register pressure very
1455 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1457 for (; I != E; ++I) {
1459 // Ignore "downgraded" registers.
1460 if (SkipDGRegs && DowngradedRegs.count(Reg))
1462 // Skip reserved registers.
1463 if (reservedRegs_.test(Reg))
1465 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1466 FreeRegInactiveCount < inactiveCounts[Reg] && !isRecentlyUsed(Reg)) {
1468 FreeRegInactiveCount = inactiveCounts[Reg];
1469 if (FreeRegInactiveCount == MaxInactiveCount)
1470 break; // We found the one with the max inactive count.
1474 // Remember what register we picked so we can skip it next time.
1475 recordRecentlyUsed(FreeReg);
1480 /// getFreePhysReg - return a free physical register for this virtual register
1481 /// interval if we have one, otherwise return 0.
1482 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1483 SmallVector<unsigned, 256> inactiveCounts;
1484 unsigned MaxInactiveCount = 0;
1486 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1487 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1489 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1491 unsigned reg = i->first->reg;
1492 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1493 "Can only allocate virtual registers!");
1495 // If this is not in a related reg class to the register we're allocating,
1497 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1498 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1499 reg = vrm_->getPhys(reg);
1500 if (inactiveCounts.size() <= reg)
1501 inactiveCounts.resize(reg+1);
1502 ++inactiveCounts[reg];
1503 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1507 // If copy coalescer has assigned a "preferred" register, check if it's
1509 unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1511 DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1512 if (isRegAvail(Preference) &&
1513 RC->contains(Preference))
1517 if (!DowngradedRegs.empty()) {
1518 unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1523 return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1526 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1527 return new RALinScan();