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/Function.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegAllocRegistry.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/ADT/EquivalenceClasses.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
47 STATISTIC(NumIters , "Number of iterations performed");
48 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
49 STATISTIC(NumCoalesce, "Number of copies coalesced");
50 STATISTIC(NumDowngrade, "Number of registers downgraded");
53 NewHeuristic("new-spilling-heuristic",
54 cl::desc("Use new spilling heuristic"),
55 cl::init(false), cl::Hidden);
58 PreSplitIntervals("pre-alloc-split",
59 cl::desc("Pre-register allocation live interval splitting"),
60 cl::init(false), cl::Hidden);
63 NewSpillFramework("new-spill-framework",
64 cl::desc("New spilling framework"),
65 cl::init(false), cl::Hidden);
67 static RegisterRegAlloc
68 linearscanRegAlloc("linearscan", "linear scan register allocator",
69 createLinearScanRegisterAllocator);
72 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
74 RALinScan() : MachineFunctionPass(&ID) {}
76 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
77 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
79 /// RelatedRegClasses - This structure is built the first time a function is
80 /// compiled, and keeps track of which register classes have registers that
81 /// belong to multiple classes or have aliases that are in other classes.
82 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
83 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
85 // NextReloadMap - For each register in the map, it maps to the another
86 // register which is defined by a reload from the same stack slot and
87 // both reloads are in the same basic block.
88 DenseMap<unsigned, unsigned> NextReloadMap;
90 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
91 // un-favored for allocation.
92 SmallSet<unsigned, 8> DowngradedRegs;
94 // DowngradeMap - A map from virtual registers to physical registers being
95 // downgraded for the virtual registers.
96 DenseMap<unsigned, unsigned> DowngradeMap;
99 MachineRegisterInfo* mri_;
100 const TargetMachine* tm_;
101 const TargetRegisterInfo* tri_;
102 const TargetInstrInfo* tii_;
103 BitVector allocatableRegs_;
106 const MachineLoopInfo *loopInfo;
108 /// handled_ - Intervals are added to the handled_ set in the order of their
109 /// start value. This is uses for backtracking.
110 std::vector<LiveInterval*> handled_;
112 /// fixed_ - Intervals that correspond to machine registers.
116 /// active_ - Intervals that are currently being processed, and which have a
117 /// live range active for the current point.
118 IntervalPtrs active_;
120 /// inactive_ - Intervals that are currently being processed, but which have
121 /// a hold at the current point.
122 IntervalPtrs inactive_;
124 typedef std::priority_queue<LiveInterval*,
125 SmallVector<LiveInterval*, 64>,
126 greater_ptr<LiveInterval> > IntervalHeap;
127 IntervalHeap unhandled_;
129 /// regUse_ - Tracks register usage.
130 SmallVector<unsigned, 32> regUse_;
131 SmallVector<unsigned, 32> regUseBackUp_;
133 /// vrm_ - Tracks register assignments.
136 std::auto_ptr<VirtRegRewriter> rewriter_;
138 std::auto_ptr<Spiller> spiller_;
141 virtual const char* getPassName() const {
142 return "Linear Scan Register Allocator";
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146 AU.addRequired<LiveIntervals>();
148 AU.addRequiredID(StrongPHIEliminationID);
149 // Make sure PassManager knows which analyses to make available
150 // to coalescing and which analyses coalescing invalidates.
151 AU.addRequiredTransitive<RegisterCoalescer>();
152 if (PreSplitIntervals)
153 AU.addRequiredID(PreAllocSplittingID);
154 AU.addRequired<LiveStacks>();
155 AU.addPreserved<LiveStacks>();
156 AU.addRequired<MachineLoopInfo>();
157 AU.addPreserved<MachineLoopInfo>();
158 AU.addRequired<VirtRegMap>();
159 AU.addPreserved<VirtRegMap>();
160 AU.addPreservedID(MachineDominatorsID);
161 MachineFunctionPass::getAnalysisUsage(AU);
164 /// runOnMachineFunction - register allocate the whole function
165 bool runOnMachineFunction(MachineFunction&);
168 /// linearScan - the linear scan algorithm
171 /// initIntervalSets - initialize the interval sets.
173 void initIntervalSets();
175 /// processActiveIntervals - expire old intervals and move non-overlapping
176 /// ones to the inactive list.
177 void processActiveIntervals(unsigned CurPoint);
179 /// processInactiveIntervals - expire old intervals and move overlapping
180 /// ones to the active list.
181 void processInactiveIntervals(unsigned CurPoint);
183 /// hasNextReloadInterval - Return the next liveinterval that's being
184 /// defined by a reload from the same SS as the specified one.
185 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
187 /// DowngradeRegister - Downgrade a register for allocation.
188 void DowngradeRegister(LiveInterval *li, unsigned Reg);
190 /// UpgradeRegister - Upgrade a register for allocation.
191 void UpgradeRegister(unsigned Reg);
193 /// assignRegOrStackSlotAtInterval - assign a register if one
194 /// is available, or spill.
195 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
197 void updateSpillWeights(std::vector<float> &Weights,
198 unsigned reg, float weight,
199 const TargetRegisterClass *RC);
201 /// findIntervalsToSpill - Determine the intervals to spill for the
202 /// specified interval. It's passed the physical registers whose spill
203 /// weight is the lowest among all the registers whose live intervals
204 /// conflict with the interval.
205 void findIntervalsToSpill(LiveInterval *cur,
206 std::vector<std::pair<unsigned,float> > &Candidates,
208 SmallVector<LiveInterval*, 8> &SpillIntervals);
210 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
211 /// try allocate the definition the same register as the source register
212 /// if the register is not defined during live time of the interval. This
213 /// eliminate a copy. This is used to coalesce copies which were not
214 /// coalesced away before allocation either due to dest and src being in
215 /// different register classes or because the coalescer was overly
217 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
220 /// Register usage / availability tracking helpers.
224 regUse_.resize(tri_->getNumRegs(), 0);
225 regUseBackUp_.resize(tri_->getNumRegs(), 0);
228 void finalizeRegUses() {
230 // Verify all the registers are "freed".
232 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
233 if (regUse_[i] != 0) {
234 cerr << tri_->getName(i) << " is still in use!\n";
242 regUseBackUp_.clear();
245 void addRegUse(unsigned physReg) {
246 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
247 "should be physical register!");
249 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
253 void delRegUse(unsigned physReg) {
254 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
255 "should be physical register!");
256 assert(regUse_[physReg] != 0);
258 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
259 assert(regUse_[*as] != 0);
264 bool isRegAvail(unsigned physReg) const {
265 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
266 "should be physical register!");
267 return regUse_[physReg] == 0;
270 void backUpRegUses() {
271 regUseBackUp_ = regUse_;
274 void restoreRegUses() {
275 regUse_ = regUseBackUp_;
279 /// Register handling helpers.
282 /// getFreePhysReg - return a free physical register for this virtual
283 /// register interval if we have one, otherwise return 0.
284 unsigned getFreePhysReg(LiveInterval* cur);
285 unsigned getFreePhysReg(const TargetRegisterClass *RC,
286 unsigned MaxInactiveCount,
287 SmallVector<unsigned, 256> &inactiveCounts,
290 /// assignVirt2StackSlot - assigns this virtual register to a
291 /// stack slot. returns the stack slot
292 int assignVirt2StackSlot(unsigned virtReg);
294 void ComputeRelatedRegClasses();
296 template <typename ItTy>
297 void printIntervals(const char* const str, ItTy i, ItTy e) const {
298 if (str) DOUT << str << " intervals:\n";
299 for (; i != e; ++i) {
300 DOUT << "\t" << *i->first << " -> ";
301 unsigned reg = i->first->reg;
302 if (TargetRegisterInfo::isVirtualRegister(reg)) {
303 reg = vrm_->getPhys(reg);
305 DOUT << tri_->getName(reg) << '\n';
309 char RALinScan::ID = 0;
312 static RegisterPass<RALinScan>
313 X("linearscan-regalloc", "Linear Scan Register Allocator");
315 bool validateRegAlloc(MachineFunction *mf, LiveIntervals *lis,
318 MachineRegisterInfo *mri = &mf->getRegInfo();
319 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
320 bool allocationValid = true;
323 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
326 LiveInterval *li = itr->second;
328 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
332 if (vrm->hasPhys(li->reg)) {
333 const TargetRegisterClass *trc = mri->getRegClass(li->reg);
335 if (lis->hasInterval(vrm->getPhys(li->reg))) {
336 if (li->overlaps(lis->getInterval(vrm->getPhys(li->reg)))) {
337 std::cerr << "vreg " << li->reg << " overlaps its assigned preg "
338 << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
342 TargetRegisterClass::iterator fReg =
343 std::find(trc->allocation_order_begin(*mf), trc->allocation_order_end(*mf),
344 vrm->getPhys(li->reg));
346 if (fReg == trc->allocation_order_end(*mf)) {
347 std::cerr << "preg " << vrm->getPhys(li->reg)
348 << "(" << tri->getName(vrm->getPhys(li->reg)) << ") is not in the allocation set for vreg "
350 allocationValid &= false;
354 std::cerr << "No preg for vreg " << li->reg << "\n";
355 // What about conflicting loads/stores?
359 for (LiveIntervals::iterator itr2 = next(itr); itr2 != end; ++itr2) {
361 LiveInterval *li2 = itr2->second;
366 if (TargetRegisterInfo::isPhysicalRegister(li2->reg)) {
367 if (li->overlaps(*li2)) {
368 if (vrm->getPhys(li->reg) == li2->reg ||
369 tri->areAliases(vrm->getPhys(li->reg), li2->reg)) {
370 std::cerr << "vreg " << li->reg << " overlaps preg "
371 << li2->reg << "(" << tri->getName(li2->reg) << ") which aliases "
372 << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
373 allocationValid &= false;
379 if (!vrm->hasPhys(li2->reg)) {
383 if (li->overlaps(*li2)) {
384 if (vrm->getPhys(li->reg) == vrm->getPhys(li2->reg) ||
385 tri->areAliases(vrm->getPhys(li->reg), vrm->getPhys(li2->reg))) {
386 std::cerr << "vreg " << li->reg << " (preg " << vrm->getPhys(li->reg)
387 << ") overlaps vreg " << li2->reg << " (preg " << vrm->getPhys(li2->reg)
388 << ") and " << vrm->getPhys(li->reg) << " aliases " << vrm->getPhys(li2->reg) << "\n";
389 allocationValid &= false;
397 return allocationValid;
402 void RALinScan::ComputeRelatedRegClasses() {
403 // First pass, add all reg classes to the union, and determine at least one
404 // reg class that each register is in.
405 bool HasAliases = false;
406 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
407 E = tri_->regclass_end(); RCI != E; ++RCI) {
408 RelatedRegClasses.insert(*RCI);
409 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
411 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
413 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
415 // Already processed this register. Just make sure we know that
416 // multiple register classes share a register.
417 RelatedRegClasses.unionSets(PRC, *RCI);
424 // Second pass, now that we know conservatively what register classes each reg
425 // belongs to, add info about aliases. We don't need to do this for targets
426 // without register aliases.
428 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
429 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
431 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
432 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
435 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
436 /// try allocate the definition the same register as the source register
437 /// if the register is not defined during live time of the interval. This
438 /// eliminate a copy. This is used to coalesce copies which were not
439 /// coalesced away before allocation either due to dest and src being in
440 /// different register classes or because the coalescer was overly
442 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
443 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
446 VNInfo *vni = cur.begin()->valno;
447 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
449 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
450 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg, PhysReg;
452 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
455 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
456 if (!vrm_->isAssignedReg(SrcReg))
458 PhysReg = vrm_->getPhys(SrcReg);
463 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
464 if (!RC->contains(PhysReg))
468 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, PhysReg)) {
469 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(PhysReg)
471 vrm_->clearVirt(cur.reg);
472 vrm_->assignVirt2Phys(cur.reg, PhysReg);
474 // Remove unnecessary kills since a copy does not clobber the register.
475 if (li_->hasInterval(SrcReg)) {
476 LiveInterval &SrcLI = li_->getInterval(SrcReg);
477 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(cur.reg),
478 E = mri_->reg_end(); I != E; ++I) {
479 MachineOperand &O = I.getOperand();
480 if (!O.isUse() || !O.isKill())
482 MachineInstr *MI = &*I;
483 if (SrcLI.liveAt(li_->getDefIndex(li_->getInstructionIndex(MI))))
495 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
497 mri_ = &fn.getRegInfo();
498 tm_ = &fn.getTarget();
499 tri_ = tm_->getRegisterInfo();
500 tii_ = tm_->getInstrInfo();
501 allocatableRegs_ = tri_->getAllocatableSet(fn);
502 li_ = &getAnalysis<LiveIntervals>();
503 ls_ = &getAnalysis<LiveStacks>();
504 loopInfo = &getAnalysis<MachineLoopInfo>();
506 // We don't run the coalescer here because we have no reason to
507 // interact with it. If the coalescer requires interaction, it
508 // won't do anything. If it doesn't require interaction, we assume
509 // it was run as a separate pass.
511 // If this is the first function compiled, compute the related reg classes.
512 if (RelatedRegClasses.empty())
513 ComputeRelatedRegClasses();
515 // Also resize register usage trackers.
518 vrm_ = &getAnalysis<VirtRegMap>();
519 if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
521 if (NewSpillFramework) {
522 spiller_.reset(createSpiller(mf_, li_, ls_, vrm_));
529 if (NewSpillFramework) {
530 bool allocValid = validateRegAlloc(mf_, li_, vrm_);
533 // Rewrite spill code and update the PhysRegsUsed set.
534 rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
536 assert(unhandled_.empty() && "Unhandled live intervals remain!");
544 NextReloadMap.clear();
545 DowngradedRegs.clear();
546 DowngradeMap.clear();
552 /// initIntervalSets - initialize the interval sets.
554 void RALinScan::initIntervalSets()
556 assert(unhandled_.empty() && fixed_.empty() &&
557 active_.empty() && inactive_.empty() &&
558 "interval sets should be empty on initialization");
560 handled_.reserve(li_->getNumIntervals());
562 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
563 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
564 mri_->setPhysRegUsed(i->second->reg);
565 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
567 unhandled_.push(i->second);
571 void RALinScan::linearScan()
573 // linear scan algorithm
574 DOUT << "********** LINEAR SCAN **********\n";
575 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
577 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
579 while (!unhandled_.empty()) {
580 // pick the interval with the earliest start point
581 LiveInterval* cur = unhandled_.top();
584 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
587 processActiveIntervals(cur->beginNumber());
588 processInactiveIntervals(cur->beginNumber());
590 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
591 "Can only allocate virtual registers!");
594 // Allocating a virtual register. try to find a free
595 // physical register or spill an interval (possibly this one) in order to
597 assignRegOrStackSlotAtInterval(cur);
599 DEBUG(printIntervals("active", active_.begin(), active_.end()));
600 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
603 // Expire any remaining active intervals
604 while (!active_.empty()) {
605 IntervalPtr &IP = active_.back();
606 unsigned reg = IP.first->reg;
607 DOUT << "\tinterval " << *IP.first << " expired\n";
608 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
609 "Can only allocate virtual registers!");
610 reg = vrm_->getPhys(reg);
615 // Expire any remaining inactive intervals
616 DEBUG(for (IntervalPtrs::reverse_iterator
617 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
618 DOUT << "\tinterval " << *i->first << " expired\n");
621 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
622 MachineFunction::iterator EntryMBB = mf_->begin();
623 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
624 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
625 LiveInterval &cur = *i->second;
627 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
630 else if (vrm_->isAssignedReg(cur.reg))
631 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
634 // Ignore splited live intervals.
635 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
637 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
639 const LiveRange &LR = *I;
640 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
641 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
642 if (LiveInMBBs[i] != EntryMBB)
643 LiveInMBBs[i]->addLiveIn(Reg);
651 // Look for physical registers that end up not being allocated even though
652 // register allocator had to spill other registers in its register class.
653 if (ls_->getNumIntervals() == 0)
655 if (!vrm_->FindUnusedRegisters(tri_, li_))
659 /// processActiveIntervals - expire old intervals and move non-overlapping ones
660 /// to the inactive list.
661 void RALinScan::processActiveIntervals(unsigned CurPoint)
663 DOUT << "\tprocessing active intervals:\n";
665 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
666 LiveInterval *Interval = active_[i].first;
667 LiveInterval::iterator IntervalPos = active_[i].second;
668 unsigned reg = Interval->reg;
670 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
672 if (IntervalPos == Interval->end()) { // Remove expired intervals.
673 DOUT << "\t\tinterval " << *Interval << " expired\n";
674 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
675 "Can only allocate virtual registers!");
676 reg = vrm_->getPhys(reg);
679 // Pop off the end of the list.
680 active_[i] = active_.back();
684 } else if (IntervalPos->start > CurPoint) {
685 // Move inactive intervals to inactive list.
686 DOUT << "\t\tinterval " << *Interval << " inactive\n";
687 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
688 "Can only allocate virtual registers!");
689 reg = vrm_->getPhys(reg);
692 inactive_.push_back(std::make_pair(Interval, IntervalPos));
694 // Pop off the end of the list.
695 active_[i] = active_.back();
699 // Otherwise, just update the iterator position.
700 active_[i].second = IntervalPos;
705 /// processInactiveIntervals - expire old intervals and move overlapping
706 /// ones to the active list.
707 void RALinScan::processInactiveIntervals(unsigned CurPoint)
709 DOUT << "\tprocessing inactive intervals:\n";
711 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
712 LiveInterval *Interval = inactive_[i].first;
713 LiveInterval::iterator IntervalPos = inactive_[i].second;
714 unsigned reg = Interval->reg;
716 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
718 if (IntervalPos == Interval->end()) { // remove expired intervals.
719 DOUT << "\t\tinterval " << *Interval << " expired\n";
721 // Pop off the end of the list.
722 inactive_[i] = inactive_.back();
723 inactive_.pop_back();
725 } else if (IntervalPos->start <= CurPoint) {
726 // move re-activated intervals in active list
727 DOUT << "\t\tinterval " << *Interval << " active\n";
728 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
729 "Can only allocate virtual registers!");
730 reg = vrm_->getPhys(reg);
733 active_.push_back(std::make_pair(Interval, IntervalPos));
735 // Pop off the end of the list.
736 inactive_[i] = inactive_.back();
737 inactive_.pop_back();
740 // Otherwise, just update the iterator position.
741 inactive_[i].second = IntervalPos;
746 /// updateSpillWeights - updates the spill weights of the specifed physical
747 /// register and its weight.
748 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
749 unsigned reg, float weight,
750 const TargetRegisterClass *RC) {
751 SmallSet<unsigned, 4> Processed;
752 SmallSet<unsigned, 4> SuperAdded;
753 SmallVector<unsigned, 4> Supers;
754 Weights[reg] += weight;
755 Processed.insert(reg);
756 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
757 Weights[*as] += weight;
758 Processed.insert(*as);
759 if (tri_->isSubRegister(*as, reg) &&
760 SuperAdded.insert(*as) &&
762 Supers.push_back(*as);
766 // If the alias is a super-register, and the super-register is in the
767 // register class we are trying to allocate. Then add the weight to all
768 // sub-registers of the super-register even if they are not aliases.
769 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
770 // bl should get the same spill weight otherwise it will be choosen
771 // as a spill candidate since spilling bh doesn't make ebx available.
772 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
773 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
774 if (!Processed.count(*sr))
775 Weights[*sr] += weight;
780 RALinScan::IntervalPtrs::iterator
781 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
782 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
784 if (I->first == LI) return I;
788 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
789 for (unsigned i = 0, e = V.size(); i != e; ++i) {
790 RALinScan::IntervalPtr &IP = V[i];
791 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
793 if (I != IP.first->begin()) --I;
798 /// addStackInterval - Create a LiveInterval for stack if the specified live
799 /// interval has been spilled.
800 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
802 MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
803 int SS = vrm_.getStackSlot(cur->reg);
804 if (SS == VirtRegMap::NO_STACK_SLOT)
807 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
808 LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
811 if (SI.hasAtLeastOneValue())
812 VNI = SI.getValNumInfo(0);
814 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
816 LiveInterval &RI = li_->getInterval(cur->reg);
817 // FIXME: This may be overly conservative.
818 SI.MergeRangesInAsValue(RI, VNI);
821 /// getConflictWeight - Return the number of conflicts between cur
822 /// live interval and defs and uses of Reg weighted by loop depthes.
824 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
825 MachineRegisterInfo *mri_,
826 const MachineLoopInfo *loopInfo) {
828 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
829 E = mri_->reg_end(); I != E; ++I) {
830 MachineInstr *MI = &*I;
831 if (cur->liveAt(li_->getInstructionIndex(MI))) {
832 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
833 Conflicts += powf(10.0f, (float)loopDepth);
839 /// findIntervalsToSpill - Determine the intervals to spill for the
840 /// specified interval. It's passed the physical registers whose spill
841 /// weight is the lowest among all the registers whose live intervals
842 /// conflict with the interval.
843 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
844 std::vector<std::pair<unsigned,float> > &Candidates,
846 SmallVector<LiveInterval*, 8> &SpillIntervals) {
847 // We have figured out the *best* register to spill. But there are other
848 // registers that are pretty good as well (spill weight within 3%). Spill
849 // the one that has fewest defs and uses that conflict with cur.
850 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
851 SmallVector<LiveInterval*, 8> SLIs[3];
853 DOUT << "\tConsidering " << NumCands << " candidates: ";
854 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
855 DOUT << 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 {
905 typedef std::pair<unsigned, float> RegWeightPair;
906 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
907 return LHS.second < RHS.second;
912 static bool weightsAreClose(float w1, float w2) {
916 float diff = w1 - w2;
917 if (diff <= 0.02f) // Within 0.02f
919 return (diff / w2) <= 0.05f; // Within 5%.
922 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
923 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
924 if (I == NextReloadMap.end())
926 return &li_->getInterval(I->second);
929 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
930 bool isNew = DowngradedRegs.insert(Reg);
931 isNew = isNew; // Silence compiler warning.
932 assert(isNew && "Multiple reloads holding the same register?");
933 DowngradeMap.insert(std::make_pair(li->reg, Reg));
934 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
935 isNew = DowngradedRegs.insert(*AS);
936 isNew = isNew; // Silence compiler warning.
937 assert(isNew && "Multiple reloads holding the same register?");
938 DowngradeMap.insert(std::make_pair(li->reg, *AS));
943 void RALinScan::UpgradeRegister(unsigned Reg) {
945 DowngradedRegs.erase(Reg);
946 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
947 DowngradedRegs.erase(*AS);
953 bool operator()(LiveInterval* A, LiveInterval* B) {
954 return A->beginNumber() < B->beginNumber();
959 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
961 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
963 DOUT << "\tallocating current interval: ";
965 // This is an implicitly defined live interval, just assign any register.
966 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
968 unsigned physReg = cur->preference;
970 physReg = *RC->allocation_order_begin(*mf_);
971 DOUT << tri_->getName(physReg) << '\n';
972 // Note the register is not really in use.
973 vrm_->assignVirt2Phys(cur->reg, physReg);
979 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
980 unsigned StartPosition = cur->beginNumber();
981 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
983 // If start of this live interval is defined by a move instruction and its
984 // source is assigned a physical register that is compatible with the target
985 // register class, then we should try to assign it the same register.
986 // This can happen when the move is from a larger register class to a smaller
987 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
988 if (!cur->preference && cur->hasAtLeastOneValue()) {
989 VNInfo *vni = cur->begin()->valno;
990 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
991 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
992 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
994 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
996 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
998 else if (vrm_->isAssignedReg(SrcReg))
999 Reg = vrm_->getPhys(SrcReg);
1002 Reg = tri_->getSubReg(Reg, SrcSubReg);
1004 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1005 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1006 cur->preference = Reg;
1012 // For every interval in inactive we overlap with, mark the
1013 // register as not free and update spill weights.
1014 for (IntervalPtrs::const_iterator i = inactive_.begin(),
1015 e = inactive_.end(); i != e; ++i) {
1016 unsigned Reg = i->first->reg;
1017 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1018 "Can only allocate virtual registers!");
1019 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1020 // If this is not in a related reg class to the register we're allocating,
1022 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1023 cur->overlapsFrom(*i->first, i->second-1)) {
1024 Reg = vrm_->getPhys(Reg);
1026 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1030 // Speculatively check to see if we can get a register right now. If not,
1031 // we know we won't be able to by adding more constraints. If so, we can
1032 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1033 // is very bad (it contains all callee clobbered registers for any functions
1034 // with a call), so we want to avoid doing that if possible.
1035 unsigned physReg = getFreePhysReg(cur);
1036 unsigned BestPhysReg = physReg;
1038 // We got a register. However, if it's in the fixed_ list, we might
1039 // conflict with it. Check to see if we conflict with it or any of its
1041 SmallSet<unsigned, 8> RegAliases;
1042 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1043 RegAliases.insert(*AS);
1045 bool ConflictsWithFixed = false;
1046 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1047 IntervalPtr &IP = fixed_[i];
1048 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1049 // Okay, this reg is on the fixed list. Check to see if we actually
1051 LiveInterval *I = IP.first;
1052 if (I->endNumber() > StartPosition) {
1053 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1055 if (II != I->begin() && II->start > StartPosition)
1057 if (cur->overlapsFrom(*I, II)) {
1058 ConflictsWithFixed = true;
1065 // Okay, the register picked by our speculative getFreePhysReg call turned
1066 // out to be in use. Actually add all of the conflicting fixed registers to
1067 // regUse_ so we can do an accurate query.
1068 if (ConflictsWithFixed) {
1069 // For every interval in fixed we overlap with, mark the register as not
1070 // free and update spill weights.
1071 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1072 IntervalPtr &IP = fixed_[i];
1073 LiveInterval *I = IP.first;
1075 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1076 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1077 I->endNumber() > StartPosition) {
1078 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1080 if (II != I->begin() && II->start > StartPosition)
1082 if (cur->overlapsFrom(*I, II)) {
1083 unsigned reg = I->reg;
1085 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1090 // Using the newly updated regUse_ object, which includes conflicts in the
1091 // future, see if there are any registers available.
1092 physReg = getFreePhysReg(cur);
1096 // Restore the physical register tracker, removing information about the
1100 // If we find a free register, we are done: assign this virtual to
1101 // the free physical register and add this interval to the active
1104 DOUT << tri_->getName(physReg) << '\n';
1105 vrm_->assignVirt2Phys(cur->reg, physReg);
1107 active_.push_back(std::make_pair(cur, cur->begin()));
1108 handled_.push_back(cur);
1110 // "Upgrade" the physical register since it has been allocated.
1111 UpgradeRegister(physReg);
1112 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1113 // "Downgrade" physReg to try to keep physReg from being allocated until
1114 // the next reload from the same SS is allocated.
1115 NextReloadLI->preference = physReg;
1116 DowngradeRegister(cur, physReg);
1120 DOUT << "no free registers\n";
1122 // Compile the spill weights into an array that is better for scanning.
1123 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1124 for (std::vector<std::pair<unsigned, float> >::iterator
1125 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1126 updateSpillWeights(SpillWeights, I->first, I->second, RC);
1128 // for each interval in active, update spill weights.
1129 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1131 unsigned reg = i->first->reg;
1132 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1133 "Can only allocate virtual registers!");
1134 reg = vrm_->getPhys(reg);
1135 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1138 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
1140 // Find a register to spill.
1141 float minWeight = HUGE_VALF;
1142 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
1145 std::vector<std::pair<unsigned,float> > RegsWeights;
1146 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1147 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1148 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1150 float regWeight = SpillWeights[reg];
1151 if (minWeight > regWeight)
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 // No need to worry about if the alias register size < regsize of RC.
1162 // We are going to spill all registers that alias it anyway.
1163 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1164 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1168 // Sort all potential spill candidates by weight.
1169 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1170 minReg = RegsWeights[0].first;
1171 minWeight = RegsWeights[0].second;
1172 if (minWeight == HUGE_VALF) {
1173 // All registers must have inf weight. Just grab one!
1174 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
1175 if (cur->weight == HUGE_VALF ||
1176 li_->getApproximateInstructionCount(*cur) == 0) {
1177 // Spill a physical register around defs and uses.
1178 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1179 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1180 // in fixed_. Reset them.
1181 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1182 IntervalPtr &IP = fixed_[i];
1183 LiveInterval *I = IP.first;
1184 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1185 IP.second = I->advanceTo(I->begin(), StartPosition);
1188 DowngradedRegs.clear();
1189 assignRegOrStackSlotAtInterval(cur);
1191 cerr << "Ran out of registers during register allocation!\n";
1198 // Find up to 3 registers to consider as spill candidates.
1199 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1200 while (LastCandidate > 1) {
1201 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1206 DOUT << "\t\tregister(s) with min weight(s): ";
1207 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
1208 DOUT << tri_->getName(RegsWeights[i].first)
1209 << " (" << RegsWeights[i].second << ")\n");
1211 // If the current has the minimum weight, we need to spill it and
1212 // add any added intervals back to unhandled, and restart
1214 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1215 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
1216 SmallVector<LiveInterval*, 8> spillIs;
1217 std::vector<LiveInterval*> added;
1219 if (!NewSpillFramework) {
1220 added = li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_);
1222 added = spiller_->spill(cur);
1225 std::sort(added.begin(), added.end(), LISorter());
1226 addStackInterval(cur, ls_, li_, mri_, *vrm_);
1228 return; // Early exit if all spills were folded.
1230 // Merge added with unhandled. Note that we have already sorted
1231 // intervals returned by addIntervalsForSpills by their starting
1233 // This also update the NextReloadMap. That is, it adds mapping from a
1234 // register defined by a reload from SS to the next reload from SS in the
1235 // same basic block.
1236 MachineBasicBlock *LastReloadMBB = 0;
1237 LiveInterval *LastReload = 0;
1238 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1239 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1240 LiveInterval *ReloadLi = added[i];
1241 if (ReloadLi->weight == HUGE_VALF &&
1242 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1243 unsigned ReloadIdx = ReloadLi->beginNumber();
1244 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1245 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1246 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1247 // Last reload of same SS is in the same MBB. We want to try to
1248 // allocate both reloads the same register and make sure the reg
1249 // isn't clobbered in between if at all possible.
1250 assert(LastReload->beginNumber() < ReloadIdx);
1251 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1253 LastReloadMBB = ReloadMBB;
1254 LastReload = ReloadLi;
1255 LastReloadSS = ReloadSS;
1257 unhandled_.push(ReloadLi);
1264 // Push the current interval back to unhandled since we are going
1265 // to re-run at least this iteration. Since we didn't modify it it
1266 // should go back right in the front of the list
1267 unhandled_.push(cur);
1269 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1270 "did not choose a register to spill?");
1272 // We spill all intervals aliasing the register with
1273 // minimum weight, rollback to the interval with the earliest
1274 // start point and let the linear scan algorithm run again
1275 SmallVector<LiveInterval*, 8> spillIs;
1277 // Determine which intervals have to be spilled.
1278 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1280 // Set of spilled vregs (used later to rollback properly)
1281 SmallSet<unsigned, 8> spilled;
1283 // The earliest start of a Spilled interval indicates up to where
1284 // in handled we need to roll back
1286 unsigned earliestStart = cur->beginNumber();
1287 LiveInterval *earliestStartInterval = cur;
1289 // Spill live intervals of virtual regs mapped to the physical register we
1290 // want to clear (and its aliases). We only spill those that overlap with the
1291 // current interval as the rest do not affect its allocation. we also keep
1292 // track of the earliest start of all spilled live intervals since this will
1293 // mark our rollback point.
1294 std::vector<LiveInterval*> added;
1295 while (!spillIs.empty()) {
1296 bool epicFail = false;
1297 LiveInterval *sli = spillIs.back();
1299 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1300 earliestStart = std::min(earliestStart, sli->beginNumber());
1301 earliestStartInterval =
1302 (earliestStartInterval->beginNumber() < sli->beginNumber()) ?
1303 earliestStartInterval : sli;
1305 if (earliestStartInterval->beginNumber()!=earliestStart) {
1307 std::cerr << "What the 1 - "
1308 << "earliestStart = " << earliestStart
1309 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1313 std::vector<LiveInterval*> newIs;
1314 if (!NewSpillFramework) {
1315 newIs = li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_);
1317 newIs = spiller_->spill(sli);
1319 addStackInterval(sli, ls_, li_, mri_, *vrm_);
1320 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1321 spilled.insert(sli->reg);
1323 if (earliestStartInterval->beginNumber()!=earliestStart) {
1325 std::cerr << "What the 2 - "
1326 << "earliestStart = " << earliestStart
1327 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1336 earliestStart = earliestStartInterval->beginNumber();
1338 DOUT << "\t\trolling back to: " << earliestStart << '\n';
1340 // Scan handled in reverse order up to the earliest start of a
1341 // spilled live interval and undo each one, restoring the state of
1343 while (!handled_.empty()) {
1344 LiveInterval* i = handled_.back();
1345 // If this interval starts before t we are done.
1346 if (i->beginNumber() < earliestStart)
1348 DOUT << "\t\t\tundo changes for: " << *i << '\n';
1349 handled_.pop_back();
1351 // When undoing a live interval allocation we must know if it is active or
1352 // inactive to properly update regUse_ and the VirtRegMap.
1353 IntervalPtrs::iterator it;
1354 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1356 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1357 if (!spilled.count(i->reg))
1359 delRegUse(vrm_->getPhys(i->reg));
1360 vrm_->clearVirt(i->reg);
1361 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1362 inactive_.erase(it);
1363 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1364 if (!spilled.count(i->reg))
1366 vrm_->clearVirt(i->reg);
1368 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1369 "Can only allocate virtual registers!");
1370 vrm_->clearVirt(i->reg);
1374 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1375 if (ii == DowngradeMap.end())
1376 // It interval has a preference, it must be defined by a copy. Clear the
1377 // preference now since the source interval allocation may have been
1381 UpgradeRegister(ii->second);
1385 // Rewind the iterators in the active, inactive, and fixed lists back to the
1386 // point we reverted to.
1387 RevertVectorIteratorsTo(active_, earliestStart);
1388 RevertVectorIteratorsTo(inactive_, earliestStart);
1389 RevertVectorIteratorsTo(fixed_, earliestStart);
1391 // Scan the rest and undo each interval that expired after t and
1392 // insert it in active (the next iteration of the algorithm will
1393 // put it in inactive if required)
1394 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1395 LiveInterval *HI = handled_[i];
1396 if (!HI->expiredAt(earliestStart) &&
1397 HI->expiredAt(cur->beginNumber())) {
1398 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1399 active_.push_back(std::make_pair(HI, HI->begin()));
1400 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1401 addRegUse(vrm_->getPhys(HI->reg));
1405 // Merge added with unhandled.
1406 // This also update the NextReloadMap. That is, it adds mapping from a
1407 // register defined by a reload from SS to the next reload from SS in the
1408 // same basic block.
1409 MachineBasicBlock *LastReloadMBB = 0;
1410 LiveInterval *LastReload = 0;
1411 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1412 std::sort(added.begin(), added.end(), LISorter());
1413 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1414 LiveInterval *ReloadLi = added[i];
1415 if (ReloadLi->weight == HUGE_VALF &&
1416 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1417 unsigned ReloadIdx = ReloadLi->beginNumber();
1418 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1419 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1420 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1421 // Last reload of same SS is in the same MBB. We want to try to
1422 // allocate both reloads the same register and make sure the reg
1423 // isn't clobbered in between if at all possible.
1424 assert(LastReload->beginNumber() < ReloadIdx);
1425 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1427 LastReloadMBB = ReloadMBB;
1428 LastReload = ReloadLi;
1429 LastReloadSS = ReloadSS;
1431 unhandled_.push(ReloadLi);
1435 unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1436 unsigned MaxInactiveCount,
1437 SmallVector<unsigned, 256> &inactiveCounts,
1439 unsigned FreeReg = 0;
1440 unsigned FreeRegInactiveCount = 0;
1442 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1443 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1444 assert(I != E && "No allocatable register in this register class!");
1446 // Scan for the first available register.
1447 for (; I != E; ++I) {
1449 // Ignore "downgraded" registers.
1450 if (SkipDGRegs && DowngradedRegs.count(Reg))
1452 if (isRegAvail(Reg)) {
1454 if (FreeReg < inactiveCounts.size())
1455 FreeRegInactiveCount = inactiveCounts[FreeReg];
1457 FreeRegInactiveCount = 0;
1462 // If there are no free regs, or if this reg has the max inactive count,
1463 // return this register.
1464 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1467 // Continue scanning the registers, looking for the one with the highest
1468 // inactive count. Alkis found that this reduced register pressure very
1469 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1471 for (; I != E; ++I) {
1473 // Ignore "downgraded" registers.
1474 if (SkipDGRegs && DowngradedRegs.count(Reg))
1476 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1477 FreeRegInactiveCount < inactiveCounts[Reg]) {
1479 FreeRegInactiveCount = inactiveCounts[Reg];
1480 if (FreeRegInactiveCount == MaxInactiveCount)
1481 break; // We found the one with the max inactive count.
1488 /// getFreePhysReg - return a free physical register for this virtual register
1489 /// interval if we have one, otherwise return 0.
1490 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1491 SmallVector<unsigned, 256> inactiveCounts;
1492 unsigned MaxInactiveCount = 0;
1494 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1495 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1497 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1499 unsigned reg = i->first->reg;
1500 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1501 "Can only allocate virtual registers!");
1503 // If this is not in a related reg class to the register we're allocating,
1505 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1506 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1507 reg = vrm_->getPhys(reg);
1508 if (inactiveCounts.size() <= reg)
1509 inactiveCounts.resize(reg+1);
1510 ++inactiveCounts[reg];
1511 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1515 // If copy coalescer has assigned a "preferred" register, check if it's
1517 if (cur->preference) {
1518 DOUT << "(preferred: " << tri_->getName(cur->preference) << ") ";
1519 if (isRegAvail(cur->preference) &&
1520 RC->contains(cur->preference))
1521 return cur->preference;
1524 if (!DowngradedRegs.empty()) {
1525 unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1530 return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
1533 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1534 return new RALinScan();