blob: 12e7d6a6975d59483fff854c7ef439df4daa0e4a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "regalloc"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015#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"
Evan Cheng26d17df2007-12-11 02:09:15 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/CodeGen/Passes.h"
24#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene1d80f1b2007-09-06 16:18:45 +000025#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000026#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Target/TargetMachine.h"
Evan Chengc4c75f52007-11-03 07:20:12 +000028#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#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"
34#include <algorithm>
35#include <set>
36#include <queue>
37#include <memory>
38#include <cmath>
39using namespace llvm;
40
41STATISTIC(NumIters , "Number of iterations performed");
42STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc4c75f52007-11-03 07:20:12 +000043STATISTIC(NumCoalesce, "Number of copies coalesced");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044
45static RegisterRegAlloc
46linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
48
49namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
51 static char ID;
52 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
53
54 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
56 private:
57 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
61 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62
63 MachineFunction* mf_;
64 const TargetMachine* tm_;
Dan Gohman1e57df32008-02-10 18:45:23 +000065 const TargetRegisterInfo* tri_;
Evan Chengc4c75f52007-11-03 07:20:12 +000066 const TargetInstrInfo* tii_;
Chris Lattner1b989192007-12-31 04:13:23 +000067 MachineRegisterInfo *reginfo_;
Evan Chengc4c75f52007-11-03 07:20:12 +000068 BitVector allocatableRegs_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 LiveIntervals* li_;
Evan Cheng26d17df2007-12-11 02:09:15 +000070 const MachineLoopInfo *loopInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071
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_;
75
76 /// fixed_ - Intervals that correspond to machine registers.
77 ///
78 IntervalPtrs fixed_;
79
80 /// active_ - Intervals that are currently being processed, and which have a
81 /// live range active for the current point.
82 IntervalPtrs active_;
83
84 /// inactive_ - Intervals that are currently being processed, but which have
85 /// a hold at the current point.
86 IntervalPtrs inactive_;
87
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_;
95
96 public:
97 virtual const char* getPassName() const {
98 return "Linear Scan Register Allocator";
99 }
100
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequired<LiveIntervals>();
David Greene1d80f1b2007-09-06 16:18:45 +0000103 // Make sure PassManager knows which analyses to make available
104 // to coalescing and which analyses coalescing invalidates.
105 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000106 AU.addRequired<MachineLoopInfo>();
Bill Wendling62264362008-01-04 20:54:55 +0000107 AU.addPreserved<MachineLoopInfo>();
108 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 MachineFunctionPass::getAnalysisUsage(AU);
110 }
111
112 /// runOnMachineFunction - register allocate the whole function
113 bool runOnMachineFunction(MachineFunction&);
114
115 private:
116 /// linearScan - the linear scan algorithm
117 void linearScan();
118
119 /// initIntervalSets - initialize the interval sets.
120 ///
121 void initIntervalSets();
122
123 /// processActiveIntervals - expire old intervals and move non-overlapping
124 /// ones to the inactive list.
125 void processActiveIntervals(unsigned CurPoint);
126
127 /// processInactiveIntervals - expire old intervals and move overlapping
128 /// ones to the active list.
129 void processInactiveIntervals(unsigned CurPoint);
130
131 /// assignRegOrStackSlotAtInterval - assign a register if one
132 /// is available, or spill.
133 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
134
Evan Chengc4c75f52007-11-03 07:20:12 +0000135 /// 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
141 /// conservative.
142 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
143
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 ///
145 /// register handling helpers
146 ///
147
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);
151
152 /// assignVirt2StackSlot - assigns this virtual register to a
153 /// stack slot. returns the stack slot
154 int assignVirt2StackSlot(unsigned virtReg);
155
156 void ComputeRelatedRegClasses();
157
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;
Dan Gohman1e57df32008-02-10 18:45:23 +0000164 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 reg = vrm_->getPhys(reg);
166 }
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000167 DOUT << tri_->getName(reg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168 }
169 }
170 };
171 char RALinScan::ID = 0;
172}
173
174void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman1e57df32008-02-10 18:45:23 +0000175 const TargetRegisterInfo &TRI = *tri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176
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;
Dan Gohman1e57df32008-02-10 18:45:23 +0000180 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
181 E = TRI.regclass_end(); RCI != E; ++RCI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 RelatedRegClasses.insert(*RCI);
183 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
184 I != E; ++I) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000185 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186
187 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
188 if (PRC) {
189 // Already processed this register. Just make sure we know that
190 // multiple register classes share a register.
191 RelatedRegClasses.unionSets(PRC, *RCI);
192 } else {
193 PRC = *RCI;
194 }
195 }
196 }
197
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.
201 if (HasAliases)
202 for (std::map<unsigned, const TargetRegisterClass*>::iterator
203 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
204 I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000205 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
207}
208
Evan Chengc4c75f52007-11-03 07:20:12 +0000209/// 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
215/// conservative.
216unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Chengb6aa6712007-11-04 08:32:21 +0000217 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc4c75f52007-11-03 07:20:12 +0000218 return Reg;
219
220 VNInfo *vni = cur.getValNumInfo(0);
221 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
222 return Reg;
223 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
224 unsigned SrcReg, DstReg;
225 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
226 return Reg;
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000227 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000228 if (!vrm_->isAssignedReg(SrcReg))
229 return Reg;
230 else
231 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000232 }
Evan Chengc4c75f52007-11-03 07:20:12 +0000233 if (Reg == SrcReg)
234 return Reg;
235
Chris Lattner1b989192007-12-31 04:13:23 +0000236 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc4c75f52007-11-03 07:20:12 +0000237 if (!RC->contains(SrcReg))
238 return Reg;
239
240 // Try to coalesce.
241 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000242 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling8eeb9792008-02-26 21:11:01 +0000243 << '\n';
Evan Chengc4c75f52007-11-03 07:20:12 +0000244 vrm_->clearVirt(cur.reg);
245 vrm_->assignVirt2Phys(cur.reg, SrcReg);
246 ++NumCoalesce;
247 return SrcReg;
248 }
249
250 return Reg;
251}
252
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
254 mf_ = &fn;
255 tm_ = &fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +0000256 tri_ = tm_->getRegisterInfo();
Evan Chengc4c75f52007-11-03 07:20:12 +0000257 tii_ = tm_->getInstrInfo();
Chris Lattner1b989192007-12-31 04:13:23 +0000258 reginfo_ = &mf_->getRegInfo();
Dan Gohman1e57df32008-02-10 18:45:23 +0000259 allocatableRegs_ = tri_->getAllocatableSet(fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000261 loopInfo = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
David Greene1d80f1b2007-09-06 16:18:45 +0000263 // 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.
267
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 // If this is the first function compiled, compute the related reg classes.
269 if (RelatedRegClasses.empty())
270 ComputeRelatedRegClasses();
271
Dan Gohman1e57df32008-02-10 18:45:23 +0000272 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 vrm_.reset(new VirtRegMap(*mf_));
274 if (!spiller_.get()) spiller_.reset(createSpiller());
275
276 initIntervalSets();
277
278 linearScan();
279
280 // Rewrite spill code and update the PhysRegsUsed set.
281 spiller_->runOnMachineFunction(*mf_, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 vrm_.reset(); // Free the VirtRegMap
283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 while (!unhandled_.empty()) unhandled_.pop();
285 fixed_.clear();
286 active_.clear();
287 inactive_.clear();
288 handled_.clear();
289
290 return true;
291}
292
293/// initIntervalSets - initialize the interval sets.
294///
295void RALinScan::initIntervalSets()
296{
297 assert(unhandled_.empty() && fixed_.empty() &&
298 active_.empty() && inactive_.empty() &&
299 "interval sets should be empty on initialization");
300
301 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000302 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
Chris Lattner1b989192007-12-31 04:13:23 +0000303 reginfo_->setPhysRegUsed(i->second.reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
305 } else
306 unhandled_.push(&i->second);
307 }
308}
309
310void RALinScan::linearScan()
311{
312 // linear scan algorithm
313 DOUT << "********** LINEAR SCAN **********\n";
314 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
315
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
318 while (!unhandled_.empty()) {
319 // pick the interval with the earliest start point
320 LiveInterval* cur = unhandled_.top();
321 unhandled_.pop();
Evan Chengd48f2bc2007-10-16 21:09:14 +0000322 ++NumIters;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
324
325 processActiveIntervals(cur->beginNumber());
326 processInactiveIntervals(cur->beginNumber());
327
Dan Gohman1e57df32008-02-10 18:45:23 +0000328 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 "Can only allocate virtual registers!");
330
331 // Allocating a virtual register. try to find a free
332 // physical register or spill an interval (possibly this one) in order to
333 // assign it one.
334 assignRegOrStackSlotAtInterval(cur);
335
336 DEBUG(printIntervals("active", active_.begin(), active_.end()));
337 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339
340 // expire any remaining active intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000341 while (!active_.empty()) {
342 IntervalPtr &IP = active_.back();
343 unsigned reg = IP.first->reg;
344 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000345 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 "Can only allocate virtual registers!");
347 reg = vrm_->getPhys(reg);
348 prt_->delRegUse(reg);
Evan Chengd48f2bc2007-10-16 21:09:14 +0000349 active_.pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 }
351
352 // expire any remaining inactive intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000353 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling1817ab82007-11-15 00:40:48 +0000354 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Chengd48f2bc2007-10-16 21:09:14 +0000355 DOUT << "\tinterval " << *i->first << " expired\n");
356 inactive_.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357
Evan Chengcecc8222007-11-17 00:40:40 +0000358 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Chengf5cdf122007-10-17 02:12:22 +0000359 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000360 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Chengf5cdf122007-10-17 02:12:22 +0000361 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000362 LiveInterval &cur = i->second;
Evan Chengf5cdf122007-10-17 02:12:22 +0000363 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000364 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Chengcecc8222007-11-17 00:40:40 +0000365 if (isPhys)
Evan Chengf5cdf122007-10-17 02:12:22 +0000366 Reg = i->second.reg;
367 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000368 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Chengf5cdf122007-10-17 02:12:22 +0000369 if (!Reg)
370 continue;
Evan Chengcecc8222007-11-17 00:40:40 +0000371 // Ignore splited live intervals.
372 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
373 continue;
Evan Chengf5cdf122007-10-17 02:12:22 +0000374 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
375 I != E; ++I) {
376 const LiveRange &LR = *I;
Evan Chengf5cdf122007-10-17 02:12:22 +0000377 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
378 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
379 if (LiveInMBBs[i] != EntryMBB)
380 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000381 LiveInMBBs.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 }
383 }
384 }
385
386 DOUT << *vrm_;
387}
388
389/// processActiveIntervals - expire old intervals and move non-overlapping ones
390/// to the inactive list.
391void RALinScan::processActiveIntervals(unsigned CurPoint)
392{
393 DOUT << "\tprocessing active intervals:\n";
394
395 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
396 LiveInterval *Interval = active_[i].first;
397 LiveInterval::iterator IntervalPos = active_[i].second;
398 unsigned reg = Interval->reg;
399
400 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
401
402 if (IntervalPos == Interval->end()) { // Remove expired intervals.
403 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000404 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 "Can only allocate virtual registers!");
406 reg = vrm_->getPhys(reg);
407 prt_->delRegUse(reg);
408
409 // Pop off the end of the list.
410 active_[i] = active_.back();
411 active_.pop_back();
412 --i; --e;
413
414 } else if (IntervalPos->start > CurPoint) {
415 // Move inactive intervals to inactive list.
416 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000417 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 "Can only allocate virtual registers!");
419 reg = vrm_->getPhys(reg);
420 prt_->delRegUse(reg);
421 // add to inactive.
422 inactive_.push_back(std::make_pair(Interval, IntervalPos));
423
424 // Pop off the end of the list.
425 active_[i] = active_.back();
426 active_.pop_back();
427 --i; --e;
428 } else {
429 // Otherwise, just update the iterator position.
430 active_[i].second = IntervalPos;
431 }
432 }
433}
434
435/// processInactiveIntervals - expire old intervals and move overlapping
436/// ones to the active list.
437void RALinScan::processInactiveIntervals(unsigned CurPoint)
438{
439 DOUT << "\tprocessing inactive intervals:\n";
440
441 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
442 LiveInterval *Interval = inactive_[i].first;
443 LiveInterval::iterator IntervalPos = inactive_[i].second;
444 unsigned reg = Interval->reg;
445
446 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
447
448 if (IntervalPos == Interval->end()) { // remove expired intervals.
449 DOUT << "\t\tinterval " << *Interval << " expired\n";
450
451 // Pop off the end of the list.
452 inactive_[i] = inactive_.back();
453 inactive_.pop_back();
454 --i; --e;
455 } else if (IntervalPos->start <= CurPoint) {
456 // move re-activated intervals in active list
457 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000458 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 "Can only allocate virtual registers!");
460 reg = vrm_->getPhys(reg);
461 prt_->addRegUse(reg);
462 // add to active
463 active_.push_back(std::make_pair(Interval, IntervalPos));
464
465 // Pop off the end of the list.
466 inactive_[i] = inactive_.back();
467 inactive_.pop_back();
468 --i; --e;
469 } else {
470 // Otherwise, just update the iterator position.
471 inactive_[i].second = IntervalPos;
472 }
473 }
474}
475
476/// updateSpillWeights - updates the spill weights of the specifed physical
477/// register and its weight.
478static void updateSpillWeights(std::vector<float> &Weights,
479 unsigned reg, float weight,
Dan Gohman1e57df32008-02-10 18:45:23 +0000480 const TargetRegisterInfo *TRI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 Weights[reg] += weight;
Dan Gohman1e57df32008-02-10 18:45:23 +0000482 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 Weights[*as] += weight;
484}
485
486static
487RALinScan::IntervalPtrs::iterator
488FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
489 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
490 I != E; ++I)
491 if (I->first == LI) return I;
492 return IP.end();
493}
494
495static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
496 for (unsigned i = 0, e = V.size(); i != e; ++i) {
497 RALinScan::IntervalPtr &IP = V[i];
498 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
499 IP.second, Point);
500 if (I != IP.first->begin()) --I;
501 IP.second = I;
502 }
503}
504
505/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
506/// spill.
507void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
508{
509 DOUT << "\tallocating current interval: ";
510
511 PhysRegTracker backupPrt = *prt_;
512
513 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
514 unsigned StartPosition = cur->beginNumber();
Chris Lattner1b989192007-12-31 04:13:23 +0000515 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc4c75f52007-11-03 07:20:12 +0000517
518 // If this live interval is defined by a move instruction and its source is
519 // assigned a physical register that is compatible with the target register
520 // class, then we should try to assign it the same register.
521 // This can happen when the move is from a larger register class to a smaller
522 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
523 if (!cur->preference && cur->containsOneValue()) {
524 VNInfo *vni = cur->getValNumInfo(0);
525 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
526 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
527 unsigned SrcReg, DstReg;
528 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
529 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000530 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000531 Reg = SrcReg;
532 else if (vrm_->isAssignedReg(SrcReg))
533 Reg = vrm_->getPhys(SrcReg);
534 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
535 cur->preference = Reg;
536 }
537 }
538 }
539
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 // for every interval in inactive we overlap with, mark the
541 // register as not free and update spill weights.
542 for (IntervalPtrs::const_iterator i = inactive_.begin(),
543 e = inactive_.end(); i != e; ++i) {
544 unsigned Reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000545 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 "Can only allocate virtual registers!");
Chris Lattner1b989192007-12-31 04:13:23 +0000547 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 // If this is not in a related reg class to the register we're allocating,
549 // don't check it.
550 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
551 cur->overlapsFrom(*i->first, i->second-1)) {
552 Reg = vrm_->getPhys(Reg);
553 prt_->addRegUse(Reg);
554 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
555 }
556 }
557
558 // Speculatively check to see if we can get a register right now. If not,
559 // we know we won't be able to by adding more constraints. If so, we can
560 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
561 // is very bad (it contains all callee clobbered registers for any functions
562 // with a call), so we want to avoid doing that if possible.
563 unsigned physReg = getFreePhysReg(cur);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000564 unsigned BestPhysReg = physReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 if (physReg) {
566 // We got a register. However, if it's in the fixed_ list, we might
567 // conflict with it. Check to see if we conflict with it or any of its
568 // aliases.
Evan Chengc4c75f52007-11-03 07:20:12 +0000569 SmallSet<unsigned, 8> RegAliases;
Dan Gohman1e57df32008-02-10 18:45:23 +0000570 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 RegAliases.insert(*AS);
572
573 bool ConflictsWithFixed = false;
574 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
575 IntervalPtr &IP = fixed_[i];
576 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
577 // Okay, this reg is on the fixed list. Check to see if we actually
578 // conflict.
579 LiveInterval *I = IP.first;
580 if (I->endNumber() > StartPosition) {
581 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
582 IP.second = II;
583 if (II != I->begin() && II->start > StartPosition)
584 --II;
585 if (cur->overlapsFrom(*I, II)) {
586 ConflictsWithFixed = true;
587 break;
588 }
589 }
590 }
591 }
592
593 // Okay, the register picked by our speculative getFreePhysReg call turned
594 // out to be in use. Actually add all of the conflicting fixed registers to
595 // prt so we can do an accurate query.
596 if (ConflictsWithFixed) {
597 // For every interval in fixed we overlap with, mark the register as not
598 // free and update spill weights.
599 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
600 IntervalPtr &IP = fixed_[i];
601 LiveInterval *I = IP.first;
602
603 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
604 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
605 I->endNumber() > StartPosition) {
606 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
607 IP.second = II;
608 if (II != I->begin() && II->start > StartPosition)
609 --II;
610 if (cur->overlapsFrom(*I, II)) {
611 unsigned reg = I->reg;
612 prt_->addRegUse(reg);
613 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
614 }
615 }
616 }
617
618 // Using the newly updated prt_ object, which includes conflicts in the
619 // future, see if there are any registers available.
620 physReg = getFreePhysReg(cur);
621 }
622 }
623
624 // Restore the physical register tracker, removing information about the
625 // future.
626 *prt_ = backupPrt;
627
628 // if we find a free register, we are done: assign this virtual to
629 // the free physical register and add this interval to the active
630 // list.
631 if (physReg) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000632 DOUT << tri_->getName(physReg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 vrm_->assignVirt2Phys(cur->reg, physReg);
634 prt_->addRegUse(physReg);
635 active_.push_back(std::make_pair(cur, cur->begin()));
636 handled_.push_back(cur);
637 return;
638 }
639 DOUT << "no free registers\n";
640
641 // Compile the spill weights into an array that is better for scanning.
Dan Gohman1e57df32008-02-10 18:45:23 +0000642 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 for (std::vector<std::pair<unsigned, float> >::iterator
644 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000645 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646
647 // for each interval in active, update spill weights.
648 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
649 i != e; ++i) {
650 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000651 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 "Can only allocate virtual registers!");
653 reg = vrm_->getPhys(reg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000654 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 }
656
657 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
658
659 // Find a register to spill.
660 float minWeight = HUGE_VALF;
661 unsigned minReg = cur->preference; // Try the preferred register first.
662
663 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
664 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
665 e = RC->allocation_order_end(*mf_); i != e; ++i) {
666 unsigned reg = *i;
667 if (minWeight > SpillWeights[reg]) {
668 minWeight = SpillWeights[reg];
669 minReg = reg;
670 }
671 }
672
673 // If we didn't find a register that is spillable, try aliases?
674 if (!minReg) {
675 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
676 e = RC->allocation_order_end(*mf_); i != e; ++i) {
677 unsigned reg = *i;
678 // No need to worry about if the alias register size < regsize of RC.
679 // We are going to spill all registers that alias it anyway.
Dan Gohman1e57df32008-02-10 18:45:23 +0000680 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 if (minWeight > SpillWeights[*as]) {
682 minWeight = SpillWeights[*as];
683 minReg = *as;
684 }
685 }
686 }
687
688 // All registers must have inf weight. Just grab one!
Evan Cheng14cc83f2008-03-11 07:19:34 +0000689 if (!minReg) {
690 if (BestPhysReg)
691 minReg = BestPhysReg;
692 else {
693 // Get the physical register with the fewest conflicts.
694 unsigned MinConflicts = ~0U;
695 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
696 e = RC->allocation_order_end(*mf_); i != e; ++i) {
697 unsigned reg = *i;
698 unsigned NumConflicts = li_->getNumConflictsWithPhysReg(*cur, reg);
699 if (NumConflicts <= MinConflicts) {
700 MinConflicts = NumConflicts;
701 minReg = reg;
702 }
703 }
704 }
705
706 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
707 // Spill a physical register around defs and uses.
708 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
709 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 }
711
712 DOUT << "\t\tregister with min weight: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000713 << tri_->getName(minReg) << " (" << minWeight << ")\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714
715 // if the current has the minimum weight, we need to spill it and
716 // add any added intervals back to unhandled, and restart
717 // linearscan.
718 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
719 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 std::vector<LiveInterval*> added =
Evan Chengcecc8222007-11-17 00:40:40 +0000721 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 if (added.empty())
723 return; // Early exit if all spills were folded.
724
725 // Merge added with unhandled. Note that we know that
726 // addIntervalsForSpills returns intervals sorted by their starting
727 // point.
728 for (unsigned i = 0, e = added.size(); i != e; ++i)
729 unhandled_.push(added[i]);
730 return;
731 }
732
733 ++NumBacktracks;
734
735 // push the current interval back to unhandled since we are going
736 // to re-run at least this iteration. Since we didn't modify it it
737 // should go back right in the front of the list
738 unhandled_.push(cur);
739
740 // otherwise we spill all intervals aliasing the register with
741 // minimum weight, rollback to the interval with the earliest
742 // start point and let the linear scan algorithm run again
743 std::vector<LiveInterval*> added;
Dan Gohman1e57df32008-02-10 18:45:23 +0000744 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 "did not choose a register to spill?");
Dan Gohman1e57df32008-02-10 18:45:23 +0000746 BitVector toSpill(tri_->getNumRegs());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747
748 // We are going to spill minReg and all its aliases.
749 toSpill[minReg] = true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000750 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 toSpill[*as] = true;
752
753 // the earliest start of a spilled interval indicates up to where
754 // in handled we need to roll back
755 unsigned earliestStart = cur->beginNumber();
756
757 // set of spilled vregs (used later to rollback properly)
Evan Chengc4c75f52007-11-03 07:20:12 +0000758 SmallSet<unsigned, 32> spilled;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759
760 // spill live intervals of virtual regs mapped to the physical register we
761 // want to clear (and its aliases). We only spill those that overlap with the
762 // current interval as the rest do not affect its allocation. we also keep
763 // track of the earliest start of all spilled live intervals since this will
764 // mark our rollback point.
765 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
766 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000767 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 toSpill[vrm_->getPhys(reg)] &&
769 cur->overlapsFrom(*i->first, i->second)) {
770 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
771 earliestStart = std::min(earliestStart, i->first->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 std::vector<LiveInterval*> newIs =
Evan Chengcecc8222007-11-17 00:40:40 +0000773 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
775 spilled.insert(reg);
776 }
777 }
778 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
779 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000780 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 toSpill[vrm_->getPhys(reg)] &&
782 cur->overlapsFrom(*i->first, i->second-1)) {
783 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
784 earliestStart = std::min(earliestStart, i->first->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 std::vector<LiveInterval*> newIs =
Evan Chengcecc8222007-11-17 00:40:40 +0000786 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
788 spilled.insert(reg);
789 }
790 }
791
792 DOUT << "\t\trolling back to: " << earliestStart << '\n';
793
794 // Scan handled in reverse order up to the earliest start of a
795 // spilled live interval and undo each one, restoring the state of
796 // unhandled.
797 while (!handled_.empty()) {
798 LiveInterval* i = handled_.back();
799 // If this interval starts before t we are done.
800 if (i->beginNumber() < earliestStart)
801 break;
802 DOUT << "\t\t\tundo changes for: " << *i << '\n';
803 handled_.pop_back();
804
805 // When undoing a live interval allocation we must know if it is active or
806 // inactive to properly update the PhysRegTracker and the VirtRegMap.
807 IntervalPtrs::iterator it;
808 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
809 active_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000810 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 if (!spilled.count(i->reg))
812 unhandled_.push(i);
813 prt_->delRegUse(vrm_->getPhys(i->reg));
814 vrm_->clearVirt(i->reg);
815 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
816 inactive_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000817 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 if (!spilled.count(i->reg))
819 unhandled_.push(i);
820 vrm_->clearVirt(i->reg);
821 } else {
Dan Gohman1e57df32008-02-10 18:45:23 +0000822 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 "Can only allocate virtual registers!");
824 vrm_->clearVirt(i->reg);
825 unhandled_.push(i);
826 }
Evan Chengb6aa6712007-11-04 08:32:21 +0000827
828 // It interval has a preference, it must be defined by a copy. Clear the
829 // preference now since the source interval allocation may have been undone
830 // as well.
831 i->preference = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 }
833
834 // Rewind the iterators in the active, inactive, and fixed lists back to the
835 // point we reverted to.
836 RevertVectorIteratorsTo(active_, earliestStart);
837 RevertVectorIteratorsTo(inactive_, earliestStart);
838 RevertVectorIteratorsTo(fixed_, earliestStart);
839
840 // scan the rest and undo each interval that expired after t and
841 // insert it in active (the next iteration of the algorithm will
842 // put it in inactive if required)
843 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
844 LiveInterval *HI = handled_[i];
845 if (!HI->expiredAt(earliestStart) &&
846 HI->expiredAt(cur->beginNumber())) {
847 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
848 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman1e57df32008-02-10 18:45:23 +0000849 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 prt_->addRegUse(vrm_->getPhys(HI->reg));
851 }
852 }
853
854 // merge added with unhandled
855 for (unsigned i = 0, e = added.size(); i != e; ++i)
856 unhandled_.push(added[i]);
857}
858
859/// getFreePhysReg - return a free physical register for this virtual register
860/// interval if we have one, otherwise return 0.
861unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000862 SmallVector<unsigned, 256> inactiveCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 unsigned MaxInactiveCount = 0;
864
Chris Lattner1b989192007-12-31 04:13:23 +0000865 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
867
868 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
869 i != e; ++i) {
870 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000871 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 "Can only allocate virtual registers!");
873
874 // If this is not in a related reg class to the register we're allocating,
875 // don't check it.
Chris Lattner1b989192007-12-31 04:13:23 +0000876 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
878 reg = vrm_->getPhys(reg);
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000879 if (inactiveCounts.size() <= reg)
880 inactiveCounts.resize(reg+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 ++inactiveCounts[reg];
882 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
883 }
884 }
885
886 unsigned FreeReg = 0;
887 unsigned FreeRegInactiveCount = 0;
888
889 // If copy coalescer has assigned a "preferred" register, check if it's
890 // available first.
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000891 if (cur->preference) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 if (prt_->isRegAvail(cur->preference)) {
893 DOUT << "\t\tassigned the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000894 << tri_->getName(cur->preference) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895 return cur->preference;
896 } else
897 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000898 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900
901 // Scan for the first available register.
902 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
903 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
904 for (; I != E; ++I)
905 if (prt_->isRegAvail(*I)) {
906 FreeReg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000907 if (FreeReg < inactiveCounts.size())
908 FreeRegInactiveCount = inactiveCounts[FreeReg];
909 else
910 FreeRegInactiveCount = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 break;
912 }
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000913
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 // If there are no free regs, or if this reg has the max inactive count,
915 // return this register.
916 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
917
918 // Continue scanning the registers, looking for the one with the highest
919 // inactive count. Alkis found that this reduced register pressure very
920 // slightly on X86 (in rev 1.94 of this file), though this should probably be
921 // reevaluated now.
922 for (; I != E; ++I) {
923 unsigned Reg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000924 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
925 FreeRegInactiveCount < inactiveCounts[Reg]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 FreeReg = Reg;
927 FreeRegInactiveCount = inactiveCounts[Reg];
928 if (FreeRegInactiveCount == MaxInactiveCount)
929 break; // We found the one with the max inactive count.
930 }
931 }
932
933 return FreeReg;
934}
935
936FunctionPass* llvm::createLinearScanRegisterAllocator() {
937 return new RALinScan();
938}