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/TargetRegisterInfo.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 TargetRegisterInfo* tri_;
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 (TargetRegisterInfo::isVirtualRegister(reg)) {
165 reg = vrm_->getPhys(reg);
167 DOUT << tri_->getName(reg) << '\n';
171 char RALinScan::ID = 0;
174 void RALinScan::ComputeRelatedRegClasses() {
175 const TargetRegisterInfo &TRI = *tri_;
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 (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
181 E = TRI.regclass_end(); RCI != E; ++RCI) {
182 RelatedRegClasses.insert(*RCI);
183 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
185 HasAliases = HasAliases || *TRI.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 = TRI.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 (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
228 if (!vrm_->isAssignedReg(SrcReg))
231 SrcReg = vrm_->getPhys(SrcReg);
236 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
237 if (!RC->contains(SrcReg))
241 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
242 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
244 vrm_->clearVirt(cur.reg);
245 vrm_->assignVirt2Phys(cur.reg, SrcReg);
253 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
255 tm_ = &fn.getTarget();
256 tri_ = tm_->getRegisterInfo();
257 tii_ = tm_->getInstrInfo();
258 reginfo_ = &mf_->getRegInfo();
259 allocatableRegs_ = tri_->getAllocatableSet(fn);
260 li_ = &getAnalysis<LiveIntervals>();
261 loopInfo = &getAnalysis<MachineLoopInfo>();
263 // We don't run the coalescer here because we have no reason to
264 // interact with it. If the coalescer requires interaction, it
265 // won't do anything. If it doesn't require interaction, we assume
266 // it was run as a separate pass.
268 // If this is the first function compiled, compute the related reg classes.
269 if (RelatedRegClasses.empty())
270 ComputeRelatedRegClasses();
272 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
273 vrm_.reset(new VirtRegMap(*mf_));
274 if (!spiller_.get()) spiller_.reset(createSpiller());
280 // Rewrite spill code and update the PhysRegsUsed set.
281 spiller_->runOnMachineFunction(*mf_, *vrm_);
282 vrm_.reset(); // Free the VirtRegMap
284 while (!unhandled_.empty()) unhandled_.pop();
293 /// initIntervalSets - initialize the interval sets.
295 void RALinScan::initIntervalSets()
297 assert(unhandled_.empty() && fixed_.empty() &&
298 active_.empty() && inactive_.empty() &&
299 "interval sets should be empty on initialization");
301 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
302 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
303 reginfo_->setPhysRegUsed(i->second.reg);
304 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
306 unhandled_.push(&i->second);
310 void RALinScan::linearScan()
312 // linear scan algorithm
313 DOUT << "********** LINEAR SCAN **********\n";
314 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
316 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
318 while (!unhandled_.empty()) {
319 // pick the interval with the earliest start point
320 LiveInterval* cur = unhandled_.top();
323 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
326 processActiveIntervals(cur->beginNumber());
327 processInactiveIntervals(cur->beginNumber());
329 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
330 "Can only allocate virtual registers!");
333 // Allocating a virtual register. try to find a free
334 // physical register or spill an interval (possibly this one) in order to
336 assignRegOrStackSlotAtInterval(cur);
338 DEBUG(printIntervals("active", active_.begin(), active_.end()));
339 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
342 // expire any remaining active intervals
343 while (!active_.empty()) {
344 IntervalPtr &IP = active_.back();
345 unsigned reg = IP.first->reg;
346 DOUT << "\tinterval " << *IP.first << " expired\n";
347 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
348 "Can only allocate virtual registers!");
349 reg = vrm_->getPhys(reg);
350 prt_->delRegUse(reg);
354 // expire any remaining inactive intervals
355 DEBUG(for (IntervalPtrs::reverse_iterator
356 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
357 DOUT << "\tinterval " << *i->first << " expired\n");
360 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
361 MachineFunction::iterator EntryMBB = mf_->begin();
362 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
363 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
364 LiveInterval &cur = i->second;
366 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
369 else if (vrm_->isAssignedReg(cur.reg))
370 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
373 // Ignore splited live intervals.
374 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
376 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
378 const LiveRange &LR = *I;
379 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
380 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
381 if (LiveInMBBs[i] != EntryMBB)
382 LiveInMBBs[i]->addLiveIn(Reg);
391 /// processActiveIntervals - expire old intervals and move non-overlapping ones
392 /// to the inactive list.
393 void RALinScan::processActiveIntervals(unsigned CurPoint)
395 DOUT << "\tprocessing active intervals:\n";
397 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
398 LiveInterval *Interval = active_[i].first;
399 LiveInterval::iterator IntervalPos = active_[i].second;
400 unsigned reg = Interval->reg;
402 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
404 if (IntervalPos == Interval->end()) { // Remove expired intervals.
405 DOUT << "\t\tinterval " << *Interval << " expired\n";
406 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
407 "Can only allocate virtual registers!");
408 reg = vrm_->getPhys(reg);
409 prt_->delRegUse(reg);
411 // Pop off the end of the list.
412 active_[i] = active_.back();
416 } else if (IntervalPos->start > CurPoint) {
417 // Move inactive intervals to inactive list.
418 DOUT << "\t\tinterval " << *Interval << " inactive\n";
419 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
420 "Can only allocate virtual registers!");
421 reg = vrm_->getPhys(reg);
422 prt_->delRegUse(reg);
424 inactive_.push_back(std::make_pair(Interval, IntervalPos));
426 // Pop off the end of the list.
427 active_[i] = active_.back();
431 // Otherwise, just update the iterator position.
432 active_[i].second = IntervalPos;
437 /// processInactiveIntervals - expire old intervals and move overlapping
438 /// ones to the active list.
439 void RALinScan::processInactiveIntervals(unsigned CurPoint)
441 DOUT << "\tprocessing inactive intervals:\n";
443 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
444 LiveInterval *Interval = inactive_[i].first;
445 LiveInterval::iterator IntervalPos = inactive_[i].second;
446 unsigned reg = Interval->reg;
448 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
450 if (IntervalPos == Interval->end()) { // remove expired intervals.
451 DOUT << "\t\tinterval " << *Interval << " expired\n";
453 // Pop off the end of the list.
454 inactive_[i] = inactive_.back();
455 inactive_.pop_back();
457 } else if (IntervalPos->start <= CurPoint) {
458 // move re-activated intervals in active list
459 DOUT << "\t\tinterval " << *Interval << " active\n";
460 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
461 "Can only allocate virtual registers!");
462 reg = vrm_->getPhys(reg);
463 prt_->addRegUse(reg);
465 active_.push_back(std::make_pair(Interval, IntervalPos));
467 // Pop off the end of the list.
468 inactive_[i] = inactive_.back();
469 inactive_.pop_back();
472 // Otherwise, just update the iterator position.
473 inactive_[i].second = IntervalPos;
478 /// updateSpillWeights - updates the spill weights of the specifed physical
479 /// register and its weight.
480 static void updateSpillWeights(std::vector<float> &Weights,
481 unsigned reg, float weight,
482 const TargetRegisterInfo *TRI) {
483 Weights[reg] += weight;
484 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
485 Weights[*as] += weight;
489 RALinScan::IntervalPtrs::iterator
490 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
491 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
493 if (I->first == LI) return I;
497 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
498 for (unsigned i = 0, e = V.size(); i != e; ++i) {
499 RALinScan::IntervalPtr &IP = V[i];
500 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
502 if (I != IP.first->begin()) --I;
507 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
509 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
511 DOUT << "\tallocating current interval: ";
513 // This is an implicitly defined live interval, just assign any register.
514 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
516 unsigned physReg = cur->preference;
518 physReg = *RC->allocation_order_begin(*mf_);
519 DOUT << tri_->getName(physReg) << '\n';
520 // Note the register is not really in use.
521 vrm_->assignVirt2Phys(cur->reg, physReg);
525 PhysRegTracker backupPrt = *prt_;
527 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
528 unsigned StartPosition = cur->beginNumber();
529 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
531 // If this live interval is defined by a move instruction and its source is
532 // assigned a physical register that is compatible with the target register
533 // class, then we should try to assign it the same register.
534 // This can happen when the move is from a larger register class to a smaller
535 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
536 if (!cur->preference && cur->containsOneValue()) {
537 VNInfo *vni = cur->getValNumInfo(0);
538 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
539 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
540 unsigned SrcReg, DstReg;
541 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
543 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
545 else if (vrm_->isAssignedReg(SrcReg))
546 Reg = vrm_->getPhys(SrcReg);
547 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
548 cur->preference = Reg;
553 // for every interval in inactive we overlap with, mark the
554 // register as not free and update spill weights.
555 for (IntervalPtrs::const_iterator i = inactive_.begin(),
556 e = inactive_.end(); i != e; ++i) {
557 unsigned Reg = i->first->reg;
558 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
559 "Can only allocate virtual registers!");
560 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
561 // If this is not in a related reg class to the register we're allocating,
563 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
564 cur->overlapsFrom(*i->first, i->second-1)) {
565 Reg = vrm_->getPhys(Reg);
566 prt_->addRegUse(Reg);
567 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
571 // Speculatively check to see if we can get a register right now. If not,
572 // we know we won't be able to by adding more constraints. If so, we can
573 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
574 // is very bad (it contains all callee clobbered registers for any functions
575 // with a call), so we want to avoid doing that if possible.
576 unsigned physReg = getFreePhysReg(cur);
577 unsigned BestPhysReg = physReg;
579 // We got a register. However, if it's in the fixed_ list, we might
580 // conflict with it. Check to see if we conflict with it or any of its
582 SmallSet<unsigned, 8> RegAliases;
583 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
584 RegAliases.insert(*AS);
586 bool ConflictsWithFixed = false;
587 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
588 IntervalPtr &IP = fixed_[i];
589 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
590 // Okay, this reg is on the fixed list. Check to see if we actually
592 LiveInterval *I = IP.first;
593 if (I->endNumber() > StartPosition) {
594 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
596 if (II != I->begin() && II->start > StartPosition)
598 if (cur->overlapsFrom(*I, II)) {
599 ConflictsWithFixed = true;
606 // Okay, the register picked by our speculative getFreePhysReg call turned
607 // out to be in use. Actually add all of the conflicting fixed registers to
608 // prt so we can do an accurate query.
609 if (ConflictsWithFixed) {
610 // For every interval in fixed we overlap with, mark the register as not
611 // free and update spill weights.
612 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
613 IntervalPtr &IP = fixed_[i];
614 LiveInterval *I = IP.first;
616 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
617 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
618 I->endNumber() > StartPosition) {
619 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
621 if (II != I->begin() && II->start > StartPosition)
623 if (cur->overlapsFrom(*I, II)) {
624 unsigned reg = I->reg;
625 prt_->addRegUse(reg);
626 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
631 // Using the newly updated prt_ object, which includes conflicts in the
632 // future, see if there are any registers available.
633 physReg = getFreePhysReg(cur);
637 // Restore the physical register tracker, removing information about the
641 // if we find a free register, we are done: assign this virtual to
642 // the free physical register and add this interval to the active
645 DOUT << tri_->getName(physReg) << '\n';
646 vrm_->assignVirt2Phys(cur->reg, physReg);
647 prt_->addRegUse(physReg);
648 active_.push_back(std::make_pair(cur, cur->begin()));
649 handled_.push_back(cur);
652 DOUT << "no free registers\n";
654 // Compile the spill weights into an array that is better for scanning.
655 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
656 for (std::vector<std::pair<unsigned, float> >::iterator
657 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
658 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
660 // for each interval in active, update spill weights.
661 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
663 unsigned reg = i->first->reg;
664 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
665 "Can only allocate virtual registers!");
666 reg = vrm_->getPhys(reg);
667 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
670 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
672 // Find a register to spill.
673 float minWeight = HUGE_VALF;
674 unsigned minReg = cur->preference; // Try the preferred register first.
676 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
677 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
678 e = RC->allocation_order_end(*mf_); i != e; ++i) {
680 if (minWeight > SpillWeights[reg]) {
681 minWeight = SpillWeights[reg];
686 // If we didn't find a register that is spillable, try aliases?
688 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
689 e = RC->allocation_order_end(*mf_); i != e; ++i) {
691 // No need to worry about if the alias register size < regsize of RC.
692 // We are going to spill all registers that alias it anyway.
693 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
694 if (minWeight > SpillWeights[*as]) {
695 minWeight = SpillWeights[*as];
701 // All registers must have inf weight. Just grab one!
703 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
704 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
705 // Spill a physical register around defs and uses.
706 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
710 DOUT << "\t\tregister with min weight: "
711 << tri_->getName(minReg) << " (" << minWeight << ")\n";
713 // if the current has the minimum weight, we need to spill it and
714 // add any added intervals back to unhandled, and restart
716 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
717 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
718 std::vector<LiveInterval*> added =
719 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
721 return; // Early exit if all spills were folded.
723 // Merge added with unhandled. Note that we know that
724 // addIntervalsForSpills returns intervals sorted by their starting
726 for (unsigned i = 0, e = added.size(); i != e; ++i)
727 unhandled_.push(added[i]);
733 // push the current interval back to unhandled since we are going
734 // to re-run at least this iteration. Since we didn't modify it it
735 // should go back right in the front of the list
736 unhandled_.push(cur);
738 // otherwise we spill all intervals aliasing the register with
739 // minimum weight, rollback to the interval with the earliest
740 // start point and let the linear scan algorithm run again
741 std::vector<LiveInterval*> added;
742 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
743 "did not choose a register to spill?");
744 BitVector toSpill(tri_->getNumRegs());
746 // We are going to spill minReg and all its aliases.
747 toSpill[minReg] = true;
748 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
751 // the earliest start of a spilled interval indicates up to where
752 // in handled we need to roll back
753 unsigned earliestStart = cur->beginNumber();
755 // set of spilled vregs (used later to rollback properly)
756 SmallSet<unsigned, 32> spilled;
758 // spill live intervals of virtual regs mapped to the physical register we
759 // want to clear (and its aliases). We only spill those that overlap with the
760 // current interval as the rest do not affect its allocation. we also keep
761 // track of the earliest start of all spilled live intervals since this will
762 // mark our rollback point.
763 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
764 unsigned reg = i->first->reg;
765 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
766 toSpill[vrm_->getPhys(reg)] &&
767 cur->overlapsFrom(*i->first, i->second)) {
768 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
769 earliestStart = std::min(earliestStart, i->first->beginNumber());
770 std::vector<LiveInterval*> newIs =
771 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
772 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
776 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
777 unsigned reg = i->first->reg;
778 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
779 toSpill[vrm_->getPhys(reg)] &&
780 cur->overlapsFrom(*i->first, i->second-1)) {
781 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
782 earliestStart = std::min(earliestStart, i->first->beginNumber());
783 std::vector<LiveInterval*> newIs =
784 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
785 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
790 DOUT << "\t\trolling back to: " << earliestStart << '\n';
792 // Scan handled in reverse order up to the earliest start of a
793 // spilled live interval and undo each one, restoring the state of
795 while (!handled_.empty()) {
796 LiveInterval* i = handled_.back();
797 // If this interval starts before t we are done.
798 if (i->beginNumber() < earliestStart)
800 DOUT << "\t\t\tundo changes for: " << *i << '\n';
803 // When undoing a live interval allocation we must know if it is active or
804 // inactive to properly update the PhysRegTracker and the VirtRegMap.
805 IntervalPtrs::iterator it;
806 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
808 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
809 if (!spilled.count(i->reg))
811 prt_->delRegUse(vrm_->getPhys(i->reg));
812 vrm_->clearVirt(i->reg);
813 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
815 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
816 if (!spilled.count(i->reg))
818 vrm_->clearVirt(i->reg);
820 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
821 "Can only allocate virtual registers!");
822 vrm_->clearVirt(i->reg);
826 // It interval has a preference, it must be defined by a copy. Clear the
827 // preference now since the source interval allocation may have been undone
832 // Rewind the iterators in the active, inactive, and fixed lists back to the
833 // point we reverted to.
834 RevertVectorIteratorsTo(active_, earliestStart);
835 RevertVectorIteratorsTo(inactive_, earliestStart);
836 RevertVectorIteratorsTo(fixed_, earliestStart);
838 // scan the rest and undo each interval that expired after t and
839 // insert it in active (the next iteration of the algorithm will
840 // put it in inactive if required)
841 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
842 LiveInterval *HI = handled_[i];
843 if (!HI->expiredAt(earliestStart) &&
844 HI->expiredAt(cur->beginNumber())) {
845 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
846 active_.push_back(std::make_pair(HI, HI->begin()));
847 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
848 prt_->addRegUse(vrm_->getPhys(HI->reg));
852 // merge added with unhandled
853 for (unsigned i = 0, e = added.size(); i != e; ++i)
854 unhandled_.push(added[i]);
857 /// getFreePhysReg - return a free physical register for this virtual register
858 /// interval if we have one, otherwise return 0.
859 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
860 SmallVector<unsigned, 256> inactiveCounts;
861 unsigned MaxInactiveCount = 0;
863 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
864 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
866 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
868 unsigned reg = i->first->reg;
869 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
870 "Can only allocate virtual registers!");
872 // If this is not in a related reg class to the register we're allocating,
874 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
875 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
876 reg = vrm_->getPhys(reg);
877 if (inactiveCounts.size() <= reg)
878 inactiveCounts.resize(reg+1);
879 ++inactiveCounts[reg];
880 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
884 unsigned FreeReg = 0;
885 unsigned FreeRegInactiveCount = 0;
887 // If copy coalescer has assigned a "preferred" register, check if it's
889 if (cur->preference) {
890 if (prt_->isRegAvail(cur->preference)) {
891 DOUT << "\t\tassigned the preferred register: "
892 << tri_->getName(cur->preference) << "\n";
893 return cur->preference;
895 DOUT << "\t\tunable to assign the preferred register: "
896 << tri_->getName(cur->preference) << "\n";
899 // Scan for the first available register.
900 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
901 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
902 assert(I != E && "No allocatable register in this register class!");
904 if (prt_->isRegAvail(*I)) {
906 if (FreeReg < inactiveCounts.size())
907 FreeRegInactiveCount = inactiveCounts[FreeReg];
909 FreeRegInactiveCount = 0;
913 // If there are no free regs, or if this reg has the max inactive count,
914 // return this register.
915 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
917 // Continue scanning the registers, looking for the one with the highest
918 // inactive count. Alkis found that this reduced register pressure very
919 // slightly on X86 (in rev 1.94 of this file), though this should probably be
921 for (; I != E; ++I) {
923 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
924 FreeRegInactiveCount < inactiveCounts[Reg]) {
926 FreeRegInactiveCount = inactiveCounts[Reg];
927 if (FreeRegInactiveCount == MaxInactiveCount)
928 break; // We found the one with the max inactive count.
935 FunctionPass* llvm::createLinearScanRegisterAllocator() {
936 return new RALinScan();