Fix spilled interval update. It was too conservative.
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a linear scan register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "regalloc"
14 #include "llvm/Function.h"
15 #include "llvm/CodeGen/LiveIntervals.h"
16 #include "llvm/CodeGen/LiveVariables.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CFG.h"
26 #include "Support/Debug.h"
27 #include "Support/DepthFirstIterator.h"
28 #include "Support/Statistic.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 namespace {
34     Statistic<> numSpilled ("ra-linearscan", "Number of registers spilled");
35     Statistic<> numReloaded("ra-linearscan", "Number of registers reloaded");
36
37     class PhysRegTracker {
38     private:
39         const MRegisterInfo* mri_;
40         std::vector<unsigned> regUse_;
41
42     public:
43         PhysRegTracker(MachineFunction* mf)
44             : mri_(mf ? mf->getTarget().getRegisterInfo() : NULL) {
45             if (mri_) {
46                 regUse_.assign(mri_->getNumRegs(), 0);
47             }
48         }
49
50         PhysRegTracker(const PhysRegTracker& rhs)
51             : mri_(rhs.mri_),
52               regUse_(rhs.regUse_) {
53         }
54
55         const PhysRegTracker& operator=(const PhysRegTracker& rhs) {
56             mri_ = rhs.mri_;
57             regUse_ = rhs.regUse_;
58             return *this;
59         }
60
61         void addPhysRegUse(unsigned physReg) {
62             ++regUse_[physReg];
63             for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
64                 physReg = *as;
65                 ++regUse_[physReg];
66             }
67         }
68
69         void delPhysRegUse(unsigned physReg) {
70             assert(regUse_[physReg] != 0);
71             --regUse_[physReg];
72             for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
73                 physReg = *as;
74                 assert(regUse_[physReg] != 0);
75                 --regUse_[physReg];
76             }
77         }
78
79         bool isPhysRegAvail(unsigned physReg) const {
80             return regUse_[physReg] == 0;
81         }
82     };
83
84     class RA : public MachineFunctionPass {
85     private:
86         MachineFunction* mf_;
87         const TargetMachine* tm_;
88         const MRegisterInfo* mri_;
89         LiveIntervals* li_;
90         typedef std::list<LiveIntervals::Interval*> IntervalPtrs;
91         IntervalPtrs unhandled_, fixed_, active_, inactive_, handled_;
92
93         PhysRegTracker prt_;
94
95         typedef std::map<unsigned, unsigned> Virt2PhysMap;
96         Virt2PhysMap v2pMap_;
97
98         typedef std::map<unsigned, int> Virt2StackSlotMap;
99         Virt2StackSlotMap v2ssMap_;
100
101         int instrAdded_;
102
103         typedef std::vector<float> SpillWeights;
104         SpillWeights spillWeights_;
105
106     public:
107         RA()
108             : prt_(NULL) {
109
110         }
111
112         virtual const char* getPassName() const {
113             return "Linear Scan Register Allocator";
114         }
115
116         virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117             AU.addRequired<LiveVariables>();
118             AU.addRequired<LiveIntervals>();
119             MachineFunctionPass::getAnalysisUsage(AU);
120         }
121
122         /// runOnMachineFunction - register allocate the whole function
123         bool runOnMachineFunction(MachineFunction&);
124
125         void releaseMemory();
126
127     private:
128         /// initIntervalSets - initializa the four interval sets:
129         /// unhandled, fixed, active and inactive
130         void initIntervalSets(LiveIntervals::Intervals& li);
131
132         /// processActiveIntervals - expire old intervals and move
133         /// non-overlapping ones to the incative list
134         void processActiveIntervals(IntervalPtrs::value_type cur);
135
136         /// processInactiveIntervals - expire old intervals and move
137         /// overlapping ones to the active list
138         void processInactiveIntervals(IntervalPtrs::value_type cur);
139
140         /// updateSpillWeights - updates the spill weights of the
141         /// specifed physical register and its weight
142         void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
143
144         /// assignRegOrStackSlotAtInterval - assign a register if one
145         /// is available, or spill.
146         void assignRegOrStackSlotAtInterval(IntervalPtrs::value_type cur);
147
148         /// addSpillCode - adds spill code for interval. The interval
149         /// must be modified by LiveIntervals::updateIntervalForSpill.
150         void addSpillCode(IntervalPtrs::value_type li, int slot);
151
152         ///
153         /// register handling helpers
154         ///
155
156         /// getFreePhysReg - return a free physical register for this
157         /// virtual register interval if we have one, otherwise return
158         /// 0
159         unsigned getFreePhysReg(IntervalPtrs::value_type cur);
160
161         /// assignVirt2PhysReg - assigns the free physical register to
162         /// the virtual register passed as arguments
163         Virt2PhysMap::iterator
164         assignVirt2PhysReg(unsigned virtReg, unsigned physReg);
165
166         /// clearVirtReg - free the physical register associated with this
167         /// virtual register and disassociate virtual->physical and
168         /// physical->virtual mappings
169         void clearVirtReg(Virt2PhysMap::iterator it);
170
171         /// assignVirt2StackSlot - assigns this virtual register to a
172         /// stack slot. returns the stack slot
173         int assignVirt2StackSlot(unsigned virtReg);
174
175         /// getStackSlot - returns the offset of the specified
176         /// register on the stack
177         int getStackSlot(unsigned virtReg);
178
179         void printVirtRegAssignment() const {
180             std::cerr << "register assignment:\n";
181
182             for (Virt2PhysMap::const_iterator
183                      i = v2pMap_.begin(), e = v2pMap_.end(); i != e; ++i) {
184                 assert(i->second != 0);
185                 std::cerr << '[' << i->first << ','
186                           << mri_->getName(i->second) << "]\n";
187             }
188             for (Virt2StackSlotMap::const_iterator
189                      i = v2ssMap_.begin(), e = v2ssMap_.end(); i != e; ++i) {
190                 std::cerr << '[' << i->first << ",ss#" << i->second << "]\n";
191             }
192             std::cerr << '\n';
193         }
194
195         void printIntervals(const char* const str,
196                             RA::IntervalPtrs::const_iterator i,
197                             RA::IntervalPtrs::const_iterator e) const {
198             if (str) std::cerr << str << " intervals:\n";
199             for (; i != e; ++i) {
200                 std::cerr << "\t\t" << **i << " -> ";
201                 unsigned reg = (*i)->reg;
202                 if (MRegisterInfo::isVirtualRegister(reg)) {
203                     Virt2PhysMap::const_iterator it = v2pMap_.find(reg);
204                     reg = (it == v2pMap_.end() ? 0 : it->second);
205                 }
206                 std::cerr << mri_->getName(reg) << '\n';
207             }
208         }
209     };
210 }
211
212 void RA::releaseMemory()
213 {
214     v2pMap_.clear();
215     v2ssMap_.clear();
216     unhandled_.clear();
217     active_.clear();
218     inactive_.clear();
219     fixed_.clear();
220     handled_.clear();
221 }
222
223 bool RA::runOnMachineFunction(MachineFunction &fn) {
224     mf_ = &fn;
225     tm_ = &fn.getTarget();
226     mri_ = tm_->getRegisterInfo();
227     li_ = &getAnalysis<LiveIntervals>();
228     prt_ = PhysRegTracker(mf_);
229
230     initIntervalSets(li_->getIntervals());
231
232     // linear scan algorithm
233     DEBUG(std::cerr << "Machine Function\n");
234
235     DEBUG(printIntervals("\tunhandled", unhandled_.begin(), unhandled_.end()));
236     DEBUG(printIntervals("\tfixed", fixed_.begin(), fixed_.end()));
237     DEBUG(printIntervals("\tactive", active_.begin(), active_.end()));
238     DEBUG(printIntervals("\tinactive", inactive_.begin(), inactive_.end()));
239
240     while (!unhandled_.empty() || !fixed_.empty()) {
241         // pick the interval with the earliest start point
242         IntervalPtrs::value_type cur;
243         if (fixed_.empty()) {
244             cur = unhandled_.front();
245             unhandled_.pop_front();
246         }
247         else if (unhandled_.empty()) {
248             cur = fixed_.front();
249             fixed_.pop_front();
250         }
251         else if (unhandled_.front()->start() < fixed_.front()->start()) {
252             cur = unhandled_.front();
253             unhandled_.pop_front();
254         }
255         else {
256             cur = fixed_.front();
257             fixed_.pop_front();
258         }
259
260         DEBUG(std::cerr << *cur << '\n');
261
262         processActiveIntervals(cur);
263         processInactiveIntervals(cur);
264
265         // if this register is fixed we are done
266         if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
267             prt_.addPhysRegUse(cur->reg);
268             active_.push_back(cur);
269             handled_.push_back(cur);
270         }
271         // otherwise we are allocating a virtual register. try to find
272         // a free physical register or spill an interval in order to
273         // assign it one (we could spill the current though).
274         else {
275             assignRegOrStackSlotAtInterval(cur);
276         }
277
278         DEBUG(printIntervals("\tactive", active_.begin(), active_.end()));
279         DEBUG(printIntervals("\tinactive", inactive_.begin(), inactive_.end()));    }
280
281     // expire any remaining active intervals
282     for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
283         unsigned reg = (*i)->reg;
284         DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
285         if (MRegisterInfo::isVirtualRegister(reg)) {
286             reg = v2pMap_[reg];
287         }
288         prt_.delPhysRegUse(reg);
289     }
290
291     DEBUG(printVirtRegAssignment());
292     DEBUG(std::cerr << "finished register allocation\n");
293
294     const TargetInstrInfo& tii = tm_->getInstrInfo();
295
296     DEBUG(std::cerr << "Rewrite machine code:\n");
297     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
298          mbbi != mbbe; ++mbbi) {
299         instrAdded_ = 0;
300
301         for (MachineBasicBlock::iterator mii = mbbi->begin(), mie = mbbi->end();
302              mii != mie; ++mii) {
303             DEBUG(std::cerr << '\t'; mii->print(std::cerr, *tm_));
304
305             // use our current mapping and actually replace every
306             // virtual register with its allocated physical registers
307             DEBUG(std::cerr << "\t\treplacing virtual registers with mapped "
308                   "physical registers:\n");
309             for (unsigned i = 0, e = mii->getNumOperands();
310                  i != e; ++i) {
311                 MachineOperand& op = mii->getOperand(i);
312                 if (op.isRegister() &&
313                     MRegisterInfo::isVirtualRegister(op.getReg())) {
314                     unsigned virtReg = op.getReg();
315                     Virt2PhysMap::iterator it = v2pMap_.find(virtReg);
316                     assert(it != v2pMap_.end() &&
317                            "all virtual registers must be allocated");
318                     unsigned physReg = it->second;
319                     assert(MRegisterInfo::isPhysicalRegister(physReg));
320                     DEBUG(std::cerr << "\t\t\t%reg" << virtReg
321                           << " -> " << mri_->getName(physReg) << '\n');
322                     mii->SetMachineOperandReg(i, physReg);
323                 }
324             }
325         }
326     }
327
328     return true;
329 }
330
331 void RA::initIntervalSets(LiveIntervals::Intervals& li)
332 {
333     assert(unhandled_.empty() && fixed_.empty() &&
334            active_.empty() && inactive_.empty() &&
335            "interval sets should be empty on initialization");
336
337     for (LiveIntervals::Intervals::iterator i = li.begin(), e = li.end();
338          i != e; ++i) {
339         if (MRegisterInfo::isPhysicalRegister(i->reg))
340             fixed_.push_back(&*i);
341         else
342             unhandled_.push_back(&*i);
343     }
344 }
345
346 void RA::processActiveIntervals(IntervalPtrs::value_type cur)
347 {
348     DEBUG(std::cerr << "\tprocessing active intervals:\n");
349     for (IntervalPtrs::iterator i = active_.begin(); i != active_.end();) {
350         unsigned reg = (*i)->reg;
351         // remove expired intervals
352         if ((*i)->expiredAt(cur->start())) {
353             DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
354             if (MRegisterInfo::isVirtualRegister(reg)) {
355                 reg = v2pMap_[reg];
356             }
357             prt_.delPhysRegUse(reg);
358             // remove from active
359             i = active_.erase(i);
360         }
361         // move inactive intervals to inactive list
362         else if (!(*i)->liveAt(cur->start())) {
363             DEBUG(std::cerr << "\t\t\tinterval " << **i << " inactive\n");
364             if (MRegisterInfo::isVirtualRegister(reg)) {
365                 reg = v2pMap_[reg];
366             }
367             prt_.delPhysRegUse(reg);
368             // add to inactive
369             inactive_.push_back(*i);
370             // remove from active
371             i = active_.erase(i);
372         }
373         else {
374             ++i;
375         }
376     }
377 }
378
379 void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
380 {
381     DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
382     for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end();) {
383         unsigned reg = (*i)->reg;
384
385         // remove expired intervals
386         if ((*i)->expiredAt(cur->start())) {
387             DEBUG(std::cerr << "\t\t\tinterval " << **i << " expired\n");
388             // remove from inactive
389             i = inactive_.erase(i);
390         }
391         // move re-activated intervals in active list
392         else if ((*i)->liveAt(cur->start())) {
393             DEBUG(std::cerr << "\t\t\tinterval " << **i << " active\n");
394             if (MRegisterInfo::isVirtualRegister(reg)) {
395                 reg = v2pMap_[reg];
396             }
397             prt_.addPhysRegUse(reg);
398             // add to active
399             active_.push_back(*i);
400             // remove from inactive
401             i = inactive_.erase(i);
402         }
403         else {
404             ++i;
405         }
406     }
407 }
408
409 void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
410 {
411     spillWeights_[reg] += weight;
412     for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
413         spillWeights_[*as] += weight;
414 }
415
416 void RA::assignRegOrStackSlotAtInterval(IntervalPtrs::value_type cur)
417 {
418     DEBUG(std::cerr << "\tallocating current interval:\n");
419
420     PhysRegTracker backupPrt = prt_;
421
422     spillWeights_.assign(mri_->getNumRegs(), 0.0);
423
424     // for each interval in active update spill weights
425     for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
426          i != e; ++i) {
427         unsigned reg = (*i)->reg;
428         if (MRegisterInfo::isVirtualRegister(reg))
429             reg = v2pMap_[reg];
430         updateSpillWeights(reg, (*i)->weight);
431     }
432
433     // for every interval in inactive we overlap with, mark the
434     // register as not free and update spill weights
435     for (IntervalPtrs::const_iterator i = inactive_.begin(),
436              e = inactive_.end(); i != e; ++i) {
437         if (cur->overlaps(**i)) {
438             unsigned reg = (*i)->reg;
439             if (MRegisterInfo::isVirtualRegister(reg))
440                 reg = v2pMap_[reg];
441             prt_.addPhysRegUse(reg);
442             updateSpillWeights(reg, (*i)->weight);
443         }
444     }
445
446     // for every interval in fixed we overlap with,
447     // mark the register as not free and update spill weights
448     for (IntervalPtrs::const_iterator i = fixed_.begin(),
449              e = fixed_.end(); i != e; ++i) {
450         if (cur->overlaps(**i)) {
451             unsigned reg = (*i)->reg;
452             prt_.addPhysRegUse(reg);
453             updateSpillWeights(reg, (*i)->weight);
454         }
455     }
456
457     unsigned physReg = getFreePhysReg(cur);
458     // restore the physical register tracker
459     prt_ = backupPrt;
460     // if we find a free register, we are done: assign this virtual to
461     // the free physical register and add this interval to the active
462     // list.
463     if (physReg) {
464         assignVirt2PhysReg(cur->reg, physReg);
465         active_.push_back(cur);
466         handled_.push_back(cur);
467         return;
468     }
469
470     DEBUG(std::cerr << "\t\tassigning stack slot at interval "<< *cur << ":\n");
471     // push the current interval back to unhandled since we are going
472     // to re-run at least this iteration
473     unhandled_.push_front(cur);
474
475     float minWeight = std::numeric_limits<float>::infinity();
476     unsigned minReg = 0;
477     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
478     for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
479          i != rc->allocation_order_end(*mf_); ++i) {
480         unsigned reg = *i;
481         if (minWeight > spillWeights_[reg]) {
482             minWeight = spillWeights_[reg];
483             minReg = reg;
484         }
485     }
486     DEBUG(std::cerr << "\t\t\tregister with min weight: "
487           << mri_->getName(minReg) << " (" << minWeight << ")\n");
488
489     // if the current has the minimum weight, we need to modify it,
490     // push it back in unhandled and let the linear scan algorithm run
491     // again
492     if (cur->weight < minWeight) {
493         DEBUG(std::cerr << "\t\t\t\tspilling(c): " << *cur;);
494         int slot = assignVirt2StackSlot(cur->reg);
495         li_->updateSpilledInterval(*cur);
496         addSpillCode(cur, slot);
497         DEBUG(std::cerr << "[ " << *cur << " ]\n");
498         return;
499     }
500
501     // otherwise we spill all intervals aliasing the register with
502     // minimum weight, rollback to the interval with the earliest
503     // start point and let the linear scan algorithm run again
504     std::vector<bool> toSpill(mri_->getNumRegs(), false);
505     toSpill[minReg] = true;
506     for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
507         toSpill[*as] = true;
508     unsigned earliestStart = cur->start();
509
510     for (IntervalPtrs::iterator i = active_.begin();
511          i != active_.end(); ++i) {
512         unsigned reg = (*i)->reg;
513         if (MRegisterInfo::isVirtualRegister(reg) &&
514             toSpill[v2pMap_[reg]] &&
515             cur->overlaps(**i)) {
516             DEBUG(std::cerr << "\t\t\t\tspilling(a): " << **i);
517             int slot = assignVirt2StackSlot((*i)->reg);
518             li_->updateSpilledInterval(**i);
519             addSpillCode(*i, slot);
520             DEBUG(std::cerr << "[ " << **i << " ]\n");
521             earliestStart = std::min(earliestStart, (*i)->start());
522         }
523     }
524     for (IntervalPtrs::iterator i = inactive_.begin();
525          i != inactive_.end(); ++i) {
526         unsigned reg = (*i)->reg;
527         if (MRegisterInfo::isVirtualRegister(reg) &&
528             toSpill[v2pMap_[reg]] &&
529             cur->overlaps(**i)) {
530             DEBUG(std::cerr << "\t\t\t\tspilling(i): " << **i << '\n');
531             int slot = assignVirt2StackSlot((*i)->reg);
532             li_->updateSpilledInterval(**i);
533             addSpillCode(*i, slot);
534             DEBUG(std::cerr << "[ " << **i << " ]\n");
535             earliestStart = std::min(earliestStart, (*i)->start());
536         }
537     }
538
539     DEBUG(std::cerr << "\t\t\t\trolling back to: " << earliestStart << '\n');
540     // scan handled in reverse order and undo each one, restoring the
541     // state of unhandled and fixed
542     while (!handled_.empty()) {
543         IntervalPtrs::value_type i = handled_.back();
544         // if this interval starts before t we are done
545         if (i->start() < earliestStart)
546             break;
547         DEBUG(std::cerr << "\t\t\t\t\tundo changes for: " << *i << '\n');
548         handled_.pop_back();
549         IntervalPtrs::iterator it;
550         if ((it = find(active_.begin(), active_.end(), i)) != active_.end()) {
551             active_.erase(it);
552             if (MRegisterInfo::isPhysicalRegister(i->reg)) {
553                 fixed_.push_front(i);
554                 prt_.delPhysRegUse(i->reg);
555             }
556             else {
557                 Virt2PhysMap::iterator v2pIt = v2pMap_.find(i->reg);
558                 clearVirtReg(v2pIt);
559                 unhandled_.push_front(i);
560                 prt_.delPhysRegUse(v2pIt->second);
561             }
562         }
563         else if ((it = find(inactive_.begin(), inactive_.end(), i)) != inactive_.end()) {
564             inactive_.erase(it);
565             if (MRegisterInfo::isPhysicalRegister(i->reg))
566                 fixed_.push_front(i);
567             else {
568                 Virt2PhysMap::iterator v2pIt = v2pMap_.find(i->reg);
569                 clearVirtReg(v2pIt);
570                 unhandled_.push_front(i);
571             }
572         }
573         else {
574             if (MRegisterInfo::isPhysicalRegister(i->reg))
575                 fixed_.push_front(i);
576             else {
577                 Virt2PhysMap::iterator v2pIt = v2pMap_.find(i->reg);
578                 clearVirtReg(v2pIt);
579                 unhandled_.push_front(i);
580             }
581         }
582     }
583
584     // scan the rest and undo each interval that expired after t and
585     // insert it in active (the next iteration of the algorithm will
586     // put it in inactive if required)
587     IntervalPtrs::iterator i = handled_.begin(), e = handled_.end();
588     for (; i != e; ++i) {
589         if (!(*i)->expiredAt(earliestStart) && (*i)->expiredAt(cur->start())) {
590             DEBUG(std::cerr << "\t\t\t\t\tundo changes for: " << **i << '\n');
591             active_.push_back(*i);
592             if (MRegisterInfo::isPhysicalRegister((*i)->reg))
593                 prt_.addPhysRegUse((*i)->reg);
594             else {
595                 assert(v2pMap_.count((*i)->reg));
596                 prt_.addPhysRegUse(v2pMap_.find((*i)->reg)->second);
597             }
598         }
599     }
600 }
601
602 void RA::addSpillCode(IntervalPtrs::value_type li, int slot)
603 {
604     // We scan the instructions corresponding to each range. We load
605     // when we have a use and spill at end of basic blocks or end of
606     // ranges only if the register was modified.
607     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li->reg);
608
609     for (LiveIntervals::Interval::Ranges::iterator i = li->ranges.begin(),
610              e = li->ranges.end(); i != e; ++i) {
611         unsigned index = i->first & ~1;
612         unsigned end = i->second;
613
614     entry:
615         bool dirty = false, loaded = false;
616
617         // skip deleted instructions. getInstructionFromIndex returns
618         // null if the instruction was deleted (because of coalescing
619         // for example)
620         while (!li_->getInstructionFromIndex(index)) index += 2;
621         MachineBasicBlock::iterator mi = li_->getInstructionFromIndex(index);
622         MachineBasicBlock* mbb = mi->getParent();
623
624         for (; index < end; index += 2) {
625             // ignore deleted instructions
626             while (!li_->getInstructionFromIndex(index)) index += 2;
627
628             // if we changed basic block we need to start over
629             mi = li_->getInstructionFromIndex(index);
630             if (mbb != mi->getParent()) {
631                 if (dirty) {
632                     mi = li_->getInstructionFromIndex(index-2);
633                     assert(mbb == mi->getParent() &&
634                            "rewound to wrong instruction?");
635                     DEBUG(std::cerr << "add store for reg" << li->reg << " to "
636                           "stack slot " << slot << " after: ";
637                           mi->print(std::cerr, *tm_));
638                     ++numSpilled;
639                     mri_->storeRegToStackSlot(*mi->getParent(),
640                                               next(mi), li->reg, slot, rc);
641                 }
642                 goto entry;
643             }
644
645             // if it is used in this instruction load it
646             for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
647                 MachineOperand& mop = mi->getOperand(i);
648                 if (mop.isRegister() && mop.getReg() == li->reg &&
649                     mop.isUse() && !loaded) {
650                     loaded = true;
651                     DEBUG(std::cerr << "add load for reg" << li->reg
652                           << " from stack slot " << slot << " before: ";
653                           mi->print(std::cerr, *tm_));
654                     ++numReloaded;
655                     mri_->loadRegFromStackSlot(*mi->getParent(),
656                                                mi, li->reg, slot, rc);
657                 }
658             }
659
660             // if it is defined in this instruction mark as dirty
661             for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
662                 MachineOperand& mop = mi->getOperand(i);
663                 if (mop.isRegister() && mop.getReg() == li->reg &&
664                     mop.isDef())
665                     dirty = loaded = true;
666             }
667         }
668         if (dirty) {
669             mi = li_->getInstructionFromIndex(index-2);
670             assert(mbb == mi->getParent() &&
671                    "rewound to wrong instruction?");
672             DEBUG(std::cerr << "add store for reg" << li->reg << " to "
673                   "stack slot " << slot << " after: ";
674                   mi->print(std::cerr, *tm_));
675             ++numSpilled;
676             mri_->storeRegToStackSlot(*mi->getParent(),
677                                       next(mi), li->reg, slot, rc);
678         }
679     }
680 }
681
682 unsigned RA::getFreePhysReg(IntervalPtrs::value_type cur)
683 {
684     DEBUG(std::cerr << "\t\tgetting free physical register: ");
685     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
686
687     for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
688          i != rc->allocation_order_end(*mf_); ++i) {
689         unsigned reg = *i;
690         if (prt_.isPhysRegAvail(reg)) {
691             DEBUG(std::cerr << mri_->getName(reg) << '\n');
692             return reg;
693         }
694     }
695
696     DEBUG(std::cerr << "no free register\n");
697     return 0;
698 }
699
700 RA::Virt2PhysMap::iterator
701 RA::assignVirt2PhysReg(unsigned virtReg, unsigned physReg)
702 {
703     bool inserted;
704     Virt2PhysMap::iterator it;
705     tie(it, inserted) = v2pMap_.insert(std::make_pair(virtReg, physReg));
706     assert(inserted && "attempting to assign a virt->phys mapping to an "
707            "already mapped register");
708     prt_.addPhysRegUse(physReg);
709     return it;
710 }
711
712 void RA::clearVirtReg(Virt2PhysMap::iterator it)
713 {
714     assert(it != v2pMap_.end() &&
715            "attempting to clear a not allocated virtual register");
716     unsigned physReg = it->second;
717     v2pMap_.erase(it);
718     DEBUG(std::cerr << "\t\t\tcleared register " << mri_->getName(physReg)
719           << "\n");
720 }
721
722
723 int RA::assignVirt2StackSlot(unsigned virtReg)
724 {
725     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
726     int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc);
727
728     bool inserted = v2ssMap_.insert(std::make_pair(virtReg, frameIndex)).second;
729     assert(inserted && "attempt to assign stack slot to spilled register!");
730     return frameIndex;
731 }
732
733 int RA::getStackSlot(unsigned virtReg)
734 {
735     assert(v2ssMap_.count(virtReg) &&
736            "attempt to get stack slot for a non spilled register");
737     return v2ssMap_.find(virtReg)->second;
738 }
739
740 FunctionPass* llvm::createLinearScanRegisterAllocator() {
741     return new RA();
742 }