LinearScanner hotspot.
[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       IntervalPtr &IP = fixed_[i];
464       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
465         // Okay, this reg is on the fixed list.  Check to see if we actually
466         // conflict.
467         LiveInterval *I = IP.first;
468         if (I->endNumber() > StartPosition) {
469           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
470           IP.second = II;
471           if (II != I->begin() && II->start > StartPosition)
472             --II;
473           if (cur->overlapsFrom(*I, II)) {
474             ConflictsWithFixed = true;
475             break;
476           }
477         }
478       }
479     }
480     
481     // Okay, the register picked by our speculative getFreePhysReg call turned
482     // out to be in use.  Actually add all of the conflicting fixed registers to
483     // prt so we can do an accurate query.
484     if (ConflictsWithFixed) {
485       // For every interval in fixed we overlap with, mark the register as not
486       // free and update spill weights.
487       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
488         IntervalPtr &IP = fixed_[i];
489         LiveInterval *I = IP.first;
490
491         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
492         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
493             I->endNumber() > StartPosition) {
494           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
495           IP.second = II;
496           if (II != I->begin() && II->start > StartPosition)
497             --II;
498           if (cur->overlapsFrom(*I, II)) {
499             unsigned reg = I->reg;
500             prt_->addRegUse(reg);
501             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
502           }
503         }
504       }
505
506       // Using the newly updated prt_ object, which includes conflicts in the
507       // future, see if there are any registers available.
508       physReg = getFreePhysReg(cur);
509     }
510   }
511     
512   // Restore the physical register tracker, removing information about the
513   // future.
514   *prt_ = backupPrt;
515   
516   // if we find a free register, we are done: assign this virtual to
517   // the free physical register and add this interval to the active
518   // list.
519   if (physReg) {
520     DEBUG(std::cerr <<  mri_->getName(physReg) << '\n');
521     vrm_->assignVirt2Phys(cur->reg, physReg);
522     prt_->addRegUse(physReg);
523     active_.push_back(std::make_pair(cur, cur->begin()));
524     handled_.push_back(cur);
525     return;
526   }
527   DEBUG(std::cerr << "no free registers\n");
528
529   // Compile the spill weights into an array that is better for scanning.
530   std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
531   for (std::vector<std::pair<unsigned, float> >::iterator
532        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
533     updateSpillWeights(SpillWeights, I->first, I->second, mri_);
534   
535   // for each interval in active, update spill weights.
536   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
537        i != e; ++i) {
538     unsigned reg = i->first->reg;
539     assert(MRegisterInfo::isVirtualRegister(reg) &&
540            "Can only allocate virtual registers!");
541     reg = vrm_->getPhys(reg);
542     updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
543   }
544  
545   DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
546
547   // Find a register to spill.
548   float minWeight = float(HUGE_VAL);
549   unsigned minReg = 0;
550   for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
551        e = RC->allocation_order_end(*mf_); i != e; ++i) {
552     unsigned reg = *i;
553     if (minWeight > SpillWeights[reg]) {
554       minWeight = SpillWeights[reg];
555       minReg = reg;
556     }
557   }
558   
559   // If we didn't find a register that is spillable, try aliases?
560   if (!minReg) {
561     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
562            e = RC->allocation_order_end(*mf_); i != e; ++i) {
563       unsigned reg = *i;
564       // No need to worry about if the alias register size < regsize of RC.
565       // We are going to spill all registers that alias it anyway.
566       for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
567         if (minWeight > SpillWeights[*as]) {
568           minWeight = SpillWeights[*as];
569           minReg = *as;
570         }
571       }
572     }
573
574     // All registers must have inf weight. Just grab one!
575     if (!minReg)
576       minReg = *RC->allocation_order_begin(*mf_);
577   }
578   
579   DEBUG(std::cerr << "\t\tregister with min weight: "
580         << mri_->getName(minReg) << " (" << minWeight << ")\n");
581
582   // if the current has the minimum weight, we need to spill it and
583   // add any added intervals back to unhandled, and restart
584   // linearscan.
585   if (cur->weight != float(HUGE_VAL) && cur->weight <= minWeight) {
586     DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
587     int slot = vrm_->assignVirt2StackSlot(cur->reg);
588     std::vector<LiveInterval*> added =
589       li_->addIntervalsForSpills(*cur, *vrm_, slot);
590     if (added.empty())
591       return;  // Early exit if all spills were folded.
592
593     // Merge added with unhandled.  Note that we know that
594     // addIntervalsForSpills returns intervals sorted by their starting
595     // point.
596     for (unsigned i = 0, e = added.size(); i != e; ++i)
597       unhandled_.push(added[i]);
598     return;
599   }
600
601   ++NumBacktracks;
602
603   // push the current interval back to unhandled since we are going
604   // to re-run at least this iteration. Since we didn't modify it it
605   // should go back right in the front of the list
606   unhandled_.push(cur);
607
608   // otherwise we spill all intervals aliasing the register with
609   // minimum weight, rollback to the interval with the earliest
610   // start point and let the linear scan algorithm run again
611   std::vector<LiveInterval*> added;
612   assert(MRegisterInfo::isPhysicalRegister(minReg) &&
613          "did not choose a register to spill?");
614   std::vector<bool> toSpill(mri_->getNumRegs(), false);
615
616   // We are going to spill minReg and all its aliases.
617   toSpill[minReg] = true;
618   for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
619     toSpill[*as] = true;
620
621   // the earliest start of a spilled interval indicates up to where
622   // in handled we need to roll back
623   unsigned earliestStart = cur->beginNumber();
624
625   // set of spilled vregs (used later to rollback properly)
626   std::set<unsigned> spilled;
627
628   // spill live intervals of virtual regs mapped to the physical register we
629   // want to clear (and its aliases).  We only spill those that overlap with the
630   // current interval as the rest do not affect its allocation. we also keep
631   // track of the earliest start of all spilled live intervals since this will
632   // mark our rollback point.
633   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
634     unsigned reg = i->first->reg;
635     if (//MRegisterInfo::isVirtualRegister(reg) &&
636         toSpill[vrm_->getPhys(reg)] &&
637         cur->overlapsFrom(*i->first, i->second)) {
638       DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
639       earliestStart = std::min(earliestStart, i->first->beginNumber());
640       int slot = vrm_->assignVirt2StackSlot(i->first->reg);
641       std::vector<LiveInterval*> newIs =
642         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
643       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
644       spilled.insert(reg);
645     }
646   }
647   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
648     unsigned reg = i->first->reg;
649     if (//MRegisterInfo::isVirtualRegister(reg) &&
650         toSpill[vrm_->getPhys(reg)] &&
651         cur->overlapsFrom(*i->first, i->second-1)) {
652       DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
653       earliestStart = std::min(earliestStart, i->first->beginNumber());
654       int slot = vrm_->assignVirt2StackSlot(reg);
655       std::vector<LiveInterval*> newIs =
656         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
657       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
658       spilled.insert(reg);
659     }
660   }
661
662   DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
663
664   // Scan handled in reverse order up to the earliest start of a
665   // spilled live interval and undo each one, restoring the state of
666   // unhandled.
667   while (!handled_.empty()) {
668     LiveInterval* i = handled_.back();
669     // If this interval starts before t we are done.
670     if (i->beginNumber() < earliestStart)
671       break;
672     DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
673     handled_.pop_back();
674
675     // When undoing a live interval allocation we must know if it is active or
676     // inactive to properly update the PhysRegTracker and the VirtRegMap.
677     IntervalPtrs::iterator it;
678     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
679       active_.erase(it);
680       assert(!MRegisterInfo::isPhysicalRegister(i->reg));
681       if (!spilled.count(i->reg))
682         unhandled_.push(i);
683       prt_->delRegUse(vrm_->getPhys(i->reg));
684       vrm_->clearVirt(i->reg);
685     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
686       inactive_.erase(it);
687       assert(!MRegisterInfo::isPhysicalRegister(i->reg));
688       if (!spilled.count(i->reg))
689         unhandled_.push(i);
690       vrm_->clearVirt(i->reg);
691     } else {
692       assert(MRegisterInfo::isVirtualRegister(i->reg) &&
693              "Can only allocate virtual registers!");
694       vrm_->clearVirt(i->reg);
695       unhandled_.push(i);
696     }
697   }
698
699   // Rewind the iterators in the active, inactive, and fixed lists back to the
700   // point we reverted to.
701   RevertVectorIteratorsTo(active_, earliestStart);
702   RevertVectorIteratorsTo(inactive_, earliestStart);
703   RevertVectorIteratorsTo(fixed_, earliestStart);
704
705   // scan the rest and undo each interval that expired after t and
706   // insert it in active (the next iteration of the algorithm will
707   // put it in inactive if required)
708   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
709     LiveInterval *HI = handled_[i];
710     if (!HI->expiredAt(earliestStart) &&
711         HI->expiredAt(cur->beginNumber())) {
712       DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
713       active_.push_back(std::make_pair(HI, HI->begin()));
714       assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
715       prt_->addRegUse(vrm_->getPhys(HI->reg));
716     }
717   }
718
719   // merge added with unhandled
720   for (unsigned i = 0, e = added.size(); i != e; ++i)
721     unhandled_.push(added[i]);
722 }
723
724 /// getFreePhysReg - return a free physical register for this virtual register
725 /// interval if we have one, otherwise return 0.
726 unsigned RA::getFreePhysReg(LiveInterval *cur) {
727   std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
728   unsigned MaxInactiveCount = 0;
729   
730   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
731   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
732  
733   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
734        i != e; ++i) {
735     unsigned reg = i->first->reg;
736     assert(MRegisterInfo::isVirtualRegister(reg) &&
737            "Can only allocate virtual registers!");
738
739     // If this is not in a related reg class to the register we're allocating, 
740     // don't check it.
741     const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
742     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
743       reg = vrm_->getPhys(reg);
744       ++inactiveCounts[reg];
745       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
746     }
747   }
748
749   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
750
751   unsigned FreeReg = 0;
752   unsigned FreeRegInactiveCount = 0;
753   
754   // Scan for the first available register.
755   TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
756   TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
757   for (; I != E; ++I)
758     if (prt_->isRegAvail(*I)) {
759       FreeReg = *I;
760       FreeRegInactiveCount = inactiveCounts[FreeReg];
761       break;
762     }
763   
764   // If there are no free regs, or if this reg has the max inactive count,
765   // return this register.
766   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
767   
768   // Continue scanning the registers, looking for the one with the highest
769   // inactive count.  Alkis found that this reduced register pressure very
770   // slightly on X86 (in rev 1.94 of this file), though this should probably be
771   // reevaluated now.
772   for (; I != E; ++I) {
773     unsigned Reg = *I;
774     if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
775       FreeReg = Reg;
776       FreeRegInactiveCount = inactiveCounts[Reg];
777       if (FreeRegInactiveCount == MaxInactiveCount)
778         break;    // We found the one with the max inactive count.
779     }
780   }
781   
782   return FreeReg;
783 }
784
785 FunctionPass* llvm::createLinearScanRegisterAllocator() {
786   return new RA();
787 }