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