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 "PhysRegTracker.h"
16 #include "VirtRegMap.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegAllocRegistry.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/ADT/EquivalenceClasses.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
42 STATISTIC(NumIters , "Number of iterations performed");
43 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
44 STATISTIC(NumCoalesce, "Number of copies coalesced");
47 NewHeuristic("new-spilling-heuristic",
48 cl::desc("Use new spilling heuristic"),
49 cl::init(false), cl::Hidden);
51 static RegisterRegAlloc
52 linearscanRegAlloc("linearscan", " linear scan register allocator",
53 createLinearScanRegisterAllocator);
56 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
58 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
60 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
61 typedef std::vector<IntervalPtr> IntervalPtrs;
63 /// RelatedRegClasses - This structure is built the first time a function is
64 /// compiled, and keeps track of which register classes have registers that
65 /// belong to multiple classes or have aliases that are in other classes.
66 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
67 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
70 MachineRegisterInfo* mri_;
71 const TargetMachine* tm_;
72 const TargetRegisterInfo* tri_;
73 const TargetInstrInfo* tii_;
74 MachineRegisterInfo *reginfo_;
75 BitVector allocatableRegs_;
78 const MachineLoopInfo *loopInfo;
80 /// handled_ - Intervals are added to the handled_ set in the order of their
81 /// start value. This is uses for backtracking.
82 std::vector<LiveInterval*> handled_;
84 /// fixed_ - Intervals that correspond to machine registers.
88 /// active_ - Intervals that are currently being processed, and which have a
89 /// live range active for the current point.
92 /// inactive_ - Intervals that are currently being processed, but which have
93 /// a hold at the current point.
94 IntervalPtrs inactive_;
96 typedef std::priority_queue<LiveInterval*,
97 std::vector<LiveInterval*>,
98 greater_ptr<LiveInterval> > IntervalHeap;
99 IntervalHeap unhandled_;
100 std::auto_ptr<PhysRegTracker> prt_;
101 std::auto_ptr<VirtRegMap> vrm_;
102 std::auto_ptr<Spiller> spiller_;
105 virtual const char* getPassName() const {
106 return "Linear Scan Register Allocator";
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addRequired<LiveIntervals>();
111 // Make sure PassManager knows which analyses to make available
112 // to coalescing and which analyses coalescing invalidates.
113 AU.addRequiredTransitive<RegisterCoalescer>();
114 AU.addRequired<LiveStacks>();
115 AU.addPreserved<LiveStacks>();
116 AU.addRequired<MachineLoopInfo>();
117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreservedID(MachineDominatorsID);
119 MachineFunctionPass::getAnalysisUsage(AU);
122 /// runOnMachineFunction - register allocate the whole function
123 bool runOnMachineFunction(MachineFunction&);
126 /// linearScan - the linear scan algorithm
129 /// initIntervalSets - initialize the interval sets.
131 void initIntervalSets();
133 /// processActiveIntervals - expire old intervals and move non-overlapping
134 /// ones to the inactive list.
135 void processActiveIntervals(unsigned CurPoint);
137 /// processInactiveIntervals - expire old intervals and move overlapping
138 /// ones to the active list.
139 void processInactiveIntervals(unsigned CurPoint);
141 /// assignRegOrStackSlotAtInterval - assign a register if one
142 /// is available, or spill.
143 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
145 /// findIntervalsToSpill - Determine the intervals to spill for the
146 /// specified interval. It's passed the physical registers whose spill
147 /// weight is the lowest among all the registers whose live intervals
148 /// conflict with the interval.
149 void findIntervalsToSpill(LiveInterval *cur,
150 std::vector<std::pair<unsigned,float> > &Candidates,
152 SmallVector<LiveInterval*, 8> &SpillIntervals);
154 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
155 /// try allocate the definition the same register as the source register
156 /// if the register is not defined during live time of the interval. This
157 /// eliminate a copy. This is used to coalesce copies which were not
158 /// coalesced away before allocation either due to dest and src being in
159 /// different register classes or because the coalescer was overly
161 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
164 /// register handling helpers
167 /// getFreePhysReg - return a free physical register for this virtual
168 /// register interval if we have one, otherwise return 0.
169 unsigned getFreePhysReg(LiveInterval* cur);
171 /// assignVirt2StackSlot - assigns this virtual register to a
172 /// stack slot. returns the stack slot
173 int assignVirt2StackSlot(unsigned virtReg);
175 void ComputeRelatedRegClasses();
177 template <typename ItTy>
178 void printIntervals(const char* const str, ItTy i, ItTy e) const {
179 if (str) DOUT << str << " intervals:\n";
180 for (; i != e; ++i) {
181 DOUT << "\t" << *i->first << " -> ";
182 unsigned reg = i->first->reg;
183 if (TargetRegisterInfo::isVirtualRegister(reg)) {
184 reg = vrm_->getPhys(reg);
186 DOUT << tri_->getName(reg) << '\n';
190 char RALinScan::ID = 0;
193 static RegisterPass<RALinScan>
194 X("linearscan-regalloc", "Linear Scan Register Allocator");
196 void RALinScan::ComputeRelatedRegClasses() {
197 const TargetRegisterInfo &TRI = *tri_;
199 // First pass, add all reg classes to the union, and determine at least one
200 // reg class that each register is in.
201 bool HasAliases = false;
202 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
203 E = TRI.regclass_end(); RCI != E; ++RCI) {
204 RelatedRegClasses.insert(*RCI);
205 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
207 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
209 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
211 // Already processed this register. Just make sure we know that
212 // multiple register classes share a register.
213 RelatedRegClasses.unionSets(PRC, *RCI);
220 // Second pass, now that we know conservatively what register classes each reg
221 // belongs to, add info about aliases. We don't need to do this for targets
222 // without register aliases.
224 for (std::map<unsigned, const TargetRegisterClass*>::iterator
225 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
227 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
228 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
231 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
232 /// try allocate the definition the same register as the source register
233 /// if the register is not defined during live time of the interval. This
234 /// eliminate a copy. This is used to coalesce copies which were not
235 /// coalesced away before allocation either due to dest and src being in
236 /// different register classes or because the coalescer was overly
238 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
239 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
242 VNInfo *vni = cur.getValNumInfo(0);
243 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
245 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
246 unsigned SrcReg, DstReg;
247 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
249 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
250 if (!vrm_->isAssignedReg(SrcReg))
253 SrcReg = vrm_->getPhys(SrcReg);
258 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
259 if (!RC->contains(SrcReg))
263 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
264 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
266 vrm_->clearVirt(cur.reg);
267 vrm_->assignVirt2Phys(cur.reg, SrcReg);
275 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
277 mri_ = &fn.getRegInfo();
278 tm_ = &fn.getTarget();
279 tri_ = tm_->getRegisterInfo();
280 tii_ = tm_->getInstrInfo();
281 reginfo_ = &mf_->getRegInfo();
282 allocatableRegs_ = tri_->getAllocatableSet(fn);
283 li_ = &getAnalysis<LiveIntervals>();
284 ls_ = &getAnalysis<LiveStacks>();
285 loopInfo = &getAnalysis<MachineLoopInfo>();
287 // We don't run the coalescer here because we have no reason to
288 // interact with it. If the coalescer requires interaction, it
289 // won't do anything. If it doesn't require interaction, we assume
290 // it was run as a separate pass.
292 // If this is the first function compiled, compute the related reg classes.
293 if (RelatedRegClasses.empty())
294 ComputeRelatedRegClasses();
296 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
297 vrm_.reset(new VirtRegMap(*mf_));
298 if (!spiller_.get()) spiller_.reset(createSpiller());
304 // Rewrite spill code and update the PhysRegsUsed set.
305 spiller_->runOnMachineFunction(*mf_, *vrm_);
306 vrm_.reset(); // Free the VirtRegMap
308 assert(unhandled_.empty() && "Unhandled live intervals remain!");
317 /// initIntervalSets - initialize the interval sets.
319 void RALinScan::initIntervalSets()
321 assert(unhandled_.empty() && fixed_.empty() &&
322 active_.empty() && inactive_.empty() &&
323 "interval sets should be empty on initialization");
325 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
326 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
327 reginfo_->setPhysRegUsed(i->second.reg);
328 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
330 unhandled_.push(&i->second);
334 void RALinScan::linearScan()
336 // linear scan algorithm
337 DOUT << "********** LINEAR SCAN **********\n";
338 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
340 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
342 while (!unhandled_.empty()) {
343 // pick the interval with the earliest start point
344 LiveInterval* cur = unhandled_.top();
347 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
350 processActiveIntervals(cur->beginNumber());
351 processInactiveIntervals(cur->beginNumber());
353 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
354 "Can only allocate virtual registers!");
357 // Allocating a virtual register. try to find a free
358 // physical register or spill an interval (possibly this one) in order to
360 assignRegOrStackSlotAtInterval(cur);
362 DEBUG(printIntervals("active", active_.begin(), active_.end()));
363 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
366 // expire any remaining active intervals
367 while (!active_.empty()) {
368 IntervalPtr &IP = active_.back();
369 unsigned reg = IP.first->reg;
370 DOUT << "\tinterval " << *IP.first << " expired\n";
371 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
372 "Can only allocate virtual registers!");
373 reg = vrm_->getPhys(reg);
374 prt_->delRegUse(reg);
378 // expire any remaining inactive intervals
379 DEBUG(for (IntervalPtrs::reverse_iterator
380 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
381 DOUT << "\tinterval " << *i->first << " expired\n");
384 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
385 MachineFunction::iterator EntryMBB = mf_->begin();
386 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
387 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
388 LiveInterval &cur = i->second;
390 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
393 else if (vrm_->isAssignedReg(cur.reg))
394 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
397 // Ignore splited live intervals.
398 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
400 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
402 const LiveRange &LR = *I;
403 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
404 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
405 if (LiveInMBBs[i] != EntryMBB)
406 LiveInMBBs[i]->addLiveIn(Reg);
415 /// processActiveIntervals - expire old intervals and move non-overlapping ones
416 /// to the inactive list.
417 void RALinScan::processActiveIntervals(unsigned CurPoint)
419 DOUT << "\tprocessing active intervals:\n";
421 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
422 LiveInterval *Interval = active_[i].first;
423 LiveInterval::iterator IntervalPos = active_[i].second;
424 unsigned reg = Interval->reg;
426 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
428 if (IntervalPos == Interval->end()) { // Remove expired intervals.
429 DOUT << "\t\tinterval " << *Interval << " expired\n";
430 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
431 "Can only allocate virtual registers!");
432 reg = vrm_->getPhys(reg);
433 prt_->delRegUse(reg);
435 // Pop off the end of the list.
436 active_[i] = active_.back();
440 } else if (IntervalPos->start > CurPoint) {
441 // Move inactive intervals to inactive list.
442 DOUT << "\t\tinterval " << *Interval << " inactive\n";
443 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
444 "Can only allocate virtual registers!");
445 reg = vrm_->getPhys(reg);
446 prt_->delRegUse(reg);
448 inactive_.push_back(std::make_pair(Interval, IntervalPos));
450 // Pop off the end of the list.
451 active_[i] = active_.back();
455 // Otherwise, just update the iterator position.
456 active_[i].second = IntervalPos;
461 /// processInactiveIntervals - expire old intervals and move overlapping
462 /// ones to the active list.
463 void RALinScan::processInactiveIntervals(unsigned CurPoint)
465 DOUT << "\tprocessing inactive intervals:\n";
467 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
468 LiveInterval *Interval = inactive_[i].first;
469 LiveInterval::iterator IntervalPos = inactive_[i].second;
470 unsigned reg = Interval->reg;
472 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
474 if (IntervalPos == Interval->end()) { // remove expired intervals.
475 DOUT << "\t\tinterval " << *Interval << " expired\n";
477 // Pop off the end of the list.
478 inactive_[i] = inactive_.back();
479 inactive_.pop_back();
481 } else if (IntervalPos->start <= CurPoint) {
482 // move re-activated intervals in active list
483 DOUT << "\t\tinterval " << *Interval << " active\n";
484 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
485 "Can only allocate virtual registers!");
486 reg = vrm_->getPhys(reg);
487 prt_->addRegUse(reg);
489 active_.push_back(std::make_pair(Interval, IntervalPos));
491 // Pop off the end of the list.
492 inactive_[i] = inactive_.back();
493 inactive_.pop_back();
496 // Otherwise, just update the iterator position.
497 inactive_[i].second = IntervalPos;
502 /// updateSpillWeights - updates the spill weights of the specifed physical
503 /// register and its weight.
504 static void updateSpillWeights(std::vector<float> &Weights,
505 unsigned reg, float weight,
506 const TargetRegisterInfo *TRI) {
507 Weights[reg] += weight;
508 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
509 Weights[*as] += weight;
513 RALinScan::IntervalPtrs::iterator
514 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
515 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
517 if (I->first == LI) return I;
521 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
522 for (unsigned i = 0, e = V.size(); i != e; ++i) {
523 RALinScan::IntervalPtr &IP = V[i];
524 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
526 if (I != IP.first->begin()) --I;
531 /// addStackInterval - Create a LiveInterval for stack if the specified live
532 /// interval has been spilled.
533 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
534 LiveIntervals *li_, float &Weight,
536 int SS = vrm_.getStackSlot(cur->reg);
537 if (SS == VirtRegMap::NO_STACK_SLOT)
539 LiveInterval &SI = ls_->getOrCreateInterval(SS);
543 if (SI.getNumValNums())
544 VNI = SI.getValNumInfo(0);
546 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
548 LiveInterval &RI = li_->getInterval(cur->reg);
549 // FIXME: This may be overly conservative.
550 SI.MergeRangesInAsValue(RI, VNI);
553 /// getConflictWeight - Return the number of conflicts between cur
554 /// live interval and defs and uses of Reg weighted by loop depthes.
555 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
557 MachineRegisterInfo *mri_,
558 const MachineLoopInfo *loopInfo) {
560 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
561 E = mri_->reg_end(); I != E; ++I) {
562 MachineInstr *MI = &*I;
563 if (cur->liveAt(li_->getInstructionIndex(MI))) {
564 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
565 Conflicts += powf(10.0f, (float)loopDepth);
571 /// findIntervalsToSpill - Determine the intervals to spill for the
572 /// specified interval. It's passed the physical registers whose spill
573 /// weight is the lowest among all the registers whose live intervals
574 /// conflict with the interval.
575 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
576 std::vector<std::pair<unsigned,float> > &Candidates,
578 SmallVector<LiveInterval*, 8> &SpillIntervals) {
579 // We have figured out the *best* register to spill. But there are other
580 // registers that are pretty good as well (spill weight within 3%). Spill
581 // the one that has fewest defs and uses that conflict with cur.
582 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
583 SmallVector<LiveInterval*, 8> SLIs[3];
585 DOUT << "\tConsidering " << NumCands << " candidates: ";
586 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
587 DOUT << tri_->getName(Candidates[i].first) << " ";
590 // Calculate the number of conflicts of each candidate.
591 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
592 unsigned Reg = i->first->reg;
593 unsigned PhysReg = vrm_->getPhys(Reg);
594 if (!cur->overlapsFrom(*i->first, i->second))
596 for (unsigned j = 0; j < NumCands; ++j) {
597 unsigned Candidate = Candidates[j].first;
598 if (tri_->regsOverlap(PhysReg, Candidate)) {
600 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
601 SLIs[j].push_back(i->first);
606 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
607 unsigned Reg = i->first->reg;
608 unsigned PhysReg = vrm_->getPhys(Reg);
609 if (!cur->overlapsFrom(*i->first, i->second-1))
611 for (unsigned j = 0; j < NumCands; ++j) {
612 unsigned Candidate = Candidates[j].first;
613 if (tri_->regsOverlap(PhysReg, Candidate)) {
615 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
616 SLIs[j].push_back(i->first);
621 // Which is the best candidate?
622 unsigned BestCandidate = 0;
623 float MinConflicts = Conflicts[0];
624 for (unsigned i = 1; i != NumCands; ++i) {
625 if (Conflicts[i] < MinConflicts) {
627 MinConflicts = Conflicts[i];
631 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
632 std::back_inserter(SpillIntervals));
636 struct WeightCompare {
637 typedef std::pair<unsigned, float> RegWeightPair;
638 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
639 return LHS.second < RHS.second;
644 static bool weightsAreClose(float w1, float w2) {
648 float diff = w1 - w2;
649 if (diff <= 0.02f) // Within 0.02f
651 return (diff / w2) <= 0.05f; // Within 5%.
654 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
656 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
658 DOUT << "\tallocating current interval: ";
660 // This is an implicitly defined live interval, just assign any register.
661 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
663 unsigned physReg = cur->preference;
665 physReg = *RC->allocation_order_begin(*mf_);
666 DOUT << tri_->getName(physReg) << '\n';
667 // Note the register is not really in use.
668 vrm_->assignVirt2Phys(cur->reg, physReg);
672 PhysRegTracker backupPrt = *prt_;
674 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
675 unsigned StartPosition = cur->beginNumber();
676 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
678 // If this live interval is defined by a move instruction and its source is
679 // assigned a physical register that is compatible with the target register
680 // class, then we should try to assign it the same register.
681 // This can happen when the move is from a larger register class to a smaller
682 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
683 if (!cur->preference && cur->containsOneValue()) {
684 VNInfo *vni = cur->getValNumInfo(0);
685 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
686 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
687 unsigned SrcReg, DstReg;
688 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
690 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
692 else if (vrm_->isAssignedReg(SrcReg))
693 Reg = vrm_->getPhys(SrcReg);
694 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
695 cur->preference = Reg;
700 // for every interval in inactive we overlap with, mark the
701 // register as not free and update spill weights.
702 for (IntervalPtrs::const_iterator i = inactive_.begin(),
703 e = inactive_.end(); i != e; ++i) {
704 unsigned Reg = i->first->reg;
705 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
706 "Can only allocate virtual registers!");
707 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
708 // If this is not in a related reg class to the register we're allocating,
710 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
711 cur->overlapsFrom(*i->first, i->second-1)) {
712 Reg = vrm_->getPhys(Reg);
713 prt_->addRegUse(Reg);
714 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
718 // Speculatively check to see if we can get a register right now. If not,
719 // we know we won't be able to by adding more constraints. If so, we can
720 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
721 // is very bad (it contains all callee clobbered registers for any functions
722 // with a call), so we want to avoid doing that if possible.
723 unsigned physReg = getFreePhysReg(cur);
724 unsigned BestPhysReg = physReg;
726 // We got a register. However, if it's in the fixed_ list, we might
727 // conflict with it. Check to see if we conflict with it or any of its
729 SmallSet<unsigned, 8> RegAliases;
730 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
731 RegAliases.insert(*AS);
733 bool ConflictsWithFixed = false;
734 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
735 IntervalPtr &IP = fixed_[i];
736 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
737 // Okay, this reg is on the fixed list. Check to see if we actually
739 LiveInterval *I = IP.first;
740 if (I->endNumber() > StartPosition) {
741 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
743 if (II != I->begin() && II->start > StartPosition)
745 if (cur->overlapsFrom(*I, II)) {
746 ConflictsWithFixed = true;
753 // Okay, the register picked by our speculative getFreePhysReg call turned
754 // out to be in use. Actually add all of the conflicting fixed registers to
755 // prt so we can do an accurate query.
756 if (ConflictsWithFixed) {
757 // For every interval in fixed we overlap with, mark the register as not
758 // free and update spill weights.
759 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
760 IntervalPtr &IP = fixed_[i];
761 LiveInterval *I = IP.first;
763 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
764 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
765 I->endNumber() > StartPosition) {
766 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
768 if (II != I->begin() && II->start > StartPosition)
770 if (cur->overlapsFrom(*I, II)) {
771 unsigned reg = I->reg;
772 prt_->addRegUse(reg);
773 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
778 // Using the newly updated prt_ object, which includes conflicts in the
779 // future, see if there are any registers available.
780 physReg = getFreePhysReg(cur);
784 // Restore the physical register tracker, removing information about the
788 // if we find a free register, we are done: assign this virtual to
789 // the free physical register and add this interval to the active
792 DOUT << tri_->getName(physReg) << '\n';
793 vrm_->assignVirt2Phys(cur->reg, physReg);
794 prt_->addRegUse(physReg);
795 active_.push_back(std::make_pair(cur, cur->begin()));
796 handled_.push_back(cur);
799 DOUT << "no free registers\n";
801 // Compile the spill weights into an array that is better for scanning.
802 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
803 for (std::vector<std::pair<unsigned, float> >::iterator
804 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
805 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
807 // for each interval in active, update spill weights.
808 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
810 unsigned reg = i->first->reg;
811 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
812 "Can only allocate virtual registers!");
813 reg = vrm_->getPhys(reg);
814 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
817 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
819 // Find a register to spill.
820 float minWeight = HUGE_VALF;
821 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
824 std::vector<std::pair<unsigned,float> > RegsWeights;
825 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
826 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
827 e = RC->allocation_order_end(*mf_); i != e; ++i) {
829 float regWeight = SpillWeights[reg];
830 if (minWeight > regWeight)
832 RegsWeights.push_back(std::make_pair(reg, regWeight));
835 // If we didn't find a register that is spillable, try aliases?
837 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
838 e = RC->allocation_order_end(*mf_); i != e; ++i) {
840 // No need to worry about if the alias register size < regsize of RC.
841 // We are going to spill all registers that alias it anyway.
842 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
843 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
847 // Sort all potential spill candidates by weight.
848 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
849 minReg = RegsWeights[0].first;
850 minWeight = RegsWeights[0].second;
851 if (minWeight == HUGE_VALF) {
852 // All registers must have inf weight. Just grab one!
853 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
854 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
855 // Spill a physical register around defs and uses.
856 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
859 // Find up to 3 registers to consider as spill candidates.
860 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
861 while (LastCandidate > 1) {
862 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
867 DOUT << "\t\tregister(s) with min weight(s): ";
868 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
869 DOUT << tri_->getName(RegsWeights[i].first)
870 << " (" << RegsWeights[i].second << ")\n");
872 // if the current has the minimum weight, we need to spill it and
873 // add any added intervals back to unhandled, and restart
875 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
876 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
878 std::vector<LiveInterval*> added =
879 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
880 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
882 return; // Early exit if all spills were folded.
884 // Merge added with unhandled. Note that we know that
885 // addIntervalsForSpills returns intervals sorted by their starting
887 for (unsigned i = 0, e = added.size(); i != e; ++i)
888 unhandled_.push(added[i]);
894 // push the current interval back to unhandled since we are going
895 // to re-run at least this iteration. Since we didn't modify it it
896 // should go back right in the front of the list
897 unhandled_.push(cur);
899 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
900 "did not choose a register to spill?");
902 // We spill all intervals aliasing the register with
903 // minimum weight, rollback to the interval with the earliest
904 // start point and let the linear scan algorithm run again
905 SmallVector<LiveInterval*, 8> spillIs;
907 // Determine which intervals have to be spilled.
908 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
910 // Set of spilled vregs (used later to rollback properly)
911 SmallSet<unsigned, 8> spilled;
913 // The earliest start of a Spilled interval indicates up to where
914 // in handled we need to roll back
915 unsigned earliestStart = cur->beginNumber();
917 // Spill live intervals of virtual regs mapped to the physical register we
918 // want to clear (and its aliases). We only spill those that overlap with the
919 // current interval as the rest do not affect its allocation. we also keep
920 // track of the earliest start of all spilled live intervals since this will
921 // mark our rollback point.
922 std::vector<LiveInterval*> added;
923 while (!spillIs.empty()) {
924 LiveInterval *sli = spillIs.back();
926 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
927 earliestStart = std::min(earliestStart, sli->beginNumber());
929 std::vector<LiveInterval*> newIs =
930 li_->addIntervalsForSpills(*sli, loopInfo, *vrm_, SSWeight);
931 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
932 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
933 spilled.insert(sli->reg);
936 DOUT << "\t\trolling back to: " << earliestStart << '\n';
938 // Scan handled in reverse order up to the earliest start of a
939 // spilled live interval and undo each one, restoring the state of
941 while (!handled_.empty()) {
942 LiveInterval* i = handled_.back();
943 // If this interval starts before t we are done.
944 if (i->beginNumber() < earliestStart)
946 DOUT << "\t\t\tundo changes for: " << *i << '\n';
949 // When undoing a live interval allocation we must know if it is active or
950 // inactive to properly update the PhysRegTracker and the VirtRegMap.
951 IntervalPtrs::iterator it;
952 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
954 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
955 if (!spilled.count(i->reg))
957 prt_->delRegUse(vrm_->getPhys(i->reg));
958 vrm_->clearVirt(i->reg);
959 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
961 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
962 if (!spilled.count(i->reg))
964 vrm_->clearVirt(i->reg);
966 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
967 "Can only allocate virtual registers!");
968 vrm_->clearVirt(i->reg);
972 // It interval has a preference, it must be defined by a copy. Clear the
973 // preference now since the source interval allocation may have been undone
978 // Rewind the iterators in the active, inactive, and fixed lists back to the
979 // point we reverted to.
980 RevertVectorIteratorsTo(active_, earliestStart);
981 RevertVectorIteratorsTo(inactive_, earliestStart);
982 RevertVectorIteratorsTo(fixed_, earliestStart);
984 // scan the rest and undo each interval that expired after t and
985 // insert it in active (the next iteration of the algorithm will
986 // put it in inactive if required)
987 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
988 LiveInterval *HI = handled_[i];
989 if (!HI->expiredAt(earliestStart) &&
990 HI->expiredAt(cur->beginNumber())) {
991 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
992 active_.push_back(std::make_pair(HI, HI->begin()));
993 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
994 prt_->addRegUse(vrm_->getPhys(HI->reg));
998 // merge added with unhandled
999 for (unsigned i = 0, e = added.size(); i != e; ++i)
1000 unhandled_.push(added[i]);
1003 /// getFreePhysReg - return a free physical register for this virtual register
1004 /// interval if we have one, otherwise return 0.
1005 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1006 SmallVector<unsigned, 256> inactiveCounts;
1007 unsigned MaxInactiveCount = 0;
1009 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
1010 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1012 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1014 unsigned reg = i->first->reg;
1015 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1016 "Can only allocate virtual registers!");
1018 // If this is not in a related reg class to the register we're allocating,
1020 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
1021 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1022 reg = vrm_->getPhys(reg);
1023 if (inactiveCounts.size() <= reg)
1024 inactiveCounts.resize(reg+1);
1025 ++inactiveCounts[reg];
1026 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1030 unsigned FreeReg = 0;
1031 unsigned FreeRegInactiveCount = 0;
1033 // If copy coalescer has assigned a "preferred" register, check if it's
1035 if (cur->preference) {
1036 if (prt_->isRegAvail(cur->preference)) {
1037 DOUT << "\t\tassigned the preferred register: "
1038 << tri_->getName(cur->preference) << "\n";
1039 return cur->preference;
1041 DOUT << "\t\tunable to assign the preferred register: "
1042 << tri_->getName(cur->preference) << "\n";
1045 // Scan for the first available register.
1046 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1047 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1048 assert(I != E && "No allocatable register in this register class!");
1050 if (prt_->isRegAvail(*I)) {
1052 if (FreeReg < inactiveCounts.size())
1053 FreeRegInactiveCount = inactiveCounts[FreeReg];
1055 FreeRegInactiveCount = 0;
1059 // If there are no free regs, or if this reg has the max inactive count,
1060 // return this register.
1061 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1063 // Continue scanning the registers, looking for the one with the highest
1064 // inactive count. Alkis found that this reduced register pressure very
1065 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1067 for (; I != E; ++I) {
1069 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1070 FreeRegInactiveCount < inactiveCounts[Reg]) {
1072 FreeRegInactiveCount = inactiveCounts[Reg];
1073 if (FreeRegInactiveCount == MaxInactiveCount)
1074 break; // We found the one with the max inactive count.
1081 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1082 return new RALinScan();