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