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