blob: 01d43fd908e7897db562f3cc1a3b1f1cf4e7b498 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- 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
14#define DEBUG_TYPE "regalloc"
15#include "llvm/CodeGen/LiveVariables.h"
16#include "llvm/CodeGen/LiveIntervalAnalysis.h"
17#include "PhysRegTracker.h"
18#include "VirtRegMap.h"
19#include "llvm/Function.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/CodeGen/RegAllocRegistry.h"
24#include "llvm/CodeGen/SSARegMap.h"
25#include "llvm/Target/MRegisterInfo.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/ADT/EquivalenceClasses.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/Compiler.h"
32#include <algorithm>
33#include <set>
34#include <queue>
35#include <memory>
36#include <cmath>
37using namespace llvm;
38
39STATISTIC(NumIters , "Number of iterations performed");
40STATISTIC(NumBacktracks, "Number of times we had to backtrack");
41
42static RegisterRegAlloc
43linearscanRegAlloc("linearscan", " linear scan register allocator",
44 createLinearScanRegisterAllocator);
45
46namespace {
47 static unsigned numIterations = 0;
48 static unsigned numIntervals = 0;
49
50 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
51 static char ID;
52 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
53
54 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
56 private:
57 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
61 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62
63 MachineFunction* mf_;
64 const TargetMachine* tm_;
65 const MRegisterInfo* mri_;
66 LiveIntervals* li_;
67
68 /// handled_ - Intervals are added to the handled_ set in the order of their
69 /// start value. This is uses for backtracking.
70 std::vector<LiveInterval*> handled_;
71
72 /// fixed_ - Intervals that correspond to machine registers.
73 ///
74 IntervalPtrs fixed_;
75
76 /// active_ - Intervals that are currently being processed, and which have a
77 /// live range active for the current point.
78 IntervalPtrs active_;
79
80 /// inactive_ - Intervals that are currently being processed, but which have
81 /// a hold at the current point.
82 IntervalPtrs inactive_;
83
84 typedef std::priority_queue<LiveInterval*,
85 std::vector<LiveInterval*>,
86 greater_ptr<LiveInterval> > IntervalHeap;
87 IntervalHeap unhandled_;
88 std::auto_ptr<PhysRegTracker> prt_;
89 std::auto_ptr<VirtRegMap> vrm_;
90 std::auto_ptr<Spiller> spiller_;
91
92 public:
93 virtual const char* getPassName() const {
94 return "Linear Scan Register Allocator";
95 }
96
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
98 AU.addRequired<LiveIntervals>();
99 AU.addRequiredID(SimpleRegisterCoalescingID);
100 MachineFunctionPass::getAnalysisUsage(AU);
101 }
102
103 /// runOnMachineFunction - register allocate the whole function
104 bool runOnMachineFunction(MachineFunction&);
105
106 private:
107 /// linearScan - the linear scan algorithm
108 void linearScan();
109
110 /// initIntervalSets - initialize the interval sets.
111 ///
112 void initIntervalSets();
113
114 /// processActiveIntervals - expire old intervals and move non-overlapping
115 /// ones to the inactive list.
116 void processActiveIntervals(unsigned CurPoint);
117
118 /// processInactiveIntervals - expire old intervals and move overlapping
119 /// ones to the active list.
120 void processInactiveIntervals(unsigned CurPoint);
121
122 /// assignRegOrStackSlotAtInterval - assign a register if one
123 /// is available, or spill.
124 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
125
126 ///
127 /// register handling helpers
128 ///
129
130 /// getFreePhysReg - return a free physical register for this virtual
131 /// register interval if we have one, otherwise return 0.
132 unsigned getFreePhysReg(LiveInterval* cur);
133
134 /// assignVirt2StackSlot - assigns this virtual register to a
135 /// stack slot. returns the stack slot
136 int assignVirt2StackSlot(unsigned virtReg);
137
138 void ComputeRelatedRegClasses();
139
140 template <typename ItTy>
141 void printIntervals(const char* const str, ItTy i, ItTy e) const {
142 if (str) DOUT << str << " intervals:\n";
143 for (; i != e; ++i) {
144 DOUT << "\t" << *i->first << " -> ";
145 unsigned reg = i->first->reg;
146 if (MRegisterInfo::isVirtualRegister(reg)) {
147 reg = vrm_->getPhys(reg);
148 }
149 DOUT << mri_->getName(reg) << '\n';
150 }
151 }
152 };
153 char RALinScan::ID = 0;
154}
155
156void RALinScan::ComputeRelatedRegClasses() {
157 const MRegisterInfo &MRI = *mri_;
158
159 // First pass, add all reg classes to the union, and determine at least one
160 // reg class that each register is in.
161 bool HasAliases = false;
162 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
163 E = MRI.regclass_end(); RCI != E; ++RCI) {
164 RelatedRegClasses.insert(*RCI);
165 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
166 I != E; ++I) {
167 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
168
169 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
170 if (PRC) {
171 // Already processed this register. Just make sure we know that
172 // multiple register classes share a register.
173 RelatedRegClasses.unionSets(PRC, *RCI);
174 } else {
175 PRC = *RCI;
176 }
177 }
178 }
179
180 // Second pass, now that we know conservatively what register classes each reg
181 // belongs to, add info about aliases. We don't need to do this for targets
182 // without register aliases.
183 if (HasAliases)
184 for (std::map<unsigned, const TargetRegisterClass*>::iterator
185 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
186 I != E; ++I)
187 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
188 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
189}
190
191bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
192 mf_ = &fn;
193 tm_ = &fn.getTarget();
194 mri_ = tm_->getRegisterInfo();
195 li_ = &getAnalysis<LiveIntervals>();
196
197 // If this is the first function compiled, compute the related reg classes.
198 if (RelatedRegClasses.empty())
199 ComputeRelatedRegClasses();
200
201 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
202 vrm_.reset(new VirtRegMap(*mf_));
203 if (!spiller_.get()) spiller_.reset(createSpiller());
204
205 initIntervalSets();
206
207 linearScan();
208
209 // Rewrite spill code and update the PhysRegsUsed set.
210 spiller_->runOnMachineFunction(*mf_, *vrm_);
211
212 vrm_.reset(); // Free the VirtRegMap
213
214
215 while (!unhandled_.empty()) unhandled_.pop();
216 fixed_.clear();
217 active_.clear();
218 inactive_.clear();
219 handled_.clear();
220
221 return true;
222}
223
224/// initIntervalSets - initialize the interval sets.
225///
226void RALinScan::initIntervalSets()
227{
228 assert(unhandled_.empty() && fixed_.empty() &&
229 active_.empty() && inactive_.empty() &&
230 "interval sets should be empty on initialization");
231
232 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
233 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
234 mf_->setPhysRegUsed(i->second.reg);
235 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
236 } else
237 unhandled_.push(&i->second);
238 }
239}
240
241void RALinScan::linearScan()
242{
243 // linear scan algorithm
244 DOUT << "********** LINEAR SCAN **********\n";
245 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
246
247 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
248 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
249 DEBUG(printIntervals("active", active_.begin(), active_.end()));
250 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
251
252 while (!unhandled_.empty()) {
253 // pick the interval with the earliest start point
254 LiveInterval* cur = unhandled_.top();
255 unhandled_.pop();
256 ++numIterations;
257 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
258
259 processActiveIntervals(cur->beginNumber());
260 processInactiveIntervals(cur->beginNumber());
261
262 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
263 "Can only allocate virtual registers!");
264
265 // Allocating a virtual register. try to find a free
266 // physical register or spill an interval (possibly this one) in order to
267 // assign it one.
268 assignRegOrStackSlotAtInterval(cur);
269
270 DEBUG(printIntervals("active", active_.begin(), active_.end()));
271 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
272 }
273 numIntervals += li_->getNumIntervals();
274 NumIters += numIterations;
275
276 // expire any remaining active intervals
277 for (IntervalPtrs::reverse_iterator
278 i = active_.rbegin(); i != active_.rend(); ) {
279 unsigned reg = i->first->reg;
280 DOUT << "\tinterval " << *i->first << " expired\n";
281 assert(MRegisterInfo::isVirtualRegister(reg) &&
282 "Can only allocate virtual registers!");
283 reg = vrm_->getPhys(reg);
284 prt_->delRegUse(reg);
285 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
286 }
287
288 // expire any remaining inactive intervals
289 for (IntervalPtrs::reverse_iterator
290 i = inactive_.rbegin(); i != inactive_.rend(); ) {
291 DOUT << "\tinterval " << *i->first << " expired\n";
292 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
293 }
294
295 // A brute force way of adding live-ins to every BB.
296 MachineFunction::iterator MBB = mf_->begin();
297 ++MBB; // Skip entry MBB.
298 for (MachineFunction::iterator E = mf_->end(); MBB != E; ++MBB) {
299 unsigned StartIdx = li_->getMBBStartIdx(MBB->getNumber());
300 for (IntervalPtrs::iterator i = fixed_.begin(), e = fixed_.end();
301 i != e; ++i)
302 if (i->first->liveAt(StartIdx))
303 MBB->addLiveIn(i->first->reg);
304
305 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
306 LiveInterval *HI = handled_[i];
307 unsigned Reg = HI->reg;
308 if (!vrm_->hasStackSlot(Reg) && HI->liveAt(StartIdx)) {
309 assert(MRegisterInfo::isVirtualRegister(Reg));
310 Reg = vrm_->getPhys(Reg);
311 MBB->addLiveIn(Reg);
312 }
313 }
314 }
315
316 DOUT << *vrm_;
317}
318
319/// processActiveIntervals - expire old intervals and move non-overlapping ones
320/// to the inactive list.
321void RALinScan::processActiveIntervals(unsigned CurPoint)
322{
323 DOUT << "\tprocessing active intervals:\n";
324
325 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
326 LiveInterval *Interval = active_[i].first;
327 LiveInterval::iterator IntervalPos = active_[i].second;
328 unsigned reg = Interval->reg;
329
330 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
331
332 if (IntervalPos == Interval->end()) { // Remove expired intervals.
333 DOUT << "\t\tinterval " << *Interval << " expired\n";
334 assert(MRegisterInfo::isVirtualRegister(reg) &&
335 "Can only allocate virtual registers!");
336 reg = vrm_->getPhys(reg);
337 prt_->delRegUse(reg);
338
339 // Pop off the end of the list.
340 active_[i] = active_.back();
341 active_.pop_back();
342 --i; --e;
343
344 } else if (IntervalPos->start > CurPoint) {
345 // Move inactive intervals to inactive list.
346 DOUT << "\t\tinterval " << *Interval << " inactive\n";
347 assert(MRegisterInfo::isVirtualRegister(reg) &&
348 "Can only allocate virtual registers!");
349 reg = vrm_->getPhys(reg);
350 prt_->delRegUse(reg);
351 // add to inactive.
352 inactive_.push_back(std::make_pair(Interval, IntervalPos));
353
354 // Pop off the end of the list.
355 active_[i] = active_.back();
356 active_.pop_back();
357 --i; --e;
358 } else {
359 // Otherwise, just update the iterator position.
360 active_[i].second = IntervalPos;
361 }
362 }
363}
364
365/// processInactiveIntervals - expire old intervals and move overlapping
366/// ones to the active list.
367void RALinScan::processInactiveIntervals(unsigned CurPoint)
368{
369 DOUT << "\tprocessing inactive intervals:\n";
370
371 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
372 LiveInterval *Interval = inactive_[i].first;
373 LiveInterval::iterator IntervalPos = inactive_[i].second;
374 unsigned reg = Interval->reg;
375
376 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
377
378 if (IntervalPos == Interval->end()) { // remove expired intervals.
379 DOUT << "\t\tinterval " << *Interval << " expired\n";
380
381 // Pop off the end of the list.
382 inactive_[i] = inactive_.back();
383 inactive_.pop_back();
384 --i; --e;
385 } else if (IntervalPos->start <= CurPoint) {
386 // move re-activated intervals in active list
387 DOUT << "\t\tinterval " << *Interval << " active\n";
388 assert(MRegisterInfo::isVirtualRegister(reg) &&
389 "Can only allocate virtual registers!");
390 reg = vrm_->getPhys(reg);
391 prt_->addRegUse(reg);
392 // add to active
393 active_.push_back(std::make_pair(Interval, IntervalPos));
394
395 // Pop off the end of the list.
396 inactive_[i] = inactive_.back();
397 inactive_.pop_back();
398 --i; --e;
399 } else {
400 // Otherwise, just update the iterator position.
401 inactive_[i].second = IntervalPos;
402 }
403 }
404}
405
406/// updateSpillWeights - updates the spill weights of the specifed physical
407/// register and its weight.
408static void updateSpillWeights(std::vector<float> &Weights,
409 unsigned reg, float weight,
410 const MRegisterInfo *MRI) {
411 Weights[reg] += weight;
412 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
413 Weights[*as] += weight;
414}
415
416static
417RALinScan::IntervalPtrs::iterator
418FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
419 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
420 I != E; ++I)
421 if (I->first == LI) return I;
422 return IP.end();
423}
424
425static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
426 for (unsigned i = 0, e = V.size(); i != e; ++i) {
427 RALinScan::IntervalPtr &IP = V[i];
428 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
429 IP.second, Point);
430 if (I != IP.first->begin()) --I;
431 IP.second = I;
432 }
433}
434
435/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
436/// spill.
437void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
438{
439 DOUT << "\tallocating current interval: ";
440
441 PhysRegTracker backupPrt = *prt_;
442
443 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
444 unsigned StartPosition = cur->beginNumber();
445 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
446 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
447
448 // for every interval in inactive we overlap with, mark the
449 // register as not free and update spill weights.
450 for (IntervalPtrs::const_iterator i = inactive_.begin(),
451 e = inactive_.end(); i != e; ++i) {
452 unsigned Reg = i->first->reg;
453 assert(MRegisterInfo::isVirtualRegister(Reg) &&
454 "Can only allocate virtual registers!");
455 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
456 // If this is not in a related reg class to the register we're allocating,
457 // don't check it.
458 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
459 cur->overlapsFrom(*i->first, i->second-1)) {
460 Reg = vrm_->getPhys(Reg);
461 prt_->addRegUse(Reg);
462 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
463 }
464 }
465
466 // Speculatively check to see if we can get a register right now. If not,
467 // we know we won't be able to by adding more constraints. If so, we can
468 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
469 // is very bad (it contains all callee clobbered registers for any functions
470 // with a call), so we want to avoid doing that if possible.
471 unsigned physReg = getFreePhysReg(cur);
472 if (physReg) {
473 // We got a register. However, if it's in the fixed_ list, we might
474 // conflict with it. Check to see if we conflict with it or any of its
475 // aliases.
476 std::set<unsigned> RegAliases;
477 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
478 RegAliases.insert(*AS);
479
480 bool ConflictsWithFixed = false;
481 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
482 IntervalPtr &IP = fixed_[i];
483 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
484 // Okay, this reg is on the fixed list. Check to see if we actually
485 // conflict.
486 LiveInterval *I = IP.first;
487 if (I->endNumber() > StartPosition) {
488 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
489 IP.second = II;
490 if (II != I->begin() && II->start > StartPosition)
491 --II;
492 if (cur->overlapsFrom(*I, II)) {
493 ConflictsWithFixed = true;
494 break;
495 }
496 }
497 }
498 }
499
500 // Okay, the register picked by our speculative getFreePhysReg call turned
501 // out to be in use. Actually add all of the conflicting fixed registers to
502 // prt so we can do an accurate query.
503 if (ConflictsWithFixed) {
504 // For every interval in fixed we overlap with, mark the register as not
505 // free and update spill weights.
506 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
507 IntervalPtr &IP = fixed_[i];
508 LiveInterval *I = IP.first;
509
510 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
511 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
512 I->endNumber() > StartPosition) {
513 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
514 IP.second = II;
515 if (II != I->begin() && II->start > StartPosition)
516 --II;
517 if (cur->overlapsFrom(*I, II)) {
518 unsigned reg = I->reg;
519 prt_->addRegUse(reg);
520 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
521 }
522 }
523 }
524
525 // Using the newly updated prt_ object, which includes conflicts in the
526 // future, see if there are any registers available.
527 physReg = getFreePhysReg(cur);
528 }
529 }
530
531 // Restore the physical register tracker, removing information about the
532 // future.
533 *prt_ = backupPrt;
534
535 // if we find a free register, we are done: assign this virtual to
536 // the free physical register and add this interval to the active
537 // list.
538 if (physReg) {
539 DOUT << mri_->getName(physReg) << '\n';
540 vrm_->assignVirt2Phys(cur->reg, physReg);
541 prt_->addRegUse(physReg);
542 active_.push_back(std::make_pair(cur, cur->begin()));
543 handled_.push_back(cur);
544 return;
545 }
546 DOUT << "no free registers\n";
547
548 // Compile the spill weights into an array that is better for scanning.
549 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
550 for (std::vector<std::pair<unsigned, float> >::iterator
551 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
552 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
553
554 // for each interval in active, update spill weights.
555 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
556 i != e; ++i) {
557 unsigned reg = i->first->reg;
558 assert(MRegisterInfo::isVirtualRegister(reg) &&
559 "Can only allocate virtual registers!");
560 reg = vrm_->getPhys(reg);
561 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
562 }
563
564 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
565
566 // Find a register to spill.
567 float minWeight = HUGE_VALF;
568 unsigned minReg = cur->preference; // Try the preferred register first.
569
570 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
571 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
572 e = RC->allocation_order_end(*mf_); i != e; ++i) {
573 unsigned reg = *i;
574 if (minWeight > SpillWeights[reg]) {
575 minWeight = SpillWeights[reg];
576 minReg = reg;
577 }
578 }
579
580 // If we didn't find a register that is spillable, try aliases?
581 if (!minReg) {
582 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
583 e = RC->allocation_order_end(*mf_); i != e; ++i) {
584 unsigned reg = *i;
585 // No need to worry about if the alias register size < regsize of RC.
586 // We are going to spill all registers that alias it anyway.
587 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
588 if (minWeight > SpillWeights[*as]) {
589 minWeight = SpillWeights[*as];
590 minReg = *as;
591 }
592 }
593 }
594
595 // All registers must have inf weight. Just grab one!
596 if (!minReg)
597 minReg = *RC->allocation_order_begin(*mf_);
598 }
599
600 DOUT << "\t\tregister with min weight: "
601 << mri_->getName(minReg) << " (" << minWeight << ")\n";
602
603 // if the current has the minimum weight, we need to spill it and
604 // add any added intervals back to unhandled, and restart
605 // linearscan.
606 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
607 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
608 // if the current interval is re-materializable, remember so and don't
609 // assign it a spill slot.
610 if (cur->remat)
611 vrm_->setVirtIsReMaterialized(cur->reg, cur->remat);
612 int slot = cur->remat ? vrm_->assignVirtReMatId(cur->reg)
613 : vrm_->assignVirt2StackSlot(cur->reg);
614 std::vector<LiveInterval*> added =
615 li_->addIntervalsForSpills(*cur, *vrm_, slot);
616 if (added.empty())
617 return; // Early exit if all spills were folded.
618
619 // Merge added with unhandled. Note that we know that
620 // addIntervalsForSpills returns intervals sorted by their starting
621 // point.
622 for (unsigned i = 0, e = added.size(); i != e; ++i)
623 unhandled_.push(added[i]);
624 return;
625 }
626
627 ++NumBacktracks;
628
629 // push the current interval back to unhandled since we are going
630 // to re-run at least this iteration. Since we didn't modify it it
631 // should go back right in the front of the list
632 unhandled_.push(cur);
633
634 // otherwise we spill all intervals aliasing the register with
635 // minimum weight, rollback to the interval with the earliest
636 // start point and let the linear scan algorithm run again
637 std::vector<LiveInterval*> added;
638 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
639 "did not choose a register to spill?");
640 BitVector toSpill(mri_->getNumRegs());
641
642 // We are going to spill minReg and all its aliases.
643 toSpill[minReg] = true;
644 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
645 toSpill[*as] = true;
646
647 // the earliest start of a spilled interval indicates up to where
648 // in handled we need to roll back
649 unsigned earliestStart = cur->beginNumber();
650
651 // set of spilled vregs (used later to rollback properly)
652 std::set<unsigned> spilled;
653
654 // spill live intervals of virtual regs mapped to the physical register we
655 // want to clear (and its aliases). We only spill those that overlap with the
656 // current interval as the rest do not affect its allocation. we also keep
657 // track of the earliest start of all spilled live intervals since this will
658 // mark our rollback point.
659 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
660 unsigned reg = i->first->reg;
661 if (//MRegisterInfo::isVirtualRegister(reg) &&
662 toSpill[vrm_->getPhys(reg)] &&
663 cur->overlapsFrom(*i->first, i->second)) {
664 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
665 earliestStart = std::min(earliestStart, i->first->beginNumber());
666 if (i->first->remat)
667 vrm_->setVirtIsReMaterialized(reg, i->first->remat);
668 int slot = i->first->remat ? vrm_->assignVirtReMatId(reg)
669 : vrm_->assignVirt2StackSlot(reg);
670 std::vector<LiveInterval*> newIs =
671 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
672 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
673 spilled.insert(reg);
674 }
675 }
676 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
677 unsigned reg = i->first->reg;
678 if (//MRegisterInfo::isVirtualRegister(reg) &&
679 toSpill[vrm_->getPhys(reg)] &&
680 cur->overlapsFrom(*i->first, i->second-1)) {
681 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
682 earliestStart = std::min(earliestStart, i->first->beginNumber());
683 if (i->first->remat)
684 vrm_->setVirtIsReMaterialized(reg, i->first->remat);
685 int slot = i->first->remat ? vrm_->assignVirtReMatId(reg)
686 : vrm_->assignVirt2StackSlot(reg);
687 std::vector<LiveInterval*> newIs =
688 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
689 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
690 spilled.insert(reg);
691 }
692 }
693
694 DOUT << "\t\trolling back to: " << earliestStart << '\n';
695
696 // Scan handled in reverse order up to the earliest start of a
697 // spilled live interval and undo each one, restoring the state of
698 // unhandled.
699 while (!handled_.empty()) {
700 LiveInterval* i = handled_.back();
701 // If this interval starts before t we are done.
702 if (i->beginNumber() < earliestStart)
703 break;
704 DOUT << "\t\t\tundo changes for: " << *i << '\n';
705 handled_.pop_back();
706
707 // When undoing a live interval allocation we must know if it is active or
708 // inactive to properly update the PhysRegTracker and the VirtRegMap.
709 IntervalPtrs::iterator it;
710 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
711 active_.erase(it);
712 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
713 if (!spilled.count(i->reg))
714 unhandled_.push(i);
715 prt_->delRegUse(vrm_->getPhys(i->reg));
716 vrm_->clearVirt(i->reg);
717 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
718 inactive_.erase(it);
719 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
720 if (!spilled.count(i->reg))
721 unhandled_.push(i);
722 vrm_->clearVirt(i->reg);
723 } else {
724 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
725 "Can only allocate virtual registers!");
726 vrm_->clearVirt(i->reg);
727 unhandled_.push(i);
728 }
729 }
730
731 // Rewind the iterators in the active, inactive, and fixed lists back to the
732 // point we reverted to.
733 RevertVectorIteratorsTo(active_, earliestStart);
734 RevertVectorIteratorsTo(inactive_, earliestStart);
735 RevertVectorIteratorsTo(fixed_, earliestStart);
736
737 // scan the rest and undo each interval that expired after t and
738 // insert it in active (the next iteration of the algorithm will
739 // put it in inactive if required)
740 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
741 LiveInterval *HI = handled_[i];
742 if (!HI->expiredAt(earliestStart) &&
743 HI->expiredAt(cur->beginNumber())) {
744 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
745 active_.push_back(std::make_pair(HI, HI->begin()));
746 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
747 prt_->addRegUse(vrm_->getPhys(HI->reg));
748 }
749 }
750
751 // merge added with unhandled
752 for (unsigned i = 0, e = added.size(); i != e; ++i)
753 unhandled_.push(added[i]);
754}
755
756/// getFreePhysReg - return a free physical register for this virtual register
757/// interval if we have one, otherwise return 0.
758unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
759 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
760 unsigned MaxInactiveCount = 0;
761
762 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
763 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
764
765 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
766 i != e; ++i) {
767 unsigned reg = i->first->reg;
768 assert(MRegisterInfo::isVirtualRegister(reg) &&
769 "Can only allocate virtual registers!");
770
771 // If this is not in a related reg class to the register we're allocating,
772 // don't check it.
773 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
774 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
775 reg = vrm_->getPhys(reg);
776 ++inactiveCounts[reg];
777 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
778 }
779 }
780
781 unsigned FreeReg = 0;
782 unsigned FreeRegInactiveCount = 0;
783
784 // If copy coalescer has assigned a "preferred" register, check if it's
785 // available first.
786 if (cur->preference)
787 if (prt_->isRegAvail(cur->preference)) {
788 DOUT << "\t\tassigned the preferred register: "
789 << mri_->getName(cur->preference) << "\n";
790 return cur->preference;
791 } else
792 DOUT << "\t\tunable to assign the preferred register: "
793 << mri_->getName(cur->preference) << "\n";
794
795 // Scan for the first available register.
796 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
797 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
798 for (; I != E; ++I)
799 if (prt_->isRegAvail(*I)) {
800 FreeReg = *I;
801 FreeRegInactiveCount = inactiveCounts[FreeReg];
802 break;
803 }
804
805 // If there are no free regs, or if this reg has the max inactive count,
806 // return this register.
807 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
808
809 // Continue scanning the registers, looking for the one with the highest
810 // inactive count. Alkis found that this reduced register pressure very
811 // slightly on X86 (in rev 1.94 of this file), though this should probably be
812 // reevaluated now.
813 for (; I != E; ++I) {
814 unsigned Reg = *I;
815 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
816 FreeReg = Reg;
817 FreeRegInactiveCount = inactiveCounts[Reg];
818 if (FreeRegInactiveCount == MaxInactiveCount)
819 break; // We found the one with the max inactive count.
820 }
821 }
822
823 return FreeReg;
824}
825
826FunctionPass* llvm::createLinearScanRegisterAllocator() {
827 return new RALinScan();
828}