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