silence a bogus warning
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a linear scan register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13
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/SSARegMap.h"
23 #include "llvm/Target/MRegisterInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/ADT/EquivalenceClasses.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/Support/Debug.h"
29 #include <algorithm>
30 #include <cmath>
31 #include <set>
32 #include <queue>
33 using namespace llvm;
34
35 namespace {
36
37   Statistic<double> efficiency
38   ("regalloc", "Ratio of intervals processed over total intervals");
39   Statistic<> NumBacktracks("regalloc", "Number of times we had to backtrack");
40
41   static unsigned numIterations = 0;
42   static unsigned numIntervals = 0;
43
44   struct RA : public MachineFunctionPass {
45     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
46     typedef std::vector<IntervalPtr> IntervalPtrs;
47   private:
48     /// RelatedRegClasses - This structure is built the first time a function is
49     /// compiled, and keeps track of which register classes have registers that
50     /// belong to multiple classes or have aliases that are in other classes.
51     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
52     std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
53
54     MachineFunction* mf_;
55     const TargetMachine* tm_;
56     const MRegisterInfo* mri_;
57     LiveIntervals* li_;
58     bool *PhysRegsUsed;
59
60     /// handled_ - Intervals are added to the handled_ set in the order of their
61     /// start value.  This is uses for backtracking.
62     std::vector<LiveInterval*> handled_;
63
64     /// fixed_ - Intervals that correspond to machine registers.
65     ///
66     IntervalPtrs fixed_;
67
68     /// active_ - Intervals that are currently being processed, and which have a
69     /// live range active for the current point.
70     IntervalPtrs active_;
71
72     /// inactive_ - Intervals that are currently being processed, but which have
73     /// a hold at the current point.
74     IntervalPtrs inactive_;
75
76     typedef std::priority_queue<LiveInterval*,
77                                 std::vector<LiveInterval*>,
78                                 greater_ptr<LiveInterval> > IntervalHeap;
79     IntervalHeap unhandled_;
80     std::auto_ptr<PhysRegTracker> prt_;
81     std::auto_ptr<VirtRegMap> vrm_;
82     std::auto_ptr<Spiller> spiller_;
83
84   public:
85     virtual const char* getPassName() const {
86       return "Linear Scan Register Allocator";
87     }
88
89     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90       AU.addRequired<LiveIntervals>();
91       MachineFunctionPass::getAnalysisUsage(AU);
92     }
93
94     /// runOnMachineFunction - register allocate the whole function
95     bool runOnMachineFunction(MachineFunction&);
96
97   private:
98     /// linearScan - the linear scan algorithm
99     void linearScan();
100
101     /// initIntervalSets - initialize the interval sets.
102     ///
103     void initIntervalSets();
104
105     /// processActiveIntervals - expire old intervals and move non-overlapping
106     /// ones to the inactive list.
107     void processActiveIntervals(unsigned CurPoint);
108
109     /// processInactiveIntervals - expire old intervals and move overlapping
110     /// ones to the active list.
111     void processInactiveIntervals(unsigned CurPoint);
112
113     /// assignRegOrStackSlotAtInterval - assign a register if one
114     /// is available, or spill.
115     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
116
117     ///
118     /// register handling helpers
119     ///
120
121     /// getFreePhysReg - return a free physical register for this virtual
122     /// register interval if we have one, otherwise return 0.
123     unsigned getFreePhysReg(LiveInterval* cur);
124
125     /// assignVirt2StackSlot - assigns this virtual register to a
126     /// stack slot. returns the stack slot
127     int assignVirt2StackSlot(unsigned virtReg);
128
129     void ComputeRelatedRegClasses();
130
131     template <typename ItTy>
132     void printIntervals(const char* const str, ItTy i, ItTy e) const {
133       if (str) std::cerr << str << " intervals:\n";
134       for (; i != e; ++i) {
135         std::cerr << "\t" << *i->first << " -> ";
136         unsigned reg = i->first->reg;
137         if (MRegisterInfo::isVirtualRegister(reg)) {
138           reg = vrm_->getPhys(reg);
139         }
140         std::cerr << mri_->getName(reg) << '\n';
141       }
142     }
143   };
144 }
145
146 void RA::ComputeRelatedRegClasses() {
147   const MRegisterInfo &MRI = *mri_;
148   
149   // First pass, add all reg classes to the union, and determine at least one
150   // reg class that each register is in.
151   bool HasAliases = false;
152   for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
153        E = MRI.regclass_end(); RCI != E; ++RCI) {
154     RelatedRegClasses.insert(*RCI);
155     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
156          I != E; ++I) {
157       HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
158       
159       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
160       if (PRC) {
161         // Already processed this register.  Just make sure we know that
162         // multiple register classes share a register.
163         RelatedRegClasses.unionSets(PRC, *RCI);
164       } else {
165         PRC = *RCI;
166       }
167     }
168   }
169   
170   // Second pass, now that we know conservatively what register classes each reg
171   // belongs to, add info about aliases.  We don't need to do this for targets
172   // without register aliases.
173   if (HasAliases)
174     for (std::map<unsigned, const TargetRegisterClass*>::iterator
175          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
176          I != E; ++I)
177       for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
178         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
179 }
180
181 bool RA::runOnMachineFunction(MachineFunction &fn) {
182   mf_ = &fn;
183   tm_ = &fn.getTarget();
184   mri_ = tm_->getRegisterInfo();
185   li_ = &getAnalysis<LiveIntervals>();
186
187   // If this is the first function compiled, compute the related reg classes.
188   if (RelatedRegClasses.empty())
189     ComputeRelatedRegClasses();
190   
191   PhysRegsUsed = new bool[mri_->getNumRegs()];
192   std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
193   fn.setUsedPhysRegs(PhysRegsUsed);
194
195   if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
196   vrm_.reset(new VirtRegMap(*mf_));
197   if (!spiller_.get()) spiller_.reset(createSpiller());
198
199   initIntervalSets();
200
201   linearScan();
202
203   // Rewrite spill code and update the PhysRegsUsed set.
204   spiller_->runOnMachineFunction(*mf_, *vrm_);
205
206   vrm_.reset();  // Free the VirtRegMap
207
208
209   while (!unhandled_.empty()) unhandled_.pop();
210   fixed_.clear();
211   active_.clear();
212   inactive_.clear();
213   handled_.clear();
214
215   return true;
216 }
217
218 /// initIntervalSets - initialize the interval sets.
219 ///
220 void RA::initIntervalSets()
221 {
222   assert(unhandled_.empty() && fixed_.empty() &&
223          active_.empty() && inactive_.empty() &&
224          "interval sets should be empty on initialization");
225
226   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
227     if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
228       PhysRegsUsed[i->second.reg] = true;
229       fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
230     } else
231       unhandled_.push(&i->second);
232   }
233 }
234
235 void RA::linearScan()
236 {
237   // linear scan algorithm
238   DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
239   DEBUG(std::cerr << "********** Function: "
240         << mf_->getFunction()->getName() << '\n');
241
242   // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
243   DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
244   DEBUG(printIntervals("active", active_.begin(), active_.end()));
245   DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
246
247   while (!unhandled_.empty()) {
248     // pick the interval with the earliest start point
249     LiveInterval* cur = unhandled_.top();
250     unhandled_.pop();
251     ++numIterations;
252     DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
253
254     processActiveIntervals(cur->beginNumber());
255     processInactiveIntervals(cur->beginNumber());
256
257     assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
258            "Can only allocate virtual registers!");
259
260     // Allocating a virtual register. try to find a free
261     // physical register or spill an interval (possibly this one) in order to
262     // assign it one.
263     assignRegOrStackSlotAtInterval(cur);
264
265     DEBUG(printIntervals("active", active_.begin(), active_.end()));
266     DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
267   }
268   numIntervals += li_->getNumIntervals();
269   efficiency = double(numIterations) / double(numIntervals);
270
271   // expire any remaining active intervals
272   for (IntervalPtrs::reverse_iterator
273          i = active_.rbegin(); i != active_.rend(); ) {
274     unsigned reg = i->first->reg;
275     DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
276     assert(MRegisterInfo::isVirtualRegister(reg) &&
277            "Can only allocate virtual registers!");
278     reg = vrm_->getPhys(reg);
279     prt_->delRegUse(reg);
280     i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
281   }
282
283   // expire any remaining inactive intervals
284   for (IntervalPtrs::reverse_iterator
285          i = inactive_.rbegin(); i != inactive_.rend(); ) {
286     DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
287     i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
288   }
289
290   DEBUG(std::cerr << *vrm_);
291 }
292
293 /// processActiveIntervals - expire old intervals and move non-overlapping ones
294 /// to the inactive list.
295 void RA::processActiveIntervals(unsigned CurPoint)
296 {
297   DEBUG(std::cerr << "\tprocessing active intervals:\n");
298
299   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
300     LiveInterval *Interval = active_[i].first;
301     LiveInterval::iterator IntervalPos = active_[i].second;
302     unsigned reg = Interval->reg;
303
304     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
305
306     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
307       DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
308       assert(MRegisterInfo::isVirtualRegister(reg) &&
309              "Can only allocate virtual registers!");
310       reg = vrm_->getPhys(reg);
311       prt_->delRegUse(reg);
312
313       // Pop off the end of the list.
314       active_[i] = active_.back();
315       active_.pop_back();
316       --i; --e;
317
318     } else if (IntervalPos->start > CurPoint) {
319       // Move inactive intervals to inactive list.
320       DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
321       assert(MRegisterInfo::isVirtualRegister(reg) &&
322              "Can only allocate virtual registers!");
323       reg = vrm_->getPhys(reg);
324       prt_->delRegUse(reg);
325       // add to inactive.
326       inactive_.push_back(std::make_pair(Interval, IntervalPos));
327
328       // Pop off the end of the list.
329       active_[i] = active_.back();
330       active_.pop_back();
331       --i; --e;
332     } else {
333       // Otherwise, just update the iterator position.
334       active_[i].second = IntervalPos;
335     }
336   }
337 }
338
339 /// processInactiveIntervals - expire old intervals and move overlapping
340 /// ones to the active list.
341 void RA::processInactiveIntervals(unsigned CurPoint)
342 {
343   DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
344
345   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
346     LiveInterval *Interval = inactive_[i].first;
347     LiveInterval::iterator IntervalPos = inactive_[i].second;
348     unsigned reg = Interval->reg;
349
350     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
351
352     if (IntervalPos == Interval->end()) {       // remove expired intervals.
353       DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
354
355       // Pop off the end of the list.
356       inactive_[i] = inactive_.back();
357       inactive_.pop_back();
358       --i; --e;
359     } else if (IntervalPos->start <= CurPoint) {
360       // move re-activated intervals in active list
361       DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
362       assert(MRegisterInfo::isVirtualRegister(reg) &&
363              "Can only allocate virtual registers!");
364       reg = vrm_->getPhys(reg);
365       prt_->addRegUse(reg);
366       // add to active
367       active_.push_back(std::make_pair(Interval, IntervalPos));
368
369       // Pop off the end of the list.
370       inactive_[i] = inactive_.back();
371       inactive_.pop_back();
372       --i; --e;
373     } else {
374       // Otherwise, just update the iterator position.
375       inactive_[i].second = IntervalPos;
376     }
377   }
378 }
379
380 /// updateSpillWeights - updates the spill weights of the specifed physical
381 /// register and its weight.
382 static void updateSpillWeights(std::vector<float> &Weights,
383                                unsigned reg, float weight,
384                                const MRegisterInfo *MRI) {
385   Weights[reg] += weight;
386   for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
387     Weights[*as] += weight;
388 }
389
390 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
391                                                        LiveInterval *LI) {
392   for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
393     if (I->first == LI) return I;
394   return IP.end();
395 }
396
397 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
398   for (unsigned i = 0, e = V.size(); i != e; ++i) {
399     RA::IntervalPtr &IP = V[i];
400     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
401                                                 IP.second, Point);
402     if (I != IP.first->begin()) --I;
403     IP.second = I;
404   }
405 }
406
407
408 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
409 /// spill.
410 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
411 {
412   DEBUG(std::cerr << "\tallocating current interval: ");
413
414   PhysRegTracker backupPrt = *prt_;
415
416   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
417   unsigned StartPosition = cur->beginNumber();
418   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
419   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
420       
421   // for every interval in inactive we overlap with, mark the
422   // register as not free and update spill weights.
423   for (IntervalPtrs::const_iterator i = inactive_.begin(),
424          e = inactive_.end(); i != e; ++i) {
425     unsigned Reg = i->first->reg;
426     assert(MRegisterInfo::isVirtualRegister(Reg) &&
427            "Can only allocate virtual registers!");
428     const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
429     // If this is not in a related reg class to the register we're allocating, 
430     // don't check it.
431     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
432         cur->overlapsFrom(*i->first, i->second-1)) {
433       Reg = vrm_->getPhys(Reg);
434       prt_->addRegUse(Reg);
435       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
436     }
437   }
438   
439   // Speculatively check to see if we can get a register right now.  If not,
440   // we know we won't be able to by adding more constraints.  If so, we can
441   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
442   // is very bad (it contains all callee clobbered registers for any functions
443   // with a call), so we want to avoid doing that if possible.
444   unsigned physReg = getFreePhysReg(cur);
445   if (physReg) {
446     // We got a register.  However, if it's in the fixed_ list, we might
447     // conflict with it.  Check to see if we conflict with it or any of its
448     // aliases.
449     std::set<unsigned> RegAliases;
450     for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
451       RegAliases.insert(*AS);
452     
453     bool ConflictsWithFixed = false;
454     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
455       if (physReg == fixed_[i].first->reg ||
456           RegAliases.count(fixed_[i].first->reg)) {
457         // Okay, this reg is on the fixed list.  Check to see if we actually
458         // conflict.
459         IntervalPtr &IP = fixed_[i];
460         LiveInterval *I = IP.first;
461         if (I->endNumber() > StartPosition) {
462           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
463           IP.second = II;
464           if (II != I->begin() && II->start > StartPosition)
465             --II;
466           if (cur->overlapsFrom(*I, II)) {
467             ConflictsWithFixed = true;
468             break;
469           }
470         }
471       }
472     }
473     
474     // Okay, the register picked by our speculative getFreePhysReg call turned
475     // out to be in use.  Actually add all of the conflicting fixed registers to
476     // prt so we can do an accurate query.
477     if (ConflictsWithFixed) {
478       // For every interval in fixed we overlap with, mark the register as not
479       // free and update spill weights.
480       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
481         IntervalPtr &IP = fixed_[i];
482         LiveInterval *I = IP.first;
483
484         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
485         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
486             I->endNumber() > StartPosition) {
487           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
488           IP.second = II;
489           if (II != I->begin() && II->start > StartPosition)
490             --II;
491           if (cur->overlapsFrom(*I, II)) {
492             unsigned reg = I->reg;
493             prt_->addRegUse(reg);
494             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
495           }
496         }
497       }
498
499       // Using the newly updated prt_ object, which includes conflicts in the
500       // future, see if there are any registers available.
501       physReg = getFreePhysReg(cur);
502     }
503   }
504     
505   // Restore the physical register tracker, removing information about the
506   // future.
507   *prt_ = backupPrt;
508   
509   // if we find a free register, we are done: assign this virtual to
510   // the free physical register and add this interval to the active
511   // list.
512   if (physReg) {
513     DEBUG(std::cerr <<  mri_->getName(physReg) << '\n');
514     vrm_->assignVirt2Phys(cur->reg, physReg);
515     prt_->addRegUse(physReg);
516     active_.push_back(std::make_pair(cur, cur->begin()));
517     handled_.push_back(cur);
518     return;
519   }
520   DEBUG(std::cerr << "no free registers\n");
521
522   // Compile the spill weights into an array that is better for scanning.
523   std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
524   for (std::vector<std::pair<unsigned, float> >::iterator
525        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
526     updateSpillWeights(SpillWeights, I->first, I->second, mri_);
527   
528   // for each interval in active, update spill weights.
529   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
530        i != e; ++i) {
531     unsigned reg = i->first->reg;
532     assert(MRegisterInfo::isVirtualRegister(reg) &&
533            "Can only allocate virtual registers!");
534     reg = vrm_->getPhys(reg);
535     updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
536   }
537  
538   DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
539
540   float minWeight = float(HUGE_VAL);
541   unsigned minReg = 0;
542   for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
543        e = RC->allocation_order_end(*mf_); i != e; ++i) {
544     unsigned reg = *i;
545     if (minWeight > SpillWeights[reg]) {
546       minWeight = SpillWeights[reg];
547       minReg = reg;
548     }
549   }
550   DEBUG(std::cerr << "\t\tregister with min weight: "
551         << mri_->getName(minReg) << " (" << minWeight << ")\n");
552
553   // if the current has the minimum weight, we need to spill it and
554   // add any added intervals back to unhandled, and restart
555   // linearscan.
556   if (cur->weight <= minWeight) {
557     DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
558     int slot = vrm_->assignVirt2StackSlot(cur->reg);
559     std::vector<LiveInterval*> added =
560       li_->addIntervalsForSpills(*cur, *vrm_, slot);
561     if (added.empty())
562       return;  // Early exit if all spills were folded.
563
564     // Merge added with unhandled.  Note that we know that
565     // addIntervalsForSpills returns intervals sorted by their starting
566     // point.
567     for (unsigned i = 0, e = added.size(); i != e; ++i)
568       unhandled_.push(added[i]);
569     return;
570   }
571
572   ++NumBacktracks;
573
574   // push the current interval back to unhandled since we are going
575   // to re-run at least this iteration. Since we didn't modify it it
576   // should go back right in the front of the list
577   unhandled_.push(cur);
578
579   // otherwise we spill all intervals aliasing the register with
580   // minimum weight, rollback to the interval with the earliest
581   // start point and let the linear scan algorithm run again
582   std::vector<LiveInterval*> added;
583   assert(MRegisterInfo::isPhysicalRegister(minReg) &&
584          "did not choose a register to spill?");
585   std::vector<bool> toSpill(mri_->getNumRegs(), false);
586
587   // We are going to spill minReg and all its aliases.
588   toSpill[minReg] = true;
589   for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
590     toSpill[*as] = true;
591
592   // the earliest start of a spilled interval indicates up to where
593   // in handled we need to roll back
594   unsigned earliestStart = cur->beginNumber();
595
596   // set of spilled vregs (used later to rollback properly)
597   std::set<unsigned> spilled;
598
599   // spill live intervals of virtual regs mapped to the physical register we
600   // want to clear (and its aliases).  We only spill those that overlap with the
601   // current interval as the rest do not affect its allocation. we also keep
602   // track of the earliest start of all spilled live intervals since this will
603   // mark our rollback point.
604   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
605     unsigned reg = i->first->reg;
606     if (//MRegisterInfo::isVirtualRegister(reg) &&
607         toSpill[vrm_->getPhys(reg)] &&
608         cur->overlapsFrom(*i->first, i->second)) {
609       DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
610       earliestStart = std::min(earliestStart, i->first->beginNumber());
611       int slot = vrm_->assignVirt2StackSlot(i->first->reg);
612       std::vector<LiveInterval*> newIs =
613         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
614       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
615       spilled.insert(reg);
616     }
617   }
618   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
619     unsigned reg = i->first->reg;
620     if (//MRegisterInfo::isVirtualRegister(reg) &&
621         toSpill[vrm_->getPhys(reg)] &&
622         cur->overlapsFrom(*i->first, i->second-1)) {
623       DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
624       earliestStart = std::min(earliestStart, i->first->beginNumber());
625       int slot = vrm_->assignVirt2StackSlot(reg);
626       std::vector<LiveInterval*> newIs =
627         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
628       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
629       spilled.insert(reg);
630     }
631   }
632
633   DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
634
635   // Scan handled in reverse order up to the earliest start of a
636   // spilled live interval and undo each one, restoring the state of
637   // unhandled.
638   while (!handled_.empty()) {
639     LiveInterval* i = handled_.back();
640     // If this interval starts before t we are done.
641     if (i->beginNumber() < earliestStart)
642       break;
643     DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
644     handled_.pop_back();
645
646     // When undoing a live interval allocation we must know if it is active or
647     // inactive to properly update the PhysRegTracker and the VirtRegMap.
648     IntervalPtrs::iterator it;
649     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
650       active_.erase(it);
651       if (MRegisterInfo::isPhysicalRegister(i->reg)) {
652         assert(0 && "daksjlfd");
653         prt_->delRegUse(i->reg);
654         unhandled_.push(i);
655       } else {
656         if (!spilled.count(i->reg))
657           unhandled_.push(i);
658         prt_->delRegUse(vrm_->getPhys(i->reg));
659         vrm_->clearVirt(i->reg);
660       }
661     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
662       inactive_.erase(it);
663       if (MRegisterInfo::isPhysicalRegister(i->reg)) {
664         assert(0 && "daksjlfd");
665         unhandled_.push(i);
666       } else {
667         if (!spilled.count(i->reg))
668           unhandled_.push(i);
669         vrm_->clearVirt(i->reg);
670       }
671     } else {
672       assert(MRegisterInfo::isVirtualRegister(i->reg) &&
673              "Can only allocate virtual registers!");
674       vrm_->clearVirt(i->reg);
675       unhandled_.push(i);
676     }
677   }
678
679   // Rewind the iterators in the active, inactive, and fixed lists back to the
680   // point we reverted to.
681   RevertVectorIteratorsTo(active_, earliestStart);
682   RevertVectorIteratorsTo(inactive_, earliestStart);
683   RevertVectorIteratorsTo(fixed_, earliestStart);
684
685   // scan the rest and undo each interval that expired after t and
686   // insert it in active (the next iteration of the algorithm will
687   // put it in inactive if required)
688   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
689     LiveInterval *HI = handled_[i];
690     if (!HI->expiredAt(earliestStart) &&
691         HI->expiredAt(cur->beginNumber())) {
692       DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
693       active_.push_back(std::make_pair(HI, HI->begin()));
694       if (MRegisterInfo::isPhysicalRegister(HI->reg)) {
695         assert(0 &&"sdflkajsdf");
696         prt_->addRegUse(HI->reg);
697       } else
698         prt_->addRegUse(vrm_->getPhys(HI->reg));
699     }
700   }
701
702   // merge added with unhandled
703   for (unsigned i = 0, e = added.size(); i != e; ++i)
704     unhandled_.push(added[i]);
705 }
706
707 /// getFreePhysReg - return a free physical register for this virtual register
708 /// interval if we have one, otherwise return 0.
709 unsigned RA::getFreePhysReg(LiveInterval* cur)
710 {
711   std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
712   unsigned MaxInactiveCount = 0;
713   
714   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
715   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
716  
717   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
718        i != e; ++i) {
719     unsigned reg = i->first->reg;
720     assert(MRegisterInfo::isVirtualRegister(reg) &&
721            "Can only allocate virtual registers!");
722
723     // If this is not in a related reg class to the register we're allocating, 
724     // don't check it.
725     const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
726     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
727       reg = vrm_->getPhys(reg);
728       ++inactiveCounts[reg];
729       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
730     }
731   }
732
733   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
734
735   unsigned FreeReg = 0;
736   unsigned FreeRegInactiveCount = 0;
737   
738   // Scan for the first available register.
739   TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
740   TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
741   for (; I != E; ++I)
742     if (prt_->isRegAvail(*I)) {
743       FreeReg = *I;
744       FreeRegInactiveCount = inactiveCounts[FreeReg];
745       break;
746     }
747   
748   // If there are no free regs, or if this reg has the max inactive count,
749   // return this register.
750   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
751   
752   // Continue scanning the registers, looking for the one with the highest
753   // inactive count.  Alkis found that this reduced register pressure very
754   // slightly on X86 (in rev 1.94 of this file), though this should probably be
755   // reevaluated now.
756   for (; I != E; ++I) {
757     unsigned Reg = *I;
758     if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
759       FreeReg = Reg;
760       FreeRegInactiveCount = inactiveCounts[Reg];
761       if (FreeRegInactiveCount == MaxInactiveCount)
762         break;    // We found the one with the max inactive count.
763     }
764   }
765   
766   return FreeReg;
767 }
768
769 FunctionPass* llvm::createLinearScanRegisterAllocator() {
770   return new RA();
771 }