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