blob: 919b94c5577b6ed1a5a0e2d52cc7f4844b947f1c [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"
Owen Anderson95dad832008-10-07 20:22:28 +000029#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000030#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000031#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000034#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000036#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000037#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000038#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000039#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000040#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041using namespace llvm;
42
Chris Lattnercd3245a2006-12-19 22:41:21 +000043STATISTIC(NumIters , "Number of iterations performed");
44STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000045STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000046
Evan Cheng3e172252008-06-20 21:45:16 +000047static cl::opt<bool>
48NewHeuristic("new-spilling-heuristic",
49 cl::desc("Use new spilling heuristic"),
50 cl::init(false), cl::Hidden);
51
Evan Chengf5cd4f02008-10-23 20:43:13 +000052static cl::opt<bool>
53PreSplitIntervals("pre-alloc-split",
54 cl::desc("Pre-register allocation live interval splitting"),
55 cl::init(false), cl::Hidden);
56
Chris Lattnercd3245a2006-12-19 22:41:21 +000057static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000058linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000059 createLinearScanRegisterAllocator);
60
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000061namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000062 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000063 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000064 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000065
Chris Lattnercbb56252004-11-18 02:42:27 +000066 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000067 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000068 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000069 /// RelatedRegClasses - This structure is built the first time a function is
70 /// compiled, and keeps track of which register classes have registers that
71 /// belong to multiple classes or have aliases that are in other classes.
72 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000073 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000074
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000075 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000076 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000078 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000079 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000080 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000081 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000082 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000083 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000084
85 /// handled_ - Intervals are added to the handled_ set in the order of their
86 /// start value. This is uses for backtracking.
87 std::vector<LiveInterval*> handled_;
88
89 /// fixed_ - Intervals that correspond to machine registers.
90 ///
91 IntervalPtrs fixed_;
92
93 /// active_ - Intervals that are currently being processed, and which have a
94 /// live range active for the current point.
95 IntervalPtrs active_;
96
97 /// inactive_ - Intervals that are currently being processed, but which have
98 /// a hold at the current point.
99 IntervalPtrs inactive_;
100
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000101 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000102 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 greater_ptr<LiveInterval> > IntervalHeap;
104 IntervalHeap unhandled_;
105 std::auto_ptr<PhysRegTracker> prt_;
106 std::auto_ptr<VirtRegMap> vrm_;
107 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000108
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 public:
110 virtual const char* getPassName() const {
111 return "Linear Scan Register Allocator";
112 }
113
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000116 if (StrongPHIElim)
117 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000118 // Make sure PassManager knows which analyses to make available
119 // to coalescing and which analyses coalescing invalidates.
120 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000121 if (PreSplitIntervals)
122 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000123 AU.addRequired<LiveStacks>();
124 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000125 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000126 AU.addPreserved<MachineLoopInfo>();
127 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 MachineFunctionPass::getAnalysisUsage(AU);
129 }
130
131 /// runOnMachineFunction - register allocate the whole function
132 bool runOnMachineFunction(MachineFunction&);
133
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000134 private:
135 /// linearScan - the linear scan algorithm
136 void linearScan();
137
Chris Lattnercbb56252004-11-18 02:42:27 +0000138 /// initIntervalSets - initialize the interval sets.
139 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140 void initIntervalSets();
141
Chris Lattnercbb56252004-11-18 02:42:27 +0000142 /// processActiveIntervals - expire old intervals and move non-overlapping
143 /// ones to the inactive list.
144 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145
Chris Lattnercbb56252004-11-18 02:42:27 +0000146 /// processInactiveIntervals - expire old intervals and move overlapping
147 /// ones to the active list.
148 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000149
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 /// assignRegOrStackSlotAtInterval - assign a register if one
151 /// is available, or spill.
152 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
153
Evan Cheng3e172252008-06-20 21:45:16 +0000154 /// findIntervalsToSpill - Determine the intervals to spill for the
155 /// specified interval. It's passed the physical registers whose spill
156 /// weight is the lowest among all the registers whose live intervals
157 /// conflict with the interval.
158 void findIntervalsToSpill(LiveInterval *cur,
159 std::vector<std::pair<unsigned,float> > &Candidates,
160 unsigned NumCands,
161 SmallVector<LiveInterval*, 8> &SpillIntervals);
162
Evan Chengc92da382007-11-03 07:20:12 +0000163 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
164 /// try allocate the definition the same register as the source register
165 /// if the register is not defined during live time of the interval. This
166 /// eliminate a copy. This is used to coalesce copies which were not
167 /// coalesced away before allocation either due to dest and src being in
168 /// different register classes or because the coalescer was overly
169 /// conservative.
170 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
171
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000172 ///
173 /// register handling helpers
174 ///
175
Chris Lattnercbb56252004-11-18 02:42:27 +0000176 /// getFreePhysReg - return a free physical register for this virtual
177 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000178 unsigned getFreePhysReg(LiveInterval* cur);
179
180 /// assignVirt2StackSlot - assigns this virtual register to a
181 /// stack slot. returns the stack slot
182 int assignVirt2StackSlot(unsigned virtReg);
183
Chris Lattnerb9805782005-08-23 22:27:31 +0000184 void ComputeRelatedRegClasses();
185
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 template <typename ItTy>
187 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000188 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000189 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000190 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000191 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000192 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000193 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000194 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000195 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000196 }
197 }
198 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000199 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000200}
201
Evan Cheng3f32d652008-06-04 09:18:41 +0000202static RegisterPass<RALinScan>
203X("linearscan-regalloc", "Linear Scan Register Allocator");
204
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000205void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000206 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000207
208 // First pass, add all reg classes to the union, and determine at least one
209 // reg class that each register is in.
210 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000211 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
212 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000213 RelatedRegClasses.insert(*RCI);
214 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
215 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000216 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000217
218 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
219 if (PRC) {
220 // Already processed this register. Just make sure we know that
221 // multiple register classes share a register.
222 RelatedRegClasses.unionSets(PRC, *RCI);
223 } else {
224 PRC = *RCI;
225 }
226 }
227 }
228
229 // Second pass, now that we know conservatively what register classes each reg
230 // belongs to, add info about aliases. We don't need to do this for targets
231 // without register aliases.
232 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000233 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000234 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
235 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000236 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000237 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
238}
239
Evan Chengc92da382007-11-03 07:20:12 +0000240/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
241/// try allocate the definition the same register as the source register
242/// if the register is not defined during live time of the interval. This
243/// eliminate a copy. This is used to coalesce copies which were not
244/// coalesced away before allocation either due to dest and src being in
245/// different register classes or because the coalescer was overly
246/// conservative.
247unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000248 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000249 return Reg;
250
251 VNInfo *vni = cur.getValNumInfo(0);
252 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
253 return Reg;
254 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
255 unsigned SrcReg, DstReg;
256 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
257 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000258 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000259 if (!vrm_->isAssignedReg(SrcReg))
260 return Reg;
261 else
262 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000263 }
Evan Chengc92da382007-11-03 07:20:12 +0000264 if (Reg == SrcReg)
265 return Reg;
266
Evan Cheng841ee1a2008-09-18 22:38:47 +0000267 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000268 if (!RC->contains(SrcReg))
269 return Reg;
270
271 // Try to coalesce.
272 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000273 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000274 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000275 vrm_->clearVirt(cur.reg);
276 vrm_->assignVirt2Phys(cur.reg, SrcReg);
277 ++NumCoalesce;
278 return SrcReg;
279 }
280
281 return Reg;
282}
283
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000284bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000285 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000286 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000287 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000288 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000289 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000290 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000292 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000293 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000294
David Greene2c17c4d2007-09-06 16:18:45 +0000295 // We don't run the coalescer here because we have no reason to
296 // interact with it. If the coalescer requires interaction, it
297 // won't do anything. If it doesn't require interaction, we assume
298 // it was run as a separate pass.
299
Chris Lattnerb9805782005-08-23 22:27:31 +0000300 // If this is the first function compiled, compute the related reg classes.
301 if (RelatedRegClasses.empty())
302 ComputeRelatedRegClasses();
303
Dan Gohman6f0d0242008-02-10 18:45:23 +0000304 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 vrm_.reset(new VirtRegMap(*mf_));
306 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000307
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000309
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000310 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000311
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000312 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000314 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000315
Dan Gohman51cd9d62008-06-23 23:51:16 +0000316 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000317 fixed_.clear();
318 active_.clear();
319 inactive_.clear();
320 handled_.clear();
321
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000322 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000323}
324
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000325/// initIntervalSets - initialize the interval sets.
326///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000327void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000328{
329 assert(unhandled_.empty() && fixed_.empty() &&
330 active_.empty() && inactive_.empty() &&
331 "interval sets should be empty on initialization");
332
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000333 handled_.reserve(li_->getNumIntervals());
334
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000335 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000336 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000337 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000338 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000339 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000340 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000341 }
342}
343
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000344void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000345{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000346 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000347 DOUT << "********** LINEAR SCAN **********\n";
348 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000349
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351
352 while (!unhandled_.empty()) {
353 // pick the interval with the earliest start point
354 LiveInterval* cur = unhandled_.top();
355 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000356 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000357 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000358
Evan Chengf30a49d2008-04-03 16:40:27 +0000359 if (!cur->empty()) {
360 processActiveIntervals(cur->beginNumber());
361 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362
Evan Chengf30a49d2008-04-03 16:40:27 +0000363 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
364 "Can only allocate virtual registers!");
365 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000366
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000367 // Allocating a virtual register. try to find a free
368 // physical register or spill an interval (possibly this one) in order to
369 // assign it one.
370 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000371
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000372 DEBUG(printIntervals("active", active_.begin(), active_.end()));
373 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000375
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000377 while (!active_.empty()) {
378 IntervalPtr &IP = active_.back();
379 unsigned reg = IP.first->reg;
380 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000381 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000382 "Can only allocate virtual registers!");
383 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000385 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000387
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000389 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000390 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000391 DOUT << "\tinterval " << *i->first << " expired\n");
392 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000393
Evan Cheng81a03822007-11-17 00:40:40 +0000394 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000395 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000396 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000397 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000398 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000399 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000400 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000401 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000402 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000404 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000405 if (!Reg)
406 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000407 // Ignore splited live intervals.
408 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
409 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000410 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
411 I != E; ++I) {
412 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000413 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000414 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
415 if (LiveInMBBs[i] != EntryMBB)
416 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000417 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000418 }
419 }
420 }
421
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000422 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000423}
424
Chris Lattnercbb56252004-11-18 02:42:27 +0000425/// processActiveIntervals - expire old intervals and move non-overlapping ones
426/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000427void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000428{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000429 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000430
Chris Lattnercbb56252004-11-18 02:42:27 +0000431 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
432 LiveInterval *Interval = active_[i].first;
433 LiveInterval::iterator IntervalPos = active_[i].second;
434 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000435
Chris Lattnercbb56252004-11-18 02:42:27 +0000436 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
437
438 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000439 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000440 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000441 "Can only allocate virtual registers!");
442 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000443 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000444
445 // Pop off the end of the list.
446 active_[i] = active_.back();
447 active_.pop_back();
448 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000449
Chris Lattnercbb56252004-11-18 02:42:27 +0000450 } else if (IntervalPos->start > CurPoint) {
451 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000452 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000453 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000454 "Can only allocate virtual registers!");
455 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000456 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000457 // add to inactive.
458 inactive_.push_back(std::make_pair(Interval, IntervalPos));
459
460 // Pop off the end of the list.
461 active_[i] = active_.back();
462 active_.pop_back();
463 --i; --e;
464 } else {
465 // Otherwise, just update the iterator position.
466 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000467 }
468 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000469}
470
Chris Lattnercbb56252004-11-18 02:42:27 +0000471/// processInactiveIntervals - expire old intervals and move overlapping
472/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000473void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000474{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000475 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000476
Chris Lattnercbb56252004-11-18 02:42:27 +0000477 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
478 LiveInterval *Interval = inactive_[i].first;
479 LiveInterval::iterator IntervalPos = inactive_[i].second;
480 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000481
Chris Lattnercbb56252004-11-18 02:42:27 +0000482 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000483
Chris Lattnercbb56252004-11-18 02:42:27 +0000484 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000485 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000486
Chris Lattnercbb56252004-11-18 02:42:27 +0000487 // Pop off the end of the list.
488 inactive_[i] = inactive_.back();
489 inactive_.pop_back();
490 --i; --e;
491 } else if (IntervalPos->start <= CurPoint) {
492 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000493 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000494 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000495 "Can only allocate virtual registers!");
496 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000497 prt_->addRegUse(reg);
498 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000499 active_.push_back(std::make_pair(Interval, IntervalPos));
500
501 // Pop off the end of the list.
502 inactive_[i] = inactive_.back();
503 inactive_.pop_back();
504 --i; --e;
505 } else {
506 // Otherwise, just update the iterator position.
507 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000508 }
509 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000510}
511
Chris Lattnercbb56252004-11-18 02:42:27 +0000512/// updateSpillWeights - updates the spill weights of the specifed physical
513/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000514static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000515 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000516 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000517 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000518 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000519 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000520}
521
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000522static
523RALinScan::IntervalPtrs::iterator
524FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
525 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
526 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000527 if (I->first == LI) return I;
528 return IP.end();
529}
530
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000531static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000532 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000533 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000534 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
535 IP.second, Point);
536 if (I != IP.first->begin()) --I;
537 IP.second = I;
538 }
539}
Chris Lattnercbb56252004-11-18 02:42:27 +0000540
Evan Cheng3f32d652008-06-04 09:18:41 +0000541/// addStackInterval - Create a LiveInterval for stack if the specified live
542/// interval has been spilled.
543static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000544 LiveIntervals *li_, float &Weight,
545 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000546 int SS = vrm_.getStackSlot(cur->reg);
547 if (SS == VirtRegMap::NO_STACK_SLOT)
548 return;
549 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000550 SI.weight += Weight;
551
Evan Cheng3f32d652008-06-04 09:18:41 +0000552 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000553 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000554 VNI = SI.getValNumInfo(0);
555 else
556 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
557
558 LiveInterval &RI = li_->getInterval(cur->reg);
559 // FIXME: This may be overly conservative.
560 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000561}
562
Evan Cheng3e172252008-06-20 21:45:16 +0000563/// getConflictWeight - Return the number of conflicts between cur
564/// live interval and defs and uses of Reg weighted by loop depthes.
565static float getConflictWeight(LiveInterval *cur, unsigned Reg,
566 LiveIntervals *li_,
567 MachineRegisterInfo *mri_,
568 const MachineLoopInfo *loopInfo) {
569 float Conflicts = 0;
570 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
571 E = mri_->reg_end(); I != E; ++I) {
572 MachineInstr *MI = &*I;
573 if (cur->liveAt(li_->getInstructionIndex(MI))) {
574 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
575 Conflicts += powf(10.0f, (float)loopDepth);
576 }
577 }
578 return Conflicts;
579}
580
581/// findIntervalsToSpill - Determine the intervals to spill for the
582/// specified interval. It's passed the physical registers whose spill
583/// weight is the lowest among all the registers whose live intervals
584/// conflict with the interval.
585void RALinScan::findIntervalsToSpill(LiveInterval *cur,
586 std::vector<std::pair<unsigned,float> > &Candidates,
587 unsigned NumCands,
588 SmallVector<LiveInterval*, 8> &SpillIntervals) {
589 // We have figured out the *best* register to spill. But there are other
590 // registers that are pretty good as well (spill weight within 3%). Spill
591 // the one that has fewest defs and uses that conflict with cur.
592 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
593 SmallVector<LiveInterval*, 8> SLIs[3];
594
595 DOUT << "\tConsidering " << NumCands << " candidates: ";
596 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
597 DOUT << tri_->getName(Candidates[i].first) << " ";
598 DOUT << "\n";);
599
600 // Calculate the number of conflicts of each candidate.
601 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
602 unsigned Reg = i->first->reg;
603 unsigned PhysReg = vrm_->getPhys(Reg);
604 if (!cur->overlapsFrom(*i->first, i->second))
605 continue;
606 for (unsigned j = 0; j < NumCands; ++j) {
607 unsigned Candidate = Candidates[j].first;
608 if (tri_->regsOverlap(PhysReg, Candidate)) {
609 if (NumCands > 1)
610 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
611 SLIs[j].push_back(i->first);
612 }
613 }
614 }
615
616 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
617 unsigned Reg = i->first->reg;
618 unsigned PhysReg = vrm_->getPhys(Reg);
619 if (!cur->overlapsFrom(*i->first, i->second-1))
620 continue;
621 for (unsigned j = 0; j < NumCands; ++j) {
622 unsigned Candidate = Candidates[j].first;
623 if (tri_->regsOverlap(PhysReg, Candidate)) {
624 if (NumCands > 1)
625 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
626 SLIs[j].push_back(i->first);
627 }
628 }
629 }
630
631 // Which is the best candidate?
632 unsigned BestCandidate = 0;
633 float MinConflicts = Conflicts[0];
634 for (unsigned i = 1; i != NumCands; ++i) {
635 if (Conflicts[i] < MinConflicts) {
636 BestCandidate = i;
637 MinConflicts = Conflicts[i];
638 }
639 }
640
641 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
642 std::back_inserter(SpillIntervals));
643}
644
645namespace {
646 struct WeightCompare {
647 typedef std::pair<unsigned, float> RegWeightPair;
648 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
649 return LHS.second < RHS.second;
650 }
651 };
652}
653
654static bool weightsAreClose(float w1, float w2) {
655 if (!NewHeuristic)
656 return false;
657
658 float diff = w1 - w2;
659 if (diff <= 0.02f) // Within 0.02f
660 return true;
661 return (diff / w2) <= 0.05f; // Within 5%.
662}
663
Chris Lattnercbb56252004-11-18 02:42:27 +0000664/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
665/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000666void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000667{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000668 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000669
Evan Chengf30a49d2008-04-03 16:40:27 +0000670 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000671 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000672 if (cur->empty()) {
673 unsigned physReg = cur->preference;
674 if (!physReg)
675 physReg = *RC->allocation_order_begin(*mf_);
676 DOUT << tri_->getName(physReg) << '\n';
677 // Note the register is not really in use.
678 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000679 return;
680 }
681
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000683
Chris Lattnera6c17502005-08-22 20:20:42 +0000684 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000685 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000686 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000687
688 // If this live interval is defined by a move instruction and its source is
689 // assigned a physical register that is compatible with the target register
690 // class, then we should try to assign it the same register.
691 // This can happen when the move is from a larger register class to a smaller
692 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
693 if (!cur->preference && cur->containsOneValue()) {
694 VNInfo *vni = cur->getValNumInfo(0);
695 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
696 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
697 unsigned SrcReg, DstReg;
Evan Chengf2b24ca2008-04-11 17:55:47 +0000698 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000699 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000700 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000701 Reg = SrcReg;
702 else if (vrm_->isAssignedReg(SrcReg))
703 Reg = vrm_->getPhys(SrcReg);
704 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
705 cur->preference = Reg;
706 }
707 }
708 }
709
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000710 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000711 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000712 for (IntervalPtrs::const_iterator i = inactive_.begin(),
713 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000714 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000715 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000716 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000717 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000718 // If this is not in a related reg class to the register we're allocating,
719 // don't check it.
720 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
721 cur->overlapsFrom(*i->first, i->second-1)) {
722 Reg = vrm_->getPhys(Reg);
723 prt_->addRegUse(Reg);
724 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000725 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000726 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000727
728 // Speculatively check to see if we can get a register right now. If not,
729 // we know we won't be able to by adding more constraints. If so, we can
730 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
731 // is very bad (it contains all callee clobbered registers for any functions
732 // with a call), so we want to avoid doing that if possible.
733 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000734 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000735 if (physReg) {
736 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000737 // conflict with it. Check to see if we conflict with it or any of its
738 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000739 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000740 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000741 RegAliases.insert(*AS);
742
Chris Lattnera411cbc2005-08-22 20:59:30 +0000743 bool ConflictsWithFixed = false;
744 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000745 IntervalPtr &IP = fixed_[i];
746 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000747 // Okay, this reg is on the fixed list. Check to see if we actually
748 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000749 LiveInterval *I = IP.first;
750 if (I->endNumber() > StartPosition) {
751 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
752 IP.second = II;
753 if (II != I->begin() && II->start > StartPosition)
754 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000755 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000756 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000757 break;
758 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000759 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000760 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000761 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000762
763 // Okay, the register picked by our speculative getFreePhysReg call turned
764 // out to be in use. Actually add all of the conflicting fixed registers to
765 // prt so we can do an accurate query.
766 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000767 // For every interval in fixed we overlap with, mark the register as not
768 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000769 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
770 IntervalPtr &IP = fixed_[i];
771 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000772
773 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
774 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
775 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000776 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
777 IP.second = II;
778 if (II != I->begin() && II->start > StartPosition)
779 --II;
780 if (cur->overlapsFrom(*I, II)) {
781 unsigned reg = I->reg;
782 prt_->addRegUse(reg);
783 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
784 }
785 }
786 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000787
Chris Lattnera411cbc2005-08-22 20:59:30 +0000788 // Using the newly updated prt_ object, which includes conflicts in the
789 // future, see if there are any registers available.
790 physReg = getFreePhysReg(cur);
791 }
792 }
793
Chris Lattnera6c17502005-08-22 20:20:42 +0000794 // Restore the physical register tracker, removing information about the
795 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000796 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000797
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000798 // if we find a free register, we are done: assign this virtual to
799 // the free physical register and add this interval to the active
800 // list.
801 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000802 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000803 vrm_->assignVirt2Phys(cur->reg, physReg);
804 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000805 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000806 handled_.push_back(cur);
807 return;
808 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000809 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000810
Chris Lattnera6c17502005-08-22 20:20:42 +0000811 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000812 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000813 for (std::vector<std::pair<unsigned, float> >::iterator
814 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000815 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000816
817 // for each interval in active, update spill weights.
818 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
819 i != e; ++i) {
820 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000821 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000822 "Can only allocate virtual registers!");
823 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000824 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000825 }
826
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000827 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000828
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000829 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000830 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000831 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
832
833 bool Found = false;
834 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000835 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
836 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
837 e = RC->allocation_order_end(*mf_); i != e; ++i) {
838 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000839 float regWeight = SpillWeights[reg];
840 if (minWeight > regWeight)
841 Found = true;
842 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000843 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000844
845 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000846 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000847 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
848 e = RC->allocation_order_end(*mf_); i != e; ++i) {
849 unsigned reg = *i;
850 // No need to worry about if the alias register size < regsize of RC.
851 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000852 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
853 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000854 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000855 }
Evan Cheng3e172252008-06-20 21:45:16 +0000856
857 // Sort all potential spill candidates by weight.
858 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
859 minReg = RegsWeights[0].first;
860 minWeight = RegsWeights[0].second;
861 if (minWeight == HUGE_VALF) {
862 // All registers must have inf weight. Just grab one!
863 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000864 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000865 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000866 // Spill a physical register around defs and uses.
867 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000868 assignRegOrStackSlotAtInterval(cur);
869 return;
870 }
Evan Cheng3e172252008-06-20 21:45:16 +0000871 }
872
873 // Find up to 3 registers to consider as spill candidates.
874 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
875 while (LastCandidate > 1) {
876 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
877 break;
878 --LastCandidate;
879 }
880
881 DOUT << "\t\tregister(s) with min weight(s): ";
882 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
883 DOUT << tri_->getName(RegsWeights[i].first)
884 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000885
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000886 // if the current has the minimum weight, we need to spill it and
887 // add any added intervals back to unhandled, and restart
888 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000889 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000890 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000891 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000892 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000893 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000894 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000895 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000896 if (added.empty())
897 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000898
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000899 // Merge added with unhandled. Note that we know that
900 // addIntervalsForSpills returns intervals sorted by their starting
901 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000902 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000903 unhandled_.push(added[i]);
904 return;
905 }
906
Chris Lattner19828d42004-11-18 03:49:30 +0000907 ++NumBacktracks;
908
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000909 // push the current interval back to unhandled since we are going
910 // to re-run at least this iteration. Since we didn't modify it it
911 // should go back right in the front of the list
912 unhandled_.push(cur);
913
Dan Gohman6f0d0242008-02-10 18:45:23 +0000914 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000915 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000916
Evan Cheng3e172252008-06-20 21:45:16 +0000917 // We spill all intervals aliasing the register with
918 // minimum weight, rollback to the interval with the earliest
919 // start point and let the linear scan algorithm run again
920 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000921
Evan Cheng3e172252008-06-20 21:45:16 +0000922 // Determine which intervals have to be spilled.
923 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
924
925 // Set of spilled vregs (used later to rollback properly)
926 SmallSet<unsigned, 8> spilled;
927
928 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000929 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000930 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000931
Evan Cheng3e172252008-06-20 21:45:16 +0000932 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000933 // want to clear (and its aliases). We only spill those that overlap with the
934 // current interval as the rest do not affect its allocation. we also keep
935 // track of the earliest start of all spilled live intervals since this will
936 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000937 std::vector<LiveInterval*> added;
938 while (!spillIs.empty()) {
939 LiveInterval *sli = spillIs.back();
940 spillIs.pop_back();
941 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
942 earliestStart = std::min(earliestStart, sli->beginNumber());
943 float SSWeight;
944 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000945 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000946 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
947 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
948 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000949 }
950
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000951 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000952
953 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000954 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000955 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000956 while (!handled_.empty()) {
957 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000958 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000959 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000960 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000961 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000962 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000963
964 // When undoing a live interval allocation we must know if it is active or
965 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000966 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000967 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000968 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000969 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000970 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000971 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000972 prt_->delRegUse(vrm_->getPhys(i->reg));
973 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000974 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000975 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000976 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000977 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000978 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000979 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000980 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000981 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000982 "Can only allocate virtual registers!");
983 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000984 unhandled_.push(i);
985 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000986
987 // It interval has a preference, it must be defined by a copy. Clear the
988 // preference now since the source interval allocation may have been undone
989 // as well.
990 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000991 }
992
Chris Lattner19828d42004-11-18 03:49:30 +0000993 // Rewind the iterators in the active, inactive, and fixed lists back to the
994 // point we reverted to.
995 RevertVectorIteratorsTo(active_, earliestStart);
996 RevertVectorIteratorsTo(inactive_, earliestStart);
997 RevertVectorIteratorsTo(fixed_, earliestStart);
998
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000999 // scan the rest and undo each interval that expired after t and
1000 // insert it in active (the next iteration of the algorithm will
1001 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001002 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1003 LiveInterval *HI = handled_[i];
1004 if (!HI->expiredAt(earliestStart) &&
1005 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001006 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001007 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001008 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001009 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001010 }
1011 }
1012
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001013 // merge added with unhandled
1014 for (unsigned i = 0, e = added.size(); i != e; ++i)
1015 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001016}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001017
Chris Lattnercbb56252004-11-18 02:42:27 +00001018/// getFreePhysReg - return a free physical register for this virtual register
1019/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001020unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001021 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001022 unsigned MaxInactiveCount = 0;
1023
Evan Cheng841ee1a2008-09-18 22:38:47 +00001024 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001025 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1026
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001027 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1028 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001029 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001030 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001031 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001032
1033 // If this is not in a related reg class to the register we're allocating,
1034 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001035 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001036 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1037 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001038 if (inactiveCounts.size() <= reg)
1039 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001040 ++inactiveCounts[reg];
1041 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1042 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001043 }
1044
Chris Lattnerf8355d92005-08-22 16:55:22 +00001045 unsigned FreeReg = 0;
1046 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001047
1048 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001049 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001050 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001051 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001052 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001053 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001054 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001055 return cur->preference;
1056 } else
1057 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001058 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001059 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001060
Chris Lattnerf8355d92005-08-22 16:55:22 +00001061 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001062 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1063 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001064 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001065 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001066 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001067 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001068 if (FreeReg < inactiveCounts.size())
1069 FreeRegInactiveCount = inactiveCounts[FreeReg];
1070 else
1071 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001072 break;
1073 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001074
Chris Lattnerf8355d92005-08-22 16:55:22 +00001075 // If there are no free regs, or if this reg has the max inactive count,
1076 // return this register.
1077 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1078
1079 // Continue scanning the registers, looking for the one with the highest
1080 // inactive count. Alkis found that this reduced register pressure very
1081 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1082 // reevaluated now.
1083 for (; I != E; ++I) {
1084 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001085 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001086 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001087 FreeReg = Reg;
1088 FreeRegInactiveCount = inactiveCounts[Reg];
1089 if (FreeRegInactiveCount == MaxInactiveCount)
1090 break; // We found the one with the max inactive count.
1091 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001092 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001093
1094 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001095}
1096
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001097FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001098 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001099}