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