blob: 4df172d40c7f61abb3b7fb75fbb36de85fd24d5f [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +000013
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
Chris Lattnerb9805782005-08-23 22:27:31 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000017#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000025#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000029#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000030#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000035#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000036#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000037#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000038#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000040using namespace llvm;
41
Chris Lattnercd3245a2006-12-19 22:41:21 +000042STATISTIC(NumIters , "Number of iterations performed");
43STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000044STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000045
Evan Cheng3e172252008-06-20 21:45:16 +000046static cl::opt<bool>
47NewHeuristic("new-spilling-heuristic",
48 cl::desc("Use new spilling heuristic"),
49 cl::init(false), cl::Hidden);
50
Chris Lattnercd3245a2006-12-19 22:41:21 +000051static RegisterRegAlloc
52linearscanRegAlloc("linearscan", " linear scan register allocator",
53 createLinearScanRegisterAllocator);
54
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000055namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000056 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000057 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000058 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000059
Chris Lattnercbb56252004-11-18 02:42:27 +000060 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
61 typedef std::vector<IntervalPtr> IntervalPtrs;
62 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000063 /// 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;
68
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000070 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000071 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000072 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000073 const TargetInstrInfo* tii_;
Chris Lattner84bc5422007-12-31 04:13:23 +000074 MachineRegisterInfo *reginfo_;
Evan Chengc92da382007-11-03 07:20:12 +000075 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000077 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000078 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000079
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_;
83
84 /// fixed_ - Intervals that correspond to machine registers.
85 ///
86 IntervalPtrs fixed_;
87
88 /// active_ - Intervals that are currently being processed, and which have a
89 /// live range active for the current point.
90 IntervalPtrs active_;
91
92 /// inactive_ - Intervals that are currently being processed, but which have
93 /// a hold at the current point.
94 IntervalPtrs inactive_;
95
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000097 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000098 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_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000103
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 public:
105 virtual const char* getPassName() const {
106 return "Linear Scan Register Allocator";
107 }
108
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000110 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000111 // Make sure PassManager knows which analyses to make available
112 // to coalescing and which analyses coalescing invalidates.
113 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000114 AU.addRequired<LiveStacks>();
115 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000116 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 MachineFunctionPass::getAnalysisUsage(AU);
120 }
121
122 /// runOnMachineFunction - register allocate the whole function
123 bool runOnMachineFunction(MachineFunction&);
124
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 private:
126 /// linearScan - the linear scan algorithm
127 void linearScan();
128
Chris Lattnercbb56252004-11-18 02:42:27 +0000129 /// initIntervalSets - initialize the interval sets.
130 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 void initIntervalSets();
132
Chris Lattnercbb56252004-11-18 02:42:27 +0000133 /// processActiveIntervals - expire old intervals and move non-overlapping
134 /// ones to the inactive list.
135 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000136
Chris Lattnercbb56252004-11-18 02:42:27 +0000137 /// processInactiveIntervals - expire old intervals and move overlapping
138 /// ones to the active list.
139 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000141 /// assignRegOrStackSlotAtInterval - assign a register if one
142 /// is available, or spill.
143 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
144
Evan Cheng3e172252008-06-20 21:45:16 +0000145 /// 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,
151 unsigned NumCands,
152 SmallVector<LiveInterval*, 8> &SpillIntervals);
153
Evan Chengc92da382007-11-03 07:20:12 +0000154 /// 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
160 /// conservative.
161 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
162
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000163 ///
164 /// register handling helpers
165 ///
166
Chris Lattnercbb56252004-11-18 02:42:27 +0000167 /// getFreePhysReg - return a free physical register for this virtual
168 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000169 unsigned getFreePhysReg(LiveInterval* cur);
170
171 /// assignVirt2StackSlot - assigns this virtual register to a
172 /// stack slot. returns the stack slot
173 int assignVirt2StackSlot(unsigned virtReg);
174
Chris Lattnerb9805782005-08-23 22:27:31 +0000175 void ComputeRelatedRegClasses();
176
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000177 template <typename ItTy>
178 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000179 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000180 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000181 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000182 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000183 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000184 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000185 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000186 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000187 }
188 }
189 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000190 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000191}
192
Evan Cheng3f32d652008-06-04 09:18:41 +0000193static RegisterPass<RALinScan>
194X("linearscan-regalloc", "Linear Scan Register Allocator");
195
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000196void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000197 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000198
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;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000202 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
203 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000204 RelatedRegClasses.insert(*RCI);
205 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
206 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000207 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000208
209 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
210 if (PRC) {
211 // Already processed this register. Just make sure we know that
212 // multiple register classes share a register.
213 RelatedRegClasses.unionSets(PRC, *RCI);
214 } else {
215 PRC = *RCI;
216 }
217 }
218 }
219
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.
223 if (HasAliases)
224 for (std::map<unsigned, const TargetRegisterClass*>::iterator
225 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
226 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000227 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000228 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
229}
230
Evan Chengc92da382007-11-03 07:20:12 +0000231/// 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
237/// conservative.
238unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000239 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000240 return Reg;
241
242 VNInfo *vni = cur.getValNumInfo(0);
243 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
244 return Reg;
245 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
246 unsigned SrcReg, DstReg;
247 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
248 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000249 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000250 if (!vrm_->isAssignedReg(SrcReg))
251 return Reg;
252 else
253 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000254 }
Evan Chengc92da382007-11-03 07:20:12 +0000255 if (Reg == SrcReg)
256 return Reg;
257
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000259 if (!RC->contains(SrcReg))
260 return Reg;
261
262 // Try to coalesce.
263 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000264 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000265 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000266 vrm_->clearVirt(cur.reg);
267 vrm_->assignVirt2Phys(cur.reg, SrcReg);
268 ++NumCoalesce;
269 return SrcReg;
270 }
271
272 return Reg;
273}
274
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000275bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000276 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000277 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000278 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000279 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000280 tii_ = tm_->getInstrInfo();
Chris Lattner84bc5422007-12-31 04:13:23 +0000281 reginfo_ = &mf_->getRegInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000282 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000283 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000284 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000285 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000286
David Greene2c17c4d2007-09-06 16:18:45 +0000287 // 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.
291
Chris Lattnerb9805782005-08-23 22:27:31 +0000292 // If this is the first function compiled, compute the related reg classes.
293 if (RelatedRegClasses.empty())
294 ComputeRelatedRegClasses();
295
Dan Gohman6f0d0242008-02-10 18:45:23 +0000296 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000297 vrm_.reset(new VirtRegMap(*mf_));
298 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000301
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000303
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000304 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000306 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000307
Dan Gohman51cd9d62008-06-23 23:51:16 +0000308 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000309 fixed_.clear();
310 active_.clear();
311 inactive_.clear();
312 handled_.clear();
313
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000314 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000315}
316
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000317/// initIntervalSets - initialize the interval sets.
318///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000319void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000320{
321 assert(unhandled_.empty() && fixed_.empty() &&
322 active_.empty() && inactive_.empty() &&
323 "interval sets should be empty on initialization");
324
325 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000326 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000327 reginfo_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000328 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000329 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000330 unhandled_.push(&i->second);
331 }
332}
333
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000334void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000335{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000337 DOUT << "********** LINEAR SCAN **********\n";
338 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000339
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000340 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000341
342 while (!unhandled_.empty()) {
343 // pick the interval with the earliest start point
344 LiveInterval* cur = unhandled_.top();
345 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000346 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000347 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348
Evan Chengf30a49d2008-04-03 16:40:27 +0000349 if (!cur->empty()) {
350 processActiveIntervals(cur->beginNumber());
351 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352
Evan Chengf30a49d2008-04-03 16:40:27 +0000353 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
354 "Can only allocate virtual registers!");
355 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000356
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000357 // Allocating a virtual register. try to find a free
358 // physical register or spill an interval (possibly this one) in order to
359 // assign it one.
360 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000362 DEBUG(printIntervals("active", active_.begin(), active_.end()));
363 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000365
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000367 while (!active_.empty()) {
368 IntervalPtr &IP = active_.back();
369 unsigned reg = IP.first->reg;
370 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000371 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000372 "Can only allocate virtual registers!");
373 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000375 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000377
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000379 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000380 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000381 DOUT << "\tinterval " << *i->first << " expired\n");
382 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000383
Evan Cheng81a03822007-11-17 00:40:40 +0000384 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000385 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000386 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000387 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000388 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000389 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000390 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000391 if (isPhys)
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000392 Reg = i->second.reg;
393 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000394 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000395 if (!Reg)
396 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000397 // Ignore splited live intervals.
398 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
399 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000400 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
401 I != E; ++I) {
402 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 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);
Evan Chenga5bfc972007-10-17 06:53:44 +0000407 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000408 }
409 }
410 }
411
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000412 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000413}
414
Chris Lattnercbb56252004-11-18 02:42:27 +0000415/// processActiveIntervals - expire old intervals and move non-overlapping ones
416/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000417void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000418{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000419 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000420
Chris Lattnercbb56252004-11-18 02:42:27 +0000421 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;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000425
Chris Lattnercbb56252004-11-18 02:42:27 +0000426 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
427
428 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000429 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000430 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000431 "Can only allocate virtual registers!");
432 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000433 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000434
435 // Pop off the end of the list.
436 active_[i] = active_.back();
437 active_.pop_back();
438 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000439
Chris Lattnercbb56252004-11-18 02:42:27 +0000440 } else if (IntervalPos->start > CurPoint) {
441 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000442 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000443 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000444 "Can only allocate virtual registers!");
445 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000447 // add to inactive.
448 inactive_.push_back(std::make_pair(Interval, IntervalPos));
449
450 // Pop off the end of the list.
451 active_[i] = active_.back();
452 active_.pop_back();
453 --i; --e;
454 } else {
455 // Otherwise, just update the iterator position.
456 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457 }
458 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000459}
460
Chris Lattnercbb56252004-11-18 02:42:27 +0000461/// processInactiveIntervals - expire old intervals and move overlapping
462/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000463void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000464{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000465 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000466
Chris Lattnercbb56252004-11-18 02:42:27 +0000467 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;
Chris Lattner23b71c12004-11-18 01:29:39 +0000471
Chris Lattnercbb56252004-11-18 02:42:27 +0000472 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000473
Chris Lattnercbb56252004-11-18 02:42:27 +0000474 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000475 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000476
Chris Lattnercbb56252004-11-18 02:42:27 +0000477 // Pop off the end of the list.
478 inactive_[i] = inactive_.back();
479 inactive_.pop_back();
480 --i; --e;
481 } else if (IntervalPos->start <= CurPoint) {
482 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000483 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000484 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000485 "Can only allocate virtual registers!");
486 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000487 prt_->addRegUse(reg);
488 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000489 active_.push_back(std::make_pair(Interval, IntervalPos));
490
491 // Pop off the end of the list.
492 inactive_[i] = inactive_.back();
493 inactive_.pop_back();
494 --i; --e;
495 } else {
496 // Otherwise, just update the iterator position.
497 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 }
499 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000500}
501
Chris Lattnercbb56252004-11-18 02:42:27 +0000502/// updateSpillWeights - updates the spill weights of the specifed physical
503/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000504static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000505 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000506 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000507 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000508 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000509 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510}
511
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000512static
513RALinScan::IntervalPtrs::iterator
514FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
515 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
516 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000517 if (I->first == LI) return I;
518 return IP.end();
519}
520
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000521static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000522 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000523 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000524 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
525 IP.second, Point);
526 if (I != IP.first->begin()) --I;
527 IP.second = I;
528 }
529}
Chris Lattnercbb56252004-11-18 02:42:27 +0000530
Evan Cheng3f32d652008-06-04 09:18:41 +0000531/// addStackInterval - Create a LiveInterval for stack if the specified live
532/// interval has been spilled.
533static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000534 LiveIntervals *li_, float &Weight,
535 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000536 int SS = vrm_.getStackSlot(cur->reg);
537 if (SS == VirtRegMap::NO_STACK_SLOT)
538 return;
539 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000540 SI.weight += Weight;
541
Evan Cheng3f32d652008-06-04 09:18:41 +0000542 VNInfo *VNI;
543 if (SI.getNumValNums())
544 VNI = SI.getValNumInfo(0);
545 else
546 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
547
548 LiveInterval &RI = li_->getInterval(cur->reg);
549 // FIXME: This may be overly conservative.
550 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000551}
552
Evan Cheng3e172252008-06-20 21:45:16 +0000553/// getConflictWeight - Return the number of conflicts between cur
554/// live interval and defs and uses of Reg weighted by loop depthes.
555static float getConflictWeight(LiveInterval *cur, unsigned Reg,
556 LiveIntervals *li_,
557 MachineRegisterInfo *mri_,
558 const MachineLoopInfo *loopInfo) {
559 float Conflicts = 0;
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);
566 }
567 }
568 return Conflicts;
569}
570
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.
575void RALinScan::findIntervalsToSpill(LiveInterval *cur,
576 std::vector<std::pair<unsigned,float> > &Candidates,
577 unsigned NumCands,
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];
584
585 DOUT << "\tConsidering " << NumCands << " candidates: ";
586 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
587 DOUT << tri_->getName(Candidates[i].first) << " ";
588 DOUT << "\n";);
589
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))
595 continue;
596 for (unsigned j = 0; j < NumCands; ++j) {
597 unsigned Candidate = Candidates[j].first;
598 if (tri_->regsOverlap(PhysReg, Candidate)) {
599 if (NumCands > 1)
600 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
601 SLIs[j].push_back(i->first);
602 }
603 }
604 }
605
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))
610 continue;
611 for (unsigned j = 0; j < NumCands; ++j) {
612 unsigned Candidate = Candidates[j].first;
613 if (tri_->regsOverlap(PhysReg, Candidate)) {
614 if (NumCands > 1)
615 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
616 SLIs[j].push_back(i->first);
617 }
618 }
619 }
620
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) {
626 BestCandidate = i;
627 MinConflicts = Conflicts[i];
628 }
629 }
630
631 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
632 std::back_inserter(SpillIntervals));
633}
634
635namespace {
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;
640 }
641 };
642}
643
644static bool weightsAreClose(float w1, float w2) {
645 if (!NewHeuristic)
646 return false;
647
648 float diff = w1 - w2;
649 if (diff <= 0.02f) // Within 0.02f
650 return true;
651 return (diff / w2) <= 0.05f; // Within 5%.
652}
653
Chris Lattnercbb56252004-11-18 02:42:27 +0000654/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
655/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000656void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000657{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000658 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000659
Evan Chengf30a49d2008-04-03 16:40:27 +0000660 // This is an implicitly defined live interval, just assign any register.
661 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
662 if (cur->empty()) {
663 unsigned physReg = cur->preference;
664 if (!physReg)
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);
Evan Chengf30a49d2008-04-03 16:40:27 +0000669 return;
670 }
671
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000672 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000673
Chris Lattnera6c17502005-08-22 20:20:42 +0000674 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000675 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000676 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000677
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;
Evan Chengf2b24ca2008-04-11 17:55:47 +0000688 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000689 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000690 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000691 Reg = SrcReg;
692 else if (vrm_->isAssignedReg(SrcReg))
693 Reg = vrm_->getPhys(SrcReg);
694 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
695 cur->preference = Reg;
696 }
697 }
698 }
699
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000701 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 for (IntervalPtrs::const_iterator i = inactive_.begin(),
703 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000704 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000705 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000706 "Can only allocate virtual registers!");
Chris Lattner84bc5422007-12-31 04:13:23 +0000707 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000708 // If this is not in a related reg class to the register we're allocating,
709 // don't check it.
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));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000715 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000717
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);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000724 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000725 if (physReg) {
726 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000727 // conflict with it. Check to see if we conflict with it or any of its
728 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000729 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000730 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000731 RegAliases.insert(*AS);
732
Chris Lattnera411cbc2005-08-22 20:59:30 +0000733 bool ConflictsWithFixed = false;
734 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000735 IntervalPtr &IP = fixed_[i];
736 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000737 // Okay, this reg is on the fixed list. Check to see if we actually
738 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000739 LiveInterval *I = IP.first;
740 if (I->endNumber() > StartPosition) {
741 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
742 IP.second = II;
743 if (II != I->begin() && II->start > StartPosition)
744 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000745 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000746 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000747 break;
748 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000749 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000750 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000751 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000752
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) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000757 // For every interval in fixed we overlap with, mark the register as not
758 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000759 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
760 IntervalPtr &IP = fixed_[i];
761 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000762
763 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
764 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
765 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000766 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
767 IP.second = II;
768 if (II != I->begin() && II->start > StartPosition)
769 --II;
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));
774 }
775 }
776 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000777
Chris Lattnera411cbc2005-08-22 20:59:30 +0000778 // Using the newly updated prt_ object, which includes conflicts in the
779 // future, see if there are any registers available.
780 physReg = getFreePhysReg(cur);
781 }
782 }
783
Chris Lattnera6c17502005-08-22 20:20:42 +0000784 // Restore the physical register tracker, removing information about the
785 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000787
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000788 // 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
790 // list.
791 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000792 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000793 vrm_->assignVirt2Phys(cur->reg, physReg);
794 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000795 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000796 handled_.push_back(cur);
797 return;
798 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000799 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000800
Chris Lattnera6c17502005-08-22 20:20:42 +0000801 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000802 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000803 for (std::vector<std::pair<unsigned, float> >::iterator
804 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000805 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000806
807 // for each interval in active, update spill weights.
808 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
809 i != e; ++i) {
810 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000811 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000812 "Can only allocate virtual registers!");
813 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000814 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000815 }
816
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000817 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000818
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000819 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000820 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000821 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
822
823 bool Found = false;
824 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000825 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) {
828 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000829 float regWeight = SpillWeights[reg];
830 if (minWeight > regWeight)
831 Found = true;
832 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000833 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000834
835 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000836 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000837 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
838 e = RC->allocation_order_end(*mf_); i != e; ++i) {
839 unsigned reg = *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.
Evan Cheng3e172252008-06-20 21:45:16 +0000842 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
843 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000844 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000845 }
Evan Cheng3e172252008-06-20 21:45:16 +0000846
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_);
Owen Andersona1566f22008-07-22 22:46:49 +0000854 if (cur->weight == HUGE_VALF ||
855 li_->getApproximateInstructionCount(*cur) == 1)
Evan Cheng3e172252008-06-20 21:45:16 +0000856 // Spill a physical register around defs and uses.
857 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
858 }
859
860 // Find up to 3 registers to consider as spill candidates.
861 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
862 while (LastCandidate > 1) {
863 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
864 break;
865 --LastCandidate;
866 }
867
868 DOUT << "\t\tregister(s) with min weight(s): ";
869 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
870 DOUT << tri_->getName(RegsWeights[i].first)
871 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000872
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000873 // if the current has the minimum weight, we need to spill it and
874 // add any added intervals back to unhandled, and restart
875 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000876 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000877 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000878 float SSWeight;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000879 std::vector<LiveInterval*> added =
Evan Cheng9c3c2212008-06-06 07:54:39 +0000880 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
881 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000882 if (added.empty())
883 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000884
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000885 // Merge added with unhandled. Note that we know that
886 // addIntervalsForSpills returns intervals sorted by their starting
887 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000888 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000889 unhandled_.push(added[i]);
890 return;
891 }
892
Chris Lattner19828d42004-11-18 03:49:30 +0000893 ++NumBacktracks;
894
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000895 // push the current interval back to unhandled since we are going
896 // to re-run at least this iteration. Since we didn't modify it it
897 // should go back right in the front of the list
898 unhandled_.push(cur);
899
Dan Gohman6f0d0242008-02-10 18:45:23 +0000900 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000901 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000902
Evan Cheng3e172252008-06-20 21:45:16 +0000903 // We spill all intervals aliasing the register with
904 // minimum weight, rollback to the interval with the earliest
905 // start point and let the linear scan algorithm run again
906 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000907
Evan Cheng3e172252008-06-20 21:45:16 +0000908 // Determine which intervals have to be spilled.
909 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
910
911 // Set of spilled vregs (used later to rollback properly)
912 SmallSet<unsigned, 8> spilled;
913
914 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000915 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000916 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000917
Evan Cheng3e172252008-06-20 21:45:16 +0000918 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000919 // want to clear (and its aliases). We only spill those that overlap with the
920 // current interval as the rest do not affect its allocation. we also keep
921 // track of the earliest start of all spilled live intervals since this will
922 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000923 std::vector<LiveInterval*> added;
924 while (!spillIs.empty()) {
925 LiveInterval *sli = spillIs.back();
926 spillIs.pop_back();
927 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
928 earliestStart = std::min(earliestStart, sli->beginNumber());
929 float SSWeight;
930 std::vector<LiveInterval*> newIs =
931 li_->addIntervalsForSpills(*sli, loopInfo, *vrm_, SSWeight);
932 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
933 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
934 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000935 }
936
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000937 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000938
939 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000940 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000941 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000942 while (!handled_.empty()) {
943 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000944 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000945 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000946 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000947 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000948 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000949
950 // When undoing a live interval allocation we must know if it is active or
951 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000952 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000953 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000954 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000955 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000956 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000957 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000958 prt_->delRegUse(vrm_->getPhys(i->reg));
959 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000960 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000961 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000962 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000963 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000964 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000965 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000966 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000967 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000968 "Can only allocate virtual registers!");
969 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000970 unhandled_.push(i);
971 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000972
973 // It interval has a preference, it must be defined by a copy. Clear the
974 // preference now since the source interval allocation may have been undone
975 // as well.
976 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000977 }
978
Chris Lattner19828d42004-11-18 03:49:30 +0000979 // Rewind the iterators in the active, inactive, and fixed lists back to the
980 // point we reverted to.
981 RevertVectorIteratorsTo(active_, earliestStart);
982 RevertVectorIteratorsTo(inactive_, earliestStart);
983 RevertVectorIteratorsTo(fixed_, earliestStart);
984
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000985 // scan the rest and undo each interval that expired after t and
986 // insert it in active (the next iteration of the algorithm will
987 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000988 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
989 LiveInterval *HI = handled_[i];
990 if (!HI->expiredAt(earliestStart) &&
991 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000992 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000993 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +0000994 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000995 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000996 }
997 }
998
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000999 // merge added with unhandled
1000 for (unsigned i = 0, e = added.size(); i != e; ++i)
1001 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001002}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001003
Chris Lattnercbb56252004-11-18 02:42:27 +00001004/// getFreePhysReg - return a free physical register for this virtual register
1005/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001006unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001007 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001008 unsigned MaxInactiveCount = 0;
1009
Chris Lattner84bc5422007-12-31 04:13:23 +00001010 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001011 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1012
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001013 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1014 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001015 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001016 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001017 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001018
1019 // If this is not in a related reg class to the register we're allocating,
1020 // don't check it.
Chris Lattner84bc5422007-12-31 04:13:23 +00001021 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001022 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1023 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001024 if (inactiveCounts.size() <= reg)
1025 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001026 ++inactiveCounts[reg];
1027 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1028 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001029 }
1030
Chris Lattnerf8355d92005-08-22 16:55:22 +00001031 unsigned FreeReg = 0;
1032 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001033
1034 // If copy coalescer has assigned a "preferred" register, check if it's
1035 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001036 if (cur->preference) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001037 if (prt_->isRegAvail(cur->preference)) {
1038 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001039 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001040 return cur->preference;
1041 } else
1042 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001043 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001044 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001045
Chris Lattnerf8355d92005-08-22 16:55:22 +00001046 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001047 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1048 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001049 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001050 for (; I != E; ++I)
1051 if (prt_->isRegAvail(*I)) {
1052 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001053 if (FreeReg < inactiveCounts.size())
1054 FreeRegInactiveCount = inactiveCounts[FreeReg];
1055 else
1056 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001057 break;
1058 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001059
Chris Lattnerf8355d92005-08-22 16:55:22 +00001060 // If there are no free regs, or if this reg has the max inactive count,
1061 // return this register.
1062 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1063
1064 // Continue scanning the registers, looking for the one with the highest
1065 // inactive count. Alkis found that this reduced register pressure very
1066 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1067 // reevaluated now.
1068 for (; I != E; ++I) {
1069 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001070 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1071 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001072 FreeReg = Reg;
1073 FreeRegInactiveCount = inactiveCounts[Reg];
1074 if (FreeRegInactiveCount == MaxInactiveCount)
1075 break; // We found the one with the max inactive count.
1076 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001077 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001078
1079 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001080}
1081
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001082FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001083 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001084}