1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Compiler.h"
38 STATISTIC(NumIters , "Number of iterations performed");
39 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
41 static RegisterRegAlloc
42 linearscanRegAlloc("linearscan", " linear scan register allocator",
43 createLinearScanRegisterAllocator);
46 static unsigned numIterations = 0;
47 static unsigned numIntervals = 0;
49 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
50 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
51 typedef std::vector<IntervalPtr> IntervalPtrs;
53 /// RelatedRegClasses - This structure is built the first time a function is
54 /// compiled, and keeps track of which register classes have registers that
55 /// belong to multiple classes or have aliases that are in other classes.
56 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
57 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
60 const TargetMachine* tm_;
61 const MRegisterInfo* mri_;
65 /// handled_ - Intervals are added to the handled_ set in the order of their
66 /// start value. This is uses for backtracking.
67 std::vector<LiveInterval*> handled_;
69 /// fixed_ - Intervals that correspond to machine registers.
73 /// active_ - Intervals that are currently being processed, and which have a
74 /// live range active for the current point.
77 /// inactive_ - Intervals that are currently being processed, but which have
78 /// a hold at the current point.
79 IntervalPtrs inactive_;
81 typedef std::priority_queue<LiveInterval*,
82 std::vector<LiveInterval*>,
83 greater_ptr<LiveInterval> > IntervalHeap;
84 IntervalHeap unhandled_;
85 std::auto_ptr<PhysRegTracker> prt_;
86 std::auto_ptr<VirtRegMap> vrm_;
87 std::auto_ptr<Spiller> spiller_;
90 virtual const char* getPassName() const {
91 return "Linear Scan Register Allocator";
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 AU.addRequired<LiveIntervals>();
96 MachineFunctionPass::getAnalysisUsage(AU);
99 /// runOnMachineFunction - register allocate the whole function
100 bool runOnMachineFunction(MachineFunction&);
103 /// linearScan - the linear scan algorithm
106 /// initIntervalSets - initialize the interval sets.
108 void initIntervalSets();
110 /// processActiveIntervals - expire old intervals and move non-overlapping
111 /// ones to the inactive list.
112 void processActiveIntervals(unsigned CurPoint);
114 /// processInactiveIntervals - expire old intervals and move overlapping
115 /// ones to the active list.
116 void processInactiveIntervals(unsigned CurPoint);
118 /// assignRegOrStackSlotAtInterval - assign a register if one
119 /// is available, or spill.
120 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
123 /// register handling helpers
126 /// getFreePhysReg - return a free physical register for this virtual
127 /// register interval if we have one, otherwise return 0.
128 unsigned getFreePhysReg(LiveInterval* cur);
130 /// assignVirt2StackSlot - assigns this virtual register to a
131 /// stack slot. returns the stack slot
132 int assignVirt2StackSlot(unsigned virtReg);
134 void ComputeRelatedRegClasses();
136 template <typename ItTy>
137 void printIntervals(const char* const str, ItTy i, ItTy e) const {
138 if (str) DOUT << str << " intervals:\n";
139 for (; i != e; ++i) {
140 DOUT << "\t" << *i->first << " -> ";
141 unsigned reg = i->first->reg;
142 if (MRegisterInfo::isVirtualRegister(reg)) {
143 reg = vrm_->getPhys(reg);
145 DOUT << mri_->getName(reg) << '\n';
151 void RA::ComputeRelatedRegClasses() {
152 const MRegisterInfo &MRI = *mri_;
154 // First pass, add all reg classes to the union, and determine at least one
155 // reg class that each register is in.
156 bool HasAliases = false;
157 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
158 E = MRI.regclass_end(); RCI != E; ++RCI) {
159 RelatedRegClasses.insert(*RCI);
160 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
162 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
164 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
166 // Already processed this register. Just make sure we know that
167 // multiple register classes share a register.
168 RelatedRegClasses.unionSets(PRC, *RCI);
175 // Second pass, now that we know conservatively what register classes each reg
176 // belongs to, add info about aliases. We don't need to do this for targets
177 // without register aliases.
179 for (std::map<unsigned, const TargetRegisterClass*>::iterator
180 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
182 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
183 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
186 bool RA::runOnMachineFunction(MachineFunction &fn) {
188 tm_ = &fn.getTarget();
189 mri_ = tm_->getRegisterInfo();
190 li_ = &getAnalysis<LiveIntervals>();
192 // If this is the first function compiled, compute the related reg classes.
193 if (RelatedRegClasses.empty())
194 ComputeRelatedRegClasses();
196 PhysRegsUsed = new bool[mri_->getNumRegs()];
197 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
198 fn.setUsedPhysRegs(PhysRegsUsed);
200 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
201 vrm_.reset(new VirtRegMap(*mf_));
202 if (!spiller_.get()) spiller_.reset(createSpiller());
208 // Rewrite spill code and update the PhysRegsUsed set.
209 spiller_->runOnMachineFunction(*mf_, *vrm_);
211 vrm_.reset(); // Free the VirtRegMap
214 while (!unhandled_.empty()) unhandled_.pop();
223 /// initIntervalSets - initialize the interval sets.
225 void RA::initIntervalSets()
227 assert(unhandled_.empty() && fixed_.empty() &&
228 active_.empty() && inactive_.empty() &&
229 "interval sets should be empty on initialization");
231 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
232 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
233 PhysRegsUsed[i->second.reg] = true;
234 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
236 unhandled_.push(&i->second);
240 void RA::linearScan()
242 // linear scan algorithm
243 DOUT << "********** LINEAR SCAN **********\n";
244 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
246 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
247 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
248 DEBUG(printIntervals("active", active_.begin(), active_.end()));
249 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
251 while (!unhandled_.empty()) {
252 // pick the interval with the earliest start point
253 LiveInterval* cur = unhandled_.top();
256 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
258 processActiveIntervals(cur->beginNumber());
259 processInactiveIntervals(cur->beginNumber());
261 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
262 "Can only allocate virtual registers!");
264 // Allocating a virtual register. try to find a free
265 // physical register or spill an interval (possibly this one) in order to
267 assignRegOrStackSlotAtInterval(cur);
269 DEBUG(printIntervals("active", active_.begin(), active_.end()));
270 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
272 numIntervals += li_->getNumIntervals();
273 NumIters += numIterations;
275 // expire any remaining active intervals
276 for (IntervalPtrs::reverse_iterator
277 i = active_.rbegin(); i != active_.rend(); ) {
278 unsigned reg = i->first->reg;
279 DOUT << "\tinterval " << *i->first << " expired\n";
280 assert(MRegisterInfo::isVirtualRegister(reg) &&
281 "Can only allocate virtual registers!");
282 reg = vrm_->getPhys(reg);
283 prt_->delRegUse(reg);
284 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
287 // expire any remaining inactive intervals
288 for (IntervalPtrs::reverse_iterator
289 i = inactive_.rbegin(); i != inactive_.rend(); ) {
290 DOUT << "\tinterval " << *i->first << " expired\n";
291 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
297 /// processActiveIntervals - expire old intervals and move non-overlapping ones
298 /// to the inactive list.
299 void RA::processActiveIntervals(unsigned CurPoint)
301 DOUT << "\tprocessing active intervals:\n";
303 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
304 LiveInterval *Interval = active_[i].first;
305 LiveInterval::iterator IntervalPos = active_[i].second;
306 unsigned reg = Interval->reg;
308 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
310 if (IntervalPos == Interval->end()) { // Remove expired intervals.
311 DOUT << "\t\tinterval " << *Interval << " expired\n";
312 assert(MRegisterInfo::isVirtualRegister(reg) &&
313 "Can only allocate virtual registers!");
314 reg = vrm_->getPhys(reg);
315 prt_->delRegUse(reg);
317 // Pop off the end of the list.
318 active_[i] = active_.back();
322 } else if (IntervalPos->start > CurPoint) {
323 // Move inactive intervals to inactive list.
324 DOUT << "\t\tinterval " << *Interval << " inactive\n";
325 assert(MRegisterInfo::isVirtualRegister(reg) &&
326 "Can only allocate virtual registers!");
327 reg = vrm_->getPhys(reg);
328 prt_->delRegUse(reg);
330 inactive_.push_back(std::make_pair(Interval, IntervalPos));
332 // Pop off the end of the list.
333 active_[i] = active_.back();
337 // Otherwise, just update the iterator position.
338 active_[i].second = IntervalPos;
343 /// processInactiveIntervals - expire old intervals and move overlapping
344 /// ones to the active list.
345 void RA::processInactiveIntervals(unsigned CurPoint)
347 DOUT << "\tprocessing inactive intervals:\n";
349 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
350 LiveInterval *Interval = inactive_[i].first;
351 LiveInterval::iterator IntervalPos = inactive_[i].second;
352 unsigned reg = Interval->reg;
354 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
356 if (IntervalPos == Interval->end()) { // remove expired intervals.
357 DOUT << "\t\tinterval " << *Interval << " expired\n";
359 // Pop off the end of the list.
360 inactive_[i] = inactive_.back();
361 inactive_.pop_back();
363 } else if (IntervalPos->start <= CurPoint) {
364 // move re-activated intervals in active list
365 DOUT << "\t\tinterval " << *Interval << " active\n";
366 assert(MRegisterInfo::isVirtualRegister(reg) &&
367 "Can only allocate virtual registers!");
368 reg = vrm_->getPhys(reg);
369 prt_->addRegUse(reg);
371 active_.push_back(std::make_pair(Interval, IntervalPos));
373 // Pop off the end of the list.
374 inactive_[i] = inactive_.back();
375 inactive_.pop_back();
378 // Otherwise, just update the iterator position.
379 inactive_[i].second = IntervalPos;
384 /// updateSpillWeights - updates the spill weights of the specifed physical
385 /// register and its weight.
386 static void updateSpillWeights(std::vector<float> &Weights,
387 unsigned reg, float weight,
388 const MRegisterInfo *MRI) {
389 Weights[reg] += weight;
390 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
391 Weights[*as] += weight;
394 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
396 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
397 if (I->first == LI) return I;
401 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
402 for (unsigned i = 0, e = V.size(); i != e; ++i) {
403 RA::IntervalPtr &IP = V[i];
404 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
406 if (I != IP.first->begin()) --I;
411 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
413 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
415 DOUT << "\tallocating current interval: ";
417 PhysRegTracker backupPrt = *prt_;
419 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
420 unsigned StartPosition = cur->beginNumber();
421 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
422 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
424 // for every interval in inactive we overlap with, mark the
425 // register as not free and update spill weights.
426 for (IntervalPtrs::const_iterator i = inactive_.begin(),
427 e = inactive_.end(); i != e; ++i) {
428 unsigned Reg = i->first->reg;
429 assert(MRegisterInfo::isVirtualRegister(Reg) &&
430 "Can only allocate virtual registers!");
431 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
432 // If this is not in a related reg class to the register we're allocating,
434 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
435 cur->overlapsFrom(*i->first, i->second-1)) {
436 Reg = vrm_->getPhys(Reg);
437 prt_->addRegUse(Reg);
438 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
442 // Speculatively check to see if we can get a register right now. If not,
443 // we know we won't be able to by adding more constraints. If so, we can
444 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
445 // is very bad (it contains all callee clobbered registers for any functions
446 // with a call), so we want to avoid doing that if possible.
447 unsigned physReg = getFreePhysReg(cur);
449 // We got a register. However, if it's in the fixed_ list, we might
450 // conflict with it. Check to see if we conflict with it or any of its
452 std::set<unsigned> RegAliases;
453 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
454 RegAliases.insert(*AS);
456 bool ConflictsWithFixed = false;
457 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
458 IntervalPtr &IP = fixed_[i];
459 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
460 // Okay, this reg is on the fixed list. Check to see if we actually
462 LiveInterval *I = IP.first;
463 if (I->endNumber() > StartPosition) {
464 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
466 if (II != I->begin() && II->start > StartPosition)
468 if (cur->overlapsFrom(*I, II)) {
469 ConflictsWithFixed = true;
476 // Okay, the register picked by our speculative getFreePhysReg call turned
477 // out to be in use. Actually add all of the conflicting fixed registers to
478 // prt so we can do an accurate query.
479 if (ConflictsWithFixed) {
480 // For every interval in fixed we overlap with, mark the register as not
481 // free and update spill weights.
482 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
483 IntervalPtr &IP = fixed_[i];
484 LiveInterval *I = IP.first;
486 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
487 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
488 I->endNumber() > StartPosition) {
489 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
491 if (II != I->begin() && II->start > StartPosition)
493 if (cur->overlapsFrom(*I, II)) {
494 unsigned reg = I->reg;
495 prt_->addRegUse(reg);
496 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
501 // Using the newly updated prt_ object, which includes conflicts in the
502 // future, see if there are any registers available.
503 physReg = getFreePhysReg(cur);
507 // Restore the physical register tracker, removing information about the
511 // if we find a free register, we are done: assign this virtual to
512 // the free physical register and add this interval to the active
515 DOUT << mri_->getName(physReg) << '\n';
516 vrm_->assignVirt2Phys(cur->reg, physReg);
517 prt_->addRegUse(physReg);
518 active_.push_back(std::make_pair(cur, cur->begin()));
519 handled_.push_back(cur);
522 DOUT << "no free registers\n";
524 // Compile the spill weights into an array that is better for scanning.
525 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
526 for (std::vector<std::pair<unsigned, float> >::iterator
527 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
528 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
530 // for each interval in active, update spill weights.
531 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
533 unsigned reg = i->first->reg;
534 assert(MRegisterInfo::isVirtualRegister(reg) &&
535 "Can only allocate virtual registers!");
536 reg = vrm_->getPhys(reg);
537 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
540 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
542 // Find a register to spill.
543 float minWeight = HUGE_VALF;
545 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
546 e = RC->allocation_order_end(*mf_); i != e; ++i) {
548 if (minWeight > SpillWeights[reg]) {
549 minWeight = SpillWeights[reg];
554 // If we didn't find a register that is spillable, try aliases?
556 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
557 e = RC->allocation_order_end(*mf_); i != e; ++i) {
559 // No need to worry about if the alias register size < regsize of RC.
560 // We are going to spill all registers that alias it anyway.
561 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
562 if (minWeight > SpillWeights[*as]) {
563 minWeight = SpillWeights[*as];
569 // All registers must have inf weight. Just grab one!
571 minReg = *RC->allocation_order_begin(*mf_);
574 DOUT << "\t\tregister with min weight: "
575 << mri_->getName(minReg) << " (" << minWeight << ")\n";
577 // if the current has the minimum weight, we need to spill it and
578 // add any added intervals back to unhandled, and restart
580 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
581 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
582 int slot = vrm_->assignVirt2StackSlot(cur->reg);
583 std::vector<LiveInterval*> added =
584 li_->addIntervalsForSpills(*cur, *vrm_, slot);
586 return; // Early exit if all spills were folded.
588 // Merge added with unhandled. Note that we know that
589 // addIntervalsForSpills returns intervals sorted by their starting
591 for (unsigned i = 0, e = added.size(); i != e; ++i)
592 unhandled_.push(added[i]);
598 // push the current interval back to unhandled since we are going
599 // to re-run at least this iteration. Since we didn't modify it it
600 // should go back right in the front of the list
601 unhandled_.push(cur);
603 // otherwise we spill all intervals aliasing the register with
604 // minimum weight, rollback to the interval with the earliest
605 // start point and let the linear scan algorithm run again
606 std::vector<LiveInterval*> added;
607 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
608 "did not choose a register to spill?");
609 std::vector<bool> toSpill(mri_->getNumRegs(), false);
611 // We are going to spill minReg and all its aliases.
612 toSpill[minReg] = true;
613 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
616 // the earliest start of a spilled interval indicates up to where
617 // in handled we need to roll back
618 unsigned earliestStart = cur->beginNumber();
620 // set of spilled vregs (used later to rollback properly)
621 std::set<unsigned> spilled;
623 // spill live intervals of virtual regs mapped to the physical register we
624 // want to clear (and its aliases). We only spill those that overlap with the
625 // current interval as the rest do not affect its allocation. we also keep
626 // track of the earliest start of all spilled live intervals since this will
627 // mark our rollback point.
628 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
629 unsigned reg = i->first->reg;
630 if (//MRegisterInfo::isVirtualRegister(reg) &&
631 toSpill[vrm_->getPhys(reg)] &&
632 cur->overlapsFrom(*i->first, i->second)) {
633 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
634 earliestStart = std::min(earliestStart, i->first->beginNumber());
635 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
636 std::vector<LiveInterval*> newIs =
637 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
638 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
642 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
643 unsigned reg = i->first->reg;
644 if (//MRegisterInfo::isVirtualRegister(reg) &&
645 toSpill[vrm_->getPhys(reg)] &&
646 cur->overlapsFrom(*i->first, i->second-1)) {
647 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
648 earliestStart = std::min(earliestStart, i->first->beginNumber());
649 int slot = vrm_->assignVirt2StackSlot(reg);
650 std::vector<LiveInterval*> newIs =
651 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
652 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
657 DOUT << "\t\trolling back to: " << earliestStart << '\n';
659 // Scan handled in reverse order up to the earliest start of a
660 // spilled live interval and undo each one, restoring the state of
662 while (!handled_.empty()) {
663 LiveInterval* i = handled_.back();
664 // If this interval starts before t we are done.
665 if (i->beginNumber() < earliestStart)
667 DOUT << "\t\t\tundo changes for: " << *i << '\n';
670 // When undoing a live interval allocation we must know if it is active or
671 // inactive to properly update the PhysRegTracker and the VirtRegMap.
672 IntervalPtrs::iterator it;
673 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
675 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
676 if (!spilled.count(i->reg))
678 prt_->delRegUse(vrm_->getPhys(i->reg));
679 vrm_->clearVirt(i->reg);
680 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
682 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
683 if (!spilled.count(i->reg))
685 vrm_->clearVirt(i->reg);
687 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
688 "Can only allocate virtual registers!");
689 vrm_->clearVirt(i->reg);
694 // Rewind the iterators in the active, inactive, and fixed lists back to the
695 // point we reverted to.
696 RevertVectorIteratorsTo(active_, earliestStart);
697 RevertVectorIteratorsTo(inactive_, earliestStart);
698 RevertVectorIteratorsTo(fixed_, earliestStart);
700 // scan the rest and undo each interval that expired after t and
701 // insert it in active (the next iteration of the algorithm will
702 // put it in inactive if required)
703 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
704 LiveInterval *HI = handled_[i];
705 if (!HI->expiredAt(earliestStart) &&
706 HI->expiredAt(cur->beginNumber())) {
707 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
708 active_.push_back(std::make_pair(HI, HI->begin()));
709 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
710 prt_->addRegUse(vrm_->getPhys(HI->reg));
714 // merge added with unhandled
715 for (unsigned i = 0, e = added.size(); i != e; ++i)
716 unhandled_.push(added[i]);
719 /// getFreePhysReg - return a free physical register for this virtual register
720 /// interval if we have one, otherwise return 0.
721 unsigned RA::getFreePhysReg(LiveInterval *cur) {
722 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
723 unsigned MaxInactiveCount = 0;
725 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
726 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
728 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
730 unsigned reg = i->first->reg;
731 assert(MRegisterInfo::isVirtualRegister(reg) &&
732 "Can only allocate virtual registers!");
734 // If this is not in a related reg class to the register we're allocating,
736 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
737 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
738 reg = vrm_->getPhys(reg);
739 ++inactiveCounts[reg];
740 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
744 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
746 unsigned FreeReg = 0;
747 unsigned FreeRegInactiveCount = 0;
749 // Scan for the first available register.
750 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
751 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
753 if (prt_->isRegAvail(*I)) {
755 FreeRegInactiveCount = inactiveCounts[FreeReg];
759 // If there are no free regs, or if this reg has the max inactive count,
760 // return this register.
761 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
763 // Continue scanning the registers, looking for the one with the highest
764 // inactive count. Alkis found that this reduced register pressure very
765 // slightly on X86 (in rev 1.94 of this file), though this should probably be
767 for (; I != E; ++I) {
769 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
771 FreeRegInactiveCount = inactiveCounts[Reg];
772 if (FreeRegInactiveCount == MaxInactiveCount)
773 break; // We found the one with the max inactive count.
780 FunctionPass* llvm::createLinearScanRegisterAllocator() {