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/LiveVariables.h"
16 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17 #include "PhysRegTracker.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/CodeGen/RegisterCoalescer.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/EquivalenceClasses.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Compiler.h"
40 STATISTIC(NumIters , "Number of iterations performed");
41 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
43 static RegisterRegAlloc
44 linearscanRegAlloc("linearscan", " linear scan register allocator",
45 createLinearScanRegisterAllocator);
48 static unsigned numIterations = 0;
49 static unsigned numIntervals = 0;
51 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
53 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
55 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
56 typedef std::vector<IntervalPtr> IntervalPtrs;
58 /// RelatedRegClasses - This structure is built the first time a function is
59 /// compiled, and keeps track of which register classes have registers that
60 /// belong to multiple classes or have aliases that are in other classes.
61 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
62 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
65 const TargetMachine* tm_;
66 const MRegisterInfo* mri_;
69 /// handled_ - Intervals are added to the handled_ set in the order of their
70 /// start value. This is uses for backtracking.
71 std::vector<LiveInterval*> handled_;
73 /// fixed_ - Intervals that correspond to machine registers.
77 /// active_ - Intervals that are currently being processed, and which have a
78 /// live range active for the current point.
81 /// inactive_ - Intervals that are currently being processed, but which have
82 /// a hold at the current point.
83 IntervalPtrs inactive_;
85 typedef std::priority_queue<LiveInterval*,
86 std::vector<LiveInterval*>,
87 greater_ptr<LiveInterval> > IntervalHeap;
88 IntervalHeap unhandled_;
89 std::auto_ptr<PhysRegTracker> prt_;
90 std::auto_ptr<VirtRegMap> vrm_;
91 std::auto_ptr<Spiller> spiller_;
94 virtual const char* getPassName() const {
95 return "Linear Scan Register Allocator";
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<LiveIntervals>();
100 // Make sure PassManager knows which analyses to make available
101 // to coalescing and which analyses coalescing invalidates.
102 AU.addRequiredTransitive<RegisterCoalescer>();
103 MachineFunctionPass::getAnalysisUsage(AU);
106 /// runOnMachineFunction - register allocate the whole function
107 bool runOnMachineFunction(MachineFunction&);
110 /// linearScan - the linear scan algorithm
113 /// initIntervalSets - initialize the interval sets.
115 void initIntervalSets();
117 /// processActiveIntervals - expire old intervals and move non-overlapping
118 /// ones to the inactive list.
119 void processActiveIntervals(unsigned CurPoint);
121 /// processInactiveIntervals - expire old intervals and move overlapping
122 /// ones to the active list.
123 void processInactiveIntervals(unsigned CurPoint);
125 /// assignRegOrStackSlotAtInterval - assign a register if one
126 /// is available, or spill.
127 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
130 /// register handling helpers
133 /// getFreePhysReg - return a free physical register for this virtual
134 /// register interval if we have one, otherwise return 0.
135 unsigned getFreePhysReg(LiveInterval* cur);
137 /// assignVirt2StackSlot - assigns this virtual register to a
138 /// stack slot. returns the stack slot
139 int assignVirt2StackSlot(unsigned virtReg);
141 void ComputeRelatedRegClasses();
143 template <typename ItTy>
144 void printIntervals(const char* const str, ItTy i, ItTy e) const {
145 if (str) DOUT << str << " intervals:\n";
146 for (; i != e; ++i) {
147 DOUT << "\t" << *i->first << " -> ";
148 unsigned reg = i->first->reg;
149 if (MRegisterInfo::isVirtualRegister(reg)) {
150 reg = vrm_->getPhys(reg);
152 DOUT << mri_->getName(reg) << '\n';
156 char RALinScan::ID = 0;
159 void RALinScan::ComputeRelatedRegClasses() {
160 const MRegisterInfo &MRI = *mri_;
162 // First pass, add all reg classes to the union, and determine at least one
163 // reg class that each register is in.
164 bool HasAliases = false;
165 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
166 E = MRI.regclass_end(); RCI != E; ++RCI) {
167 RelatedRegClasses.insert(*RCI);
168 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
170 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
172 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
174 // Already processed this register. Just make sure we know that
175 // multiple register classes share a register.
176 RelatedRegClasses.unionSets(PRC, *RCI);
183 // Second pass, now that we know conservatively what register classes each reg
184 // belongs to, add info about aliases. We don't need to do this for targets
185 // without register aliases.
187 for (std::map<unsigned, const TargetRegisterClass*>::iterator
188 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
190 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
191 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
194 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
196 tm_ = &fn.getTarget();
197 mri_ = tm_->getRegisterInfo();
198 li_ = &getAnalysis<LiveIntervals>();
200 // We don't run the coalescer here because we have no reason to
201 // interact with it. If the coalescer requires interaction, it
202 // won't do anything. If it doesn't require interaction, we assume
203 // it was run as a separate pass.
205 // If this is the first function compiled, compute the related reg classes.
206 if (RelatedRegClasses.empty())
207 ComputeRelatedRegClasses();
209 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
210 vrm_.reset(new VirtRegMap(*mf_));
211 if (!spiller_.get()) spiller_.reset(createSpiller());
217 // Rewrite spill code and update the PhysRegsUsed set.
218 spiller_->runOnMachineFunction(*mf_, *vrm_);
220 vrm_.reset(); // Free the VirtRegMap
223 while (!unhandled_.empty()) unhandled_.pop();
232 /// initIntervalSets - initialize the interval sets.
234 void RALinScan::initIntervalSets()
236 assert(unhandled_.empty() && fixed_.empty() &&
237 active_.empty() && inactive_.empty() &&
238 "interval sets should be empty on initialization");
240 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
241 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
242 mf_->setPhysRegUsed(i->second.reg);
243 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
245 unhandled_.push(&i->second);
249 void RALinScan::linearScan()
251 // linear scan algorithm
252 DOUT << "********** LINEAR SCAN **********\n";
253 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
255 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
256 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
257 DEBUG(printIntervals("active", active_.begin(), active_.end()));
258 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
260 while (!unhandled_.empty()) {
261 // pick the interval with the earliest start point
262 LiveInterval* cur = unhandled_.top();
265 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
267 processActiveIntervals(cur->beginNumber());
268 processInactiveIntervals(cur->beginNumber());
270 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
271 "Can only allocate virtual registers!");
273 // Allocating a virtual register. try to find a free
274 // physical register or spill an interval (possibly this one) in order to
276 assignRegOrStackSlotAtInterval(cur);
278 DEBUG(printIntervals("active", active_.begin(), active_.end()));
279 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
281 numIntervals += li_->getNumIntervals();
282 NumIters += numIterations;
284 // expire any remaining active intervals
285 for (IntervalPtrs::reverse_iterator
286 i = active_.rbegin(); i != active_.rend(); ) {
287 unsigned reg = i->first->reg;
288 DOUT << "\tinterval " << *i->first << " expired\n";
289 assert(MRegisterInfo::isVirtualRegister(reg) &&
290 "Can only allocate virtual registers!");
291 reg = vrm_->getPhys(reg);
292 prt_->delRegUse(reg);
293 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
296 // expire any remaining inactive intervals
297 for (IntervalPtrs::reverse_iterator
298 i = inactive_.rbegin(); i != inactive_.rend(); ) {
299 DOUT << "\tinterval " << *i->first << " expired\n";
300 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
303 // A brute force way of adding live-ins to every BB.
304 MachineFunction::iterator MBB = mf_->begin();
305 ++MBB; // Skip entry MBB.
306 for (MachineFunction::iterator E = mf_->end(); MBB != E; ++MBB) {
307 unsigned StartIdx = li_->getMBBStartIdx(MBB->getNumber());
308 for (IntervalPtrs::iterator i = fixed_.begin(), e = fixed_.end();
310 if (i->first->liveAt(StartIdx))
311 MBB->addLiveIn(i->first->reg);
313 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
314 LiveInterval *HI = handled_[i];
315 unsigned Reg = HI->reg;
316 if (vrm_->isAssignedReg(Reg) && HI->liveAt(StartIdx)) {
317 assert(MRegisterInfo::isVirtualRegister(Reg));
318 Reg = vrm_->getPhys(Reg);
327 /// processActiveIntervals - expire old intervals and move non-overlapping ones
328 /// to the inactive list.
329 void RALinScan::processActiveIntervals(unsigned CurPoint)
331 DOUT << "\tprocessing active intervals:\n";
333 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
334 LiveInterval *Interval = active_[i].first;
335 LiveInterval::iterator IntervalPos = active_[i].second;
336 unsigned reg = Interval->reg;
338 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
340 if (IntervalPos == Interval->end()) { // Remove expired intervals.
341 DOUT << "\t\tinterval " << *Interval << " expired\n";
342 assert(MRegisterInfo::isVirtualRegister(reg) &&
343 "Can only allocate virtual registers!");
344 reg = vrm_->getPhys(reg);
345 prt_->delRegUse(reg);
347 // Pop off the end of the list.
348 active_[i] = active_.back();
352 } else if (IntervalPos->start > CurPoint) {
353 // Move inactive intervals to inactive list.
354 DOUT << "\t\tinterval " << *Interval << " inactive\n";
355 assert(MRegisterInfo::isVirtualRegister(reg) &&
356 "Can only allocate virtual registers!");
357 reg = vrm_->getPhys(reg);
358 prt_->delRegUse(reg);
360 inactive_.push_back(std::make_pair(Interval, IntervalPos));
362 // Pop off the end of the list.
363 active_[i] = active_.back();
367 // Otherwise, just update the iterator position.
368 active_[i].second = IntervalPos;
373 /// processInactiveIntervals - expire old intervals and move overlapping
374 /// ones to the active list.
375 void RALinScan::processInactiveIntervals(unsigned CurPoint)
377 DOUT << "\tprocessing inactive intervals:\n";
379 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
380 LiveInterval *Interval = inactive_[i].first;
381 LiveInterval::iterator IntervalPos = inactive_[i].second;
382 unsigned reg = Interval->reg;
384 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
386 if (IntervalPos == Interval->end()) { // remove expired intervals.
387 DOUT << "\t\tinterval " << *Interval << " expired\n";
389 // Pop off the end of the list.
390 inactive_[i] = inactive_.back();
391 inactive_.pop_back();
393 } else if (IntervalPos->start <= CurPoint) {
394 // move re-activated intervals in active list
395 DOUT << "\t\tinterval " << *Interval << " active\n";
396 assert(MRegisterInfo::isVirtualRegister(reg) &&
397 "Can only allocate virtual registers!");
398 reg = vrm_->getPhys(reg);
399 prt_->addRegUse(reg);
401 active_.push_back(std::make_pair(Interval, IntervalPos));
403 // Pop off the end of the list.
404 inactive_[i] = inactive_.back();
405 inactive_.pop_back();
408 // Otherwise, just update the iterator position.
409 inactive_[i].second = IntervalPos;
414 /// updateSpillWeights - updates the spill weights of the specifed physical
415 /// register and its weight.
416 static void updateSpillWeights(std::vector<float> &Weights,
417 unsigned reg, float weight,
418 const MRegisterInfo *MRI) {
419 Weights[reg] += weight;
420 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
421 Weights[*as] += weight;
425 RALinScan::IntervalPtrs::iterator
426 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
427 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
429 if (I->first == LI) return I;
433 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
434 for (unsigned i = 0, e = V.size(); i != e; ++i) {
435 RALinScan::IntervalPtr &IP = V[i];
436 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
438 if (I != IP.first->begin()) --I;
443 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
445 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
447 DOUT << "\tallocating current interval: ";
449 PhysRegTracker backupPrt = *prt_;
451 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
452 unsigned StartPosition = cur->beginNumber();
453 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
454 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
456 // for every interval in inactive we overlap with, mark the
457 // register as not free and update spill weights.
458 for (IntervalPtrs::const_iterator i = inactive_.begin(),
459 e = inactive_.end(); i != e; ++i) {
460 unsigned Reg = i->first->reg;
461 assert(MRegisterInfo::isVirtualRegister(Reg) &&
462 "Can only allocate virtual registers!");
463 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
464 // If this is not in a related reg class to the register we're allocating,
466 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
467 cur->overlapsFrom(*i->first, i->second-1)) {
468 Reg = vrm_->getPhys(Reg);
469 prt_->addRegUse(Reg);
470 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
474 // Speculatively check to see if we can get a register right now. If not,
475 // we know we won't be able to by adding more constraints. If so, we can
476 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
477 // is very bad (it contains all callee clobbered registers for any functions
478 // with a call), so we want to avoid doing that if possible.
479 unsigned physReg = getFreePhysReg(cur);
481 // We got a register. However, if it's in the fixed_ list, we might
482 // conflict with it. Check to see if we conflict with it or any of its
484 std::set<unsigned> RegAliases;
485 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
486 RegAliases.insert(*AS);
488 bool ConflictsWithFixed = false;
489 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
490 IntervalPtr &IP = fixed_[i];
491 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
492 // Okay, this reg is on the fixed list. Check to see if we actually
494 LiveInterval *I = IP.first;
495 if (I->endNumber() > StartPosition) {
496 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
498 if (II != I->begin() && II->start > StartPosition)
500 if (cur->overlapsFrom(*I, II)) {
501 ConflictsWithFixed = true;
508 // Okay, the register picked by our speculative getFreePhysReg call turned
509 // out to be in use. Actually add all of the conflicting fixed registers to
510 // prt so we can do an accurate query.
511 if (ConflictsWithFixed) {
512 // For every interval in fixed we overlap with, mark the register as not
513 // free and update spill weights.
514 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
515 IntervalPtr &IP = fixed_[i];
516 LiveInterval *I = IP.first;
518 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
519 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
520 I->endNumber() > StartPosition) {
521 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
523 if (II != I->begin() && II->start > StartPosition)
525 if (cur->overlapsFrom(*I, II)) {
526 unsigned reg = I->reg;
527 prt_->addRegUse(reg);
528 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
533 // Using the newly updated prt_ object, which includes conflicts in the
534 // future, see if there are any registers available.
535 physReg = getFreePhysReg(cur);
539 // Restore the physical register tracker, removing information about the
543 // if we find a free register, we are done: assign this virtual to
544 // the free physical register and add this interval to the active
547 DOUT << mri_->getName(physReg) << '\n';
548 vrm_->assignVirt2Phys(cur->reg, physReg);
549 prt_->addRegUse(physReg);
550 active_.push_back(std::make_pair(cur, cur->begin()));
551 handled_.push_back(cur);
554 DOUT << "no free registers\n";
556 // Compile the spill weights into an array that is better for scanning.
557 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
558 for (std::vector<std::pair<unsigned, float> >::iterator
559 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
560 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
562 // for each interval in active, update spill weights.
563 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
565 unsigned reg = i->first->reg;
566 assert(MRegisterInfo::isVirtualRegister(reg) &&
567 "Can only allocate virtual registers!");
568 reg = vrm_->getPhys(reg);
569 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
572 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
574 // Find a register to spill.
575 float minWeight = HUGE_VALF;
576 unsigned minReg = cur->preference; // Try the preferred register first.
578 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
579 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
580 e = RC->allocation_order_end(*mf_); i != e; ++i) {
582 if (minWeight > SpillWeights[reg]) {
583 minWeight = SpillWeights[reg];
588 // If we didn't find a register that is spillable, try aliases?
590 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
591 e = RC->allocation_order_end(*mf_); i != e; ++i) {
593 // No need to worry about if the alias register size < regsize of RC.
594 // We are going to spill all registers that alias it anyway.
595 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
596 if (minWeight > SpillWeights[*as]) {
597 minWeight = SpillWeights[*as];
603 // All registers must have inf weight. Just grab one!
605 minReg = *RC->allocation_order_begin(*mf_);
608 DOUT << "\t\tregister with min weight: "
609 << mri_->getName(minReg) << " (" << minWeight << ")\n";
611 // if the current has the minimum weight, we need to spill it and
612 // add any added intervals back to unhandled, and restart
614 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
615 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
616 std::vector<LiveInterval*> added =
617 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
619 return; // Early exit if all spills were folded.
621 // Merge added with unhandled. Note that we know that
622 // addIntervalsForSpills returns intervals sorted by their starting
624 for (unsigned i = 0, e = added.size(); i != e; ++i)
625 unhandled_.push(added[i]);
631 // push the current interval back to unhandled since we are going
632 // to re-run at least this iteration. Since we didn't modify it it
633 // should go back right in the front of the list
634 unhandled_.push(cur);
636 // otherwise we spill all intervals aliasing the register with
637 // minimum weight, rollback to the interval with the earliest
638 // start point and let the linear scan algorithm run again
639 std::vector<LiveInterval*> added;
640 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
641 "did not choose a register to spill?");
642 BitVector toSpill(mri_->getNumRegs());
644 // We are going to spill minReg and all its aliases.
645 toSpill[minReg] = true;
646 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
649 // the earliest start of a spilled interval indicates up to where
650 // in handled we need to roll back
651 unsigned earliestStart = cur->beginNumber();
653 // set of spilled vregs (used later to rollback properly)
654 std::set<unsigned> spilled;
656 // spill live intervals of virtual regs mapped to the physical register we
657 // want to clear (and its aliases). We only spill those that overlap with the
658 // current interval as the rest do not affect its allocation. we also keep
659 // track of the earliest start of all spilled live intervals since this will
660 // mark our rollback point.
661 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
662 unsigned reg = i->first->reg;
663 if (//MRegisterInfo::isVirtualRegister(reg) &&
664 toSpill[vrm_->getPhys(reg)] &&
665 cur->overlapsFrom(*i->first, i->second)) {
666 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
667 earliestStart = std::min(earliestStart, i->first->beginNumber());
668 std::vector<LiveInterval*> newIs =
669 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
670 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
674 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
675 unsigned reg = i->first->reg;
676 if (//MRegisterInfo::isVirtualRegister(reg) &&
677 toSpill[vrm_->getPhys(reg)] &&
678 cur->overlapsFrom(*i->first, i->second-1)) {
679 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
680 earliestStart = std::min(earliestStart, i->first->beginNumber());
681 std::vector<LiveInterval*> newIs =
682 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
683 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
688 DOUT << "\t\trolling back to: " << earliestStart << '\n';
690 // Scan handled in reverse order up to the earliest start of a
691 // spilled live interval and undo each one, restoring the state of
693 while (!handled_.empty()) {
694 LiveInterval* i = handled_.back();
695 // If this interval starts before t we are done.
696 if (i->beginNumber() < earliestStart)
698 DOUT << "\t\t\tundo changes for: " << *i << '\n';
701 // When undoing a live interval allocation we must know if it is active or
702 // inactive to properly update the PhysRegTracker and the VirtRegMap.
703 IntervalPtrs::iterator it;
704 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
706 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
707 if (!spilled.count(i->reg))
709 prt_->delRegUse(vrm_->getPhys(i->reg));
710 vrm_->clearVirt(i->reg);
711 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
713 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
714 if (!spilled.count(i->reg))
716 vrm_->clearVirt(i->reg);
718 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
719 "Can only allocate virtual registers!");
720 vrm_->clearVirt(i->reg);
725 // Rewind the iterators in the active, inactive, and fixed lists back to the
726 // point we reverted to.
727 RevertVectorIteratorsTo(active_, earliestStart);
728 RevertVectorIteratorsTo(inactive_, earliestStart);
729 RevertVectorIteratorsTo(fixed_, earliestStart);
731 // scan the rest and undo each interval that expired after t and
732 // insert it in active (the next iteration of the algorithm will
733 // put it in inactive if required)
734 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
735 LiveInterval *HI = handled_[i];
736 if (!HI->expiredAt(earliestStart) &&
737 HI->expiredAt(cur->beginNumber())) {
738 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
739 active_.push_back(std::make_pair(HI, HI->begin()));
740 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
741 prt_->addRegUse(vrm_->getPhys(HI->reg));
745 // merge added with unhandled
746 for (unsigned i = 0, e = added.size(); i != e; ++i)
747 unhandled_.push(added[i]);
750 /// getFreePhysReg - return a free physical register for this virtual register
751 /// interval if we have one, otherwise return 0.
752 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
753 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
754 unsigned MaxInactiveCount = 0;
756 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
757 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
759 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
761 unsigned reg = i->first->reg;
762 assert(MRegisterInfo::isVirtualRegister(reg) &&
763 "Can only allocate virtual registers!");
765 // If this is not in a related reg class to the register we're allocating,
767 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
768 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
769 reg = vrm_->getPhys(reg);
770 ++inactiveCounts[reg];
771 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
775 unsigned FreeReg = 0;
776 unsigned FreeRegInactiveCount = 0;
778 // If copy coalescer has assigned a "preferred" register, check if it's
781 if (prt_->isRegAvail(cur->preference)) {
782 DOUT << "\t\tassigned the preferred register: "
783 << mri_->getName(cur->preference) << "\n";
784 return cur->preference;
786 DOUT << "\t\tunable to assign the preferred register: "
787 << mri_->getName(cur->preference) << "\n";
789 // Scan for the first available register.
790 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
791 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
793 if (prt_->isRegAvail(*I)) {
795 FreeRegInactiveCount = inactiveCounts[FreeReg];
799 // If there are no free regs, or if this reg has the max inactive count,
800 // return this register.
801 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
803 // Continue scanning the registers, looking for the one with the highest
804 // inactive count. Alkis found that this reduced register pressure very
805 // slightly on X86 (in rev 1.94 of this file), though this should probably be
807 for (; I != E; ++I) {
809 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
811 FreeRegInactiveCount = inactiveCounts[Reg];
812 if (FreeRegInactiveCount == MaxInactiveCount)
813 break; // We found the one with the max inactive count.
820 FunctionPass* llvm::createLinearScanRegisterAllocator() {
821 return new RALinScan();