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