Update to in-place spilling framework. Includes live interval scaling and trivial...
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "VirtRegMap.h"
16 #include "VirtRegRewriter.h"
17 #include "Spiller.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegAllocRegistry.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/ADT/EquivalenceClasses.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
38 #include <algorithm>
39 #include <set>
40 #include <queue>
41 #include <memory>
42 #include <cmath>
43 #include <iostream>
44
45 using namespace llvm;
46
47 STATISTIC(NumIters     , "Number of iterations performed");
48 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
49 STATISTIC(NumCoalesce,   "Number of copies coalesced");
50 STATISTIC(NumDowngrade,  "Number of registers downgraded");
51
52 static cl::opt<bool>
53 NewHeuristic("new-spilling-heuristic",
54              cl::desc("Use new spilling heuristic"),
55              cl::init(false), cl::Hidden);
56
57 static cl::opt<bool>
58 PreSplitIntervals("pre-alloc-split",
59                   cl::desc("Pre-register allocation live interval splitting"),
60                   cl::init(false), cl::Hidden);
61
62 static cl::opt<bool>
63 NewSpillFramework("new-spill-framework",
64                   cl::desc("New spilling framework"),
65                   cl::init(false), cl::Hidden);
66
67 static RegisterRegAlloc
68 linearscanRegAlloc("linearscan", "linear scan register allocator",
69                    createLinearScanRegisterAllocator);
70
71 namespace {
72   struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
73     static char ID;
74     RALinScan() : MachineFunctionPass(&ID) {}
75
76     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
77     typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
78   private:
79     /// RelatedRegClasses - This structure is built the first time a function is
80     /// compiled, and keeps track of which register classes have registers that
81     /// belong to multiple classes or have aliases that are in other classes.
82     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
83     DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
84
85     // NextReloadMap - For each register in the map, it maps to the another
86     // register which is defined by a reload from the same stack slot and
87     // both reloads are in the same basic block.
88     DenseMap<unsigned, unsigned> NextReloadMap;
89
90     // DowngradedRegs - A set of registers which are being "downgraded", i.e.
91     // un-favored for allocation.
92     SmallSet<unsigned, 8> DowngradedRegs;
93
94     // DowngradeMap - A map from virtual registers to physical registers being
95     // downgraded for the virtual registers.
96     DenseMap<unsigned, unsigned> DowngradeMap;
97
98     MachineFunction* mf_;
99     MachineRegisterInfo* mri_;
100     const TargetMachine* tm_;
101     const TargetRegisterInfo* tri_;
102     const TargetInstrInfo* tii_;
103     BitVector allocatableRegs_;
104     LiveIntervals* li_;
105     LiveStacks* ls_;
106     const MachineLoopInfo *loopInfo;
107
108     /// handled_ - Intervals are added to the handled_ set in the order of their
109     /// start value.  This is uses for backtracking.
110     std::vector<LiveInterval*> handled_;
111
112     /// fixed_ - Intervals that correspond to machine registers.
113     ///
114     IntervalPtrs fixed_;
115
116     /// active_ - Intervals that are currently being processed, and which have a
117     /// live range active for the current point.
118     IntervalPtrs active_;
119
120     /// inactive_ - Intervals that are currently being processed, but which have
121     /// a hold at the current point.
122     IntervalPtrs inactive_;
123
124     typedef std::priority_queue<LiveInterval*,
125                                 SmallVector<LiveInterval*, 64>,
126                                 greater_ptr<LiveInterval> > IntervalHeap;
127     IntervalHeap unhandled_;
128
129     /// regUse_ - Tracks register usage.
130     SmallVector<unsigned, 32> regUse_;
131     SmallVector<unsigned, 32> regUseBackUp_;
132
133     /// vrm_ - Tracks register assignments.
134     VirtRegMap* vrm_;
135
136     std::auto_ptr<VirtRegRewriter> rewriter_;
137
138     std::auto_ptr<Spiller> spiller_;
139
140   public:
141     virtual const char* getPassName() const {
142       return "Linear Scan Register Allocator";
143     }
144
145     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146       AU.addRequired<LiveIntervals>();
147       if (StrongPHIElim)
148         AU.addRequiredID(StrongPHIEliminationID);
149       // Make sure PassManager knows which analyses to make available
150       // to coalescing and which analyses coalescing invalidates.
151       AU.addRequiredTransitive<RegisterCoalescer>();
152       if (PreSplitIntervals)
153         AU.addRequiredID(PreAllocSplittingID);
154       AU.addRequired<LiveStacks>();
155       AU.addPreserved<LiveStacks>();
156       AU.addRequired<MachineLoopInfo>();
157       AU.addPreserved<MachineLoopInfo>();
158       AU.addRequired<VirtRegMap>();
159       AU.addPreserved<VirtRegMap>();
160       AU.addPreservedID(MachineDominatorsID);
161       MachineFunctionPass::getAnalysisUsage(AU);
162     }
163
164     /// runOnMachineFunction - register allocate the whole function
165     bool runOnMachineFunction(MachineFunction&);
166
167   private:
168     /// linearScan - the linear scan algorithm
169     void linearScan();
170
171     /// initIntervalSets - initialize the interval sets.
172     ///
173     void initIntervalSets();
174
175     /// processActiveIntervals - expire old intervals and move non-overlapping
176     /// ones to the inactive list.
177     void processActiveIntervals(unsigned CurPoint);
178
179     /// processInactiveIntervals - expire old intervals and move overlapping
180     /// ones to the active list.
181     void processInactiveIntervals(unsigned CurPoint);
182
183     /// hasNextReloadInterval - Return the next liveinterval that's being
184     /// defined by a reload from the same SS as the specified one.
185     LiveInterval *hasNextReloadInterval(LiveInterval *cur);
186
187     /// DowngradeRegister - Downgrade a register for allocation.
188     void DowngradeRegister(LiveInterval *li, unsigned Reg);
189
190     /// UpgradeRegister - Upgrade a register for allocation.
191     void UpgradeRegister(unsigned Reg);
192
193     /// assignRegOrStackSlotAtInterval - assign a register if one
194     /// is available, or spill.
195     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
196
197     void updateSpillWeights(std::vector<float> &Weights,
198                             unsigned reg, float weight,
199                             const TargetRegisterClass *RC);
200
201     /// findIntervalsToSpill - Determine the intervals to spill for the
202     /// specified interval. It's passed the physical registers whose spill
203     /// weight is the lowest among all the registers whose live intervals
204     /// conflict with the interval.
205     void findIntervalsToSpill(LiveInterval *cur,
206                             std::vector<std::pair<unsigned,float> > &Candidates,
207                             unsigned NumCands,
208                             SmallVector<LiveInterval*, 8> &SpillIntervals);
209
210     /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
211     /// try allocate the definition the same register as the source register
212     /// if the register is not defined during live time of the interval. This
213     /// eliminate a copy. This is used to coalesce copies which were not
214     /// coalesced away before allocation either due to dest and src being in
215     /// different register classes or because the coalescer was overly
216     /// conservative.
217     unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
218
219     ///
220     /// Register usage / availability tracking helpers.
221     ///
222
223     void initRegUses() {
224       regUse_.resize(tri_->getNumRegs(), 0);
225       regUseBackUp_.resize(tri_->getNumRegs(), 0);
226     }
227
228     void finalizeRegUses() {
229 #ifndef NDEBUG
230       // Verify all the registers are "freed".
231       bool Error = false;
232       for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
233         if (regUse_[i] != 0) {
234           cerr << tri_->getName(i) << " is still in use!\n";
235           Error = true;
236         }
237       }
238       if (Error)
239         abort();
240 #endif
241       regUse_.clear();
242       regUseBackUp_.clear();
243     }
244
245     void addRegUse(unsigned physReg) {
246       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
247              "should be physical register!");
248       ++regUse_[physReg];
249       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
250         ++regUse_[*as];
251     }
252
253     void delRegUse(unsigned physReg) {
254       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
255              "should be physical register!");
256       assert(regUse_[physReg] != 0);
257       --regUse_[physReg];
258       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
259         assert(regUse_[*as] != 0);
260         --regUse_[*as];
261       }
262     }
263
264     bool isRegAvail(unsigned physReg) const {
265       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
266              "should be physical register!");
267       return regUse_[physReg] == 0;
268     }
269
270     void backUpRegUses() {
271       regUseBackUp_ = regUse_;
272     }
273
274     void restoreRegUses() {
275       regUse_ = regUseBackUp_;
276     }
277
278     ///
279     /// Register handling helpers.
280     ///
281
282     /// getFreePhysReg - return a free physical register for this virtual
283     /// register interval if we have one, otherwise return 0.
284     unsigned getFreePhysReg(LiveInterval* cur);
285     unsigned getFreePhysReg(const TargetRegisterClass *RC,
286                             unsigned MaxInactiveCount,
287                             SmallVector<unsigned, 256> &inactiveCounts,
288                             bool SkipDGRegs);
289
290     /// assignVirt2StackSlot - assigns this virtual register to a
291     /// stack slot. returns the stack slot
292     int assignVirt2StackSlot(unsigned virtReg);
293
294     void ComputeRelatedRegClasses();
295
296     template <typename ItTy>
297     void printIntervals(const char* const str, ItTy i, ItTy e) const {
298       if (str) DOUT << str << " intervals:\n";
299       for (; i != e; ++i) {
300         DOUT << "\t" << *i->first << " -> ";
301         unsigned reg = i->first->reg;
302         if (TargetRegisterInfo::isVirtualRegister(reg)) {
303           reg = vrm_->getPhys(reg);
304         }
305         DOUT << tri_->getName(reg) << '\n';
306       }
307     }
308   };
309   char RALinScan::ID = 0;
310 }
311
312 static RegisterPass<RALinScan>
313 X("linearscan-regalloc", "Linear Scan Register Allocator");
314
315 bool validateRegAlloc(MachineFunction *mf, LiveIntervals *lis,
316                       VirtRegMap *vrm) {
317
318   MachineRegisterInfo *mri = &mf->getRegInfo();
319   const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
320   bool allocationValid = true;
321
322
323   for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
324        itr != end; ++itr) {
325
326     LiveInterval *li = itr->second;
327
328     if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
329       continue;
330     }
331
332     if (vrm->hasPhys(li->reg)) {
333       const TargetRegisterClass *trc = mri->getRegClass(li->reg);
334       
335       if (lis->hasInterval(vrm->getPhys(li->reg))) {
336         if (li->overlaps(lis->getInterval(vrm->getPhys(li->reg)))) {
337           std::cerr << "vreg " << li->reg << " overlaps its assigned preg "
338                     << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
339         }
340       }
341
342       TargetRegisterClass::iterator fReg =
343         std::find(trc->allocation_order_begin(*mf), trc->allocation_order_end(*mf),
344                   vrm->getPhys(li->reg));
345
346       if (fReg == trc->allocation_order_end(*mf)) {
347         std::cerr << "preg " << vrm->getPhys(li->reg) 
348                   << "(" << tri->getName(vrm->getPhys(li->reg)) << ") is not in the allocation set for vreg "
349                   << li->reg << "\n";
350         allocationValid &= false;
351       }
352     }
353     else {
354       std::cerr << "No preg for vreg " << li->reg << "\n";
355       // What about conflicting loads/stores?
356       continue;
357     }
358
359     for (LiveIntervals::iterator itr2 = next(itr); itr2 != end; ++itr2) {
360
361       LiveInterval *li2 = itr2->second;
362
363       if (li2->empty())
364         continue;
365
366       if (TargetRegisterInfo::isPhysicalRegister(li2->reg)) {
367         if (li->overlaps(*li2)) {
368           if (vrm->getPhys(li->reg) == li2->reg ||
369               tri->areAliases(vrm->getPhys(li->reg), li2->reg)) {
370             std::cerr << "vreg " << li->reg << " overlaps preg "
371                       << li2->reg << "(" << tri->getName(li2->reg) << ") which aliases "
372                       << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
373             allocationValid &= false;
374           }
375         }
376       }
377       else {
378
379         if (!vrm->hasPhys(li2->reg)) {
380           continue;
381         }
382
383         if (li->overlaps(*li2)) {
384           if (vrm->getPhys(li->reg) == vrm->getPhys(li2->reg) ||
385               tri->areAliases(vrm->getPhys(li->reg), vrm->getPhys(li2->reg))) {
386             std::cerr << "vreg " << li->reg << " (preg " << vrm->getPhys(li->reg)
387                       << ") overlaps vreg " << li2->reg << " (preg " << vrm->getPhys(li2->reg)
388                       << ") and " << vrm->getPhys(li->reg) << " aliases " << vrm->getPhys(li2->reg) << "\n";
389             allocationValid &= false;
390           } 
391         }
392       }
393     } 
394
395   } 
396
397   return allocationValid;
398
399 }
400
401
402 void RALinScan::ComputeRelatedRegClasses() {
403   // First pass, add all reg classes to the union, and determine at least one
404   // reg class that each register is in.
405   bool HasAliases = false;
406   for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
407        E = tri_->regclass_end(); RCI != E; ++RCI) {
408     RelatedRegClasses.insert(*RCI);
409     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
410          I != E; ++I) {
411       HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
412       
413       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
414       if (PRC) {
415         // Already processed this register.  Just make sure we know that
416         // multiple register classes share a register.
417         RelatedRegClasses.unionSets(PRC, *RCI);
418       } else {
419         PRC = *RCI;
420       }
421     }
422   }
423   
424   // Second pass, now that we know conservatively what register classes each reg
425   // belongs to, add info about aliases.  We don't need to do this for targets
426   // without register aliases.
427   if (HasAliases)
428     for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
429          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
430          I != E; ++I)
431       for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
432         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
433 }
434
435 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
436 /// try allocate the definition the same register as the source register
437 /// if the register is not defined during live time of the interval. This
438 /// eliminate a copy. This is used to coalesce copies which were not
439 /// coalesced away before allocation either due to dest and src being in
440 /// different register classes or because the coalescer was overly
441 /// conservative.
442 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
443   if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
444     return Reg;
445
446   VNInfo *vni = cur.begin()->valno;
447   if (!vni->def || vni->def == ~1U || vni->def == ~0U)
448     return Reg;
449   MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
450   unsigned SrcReg, DstReg, SrcSubReg, DstSubReg, PhysReg;
451   if (!CopyMI ||
452       !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
453     return Reg;
454   PhysReg = SrcReg;
455   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
456     if (!vrm_->isAssignedReg(SrcReg))
457       return Reg;
458     PhysReg = vrm_->getPhys(SrcReg);
459   }
460   if (Reg == PhysReg)
461     return Reg;
462
463   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
464   if (!RC->contains(PhysReg))
465     return Reg;
466
467   // Try to coalesce.
468   if (!li_->conflictsWithPhysRegDef(cur, *vrm_, PhysReg)) {
469     DOUT << "Coalescing: " << cur << " -> " << tri_->getName(PhysReg)
470          << '\n';
471     vrm_->clearVirt(cur.reg);
472     vrm_->assignVirt2Phys(cur.reg, PhysReg);
473
474     // Remove unnecessary kills since a copy does not clobber the register.
475     if (li_->hasInterval(SrcReg)) {
476       LiveInterval &SrcLI = li_->getInterval(SrcReg);
477       for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(cur.reg),
478              E = mri_->reg_end(); I != E; ++I) {
479         MachineOperand &O = I.getOperand();
480         if (!O.isUse() || !O.isKill())
481           continue;
482         MachineInstr *MI = &*I;
483         if (SrcLI.liveAt(li_->getDefIndex(li_->getInstructionIndex(MI))))
484           O.setIsKill(false);
485       }
486     }
487
488     ++NumCoalesce;
489     return SrcReg;
490   }
491
492   return Reg;
493 }
494
495 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
496   mf_ = &fn;
497   mri_ = &fn.getRegInfo();
498   tm_ = &fn.getTarget();
499   tri_ = tm_->getRegisterInfo();
500   tii_ = tm_->getInstrInfo();
501   allocatableRegs_ = tri_->getAllocatableSet(fn);
502   li_ = &getAnalysis<LiveIntervals>();
503   ls_ = &getAnalysis<LiveStacks>();
504   loopInfo = &getAnalysis<MachineLoopInfo>();
505
506   // We don't run the coalescer here because we have no reason to
507   // interact with it.  If the coalescer requires interaction, it
508   // won't do anything.  If it doesn't require interaction, we assume
509   // it was run as a separate pass.
510
511   // If this is the first function compiled, compute the related reg classes.
512   if (RelatedRegClasses.empty())
513     ComputeRelatedRegClasses();
514
515   // Also resize register usage trackers.
516   initRegUses();
517
518   vrm_ = &getAnalysis<VirtRegMap>();
519   if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
520   
521   if (NewSpillFramework) {
522     spiller_.reset(createSpiller(mf_, li_, ls_, vrm_));
523   }
524   
525   initIntervalSets();
526
527   linearScan();
528
529   if (NewSpillFramework) {
530     bool allocValid = validateRegAlloc(mf_, li_, vrm_);
531   }
532
533   // Rewrite spill code and update the PhysRegsUsed set.
534   rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
535
536   assert(unhandled_.empty() && "Unhandled live intervals remain!");
537
538   finalizeRegUses();
539
540   fixed_.clear();
541   active_.clear();
542   inactive_.clear();
543   handled_.clear();
544   NextReloadMap.clear();
545   DowngradedRegs.clear();
546   DowngradeMap.clear();
547   spiller_.reset(0);
548
549   return true;
550 }
551
552 /// initIntervalSets - initialize the interval sets.
553 ///
554 void RALinScan::initIntervalSets()
555 {
556   assert(unhandled_.empty() && fixed_.empty() &&
557          active_.empty() && inactive_.empty() &&
558          "interval sets should be empty on initialization");
559
560   handled_.reserve(li_->getNumIntervals());
561
562   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
563     if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
564       mri_->setPhysRegUsed(i->second->reg);
565       fixed_.push_back(std::make_pair(i->second, i->second->begin()));
566     } else
567       unhandled_.push(i->second);
568   }
569 }
570
571 void RALinScan::linearScan()
572 {
573   // linear scan algorithm
574   DOUT << "********** LINEAR SCAN **********\n";
575   DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
576
577   DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
578
579   while (!unhandled_.empty()) {
580     // pick the interval with the earliest start point
581     LiveInterval* cur = unhandled_.top();
582     unhandled_.pop();
583     ++NumIters;
584     DOUT << "\n*** CURRENT ***: " << *cur << '\n';
585
586     if (!cur->empty()) {
587       processActiveIntervals(cur->beginNumber());
588       processInactiveIntervals(cur->beginNumber());
589
590       assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
591              "Can only allocate virtual registers!");
592     }
593
594     // Allocating a virtual register. try to find a free
595     // physical register or spill an interval (possibly this one) in order to
596     // assign it one.
597     assignRegOrStackSlotAtInterval(cur);
598
599     DEBUG(printIntervals("active", active_.begin(), active_.end()));
600     DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
601   }
602
603   // Expire any remaining active intervals
604   while (!active_.empty()) {
605     IntervalPtr &IP = active_.back();
606     unsigned reg = IP.first->reg;
607     DOUT << "\tinterval " << *IP.first << " expired\n";
608     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
609            "Can only allocate virtual registers!");
610     reg = vrm_->getPhys(reg);
611     delRegUse(reg);
612     active_.pop_back();
613   }
614
615   // Expire any remaining inactive intervals
616   DEBUG(for (IntervalPtrs::reverse_iterator
617                i = inactive_.rbegin(); i != inactive_.rend(); ++i)
618         DOUT << "\tinterval " << *i->first << " expired\n");
619   inactive_.clear();
620
621   // Add live-ins to every BB except for entry. Also perform trivial coalescing.
622   MachineFunction::iterator EntryMBB = mf_->begin();
623   SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
624   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
625     LiveInterval &cur = *i->second;
626     unsigned Reg = 0;
627     bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
628     if (isPhys)
629       Reg = cur.reg;
630     else if (vrm_->isAssignedReg(cur.reg))
631       Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
632     if (!Reg)
633       continue;
634     // Ignore splited live intervals.
635     if (!isPhys && vrm_->getPreSplitReg(cur.reg))
636       continue;
637     for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
638          I != E; ++I) {
639       const LiveRange &LR = *I;
640       if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
641         for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
642           if (LiveInMBBs[i] != EntryMBB)
643             LiveInMBBs[i]->addLiveIn(Reg);
644         LiveInMBBs.clear();
645       }
646     }
647   }
648
649   DOUT << *vrm_;
650
651   // Look for physical registers that end up not being allocated even though
652   // register allocator had to spill other registers in its register class.
653   if (ls_->getNumIntervals() == 0)
654     return;
655   if (!vrm_->FindUnusedRegisters(tri_, li_))
656     return;
657 }
658
659 /// processActiveIntervals - expire old intervals and move non-overlapping ones
660 /// to the inactive list.
661 void RALinScan::processActiveIntervals(unsigned CurPoint)
662 {
663   DOUT << "\tprocessing active intervals:\n";
664
665   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
666     LiveInterval *Interval = active_[i].first;
667     LiveInterval::iterator IntervalPos = active_[i].second;
668     unsigned reg = Interval->reg;
669
670     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
671
672     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
673       DOUT << "\t\tinterval " << *Interval << " expired\n";
674       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
675              "Can only allocate virtual registers!");
676       reg = vrm_->getPhys(reg);
677       delRegUse(reg);
678
679       // Pop off the end of the list.
680       active_[i] = active_.back();
681       active_.pop_back();
682       --i; --e;
683
684     } else if (IntervalPos->start > CurPoint) {
685       // Move inactive intervals to inactive list.
686       DOUT << "\t\tinterval " << *Interval << " inactive\n";
687       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
688              "Can only allocate virtual registers!");
689       reg = vrm_->getPhys(reg);
690       delRegUse(reg);
691       // add to inactive.
692       inactive_.push_back(std::make_pair(Interval, IntervalPos));
693
694       // Pop off the end of the list.
695       active_[i] = active_.back();
696       active_.pop_back();
697       --i; --e;
698     } else {
699       // Otherwise, just update the iterator position.
700       active_[i].second = IntervalPos;
701     }
702   }
703 }
704
705 /// processInactiveIntervals - expire old intervals and move overlapping
706 /// ones to the active list.
707 void RALinScan::processInactiveIntervals(unsigned CurPoint)
708 {
709   DOUT << "\tprocessing inactive intervals:\n";
710
711   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
712     LiveInterval *Interval = inactive_[i].first;
713     LiveInterval::iterator IntervalPos = inactive_[i].second;
714     unsigned reg = Interval->reg;
715
716     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
717
718     if (IntervalPos == Interval->end()) {       // remove expired intervals.
719       DOUT << "\t\tinterval " << *Interval << " expired\n";
720
721       // Pop off the end of the list.
722       inactive_[i] = inactive_.back();
723       inactive_.pop_back();
724       --i; --e;
725     } else if (IntervalPos->start <= CurPoint) {
726       // move re-activated intervals in active list
727       DOUT << "\t\tinterval " << *Interval << " active\n";
728       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
729              "Can only allocate virtual registers!");
730       reg = vrm_->getPhys(reg);
731       addRegUse(reg);
732       // add to active
733       active_.push_back(std::make_pair(Interval, IntervalPos));
734
735       // Pop off the end of the list.
736       inactive_[i] = inactive_.back();
737       inactive_.pop_back();
738       --i; --e;
739     } else {
740       // Otherwise, just update the iterator position.
741       inactive_[i].second = IntervalPos;
742     }
743   }
744 }
745
746 /// updateSpillWeights - updates the spill weights of the specifed physical
747 /// register and its weight.
748 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
749                                    unsigned reg, float weight,
750                                    const TargetRegisterClass *RC) {
751   SmallSet<unsigned, 4> Processed;
752   SmallSet<unsigned, 4> SuperAdded;
753   SmallVector<unsigned, 4> Supers;
754   Weights[reg] += weight;
755   Processed.insert(reg);
756   for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
757     Weights[*as] += weight;
758     Processed.insert(*as);
759     if (tri_->isSubRegister(*as, reg) &&
760         SuperAdded.insert(*as) &&
761         RC->contains(*as)) {
762       Supers.push_back(*as);
763     }
764   }
765
766   // If the alias is a super-register, and the super-register is in the
767   // register class we are trying to allocate. Then add the weight to all
768   // sub-registers of the super-register even if they are not aliases.
769   // e.g. allocating for GR32, bh is not used, updating bl spill weight.
770   //      bl should get the same spill weight otherwise it will be choosen
771   //      as a spill candidate since spilling bh doesn't make ebx available.
772   for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
773     for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
774       if (!Processed.count(*sr))
775         Weights[*sr] += weight;
776   }
777 }
778
779 static
780 RALinScan::IntervalPtrs::iterator
781 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
782   for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
783        I != E; ++I)
784     if (I->first == LI) return I;
785   return IP.end();
786 }
787
788 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
789   for (unsigned i = 0, e = V.size(); i != e; ++i) {
790     RALinScan::IntervalPtr &IP = V[i];
791     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
792                                                 IP.second, Point);
793     if (I != IP.first->begin()) --I;
794     IP.second = I;
795   }
796 }
797
798 /// addStackInterval - Create a LiveInterval for stack if the specified live
799 /// interval has been spilled.
800 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
801                              LiveIntervals *li_,
802                              MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
803   int SS = vrm_.getStackSlot(cur->reg);
804   if (SS == VirtRegMap::NO_STACK_SLOT)
805     return;
806
807   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
808   LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
809
810   VNInfo *VNI;
811   if (SI.hasAtLeastOneValue())
812     VNI = SI.getValNumInfo(0);
813   else
814     VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
815
816   LiveInterval &RI = li_->getInterval(cur->reg);
817   // FIXME: This may be overly conservative.
818   SI.MergeRangesInAsValue(RI, VNI);
819 }
820
821 /// getConflictWeight - Return the number of conflicts between cur
822 /// live interval and defs and uses of Reg weighted by loop depthes.
823 static
824 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
825                         MachineRegisterInfo *mri_,
826                         const MachineLoopInfo *loopInfo) {
827   float Conflicts = 0;
828   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
829          E = mri_->reg_end(); I != E; ++I) {
830     MachineInstr *MI = &*I;
831     if (cur->liveAt(li_->getInstructionIndex(MI))) {
832       unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
833       Conflicts += powf(10.0f, (float)loopDepth);
834     }
835   }
836   return Conflicts;
837 }
838
839 /// findIntervalsToSpill - Determine the intervals to spill for the
840 /// specified interval. It's passed the physical registers whose spill
841 /// weight is the lowest among all the registers whose live intervals
842 /// conflict with the interval.
843 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
844                             std::vector<std::pair<unsigned,float> > &Candidates,
845                             unsigned NumCands,
846                             SmallVector<LiveInterval*, 8> &SpillIntervals) {
847   // We have figured out the *best* register to spill. But there are other
848   // registers that are pretty good as well (spill weight within 3%). Spill
849   // the one that has fewest defs and uses that conflict with cur.
850   float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
851   SmallVector<LiveInterval*, 8> SLIs[3];
852
853   DOUT << "\tConsidering " << NumCands << " candidates: ";
854   DEBUG(for (unsigned i = 0; i != NumCands; ++i)
855           DOUT << tri_->getName(Candidates[i].first) << " ";
856         DOUT << "\n";);
857   
858   // Calculate the number of conflicts of each candidate.
859   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
860     unsigned Reg = i->first->reg;
861     unsigned PhysReg = vrm_->getPhys(Reg);
862     if (!cur->overlapsFrom(*i->first, i->second))
863       continue;
864     for (unsigned j = 0; j < NumCands; ++j) {
865       unsigned Candidate = Candidates[j].first;
866       if (tri_->regsOverlap(PhysReg, Candidate)) {
867         if (NumCands > 1)
868           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
869         SLIs[j].push_back(i->first);
870       }
871     }
872   }
873
874   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
875     unsigned Reg = i->first->reg;
876     unsigned PhysReg = vrm_->getPhys(Reg);
877     if (!cur->overlapsFrom(*i->first, i->second-1))
878       continue;
879     for (unsigned j = 0; j < NumCands; ++j) {
880       unsigned Candidate = Candidates[j].first;
881       if (tri_->regsOverlap(PhysReg, Candidate)) {
882         if (NumCands > 1)
883           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
884         SLIs[j].push_back(i->first);
885       }
886     }
887   }
888
889   // Which is the best candidate?
890   unsigned BestCandidate = 0;
891   float MinConflicts = Conflicts[0];
892   for (unsigned i = 1; i != NumCands; ++i) {
893     if (Conflicts[i] < MinConflicts) {
894       BestCandidate = i;
895       MinConflicts = Conflicts[i];
896     }
897   }
898
899   std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
900             std::back_inserter(SpillIntervals));
901 }
902
903 namespace {
904   struct WeightCompare {
905     typedef std::pair<unsigned, float> RegWeightPair;
906     bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
907       return LHS.second < RHS.second;
908     }
909   };
910 }
911
912 static bool weightsAreClose(float w1, float w2) {
913   if (!NewHeuristic)
914     return false;
915
916   float diff = w1 - w2;
917   if (diff <= 0.02f)  // Within 0.02f
918     return true;
919   return (diff / w2) <= 0.05f;  // Within 5%.
920 }
921
922 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
923   DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
924   if (I == NextReloadMap.end())
925     return 0;
926   return &li_->getInterval(I->second);
927 }
928
929 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
930   bool isNew = DowngradedRegs.insert(Reg);
931   isNew = isNew; // Silence compiler warning.
932   assert(isNew && "Multiple reloads holding the same register?");
933   DowngradeMap.insert(std::make_pair(li->reg, Reg));
934   for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
935     isNew = DowngradedRegs.insert(*AS);
936     isNew = isNew; // Silence compiler warning.
937     assert(isNew && "Multiple reloads holding the same register?");
938     DowngradeMap.insert(std::make_pair(li->reg, *AS));
939   }
940   ++NumDowngrade;
941 }
942
943 void RALinScan::UpgradeRegister(unsigned Reg) {
944   if (Reg) {
945     DowngradedRegs.erase(Reg);
946     for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
947       DowngradedRegs.erase(*AS);
948   }
949 }
950
951 namespace {
952   struct LISorter {
953     bool operator()(LiveInterval* A, LiveInterval* B) {
954       return A->beginNumber() < B->beginNumber();
955     }
956   };
957 }
958
959 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
960 /// spill.
961 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
962 {
963   DOUT << "\tallocating current interval: ";
964
965   // This is an implicitly defined live interval, just assign any register.
966   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
967   if (cur->empty()) {
968     unsigned physReg = cur->preference;
969     if (!physReg)
970       physReg = *RC->allocation_order_begin(*mf_);
971     DOUT <<  tri_->getName(physReg) << '\n';
972     // Note the register is not really in use.
973     vrm_->assignVirt2Phys(cur->reg, physReg);
974     return;
975   }
976
977   backUpRegUses();
978
979   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
980   unsigned StartPosition = cur->beginNumber();
981   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
982
983   // If start of this live interval is defined by a move instruction and its
984   // source is assigned a physical register that is compatible with the target
985   // register class, then we should try to assign it the same register.
986   // This can happen when the move is from a larger register class to a smaller
987   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
988   if (!cur->preference && cur->hasAtLeastOneValue()) {
989     VNInfo *vni = cur->begin()->valno;
990     if (vni->def && vni->def != ~1U && vni->def != ~0U) {
991       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
992       unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
993       if (CopyMI &&
994           tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
995         unsigned Reg = 0;
996         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
997           Reg = SrcReg;
998         else if (vrm_->isAssignedReg(SrcReg))
999           Reg = vrm_->getPhys(SrcReg);
1000         if (Reg) {
1001           if (SrcSubReg)
1002             Reg = tri_->getSubReg(Reg, SrcSubReg);
1003           if (DstSubReg)
1004             Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1005           if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1006             cur->preference = Reg;
1007         }
1008       }
1009     }
1010   }
1011
1012   // For every interval in inactive we overlap with, mark the
1013   // register as not free and update spill weights.
1014   for (IntervalPtrs::const_iterator i = inactive_.begin(),
1015          e = inactive_.end(); i != e; ++i) {
1016     unsigned Reg = i->first->reg;
1017     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1018            "Can only allocate virtual registers!");
1019     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1020     // If this is not in a related reg class to the register we're allocating, 
1021     // don't check it.
1022     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1023         cur->overlapsFrom(*i->first, i->second-1)) {
1024       Reg = vrm_->getPhys(Reg);
1025       addRegUse(Reg);
1026       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1027     }
1028   }
1029   
1030   // Speculatively check to see if we can get a register right now.  If not,
1031   // we know we won't be able to by adding more constraints.  If so, we can
1032   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
1033   // is very bad (it contains all callee clobbered registers for any functions
1034   // with a call), so we want to avoid doing that if possible.
1035   unsigned physReg = getFreePhysReg(cur);
1036   unsigned BestPhysReg = physReg;
1037   if (physReg) {
1038     // We got a register.  However, if it's in the fixed_ list, we might
1039     // conflict with it.  Check to see if we conflict with it or any of its
1040     // aliases.
1041     SmallSet<unsigned, 8> RegAliases;
1042     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1043       RegAliases.insert(*AS);
1044     
1045     bool ConflictsWithFixed = false;
1046     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1047       IntervalPtr &IP = fixed_[i];
1048       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1049         // Okay, this reg is on the fixed list.  Check to see if we actually
1050         // conflict.
1051         LiveInterval *I = IP.first;
1052         if (I->endNumber() > StartPosition) {
1053           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1054           IP.second = II;
1055           if (II != I->begin() && II->start > StartPosition)
1056             --II;
1057           if (cur->overlapsFrom(*I, II)) {
1058             ConflictsWithFixed = true;
1059             break;
1060           }
1061         }
1062       }
1063     }
1064     
1065     // Okay, the register picked by our speculative getFreePhysReg call turned
1066     // out to be in use.  Actually add all of the conflicting fixed registers to
1067     // regUse_ so we can do an accurate query.
1068     if (ConflictsWithFixed) {
1069       // For every interval in fixed we overlap with, mark the register as not
1070       // free and update spill weights.
1071       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1072         IntervalPtr &IP = fixed_[i];
1073         LiveInterval *I = IP.first;
1074
1075         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1076         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
1077             I->endNumber() > StartPosition) {
1078           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1079           IP.second = II;
1080           if (II != I->begin() && II->start > StartPosition)
1081             --II;
1082           if (cur->overlapsFrom(*I, II)) {
1083             unsigned reg = I->reg;
1084             addRegUse(reg);
1085             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1086           }
1087         }
1088       }
1089
1090       // Using the newly updated regUse_ object, which includes conflicts in the
1091       // future, see if there are any registers available.
1092       physReg = getFreePhysReg(cur);
1093     }
1094   }
1095     
1096   // Restore the physical register tracker, removing information about the
1097   // future.
1098   restoreRegUses();
1099   
1100   // If we find a free register, we are done: assign this virtual to
1101   // the free physical register and add this interval to the active
1102   // list.
1103   if (physReg) {
1104     DOUT <<  tri_->getName(physReg) << '\n';
1105     vrm_->assignVirt2Phys(cur->reg, physReg);
1106     addRegUse(physReg);
1107     active_.push_back(std::make_pair(cur, cur->begin()));
1108     handled_.push_back(cur);
1109
1110     // "Upgrade" the physical register since it has been allocated.
1111     UpgradeRegister(physReg);
1112     if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1113       // "Downgrade" physReg to try to keep physReg from being allocated until
1114       // the next reload from the same SS is allocated. 
1115       NextReloadLI->preference = physReg;
1116       DowngradeRegister(cur, physReg);
1117     }
1118     return;
1119   }
1120   DOUT << "no free registers\n";
1121
1122   // Compile the spill weights into an array that is better for scanning.
1123   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1124   for (std::vector<std::pair<unsigned, float> >::iterator
1125        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1126     updateSpillWeights(SpillWeights, I->first, I->second, RC);
1127   
1128   // for each interval in active, update spill weights.
1129   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1130        i != e; ++i) {
1131     unsigned reg = i->first->reg;
1132     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1133            "Can only allocate virtual registers!");
1134     reg = vrm_->getPhys(reg);
1135     updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1136   }
1137  
1138   DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
1139
1140   // Find a register to spill.
1141   float minWeight = HUGE_VALF;
1142   unsigned minReg = 0; /*cur->preference*/;  // Try the pref register first.
1143
1144   bool Found = false;
1145   std::vector<std::pair<unsigned,float> > RegsWeights;
1146   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1147     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1148            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1149       unsigned reg = *i;
1150       float regWeight = SpillWeights[reg];
1151       if (minWeight > regWeight)
1152         Found = true;
1153       RegsWeights.push_back(std::make_pair(reg, regWeight));
1154     }
1155   
1156   // If we didn't find a register that is spillable, try aliases?
1157   if (!Found) {
1158     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1159            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1160       unsigned reg = *i;
1161       // No need to worry about if the alias register size < regsize of RC.
1162       // We are going to spill all registers that alias it anyway.
1163       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1164         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1165     }
1166   }
1167
1168   // Sort all potential spill candidates by weight.
1169   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1170   minReg = RegsWeights[0].first;
1171   minWeight = RegsWeights[0].second;
1172   if (minWeight == HUGE_VALF) {
1173     // All registers must have inf weight. Just grab one!
1174     minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
1175     if (cur->weight == HUGE_VALF ||
1176         li_->getApproximateInstructionCount(*cur) == 0) {
1177       // Spill a physical register around defs and uses.
1178       if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1179         // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1180         // in fixed_. Reset them.
1181         for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1182           IntervalPtr &IP = fixed_[i];
1183           LiveInterval *I = IP.first;
1184           if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1185             IP.second = I->advanceTo(I->begin(), StartPosition);
1186         }
1187
1188         DowngradedRegs.clear();
1189         assignRegOrStackSlotAtInterval(cur);
1190       } else {
1191         cerr << "Ran out of registers during register allocation!\n";
1192         exit(1);
1193       }
1194       return;
1195     }
1196   }
1197
1198   // Find up to 3 registers to consider as spill candidates.
1199   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1200   while (LastCandidate > 1) {
1201     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1202       break;
1203     --LastCandidate;
1204   }
1205
1206   DOUT << "\t\tregister(s) with min weight(s): ";
1207   DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
1208           DOUT << tri_->getName(RegsWeights[i].first)
1209                << " (" << RegsWeights[i].second << ")\n");
1210
1211   // If the current has the minimum weight, we need to spill it and
1212   // add any added intervals back to unhandled, and restart
1213   // linearscan.
1214   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1215     DOUT << "\t\t\tspilling(c): " << *cur << '\n';
1216     SmallVector<LiveInterval*, 8> spillIs;
1217     std::vector<LiveInterval*> added;
1218     
1219     if (!NewSpillFramework) {
1220       added = li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_);
1221     } else {
1222       added = spiller_->spill(cur); 
1223     }
1224
1225     std::sort(added.begin(), added.end(), LISorter());
1226     addStackInterval(cur, ls_, li_, mri_, *vrm_);
1227     if (added.empty())
1228       return;  // Early exit if all spills were folded.
1229
1230     // Merge added with unhandled.  Note that we have already sorted
1231     // intervals returned by addIntervalsForSpills by their starting
1232     // point.
1233     // This also update the NextReloadMap. That is, it adds mapping from a
1234     // register defined by a reload from SS to the next reload from SS in the
1235     // same basic block.
1236     MachineBasicBlock *LastReloadMBB = 0;
1237     LiveInterval *LastReload = 0;
1238     int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1239     for (unsigned i = 0, e = added.size(); i != e; ++i) {
1240       LiveInterval *ReloadLi = added[i];
1241       if (ReloadLi->weight == HUGE_VALF &&
1242           li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1243         unsigned ReloadIdx = ReloadLi->beginNumber();
1244         MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1245         int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1246         if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1247           // Last reload of same SS is in the same MBB. We want to try to
1248           // allocate both reloads the same register and make sure the reg
1249           // isn't clobbered in between if at all possible.
1250           assert(LastReload->beginNumber() < ReloadIdx);
1251           NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1252         }
1253         LastReloadMBB = ReloadMBB;
1254         LastReload = ReloadLi;
1255         LastReloadSS = ReloadSS;
1256       }
1257       unhandled_.push(ReloadLi);
1258     }
1259     return;
1260   }
1261
1262   ++NumBacktracks;
1263
1264   // Push the current interval back to unhandled since we are going
1265   // to re-run at least this iteration. Since we didn't modify it it
1266   // should go back right in the front of the list
1267   unhandled_.push(cur);
1268
1269   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1270          "did not choose a register to spill?");
1271
1272   // We spill all intervals aliasing the register with
1273   // minimum weight, rollback to the interval with the earliest
1274   // start point and let the linear scan algorithm run again
1275   SmallVector<LiveInterval*, 8> spillIs;
1276
1277   // Determine which intervals have to be spilled.
1278   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1279
1280   // Set of spilled vregs (used later to rollback properly)
1281   SmallSet<unsigned, 8> spilled;
1282
1283   // The earliest start of a Spilled interval indicates up to where
1284   // in handled we need to roll back
1285   
1286   unsigned earliestStart = cur->beginNumber();
1287   LiveInterval *earliestStartInterval = cur;
1288
1289   // Spill live intervals of virtual regs mapped to the physical register we
1290   // want to clear (and its aliases).  We only spill those that overlap with the
1291   // current interval as the rest do not affect its allocation. we also keep
1292   // track of the earliest start of all spilled live intervals since this will
1293   // mark our rollback point.
1294   std::vector<LiveInterval*> added;
1295   while (!spillIs.empty()) {
1296     bool epicFail = false;
1297     LiveInterval *sli = spillIs.back();
1298     spillIs.pop_back();
1299     DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1300     earliestStart = std::min(earliestStart, sli->beginNumber());
1301     earliestStartInterval =
1302       (earliestStartInterval->beginNumber() < sli->beginNumber()) ?
1303          earliestStartInterval : sli;
1304     
1305     if (earliestStartInterval->beginNumber()!=earliestStart) {
1306       epicFail |= true;
1307       std::cerr << "What the 1 - "
1308                 << "earliestStart = " << earliestStart
1309                 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1310                 << "\n";
1311     }
1312    
1313     std::vector<LiveInterval*> newIs;
1314     if (!NewSpillFramework) {
1315       newIs = li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_);
1316     } else {
1317       newIs = spiller_->spill(sli);
1318     }
1319     addStackInterval(sli, ls_, li_, mri_, *vrm_);
1320     std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1321     spilled.insert(sli->reg);
1322
1323     if (earliestStartInterval->beginNumber()!=earliestStart) {
1324       epicFail |= true;
1325       std::cerr << "What the 2 - "
1326                 << "earliestStart = " << earliestStart
1327                 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1328                 << "\n";
1329     }
1330
1331     if (epicFail) {
1332       //abort();
1333     }
1334   }
1335
1336   earliestStart = earliestStartInterval->beginNumber();
1337
1338   DOUT << "\t\trolling back to: " << earliestStart << '\n';
1339
1340   // Scan handled in reverse order up to the earliest start of a
1341   // spilled live interval and undo each one, restoring the state of
1342   // unhandled.
1343   while (!handled_.empty()) {
1344     LiveInterval* i = handled_.back();
1345     // If this interval starts before t we are done.
1346     if (i->beginNumber() < earliestStart)
1347       break;
1348     DOUT << "\t\t\tundo changes for: " << *i << '\n';
1349     handled_.pop_back();
1350
1351     // When undoing a live interval allocation we must know if it is active or
1352     // inactive to properly update regUse_ and the VirtRegMap.
1353     IntervalPtrs::iterator it;
1354     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1355       active_.erase(it);
1356       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1357       if (!spilled.count(i->reg))
1358         unhandled_.push(i);
1359       delRegUse(vrm_->getPhys(i->reg));
1360       vrm_->clearVirt(i->reg);
1361     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1362       inactive_.erase(it);
1363       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1364       if (!spilled.count(i->reg))
1365         unhandled_.push(i);
1366       vrm_->clearVirt(i->reg);
1367     } else {
1368       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1369              "Can only allocate virtual registers!");
1370       vrm_->clearVirt(i->reg);
1371       unhandled_.push(i);
1372     }
1373
1374     DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1375     if (ii == DowngradeMap.end())
1376       // It interval has a preference, it must be defined by a copy. Clear the
1377       // preference now since the source interval allocation may have been
1378       // undone as well.
1379       i->preference = 0;
1380     else {
1381       UpgradeRegister(ii->second);
1382     }
1383   }
1384
1385   // Rewind the iterators in the active, inactive, and fixed lists back to the
1386   // point we reverted to.
1387   RevertVectorIteratorsTo(active_, earliestStart);
1388   RevertVectorIteratorsTo(inactive_, earliestStart);
1389   RevertVectorIteratorsTo(fixed_, earliestStart);
1390
1391   // Scan the rest and undo each interval that expired after t and
1392   // insert it in active (the next iteration of the algorithm will
1393   // put it in inactive if required)
1394   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1395     LiveInterval *HI = handled_[i];
1396     if (!HI->expiredAt(earliestStart) &&
1397         HI->expiredAt(cur->beginNumber())) {
1398       DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1399       active_.push_back(std::make_pair(HI, HI->begin()));
1400       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1401       addRegUse(vrm_->getPhys(HI->reg));
1402     }
1403   }
1404
1405   // Merge added with unhandled.
1406   // This also update the NextReloadMap. That is, it adds mapping from a
1407   // register defined by a reload from SS to the next reload from SS in the
1408   // same basic block.
1409   MachineBasicBlock *LastReloadMBB = 0;
1410   LiveInterval *LastReload = 0;
1411   int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1412   std::sort(added.begin(), added.end(), LISorter());
1413   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1414     LiveInterval *ReloadLi = added[i];
1415     if (ReloadLi->weight == HUGE_VALF &&
1416         li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1417       unsigned ReloadIdx = ReloadLi->beginNumber();
1418       MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1419       int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1420       if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1421         // Last reload of same SS is in the same MBB. We want to try to
1422         // allocate both reloads the same register and make sure the reg
1423         // isn't clobbered in between if at all possible.
1424         assert(LastReload->beginNumber() < ReloadIdx);
1425         NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1426       }
1427       LastReloadMBB = ReloadMBB;
1428       LastReload = ReloadLi;
1429       LastReloadSS = ReloadSS;
1430     }
1431     unhandled_.push(ReloadLi);
1432   }
1433 }
1434
1435 unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1436                                    unsigned MaxInactiveCount,
1437                                    SmallVector<unsigned, 256> &inactiveCounts,
1438                                    bool SkipDGRegs) {
1439   unsigned FreeReg = 0;
1440   unsigned FreeRegInactiveCount = 0;
1441
1442   TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1443   TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1444   assert(I != E && "No allocatable register in this register class!");
1445
1446   // Scan for the first available register.
1447   for (; I != E; ++I) {
1448     unsigned Reg = *I;
1449     // Ignore "downgraded" registers.
1450     if (SkipDGRegs && DowngradedRegs.count(Reg))
1451       continue;
1452     if (isRegAvail(Reg)) {
1453       FreeReg = Reg;
1454       if (FreeReg < inactiveCounts.size())
1455         FreeRegInactiveCount = inactiveCounts[FreeReg];
1456       else
1457         FreeRegInactiveCount = 0;
1458       break;
1459     }
1460   }
1461
1462   // If there are no free regs, or if this reg has the max inactive count,
1463   // return this register.
1464   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1465     return FreeReg;
1466   
1467   // Continue scanning the registers, looking for the one with the highest
1468   // inactive count.  Alkis found that this reduced register pressure very
1469   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1470   // reevaluated now.
1471   for (; I != E; ++I) {
1472     unsigned Reg = *I;
1473     // Ignore "downgraded" registers.
1474     if (SkipDGRegs && DowngradedRegs.count(Reg))
1475       continue;
1476     if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1477         FreeRegInactiveCount < inactiveCounts[Reg]) {
1478       FreeReg = Reg;
1479       FreeRegInactiveCount = inactiveCounts[Reg];
1480       if (FreeRegInactiveCount == MaxInactiveCount)
1481         break;    // We found the one with the max inactive count.
1482     }
1483   }
1484
1485   return FreeReg;
1486 }
1487
1488 /// getFreePhysReg - return a free physical register for this virtual register
1489 /// interval if we have one, otherwise return 0.
1490 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1491   SmallVector<unsigned, 256> inactiveCounts;
1492   unsigned MaxInactiveCount = 0;
1493   
1494   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1495   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1496  
1497   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1498        i != e; ++i) {
1499     unsigned reg = i->first->reg;
1500     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1501            "Can only allocate virtual registers!");
1502
1503     // If this is not in a related reg class to the register we're allocating, 
1504     // don't check it.
1505     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1506     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1507       reg = vrm_->getPhys(reg);
1508       if (inactiveCounts.size() <= reg)
1509         inactiveCounts.resize(reg+1);
1510       ++inactiveCounts[reg];
1511       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1512     }
1513   }
1514
1515   // If copy coalescer has assigned a "preferred" register, check if it's
1516   // available first.
1517   if (cur->preference) {
1518     DOUT << "(preferred: " << tri_->getName(cur->preference) << ") ";
1519     if (isRegAvail(cur->preference) && 
1520         RC->contains(cur->preference))
1521       return cur->preference;
1522   }
1523
1524   if (!DowngradedRegs.empty()) {
1525     unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1526                                       true);
1527     if (FreeReg)
1528       return FreeReg;
1529   }
1530   return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
1531 }
1532
1533 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1534   return new RALinScan();
1535 }