1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CodeGen/LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/ADT/EquivalenceClasses.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Compiler.h"
41 STATISTIC(NumIters , "Number of iterations performed");
42 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
43 STATISTIC(NumCoalesce, "Number of copies coalesced");
45 static RegisterRegAlloc
46 linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
50 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
52 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
54 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
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;
64 const TargetMachine* tm_;
65 const MRegisterInfo* mri_;
66 const TargetInstrInfo* tii_;
67 MachineRegisterInfo *reginfo_;
68 BitVector allocatableRegs_;
70 const MachineLoopInfo *loopInfo;
72 /// handled_ - Intervals are added to the handled_ set in the order of their
73 /// start value. This is uses for backtracking.
74 std::vector<LiveInterval*> handled_;
76 /// fixed_ - Intervals that correspond to machine registers.
80 /// active_ - Intervals that are currently being processed, and which have a
81 /// live range active for the current point.
84 /// inactive_ - Intervals that are currently being processed, but which have
85 /// a hold at the current point.
86 IntervalPtrs inactive_;
88 typedef std::priority_queue<LiveInterval*,
89 std::vector<LiveInterval*>,
90 greater_ptr<LiveInterval> > IntervalHeap;
91 IntervalHeap unhandled_;
92 std::auto_ptr<PhysRegTracker> prt_;
93 std::auto_ptr<VirtRegMap> vrm_;
94 std::auto_ptr<Spiller> spiller_;
97 virtual const char* getPassName() const {
98 return "Linear Scan Register Allocator";
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequired<LiveIntervals>();
103 // Make sure PassManager knows which analyses to make available
104 // to coalescing and which analyses coalescing invalidates.
105 AU.addRequiredTransitive<RegisterCoalescer>();
106 AU.addRequired<MachineLoopInfo>();
107 AU.addPreserved<MachineLoopInfo>();
108 AU.addPreservedID(MachineDominatorsID);
109 MachineFunctionPass::getAnalysisUsage(AU);
112 /// runOnMachineFunction - register allocate the whole function
113 bool runOnMachineFunction(MachineFunction&);
116 /// linearScan - the linear scan algorithm
119 /// initIntervalSets - initialize the interval sets.
121 void initIntervalSets();
123 /// processActiveIntervals - expire old intervals and move non-overlapping
124 /// ones to the inactive list.
125 void processActiveIntervals(unsigned CurPoint);
127 /// processInactiveIntervals - expire old intervals and move overlapping
128 /// ones to the active list.
129 void processInactiveIntervals(unsigned CurPoint);
131 /// assignRegOrStackSlotAtInterval - assign a register if one
132 /// is available, or spill.
133 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
135 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
136 /// try allocate the definition the same register as the source register
137 /// if the register is not defined during live time of the interval. This
138 /// eliminate a copy. This is used to coalesce copies which were not
139 /// coalesced away before allocation either due to dest and src being in
140 /// different register classes or because the coalescer was overly
142 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
145 /// register handling helpers
148 /// getFreePhysReg - return a free physical register for this virtual
149 /// register interval if we have one, otherwise return 0.
150 unsigned getFreePhysReg(LiveInterval* cur);
152 /// assignVirt2StackSlot - assigns this virtual register to a
153 /// stack slot. returns the stack slot
154 int assignVirt2StackSlot(unsigned virtReg);
156 void ComputeRelatedRegClasses();
158 template <typename ItTy>
159 void printIntervals(const char* const str, ItTy i, ItTy e) const {
160 if (str) DOUT << str << " intervals:\n";
161 for (; i != e; ++i) {
162 DOUT << "\t" << *i->first << " -> ";
163 unsigned reg = i->first->reg;
164 if (MRegisterInfo::isVirtualRegister(reg)) {
165 reg = vrm_->getPhys(reg);
167 DOUT << mri_->getName(reg) << '\n';
171 char RALinScan::ID = 0;
174 void RALinScan::ComputeRelatedRegClasses() {
175 const MRegisterInfo &MRI = *mri_;
177 // First pass, add all reg classes to the union, and determine at least one
178 // reg class that each register is in.
179 bool HasAliases = false;
180 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
181 E = MRI.regclass_end(); RCI != E; ++RCI) {
182 RelatedRegClasses.insert(*RCI);
183 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
185 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
187 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
189 // Already processed this register. Just make sure we know that
190 // multiple register classes share a register.
191 RelatedRegClasses.unionSets(PRC, *RCI);
198 // Second pass, now that we know conservatively what register classes each reg
199 // belongs to, add info about aliases. We don't need to do this for targets
200 // without register aliases.
202 for (std::map<unsigned, const TargetRegisterClass*>::iterator
203 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
205 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
206 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
209 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
210 /// try allocate the definition the same register as the source register
211 /// if the register is not defined during live time of the interval. This
212 /// eliminate a copy. This is used to coalesce copies which were not
213 /// coalesced away before allocation either due to dest and src being in
214 /// different register classes or because the coalescer was overly
216 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
217 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
220 VNInfo *vni = cur.getValNumInfo(0);
221 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
223 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
224 unsigned SrcReg, DstReg;
225 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
227 if (MRegisterInfo::isVirtualRegister(SrcReg))
228 if (!vrm_->isAssignedReg(SrcReg))
231 SrcReg = vrm_->getPhys(SrcReg);
235 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
236 if (!RC->contains(SrcReg))
240 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
241 DOUT << "Coalescing: " << cur << " -> " << mri_->getName(SrcReg) << '\n';
242 vrm_->clearVirt(cur.reg);
243 vrm_->assignVirt2Phys(cur.reg, SrcReg);
251 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
253 tm_ = &fn.getTarget();
254 mri_ = tm_->getRegisterInfo();
255 tii_ = tm_->getInstrInfo();
256 reginfo_ = &mf_->getRegInfo();
257 allocatableRegs_ = mri_->getAllocatableSet(fn);
258 li_ = &getAnalysis<LiveIntervals>();
259 loopInfo = &getAnalysis<MachineLoopInfo>();
261 // We don't run the coalescer here because we have no reason to
262 // interact with it. If the coalescer requires interaction, it
263 // won't do anything. If it doesn't require interaction, we assume
264 // it was run as a separate pass.
266 // If this is the first function compiled, compute the related reg classes.
267 if (RelatedRegClasses.empty())
268 ComputeRelatedRegClasses();
270 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
271 vrm_.reset(new VirtRegMap(*mf_));
272 if (!spiller_.get()) spiller_.reset(createSpiller());
278 // Rewrite spill code and update the PhysRegsUsed set.
279 spiller_->runOnMachineFunction(*mf_, *vrm_);
280 vrm_.reset(); // Free the VirtRegMap
282 while (!unhandled_.empty()) unhandled_.pop();
291 /// initIntervalSets - initialize the interval sets.
293 void RALinScan::initIntervalSets()
295 assert(unhandled_.empty() && fixed_.empty() &&
296 active_.empty() && inactive_.empty() &&
297 "interval sets should be empty on initialization");
299 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
300 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
301 reginfo_->setPhysRegUsed(i->second.reg);
302 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
304 unhandled_.push(&i->second);
308 void RALinScan::linearScan()
310 // linear scan algorithm
311 DOUT << "********** LINEAR SCAN **********\n";
312 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
314 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
316 while (!unhandled_.empty()) {
317 // pick the interval with the earliest start point
318 LiveInterval* cur = unhandled_.top();
321 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
323 processActiveIntervals(cur->beginNumber());
324 processInactiveIntervals(cur->beginNumber());
326 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
327 "Can only allocate virtual registers!");
329 // Allocating a virtual register. try to find a free
330 // physical register or spill an interval (possibly this one) in order to
332 assignRegOrStackSlotAtInterval(cur);
334 DEBUG(printIntervals("active", active_.begin(), active_.end()));
335 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
338 // expire any remaining active intervals
339 while (!active_.empty()) {
340 IntervalPtr &IP = active_.back();
341 unsigned reg = IP.first->reg;
342 DOUT << "\tinterval " << *IP.first << " expired\n";
343 assert(MRegisterInfo::isVirtualRegister(reg) &&
344 "Can only allocate virtual registers!");
345 reg = vrm_->getPhys(reg);
346 prt_->delRegUse(reg);
350 // expire any remaining inactive intervals
351 DEBUG(for (IntervalPtrs::reverse_iterator
352 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
353 DOUT << "\tinterval " << *i->first << " expired\n");
356 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
357 MachineFunction::iterator EntryMBB = mf_->begin();
358 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
359 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
360 LiveInterval &cur = i->second;
362 bool isPhys = MRegisterInfo::isPhysicalRegister(cur.reg);
365 else if (vrm_->isAssignedReg(cur.reg))
366 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
369 // Ignore splited live intervals.
370 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
372 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
374 const LiveRange &LR = *I;
375 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
376 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
377 if (LiveInMBBs[i] != EntryMBB)
378 LiveInMBBs[i]->addLiveIn(Reg);
387 /// processActiveIntervals - expire old intervals and move non-overlapping ones
388 /// to the inactive list.
389 void RALinScan::processActiveIntervals(unsigned CurPoint)
391 DOUT << "\tprocessing active intervals:\n";
393 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
394 LiveInterval *Interval = active_[i].first;
395 LiveInterval::iterator IntervalPos = active_[i].second;
396 unsigned reg = Interval->reg;
398 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
400 if (IntervalPos == Interval->end()) { // Remove expired intervals.
401 DOUT << "\t\tinterval " << *Interval << " expired\n";
402 assert(MRegisterInfo::isVirtualRegister(reg) &&
403 "Can only allocate virtual registers!");
404 reg = vrm_->getPhys(reg);
405 prt_->delRegUse(reg);
407 // Pop off the end of the list.
408 active_[i] = active_.back();
412 } else if (IntervalPos->start > CurPoint) {
413 // Move inactive intervals to inactive list.
414 DOUT << "\t\tinterval " << *Interval << " inactive\n";
415 assert(MRegisterInfo::isVirtualRegister(reg) &&
416 "Can only allocate virtual registers!");
417 reg = vrm_->getPhys(reg);
418 prt_->delRegUse(reg);
420 inactive_.push_back(std::make_pair(Interval, IntervalPos));
422 // Pop off the end of the list.
423 active_[i] = active_.back();
427 // Otherwise, just update the iterator position.
428 active_[i].second = IntervalPos;
433 /// processInactiveIntervals - expire old intervals and move overlapping
434 /// ones to the active list.
435 void RALinScan::processInactiveIntervals(unsigned CurPoint)
437 DOUT << "\tprocessing inactive intervals:\n";
439 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
440 LiveInterval *Interval = inactive_[i].first;
441 LiveInterval::iterator IntervalPos = inactive_[i].second;
442 unsigned reg = Interval->reg;
444 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
446 if (IntervalPos == Interval->end()) { // remove expired intervals.
447 DOUT << "\t\tinterval " << *Interval << " expired\n";
449 // Pop off the end of the list.
450 inactive_[i] = inactive_.back();
451 inactive_.pop_back();
453 } else if (IntervalPos->start <= CurPoint) {
454 // move re-activated intervals in active list
455 DOUT << "\t\tinterval " << *Interval << " active\n";
456 assert(MRegisterInfo::isVirtualRegister(reg) &&
457 "Can only allocate virtual registers!");
458 reg = vrm_->getPhys(reg);
459 prt_->addRegUse(reg);
461 active_.push_back(std::make_pair(Interval, IntervalPos));
463 // Pop off the end of the list.
464 inactive_[i] = inactive_.back();
465 inactive_.pop_back();
468 // Otherwise, just update the iterator position.
469 inactive_[i].second = IntervalPos;
474 /// updateSpillWeights - updates the spill weights of the specifed physical
475 /// register and its weight.
476 static void updateSpillWeights(std::vector<float> &Weights,
477 unsigned reg, float weight,
478 const MRegisterInfo *MRI) {
479 Weights[reg] += weight;
480 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
481 Weights[*as] += weight;
485 RALinScan::IntervalPtrs::iterator
486 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
487 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
489 if (I->first == LI) return I;
493 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
494 for (unsigned i = 0, e = V.size(); i != e; ++i) {
495 RALinScan::IntervalPtr &IP = V[i];
496 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
498 if (I != IP.first->begin()) --I;
503 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
505 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
507 DOUT << "\tallocating current interval: ";
509 PhysRegTracker backupPrt = *prt_;
511 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
512 unsigned StartPosition = cur->beginNumber();
513 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
514 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
516 // If this live interval is defined by a move instruction and its source is
517 // assigned a physical register that is compatible with the target register
518 // class, then we should try to assign it the same register.
519 // This can happen when the move is from a larger register class to a smaller
520 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
521 if (!cur->preference && cur->containsOneValue()) {
522 VNInfo *vni = cur->getValNumInfo(0);
523 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
524 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
525 unsigned SrcReg, DstReg;
526 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
528 if (MRegisterInfo::isPhysicalRegister(SrcReg))
530 else if (vrm_->isAssignedReg(SrcReg))
531 Reg = vrm_->getPhys(SrcReg);
532 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
533 cur->preference = Reg;
538 // for every interval in inactive we overlap with, mark the
539 // register as not free and update spill weights.
540 for (IntervalPtrs::const_iterator i = inactive_.begin(),
541 e = inactive_.end(); i != e; ++i) {
542 unsigned Reg = i->first->reg;
543 assert(MRegisterInfo::isVirtualRegister(Reg) &&
544 "Can only allocate virtual registers!");
545 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
546 // If this is not in a related reg class to the register we're allocating,
548 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
549 cur->overlapsFrom(*i->first, i->second-1)) {
550 Reg = vrm_->getPhys(Reg);
551 prt_->addRegUse(Reg);
552 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
556 // Speculatively check to see if we can get a register right now. If not,
557 // we know we won't be able to by adding more constraints. If so, we can
558 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
559 // is very bad (it contains all callee clobbered registers for any functions
560 // with a call), so we want to avoid doing that if possible.
561 unsigned physReg = getFreePhysReg(cur);
563 // We got a register. However, if it's in the fixed_ list, we might
564 // conflict with it. Check to see if we conflict with it or any of its
566 SmallSet<unsigned, 8> RegAliases;
567 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
568 RegAliases.insert(*AS);
570 bool ConflictsWithFixed = false;
571 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
572 IntervalPtr &IP = fixed_[i];
573 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
574 // Okay, this reg is on the fixed list. Check to see if we actually
576 LiveInterval *I = IP.first;
577 if (I->endNumber() > StartPosition) {
578 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
580 if (II != I->begin() && II->start > StartPosition)
582 if (cur->overlapsFrom(*I, II)) {
583 ConflictsWithFixed = true;
590 // Okay, the register picked by our speculative getFreePhysReg call turned
591 // out to be in use. Actually add all of the conflicting fixed registers to
592 // prt so we can do an accurate query.
593 if (ConflictsWithFixed) {
594 // For every interval in fixed we overlap with, mark the register as not
595 // free and update spill weights.
596 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
597 IntervalPtr &IP = fixed_[i];
598 LiveInterval *I = IP.first;
600 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
601 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
602 I->endNumber() > StartPosition) {
603 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
605 if (II != I->begin() && II->start > StartPosition)
607 if (cur->overlapsFrom(*I, II)) {
608 unsigned reg = I->reg;
609 prt_->addRegUse(reg);
610 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
615 // Using the newly updated prt_ object, which includes conflicts in the
616 // future, see if there are any registers available.
617 physReg = getFreePhysReg(cur);
621 // Restore the physical register tracker, removing information about the
625 // if we find a free register, we are done: assign this virtual to
626 // the free physical register and add this interval to the active
629 DOUT << mri_->getName(physReg) << '\n';
630 vrm_->assignVirt2Phys(cur->reg, physReg);
631 prt_->addRegUse(physReg);
632 active_.push_back(std::make_pair(cur, cur->begin()));
633 handled_.push_back(cur);
636 DOUT << "no free registers\n";
638 // Compile the spill weights into an array that is better for scanning.
639 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
640 for (std::vector<std::pair<unsigned, float> >::iterator
641 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
642 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
644 // for each interval in active, update spill weights.
645 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
647 unsigned reg = i->first->reg;
648 assert(MRegisterInfo::isVirtualRegister(reg) &&
649 "Can only allocate virtual registers!");
650 reg = vrm_->getPhys(reg);
651 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
654 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
656 // Find a register to spill.
657 float minWeight = HUGE_VALF;
658 unsigned minReg = cur->preference; // Try the preferred register first.
660 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
661 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
662 e = RC->allocation_order_end(*mf_); i != e; ++i) {
664 if (minWeight > SpillWeights[reg]) {
665 minWeight = SpillWeights[reg];
670 // If we didn't find a register that is spillable, try aliases?
672 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
673 e = RC->allocation_order_end(*mf_); i != e; ++i) {
675 // No need to worry about if the alias register size < regsize of RC.
676 // We are going to spill all registers that alias it anyway.
677 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
678 if (minWeight > SpillWeights[*as]) {
679 minWeight = SpillWeights[*as];
685 // All registers must have inf weight. Just grab one!
687 minReg = *RC->allocation_order_begin(*mf_);
690 DOUT << "\t\tregister with min weight: "
691 << mri_->getName(minReg) << " (" << minWeight << ")\n";
693 // if the current has the minimum weight, we need to spill it and
694 // add any added intervals back to unhandled, and restart
696 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
697 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
698 std::vector<LiveInterval*> added =
699 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
701 return; // Early exit if all spills were folded.
703 // Merge added with unhandled. Note that we know that
704 // addIntervalsForSpills returns intervals sorted by their starting
706 for (unsigned i = 0, e = added.size(); i != e; ++i)
707 unhandled_.push(added[i]);
713 // push the current interval back to unhandled since we are going
714 // to re-run at least this iteration. Since we didn't modify it it
715 // should go back right in the front of the list
716 unhandled_.push(cur);
718 // otherwise we spill all intervals aliasing the register with
719 // minimum weight, rollback to the interval with the earliest
720 // start point and let the linear scan algorithm run again
721 std::vector<LiveInterval*> added;
722 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
723 "did not choose a register to spill?");
724 BitVector toSpill(mri_->getNumRegs());
726 // We are going to spill minReg and all its aliases.
727 toSpill[minReg] = true;
728 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
731 // the earliest start of a spilled interval indicates up to where
732 // in handled we need to roll back
733 unsigned earliestStart = cur->beginNumber();
735 // set of spilled vregs (used later to rollback properly)
736 SmallSet<unsigned, 32> spilled;
738 // spill live intervals of virtual regs mapped to the physical register we
739 // want to clear (and its aliases). We only spill those that overlap with the
740 // current interval as the rest do not affect its allocation. we also keep
741 // track of the earliest start of all spilled live intervals since this will
742 // mark our rollback point.
743 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
744 unsigned reg = i->first->reg;
745 if (//MRegisterInfo::isVirtualRegister(reg) &&
746 toSpill[vrm_->getPhys(reg)] &&
747 cur->overlapsFrom(*i->first, i->second)) {
748 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
749 earliestStart = std::min(earliestStart, i->first->beginNumber());
750 std::vector<LiveInterval*> newIs =
751 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
752 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
756 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
757 unsigned reg = i->first->reg;
758 if (//MRegisterInfo::isVirtualRegister(reg) &&
759 toSpill[vrm_->getPhys(reg)] &&
760 cur->overlapsFrom(*i->first, i->second-1)) {
761 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
762 earliestStart = std::min(earliestStart, i->first->beginNumber());
763 std::vector<LiveInterval*> newIs =
764 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
765 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
770 DOUT << "\t\trolling back to: " << earliestStart << '\n';
772 // Scan handled in reverse order up to the earliest start of a
773 // spilled live interval and undo each one, restoring the state of
775 while (!handled_.empty()) {
776 LiveInterval* i = handled_.back();
777 // If this interval starts before t we are done.
778 if (i->beginNumber() < earliestStart)
780 DOUT << "\t\t\tundo changes for: " << *i << '\n';
783 // When undoing a live interval allocation we must know if it is active or
784 // inactive to properly update the PhysRegTracker and the VirtRegMap.
785 IntervalPtrs::iterator it;
786 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
788 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
789 if (!spilled.count(i->reg))
791 prt_->delRegUse(vrm_->getPhys(i->reg));
792 vrm_->clearVirt(i->reg);
793 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
795 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
796 if (!spilled.count(i->reg))
798 vrm_->clearVirt(i->reg);
800 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
801 "Can only allocate virtual registers!");
802 vrm_->clearVirt(i->reg);
806 // It interval has a preference, it must be defined by a copy. Clear the
807 // preference now since the source interval allocation may have been undone
812 // Rewind the iterators in the active, inactive, and fixed lists back to the
813 // point we reverted to.
814 RevertVectorIteratorsTo(active_, earliestStart);
815 RevertVectorIteratorsTo(inactive_, earliestStart);
816 RevertVectorIteratorsTo(fixed_, earliestStart);
818 // scan the rest and undo each interval that expired after t and
819 // insert it in active (the next iteration of the algorithm will
820 // put it in inactive if required)
821 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
822 LiveInterval *HI = handled_[i];
823 if (!HI->expiredAt(earliestStart) &&
824 HI->expiredAt(cur->beginNumber())) {
825 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
826 active_.push_back(std::make_pair(HI, HI->begin()));
827 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
828 prt_->addRegUse(vrm_->getPhys(HI->reg));
832 // merge added with unhandled
833 for (unsigned i = 0, e = added.size(); i != e; ++i)
834 unhandled_.push(added[i]);
837 /// getFreePhysReg - return a free physical register for this virtual register
838 /// interval if we have one, otherwise return 0.
839 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
840 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
841 unsigned MaxInactiveCount = 0;
843 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
844 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
846 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
848 unsigned reg = i->first->reg;
849 assert(MRegisterInfo::isVirtualRegister(reg) &&
850 "Can only allocate virtual registers!");
852 // If this is not in a related reg class to the register we're allocating,
854 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
855 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
856 reg = vrm_->getPhys(reg);
857 ++inactiveCounts[reg];
858 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
862 unsigned FreeReg = 0;
863 unsigned FreeRegInactiveCount = 0;
865 // If copy coalescer has assigned a "preferred" register, check if it's
868 if (prt_->isRegAvail(cur->preference)) {
869 DOUT << "\t\tassigned the preferred register: "
870 << mri_->getName(cur->preference) << "\n";
871 return cur->preference;
873 DOUT << "\t\tunable to assign the preferred register: "
874 << mri_->getName(cur->preference) << "\n";
876 // Scan for the first available register.
877 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
878 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
880 if (prt_->isRegAvail(*I)) {
882 FreeRegInactiveCount = inactiveCounts[FreeReg];
886 // If there are no free regs, or if this reg has the max inactive count,
887 // return this register.
888 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
890 // Continue scanning the registers, looking for the one with the highest
891 // inactive count. Alkis found that this reduced register pressure very
892 // slightly on X86 (in rev 1.94 of this file), though this should probably be
894 for (; I != E; ++I) {
896 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
898 FreeRegInactiveCount = inactiveCounts[Reg];
899 if (FreeRegInactiveCount == MaxInactiveCount)
900 break; // We found the one with the max inactive count.
907 FunctionPass* llvm::createLinearScanRegisterAllocator() {
908 return new RALinScan();