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