1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/Function.h"
16 #include "llvm/CodeGen/LiveVariables.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/MRegisterInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "Support/Debug.h"
24 #include "Support/Statistic.h"
25 #include "Support/STLExtras.h"
26 #include "LiveIntervals.h"
27 #include "PhysRegTracker.h"
28 #include "VirtRegMap.h"
38 Statistic<double> efficiency
39 ("regalloc", "Ratio of intervals processed over total intervals");
41 static unsigned numIterations = 0;
42 static unsigned numIntervals = 0;
44 class RA : public MachineFunctionPass {
47 const TargetMachine* tm_;
48 const MRegisterInfo* mri_;
50 typedef std::list<LiveInterval*> IntervalPtrs;
51 IntervalPtrs unhandled_, fixed_, active_, inactive_, handled_;
53 std::auto_ptr<PhysRegTracker> prt_;
54 std::auto_ptr<VirtRegMap> vrm_;
55 std::auto_ptr<Spiller> spiller_;
57 typedef std::vector<float> SpillWeights;
58 SpillWeights spillWeights_;
61 virtual const char* getPassName() const {
62 return "Linear Scan Register Allocator";
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<LiveVariables>();
67 AU.addRequired<LiveIntervals>();
68 MachineFunctionPass::getAnalysisUsage(AU);
71 /// runOnMachineFunction - register allocate the whole function
72 bool runOnMachineFunction(MachineFunction&);
77 /// linearScan - the linear scan algorithm
80 /// initIntervalSets - initializa the four interval sets:
81 /// unhandled, fixed, active and inactive
82 void initIntervalSets(LiveIntervals::Intervals& li);
84 /// processActiveIntervals - expire old intervals and move
85 /// non-overlapping ones to the incative list
86 void processActiveIntervals(IntervalPtrs::value_type cur);
88 /// processInactiveIntervals - expire old intervals and move
89 /// overlapping ones to the active list
90 void processInactiveIntervals(IntervalPtrs::value_type cur);
92 /// updateSpillWeights - updates the spill weights of the
93 /// specifed physical register and its weight
94 void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
96 /// assignRegOrStackSlotAtInterval - assign a register if one
97 /// is available, or spill.
98 void assignRegOrStackSlotAtInterval(IntervalPtrs::value_type cur);
101 /// register handling helpers
104 /// getFreePhysReg - return a free physical register for this
105 /// virtual register interval if we have one, otherwise return
107 unsigned getFreePhysReg(IntervalPtrs::value_type cur);
109 /// assignVirt2StackSlot - assigns this virtual register to a
110 /// stack slot. returns the stack slot
111 int assignVirt2StackSlot(unsigned virtReg);
113 void printIntervals(const char* const str,
114 RA::IntervalPtrs::const_iterator i,
115 RA::IntervalPtrs::const_iterator e) const {
116 if (str) std::cerr << str << " intervals:\n";
117 for (; i != e; ++i) {
118 std::cerr << "\t" << **i << " -> ";
119 unsigned reg = (*i)->reg;
120 if (MRegisterInfo::isVirtualRegister(reg)) {
121 reg = vrm_->getPhys(reg);
123 std::cerr << mri_->getName(reg) << '\n';
127 // void verifyAssignment() const {
128 // for (Virt2PhysMap::const_iterator i = v2pMap_.begin(),
129 // e = v2pMap_.end(); i != e; ++i)
130 // for (Virt2PhysMap::const_iterator i2 = next(i); i2 != e; ++i2)
131 // if (MRegisterInfo::isVirtualRegister(i->second) &&
132 // (i->second == i2->second ||
133 // mri_->areAliases(i->second, i2->second))) {
135 // &in = li_->getInterval(i->second),
136 // &in2 = li_->getInterval(i2->second);
137 // if (in.overlaps(in2)) {
138 // std::cerr << in << " overlaps " << in2 << '\n';
146 void RA::releaseMemory()
155 bool RA::runOnMachineFunction(MachineFunction &fn) {
157 tm_ = &fn.getTarget();
158 mri_ = tm_->getRegisterInfo();
159 li_ = &getAnalysis<LiveIntervals>();
160 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
161 vrm_.reset(new VirtRegMap(*mf_));
162 if (!spiller_.get()) spiller_.reset(createSpiller());
164 initIntervalSets(li_->getIntervals());
168 spiller_->runOnMachineFunction(*mf_, *vrm_);
173 void RA::linearScan()
175 // linear scan algorithm
176 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
177 DEBUG(std::cerr << "********** Function: "
178 << mf_->getFunction()->getName() << '\n');
180 DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
181 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
182 DEBUG(printIntervals("active", active_.begin(), active_.end()));
183 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
185 while (!unhandled_.empty()) {
186 // pick the interval with the earliest start point
187 IntervalPtrs::value_type cur = unhandled_.front();
188 unhandled_.pop_front();
190 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
192 processActiveIntervals(cur);
193 processInactiveIntervals(cur);
195 // if this register is fixed we are done
196 if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
197 prt_->addRegUse(cur->reg);
198 active_.push_back(cur);
199 handled_.push_back(cur);
201 // otherwise we are allocating a virtual register. try to find
202 // a free physical register or spill an interval in order to
203 // assign it one (we could spill the current though).
205 assignRegOrStackSlotAtInterval(cur);
208 DEBUG(printIntervals("active", active_.begin(), active_.end()));
209 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
210 // DEBUG(verifyAssignment());
212 numIntervals += li_->getIntervals().size();
213 efficiency = double(numIterations) / double(numIntervals);
215 // expire any remaining active intervals
216 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
217 unsigned reg = (*i)->reg;
218 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
219 if (MRegisterInfo::isVirtualRegister(reg))
220 reg = vrm_->getPhys(reg);
221 prt_->delRegUse(reg);
224 DEBUG(std::cerr << *vrm_);
227 void RA::initIntervalSets(LiveIntervals::Intervals& li)
229 assert(unhandled_.empty() && fixed_.empty() &&
230 active_.empty() && inactive_.empty() &&
231 "interval sets should be empty on initialization");
233 for (LiveIntervals::Intervals::iterator i = li.begin(), e = li.end();
235 unhandled_.push_back(&*i);
236 if (MRegisterInfo::isPhysicalRegister(i->reg))
237 fixed_.push_back(&*i);
241 void RA::processActiveIntervals(IntervalPtrs::value_type cur)
243 DEBUG(std::cerr << "\tprocessing active intervals:\n");
244 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end();) {
245 unsigned reg = (*i)->reg;
246 // remove expired intervals
247 if ((*i)->expiredAt(cur->start())) {
248 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
249 if (MRegisterInfo::isVirtualRegister(reg))
250 reg = vrm_->getPhys(reg);
251 prt_->delRegUse(reg);
252 // remove from active
253 i = active_.erase(i);
255 // move inactive intervals to inactive list
256 else if (!(*i)->liveAt(cur->start())) {
257 DEBUG(std::cerr << "\t\tinterval " << **i << " inactive\n");
258 if (MRegisterInfo::isVirtualRegister(reg))
259 reg = vrm_->getPhys(reg);
260 prt_->delRegUse(reg);
262 inactive_.push_back(*i);
263 // remove from active
264 i = active_.erase(i);
272 void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
274 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
275 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end();) {
276 unsigned reg = (*i)->reg;
278 // remove expired intervals
279 if ((*i)->expiredAt(cur->start())) {
280 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
281 // remove from inactive
282 i = inactive_.erase(i);
284 // move re-activated intervals in active list
285 else if ((*i)->liveAt(cur->start())) {
286 DEBUG(std::cerr << "\t\tinterval " << **i << " active\n");
287 if (MRegisterInfo::isVirtualRegister(reg))
288 reg = vrm_->getPhys(reg);
289 prt_->addRegUse(reg);
291 active_.push_back(*i);
292 // remove from inactive
293 i = inactive_.erase(i);
301 void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
303 spillWeights_[reg] += weight;
304 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
305 spillWeights_[*as] += weight;
308 void RA::assignRegOrStackSlotAtInterval(IntervalPtrs::value_type cur)
310 DEBUG(std::cerr << "\tallocating current interval: ");
312 PhysRegTracker backupPrt = *prt_;
314 spillWeights_.assign(mri_->getNumRegs(), 0.0);
316 // for each interval in active update spill weights
317 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
319 unsigned reg = (*i)->reg;
320 if (MRegisterInfo::isVirtualRegister(reg))
321 reg = vrm_->getPhys(reg);
322 updateSpillWeights(reg, (*i)->weight);
325 // for every interval in inactive we overlap with, mark the
326 // register as not free and update spill weights
327 for (IntervalPtrs::const_iterator i = inactive_.begin(),
328 e = inactive_.end(); i != e; ++i) {
329 if (cur->overlaps(**i)) {
330 unsigned reg = (*i)->reg;
331 if (MRegisterInfo::isVirtualRegister(reg))
332 reg = vrm_->getPhys(reg);
333 prt_->addRegUse(reg);
334 updateSpillWeights(reg, (*i)->weight);
338 // for every interval in fixed we overlap with,
339 // mark the register as not free and update spill weights
340 for (IntervalPtrs::const_iterator i = fixed_.begin(),
341 e = fixed_.end(); i != e; ++i) {
342 if (cur->overlaps(**i)) {
343 unsigned reg = (*i)->reg;
344 prt_->addRegUse(reg);
345 updateSpillWeights(reg, (*i)->weight);
349 unsigned physReg = getFreePhysReg(cur);
350 // restore the physical register tracker
352 // if we find a free register, we are done: assign this virtual to
353 // the free physical register and add this interval to the active
356 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
357 vrm_->assignVirt2Phys(cur->reg, physReg);
358 prt_->addRegUse(physReg);
359 active_.push_back(cur);
360 handled_.push_back(cur);
363 DEBUG(std::cerr << "no free registers\n");
365 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
367 float minWeight = HUGE_VAL;
369 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
370 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
371 i != rc->allocation_order_end(*mf_); ++i) {
373 if (minWeight > spillWeights_[reg]) {
374 minWeight = spillWeights_[reg];
378 DEBUG(std::cerr << "\t\tregister with min weight: "
379 << mri_->getName(minReg) << " (" << minWeight << ")\n");
381 // if the current has the minimum weight, we need to spill it and
382 // add any added intervals back to unhandled, and restart
384 if (cur->weight <= minWeight) {
385 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
386 int slot = vrm_->assignVirt2StackSlot(cur->reg);
387 std::vector<LiveInterval*> added =
388 li_->addIntervalsForSpills(*cur, *vrm_, slot);
390 // merge added with unhandled
391 std::vector<LiveInterval*>::iterator addedIt = added.begin();
392 std::vector<LiveInterval*>::iterator addedItEnd = added.end();
393 for (IntervalPtrs::iterator i = unhandled_.begin(), e = unhandled_.end();
394 i != e && addedIt != addedItEnd; ++i) {
395 if ((*i)->start() > (*addedIt)->start())
396 i = unhandled_.insert(i, *(addedIt++));
398 while (addedIt != addedItEnd)
399 unhandled_.push_back(*(addedIt++));
404 // push the current interval back to unhandled since we are going
405 // to re-run at least this iteration. Since we didn't modify it it
406 // should go back right in the front of the list
407 unhandled_.push_front(cur);
409 // otherwise we spill all intervals aliasing the register with
410 // minimum weight, rollback to the interval with the earliest
411 // start point and let the linear scan algorithm run again
412 std::vector<LiveInterval*> added;
413 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
414 "did not choose a register to spill?");
415 std::vector<bool> toSpill(mri_->getNumRegs(), false);
416 toSpill[minReg] = true;
417 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
419 unsigned earliestStart = cur->start();
421 std::set<unsigned> spilled;
423 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
424 unsigned reg = (*i)->reg;
425 if (MRegisterInfo::isVirtualRegister(reg) &&
426 toSpill[vrm_->getPhys(reg)] &&
427 cur->overlaps(**i)) {
428 DEBUG(std::cerr << "\t\t\tspilling(a): " << **i << '\n');
429 earliestStart = std::min(earliestStart, (*i)->start());
430 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
431 std::vector<LiveInterval*> newIs =
432 li_->addIntervalsForSpills(**i, *vrm_, slot);
433 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
437 for (IntervalPtrs::iterator i = inactive_.begin();
438 i != inactive_.end(); ++i) {
439 unsigned reg = (*i)->reg;
440 if (MRegisterInfo::isVirtualRegister(reg) &&
441 toSpill[vrm_->getPhys(reg)] &&
442 cur->overlaps(**i)) {
443 DEBUG(std::cerr << "\t\t\tspilling(i): " << **i << '\n');
444 earliestStart = std::min(earliestStart, (*i)->start());
445 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
446 std::vector<LiveInterval*> newIs =
447 li_->addIntervalsForSpills(**i, *vrm_, slot);
448 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
453 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
454 // scan handled in reverse order and undo each one, restoring the
455 // state of unhandled
456 while (!handled_.empty()) {
457 IntervalPtrs::value_type i = handled_.back();
458 // if this interval starts before t we are done
459 if (i->start() < earliestStart)
461 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
463 IntervalPtrs::iterator it;
464 if ((it = find(active_.begin(), active_.end(), i)) != active_.end()) {
466 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
467 prt_->delRegUse(i->reg);
468 unhandled_.push_front(i);
471 if (!spilled.count(i->reg))
472 unhandled_.push_front(i);
473 prt_->delRegUse(vrm_->getPhys(i->reg));
474 vrm_->clearVirt(i->reg);
477 else if ((it = find(inactive_.begin(), inactive_.end(), i)) != inactive_.end()) {
479 if (MRegisterInfo::isPhysicalRegister(i->reg))
480 unhandled_.push_front(i);
482 if (!spilled.count(i->reg))
483 unhandled_.push_front(i);
484 vrm_->clearVirt(i->reg);
488 if (MRegisterInfo::isVirtualRegister(i->reg))
489 vrm_->clearVirt(i->reg);
490 unhandled_.push_front(i);
494 // scan the rest and undo each interval that expired after t and
495 // insert it in active (the next iteration of the algorithm will
496 // put it in inactive if required)
497 IntervalPtrs::iterator i = handled_.begin(), e = handled_.end();
498 for (; i != e; ++i) {
499 if (!(*i)->expiredAt(earliestStart) && (*i)->expiredAt(cur->start())) {
500 DEBUG(std::cerr << "\t\t\tundo changes for: " << **i << '\n');
501 active_.push_back(*i);
502 if (MRegisterInfo::isPhysicalRegister((*i)->reg))
503 prt_->addRegUse((*i)->reg);
505 prt_->addRegUse(vrm_->getPhys((*i)->reg));
509 std::sort(added.begin(), added.end(), less_ptr<LiveInterval>());
510 // merge added with unhandled
511 std::vector<LiveInterval*>::iterator addedIt = added.begin();
512 std::vector<LiveInterval*>::iterator addedItEnd = added.end();
513 for (IntervalPtrs::iterator i = unhandled_.begin(), e = unhandled_.end();
514 i != e && addedIt != addedItEnd; ++i) {
515 if ((*i)->start() > (*addedIt)->start())
516 i = unhandled_.insert(i, *(addedIt++));
518 while (addedIt != addedItEnd)
519 unhandled_.push_back(*(addedIt++));
523 unsigned RA::getFreePhysReg(IntervalPtrs::value_type cur)
525 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
527 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
528 i != rc->allocation_order_end(*mf_); ++i) {
530 if (prt_->isRegAvail(reg))
536 FunctionPass* llvm::createLinearScanRegisterAllocator() {