blob: 8c20a632c9deae40e1fe739a489890e6f160aaee [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"
Owen Anderson1ed5b712009-03-11 22:31:21 +000017#include "Spiller.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000027#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000030#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000031#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000032#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000033#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000036#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000037#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000038#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000039#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000040#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000041#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000042#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000043using namespace llvm;
44
Chris Lattnercd3245a2006-12-19 22:41:21 +000045STATISTIC(NumIters , "Number of iterations performed");
46STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000047STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000048
Evan Cheng3e172252008-06-20 21:45:16 +000049static cl::opt<bool>
50NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden);
53
Evan Chengf5cd4f02008-10-23 20:43:13 +000054static cl::opt<bool>
55PreSplitIntervals("pre-alloc-split",
56 cl::desc("Pre-register allocation live interval splitting"),
57 cl::init(false), cl::Hidden);
58
Chris Lattnercd3245a2006-12-19 22:41:21 +000059static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000060linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000061 createLinearScanRegisterAllocator);
62
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000063namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000064 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000065 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000066 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000067
Chris Lattnercbb56252004-11-18 02:42:27 +000068 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000069 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000070 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000071 /// RelatedRegClasses - This structure is built the first time a function is
72 /// compiled, and keeps track of which register classes have registers that
73 /// belong to multiple classes or have aliases that are in other classes.
74 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000075 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000076
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000078 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000079 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000080 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000081 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000082 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000084 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000085 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000086
87 /// handled_ - Intervals are added to the handled_ set in the order of their
88 /// start value. This is uses for backtracking.
89 std::vector<LiveInterval*> handled_;
90
91 /// fixed_ - Intervals that correspond to machine registers.
92 ///
93 IntervalPtrs fixed_;
94
95 /// active_ - Intervals that are currently being processed, and which have a
96 /// live range active for the current point.
97 IntervalPtrs active_;
98
99 /// inactive_ - Intervals that are currently being processed, but which have
100 /// a hold at the current point.
101 IntervalPtrs inactive_;
102
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000104 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 greater_ptr<LiveInterval> > IntervalHeap;
106 IntervalHeap unhandled_;
107 std::auto_ptr<PhysRegTracker> prt_;
108 std::auto_ptr<VirtRegMap> vrm_;
109 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000110
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000111 public:
112 virtual const char* getPassName() const {
113 return "Linear Scan Register Allocator";
114 }
115
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000117 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000118 if (StrongPHIElim)
119 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000120 // Make sure PassManager knows which analyses to make available
121 // to coalescing and which analyses coalescing invalidates.
122 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000123 if (PreSplitIntervals)
124 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000125 AU.addRequired<LiveStacks>();
126 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000127 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000128 AU.addPreserved<MachineLoopInfo>();
129 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130 MachineFunctionPass::getAnalysisUsage(AU);
131 }
132
133 /// runOnMachineFunction - register allocate the whole function
134 bool runOnMachineFunction(MachineFunction&);
135
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000136 private:
137 /// linearScan - the linear scan algorithm
138 void linearScan();
139
Chris Lattnercbb56252004-11-18 02:42:27 +0000140 /// initIntervalSets - initialize the interval sets.
141 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142 void initIntervalSets();
143
Chris Lattnercbb56252004-11-18 02:42:27 +0000144 /// processActiveIntervals - expire old intervals and move non-overlapping
145 /// ones to the inactive list.
146 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000147
Chris Lattnercbb56252004-11-18 02:42:27 +0000148 /// processInactiveIntervals - expire old intervals and move overlapping
149 /// ones to the active list.
150 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000151
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000152 /// assignRegOrStackSlotAtInterval - assign a register if one
153 /// is available, or spill.
154 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
155
Evan Cheng3e172252008-06-20 21:45:16 +0000156 /// findIntervalsToSpill - Determine the intervals to spill for the
157 /// specified interval. It's passed the physical registers whose spill
158 /// weight is the lowest among all the registers whose live intervals
159 /// conflict with the interval.
160 void findIntervalsToSpill(LiveInterval *cur,
161 std::vector<std::pair<unsigned,float> > &Candidates,
162 unsigned NumCands,
163 SmallVector<LiveInterval*, 8> &SpillIntervals);
164
Evan Chengc92da382007-11-03 07:20:12 +0000165 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
166 /// try allocate the definition the same register as the source register
167 /// if the register is not defined during live time of the interval. This
168 /// eliminate a copy. This is used to coalesce copies which were not
169 /// coalesced away before allocation either due to dest and src being in
170 /// different register classes or because the coalescer was overly
171 /// conservative.
172 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
173
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000174 ///
175 /// register handling helpers
176 ///
177
Chris Lattnercbb56252004-11-18 02:42:27 +0000178 /// getFreePhysReg - return a free physical register for this virtual
179 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000180 unsigned getFreePhysReg(LiveInterval* cur);
181
182 /// assignVirt2StackSlot - assigns this virtual register to a
183 /// stack slot. returns the stack slot
184 int assignVirt2StackSlot(unsigned virtReg);
185
Chris Lattnerb9805782005-08-23 22:27:31 +0000186 void ComputeRelatedRegClasses();
187
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000188 template <typename ItTy>
189 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000190 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000191 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000192 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000193 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000194 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000195 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000196 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000197 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000198 }
199 }
200 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000201 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000202}
203
Evan Cheng3f32d652008-06-04 09:18:41 +0000204static RegisterPass<RALinScan>
205X("linearscan-regalloc", "Linear Scan Register Allocator");
206
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000207void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000208 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000209
210 // First pass, add all reg classes to the union, and determine at least one
211 // reg class that each register is in.
212 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000213 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
214 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000215 RelatedRegClasses.insert(*RCI);
216 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
217 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000218 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000219
220 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
221 if (PRC) {
222 // Already processed this register. Just make sure we know that
223 // multiple register classes share a register.
224 RelatedRegClasses.unionSets(PRC, *RCI);
225 } else {
226 PRC = *RCI;
227 }
228 }
229 }
230
231 // Second pass, now that we know conservatively what register classes each reg
232 // belongs to, add info about aliases. We don't need to do this for targets
233 // without register aliases.
234 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000235 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000236 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
237 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000238 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000239 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
240}
241
Evan Chengc92da382007-11-03 07:20:12 +0000242/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
243/// try allocate the definition the same register as the source register
244/// if the register is not defined during live time of the interval. This
245/// eliminate a copy. This is used to coalesce copies which were not
246/// coalesced away before allocation either due to dest and src being in
247/// different register classes or because the coalescer was overly
248/// conservative.
249unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000250 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000251 return Reg;
252
Evan Chengd0deec22009-01-20 00:16:18 +0000253 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000254 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
255 return Reg;
256 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000257 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
258 if (!CopyMI ||
259 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000260 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000261 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000262 if (!vrm_->isAssignedReg(SrcReg))
263 return Reg;
264 else
265 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000266 }
Evan Chengc92da382007-11-03 07:20:12 +0000267 if (Reg == SrcReg)
268 return Reg;
269
Evan Cheng841ee1a2008-09-18 22:38:47 +0000270 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000271 if (!RC->contains(SrcReg))
272 return Reg;
273
274 // Try to coalesce.
275 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000276 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000277 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000278 vrm_->clearVirt(cur.reg);
279 vrm_->assignVirt2Phys(cur.reg, SrcReg);
280 ++NumCoalesce;
281 return SrcReg;
282 }
283
284 return Reg;
285}
286
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000287bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000288 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000289 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000290 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000291 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000292 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000293 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000294 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000295 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000296 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000297
David Greene2c17c4d2007-09-06 16:18:45 +0000298 // We don't run the coalescer here because we have no reason to
299 // interact with it. If the coalescer requires interaction, it
300 // won't do anything. If it doesn't require interaction, we assume
301 // it was run as a separate pass.
302
Chris Lattnerb9805782005-08-23 22:27:31 +0000303 // If this is the first function compiled, compute the related reg classes.
304 if (RelatedRegClasses.empty())
305 ComputeRelatedRegClasses();
306
Dan Gohman6f0d0242008-02-10 18:45:23 +0000307 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308 vrm_.reset(new VirtRegMap(*mf_));
309 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000310
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000312
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000314
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000315 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000317 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000318
Dan Gohman51cd9d62008-06-23 23:51:16 +0000319 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000320 fixed_.clear();
321 active_.clear();
322 inactive_.clear();
323 handled_.clear();
324
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000325 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000326}
327
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000328/// initIntervalSets - initialize the interval sets.
329///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000330void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000331{
332 assert(unhandled_.empty() && fixed_.empty() &&
333 active_.empty() && inactive_.empty() &&
334 "interval sets should be empty on initialization");
335
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000336 handled_.reserve(li_->getNumIntervals());
337
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000338 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000339 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000340 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000341 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000342 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000343 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000344 }
345}
346
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000347void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000348{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000349 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000350 DOUT << "********** LINEAR SCAN **********\n";
351 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000352
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000353 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354
355 while (!unhandled_.empty()) {
356 // pick the interval with the earliest start point
357 LiveInterval* cur = unhandled_.top();
358 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000359 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000360 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361
Evan Chengf30a49d2008-04-03 16:40:27 +0000362 if (!cur->empty()) {
363 processActiveIntervals(cur->beginNumber());
364 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000365
Evan Chengf30a49d2008-04-03 16:40:27 +0000366 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
367 "Can only allocate virtual registers!");
368 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000369
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000370 // Allocating a virtual register. try to find a free
371 // physical register or spill an interval (possibly this one) in order to
372 // assign it one.
373 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000375 DEBUG(printIntervals("active", active_.begin(), active_.end()));
376 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000377 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000378
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000380 while (!active_.empty()) {
381 IntervalPtr &IP = active_.back();
382 unsigned reg = IP.first->reg;
383 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000384 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000385 "Can only allocate virtual registers!");
386 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000387 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000388 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000389 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000390
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000392 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000393 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000394 DOUT << "\tinterval " << *i->first << " expired\n");
395 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000396
Evan Cheng81a03822007-11-17 00:40:40 +0000397 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000398 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000399 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000400 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000401 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000402 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000403 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000404 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000405 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000406 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000407 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000408 if (!Reg)
409 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000410 // Ignore splited live intervals.
411 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
412 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000413 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
414 I != E; ++I) {
415 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000416 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000417 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
418 if (LiveInMBBs[i] != EntryMBB)
419 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000420 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000421 }
422 }
423 }
424
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000425 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000426}
427
Chris Lattnercbb56252004-11-18 02:42:27 +0000428/// processActiveIntervals - expire old intervals and move non-overlapping ones
429/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000430void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000431{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000432 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000433
Chris Lattnercbb56252004-11-18 02:42:27 +0000434 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
435 LiveInterval *Interval = active_[i].first;
436 LiveInterval::iterator IntervalPos = active_[i].second;
437 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000438
Chris Lattnercbb56252004-11-18 02:42:27 +0000439 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
440
441 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000442 DOUT << "\t\tinterval " << *Interval << " expired\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
448 // Pop off the end of the list.
449 active_[i] = active_.back();
450 active_.pop_back();
451 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000452
Chris Lattnercbb56252004-11-18 02:42:27 +0000453 } else if (IntervalPos->start > CurPoint) {
454 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000455 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000456 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000457 "Can only allocate virtual registers!");
458 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000460 // add to inactive.
461 inactive_.push_back(std::make_pair(Interval, IntervalPos));
462
463 // Pop off the end of the list.
464 active_[i] = active_.back();
465 active_.pop_back();
466 --i; --e;
467 } else {
468 // Otherwise, just update the iterator position.
469 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000470 }
471 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000472}
473
Chris Lattnercbb56252004-11-18 02:42:27 +0000474/// processInactiveIntervals - expire old intervals and move overlapping
475/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000476void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000477{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000478 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000479
Chris Lattnercbb56252004-11-18 02:42:27 +0000480 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
481 LiveInterval *Interval = inactive_[i].first;
482 LiveInterval::iterator IntervalPos = inactive_[i].second;
483 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000484
Chris Lattnercbb56252004-11-18 02:42:27 +0000485 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000486
Chris Lattnercbb56252004-11-18 02:42:27 +0000487 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000488 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000489
Chris Lattnercbb56252004-11-18 02:42:27 +0000490 // Pop off the end of the list.
491 inactive_[i] = inactive_.back();
492 inactive_.pop_back();
493 --i; --e;
494 } else if (IntervalPos->start <= CurPoint) {
495 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000496 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000497 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000498 "Can only allocate virtual registers!");
499 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000500 prt_->addRegUse(reg);
501 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000502 active_.push_back(std::make_pair(Interval, IntervalPos));
503
504 // Pop off the end of the list.
505 inactive_[i] = inactive_.back();
506 inactive_.pop_back();
507 --i; --e;
508 } else {
509 // Otherwise, just update the iterator position.
510 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000511 }
512 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000513}
514
Chris Lattnercbb56252004-11-18 02:42:27 +0000515/// updateSpillWeights - updates the spill weights of the specifed physical
516/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000517static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000518 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000519 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000520 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000521 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000522 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000523}
524
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000525static
526RALinScan::IntervalPtrs::iterator
527FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
528 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
529 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000530 if (I->first == LI) return I;
531 return IP.end();
532}
533
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000534static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000535 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000536 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000537 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
538 IP.second, Point);
539 if (I != IP.first->begin()) --I;
540 IP.second = I;
541 }
542}
Chris Lattnercbb56252004-11-18 02:42:27 +0000543
Evan Cheng3f32d652008-06-04 09:18:41 +0000544/// addStackInterval - Create a LiveInterval for stack if the specified live
545/// interval has been spilled.
546static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000547 LiveIntervals *li_, float &Weight,
548 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000549 int SS = vrm_.getStackSlot(cur->reg);
550 if (SS == VirtRegMap::NO_STACK_SLOT)
551 return;
552 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000553 SI.weight += Weight;
554
Evan Cheng3f32d652008-06-04 09:18:41 +0000555 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000556 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000557 VNI = SI.getValNumInfo(0);
558 else
559 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
560
561 LiveInterval &RI = li_->getInterval(cur->reg);
562 // FIXME: This may be overly conservative.
563 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000564}
565
Evan Cheng3e172252008-06-20 21:45:16 +0000566/// getConflictWeight - Return the number of conflicts between cur
567/// live interval and defs and uses of Reg weighted by loop depthes.
568static float getConflictWeight(LiveInterval *cur, unsigned Reg,
569 LiveIntervals *li_,
570 MachineRegisterInfo *mri_,
571 const MachineLoopInfo *loopInfo) {
572 float Conflicts = 0;
573 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
574 E = mri_->reg_end(); I != E; ++I) {
575 MachineInstr *MI = &*I;
576 if (cur->liveAt(li_->getInstructionIndex(MI))) {
577 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
578 Conflicts += powf(10.0f, (float)loopDepth);
579 }
580 }
581 return Conflicts;
582}
583
584/// findIntervalsToSpill - Determine the intervals to spill for the
585/// specified interval. It's passed the physical registers whose spill
586/// weight is the lowest among all the registers whose live intervals
587/// conflict with the interval.
588void RALinScan::findIntervalsToSpill(LiveInterval *cur,
589 std::vector<std::pair<unsigned,float> > &Candidates,
590 unsigned NumCands,
591 SmallVector<LiveInterval*, 8> &SpillIntervals) {
592 // We have figured out the *best* register to spill. But there are other
593 // registers that are pretty good as well (spill weight within 3%). Spill
594 // the one that has fewest defs and uses that conflict with cur.
595 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
596 SmallVector<LiveInterval*, 8> SLIs[3];
597
598 DOUT << "\tConsidering " << NumCands << " candidates: ";
599 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
600 DOUT << tri_->getName(Candidates[i].first) << " ";
601 DOUT << "\n";);
602
603 // Calculate the number of conflicts of each candidate.
604 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
605 unsigned Reg = i->first->reg;
606 unsigned PhysReg = vrm_->getPhys(Reg);
607 if (!cur->overlapsFrom(*i->first, i->second))
608 continue;
609 for (unsigned j = 0; j < NumCands; ++j) {
610 unsigned Candidate = Candidates[j].first;
611 if (tri_->regsOverlap(PhysReg, Candidate)) {
612 if (NumCands > 1)
613 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
614 SLIs[j].push_back(i->first);
615 }
616 }
617 }
618
619 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
620 unsigned Reg = i->first->reg;
621 unsigned PhysReg = vrm_->getPhys(Reg);
622 if (!cur->overlapsFrom(*i->first, i->second-1))
623 continue;
624 for (unsigned j = 0; j < NumCands; ++j) {
625 unsigned Candidate = Candidates[j].first;
626 if (tri_->regsOverlap(PhysReg, Candidate)) {
627 if (NumCands > 1)
628 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
629 SLIs[j].push_back(i->first);
630 }
631 }
632 }
633
634 // Which is the best candidate?
635 unsigned BestCandidate = 0;
636 float MinConflicts = Conflicts[0];
637 for (unsigned i = 1; i != NumCands; ++i) {
638 if (Conflicts[i] < MinConflicts) {
639 BestCandidate = i;
640 MinConflicts = Conflicts[i];
641 }
642 }
643
644 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
645 std::back_inserter(SpillIntervals));
646}
647
648namespace {
649 struct WeightCompare {
650 typedef std::pair<unsigned, float> RegWeightPair;
651 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
652 return LHS.second < RHS.second;
653 }
654 };
655}
656
657static bool weightsAreClose(float w1, float w2) {
658 if (!NewHeuristic)
659 return false;
660
661 float diff = w1 - w2;
662 if (diff <= 0.02f) // Within 0.02f
663 return true;
664 return (diff / w2) <= 0.05f; // Within 5%.
665}
666
Chris Lattnercbb56252004-11-18 02:42:27 +0000667/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
668/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000669void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000670{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000671 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000672
Evan Chengf30a49d2008-04-03 16:40:27 +0000673 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000674 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000675 if (cur->empty()) {
676 unsigned physReg = cur->preference;
677 if (!physReg)
678 physReg = *RC->allocation_order_begin(*mf_);
679 DOUT << tri_->getName(physReg) << '\n';
680 // Note the register is not really in use.
681 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000682 return;
683 }
684
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000686
Chris Lattnera6c17502005-08-22 20:20:42 +0000687 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000688 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000689 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000690
Evan Chengd0deec22009-01-20 00:16:18 +0000691 // If start of this live interval is defined by a move instruction and its
692 // source is assigned a physical register that is compatible with the target
693 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000694 // This can happen when the move is from a larger register class to a smaller
695 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000696 if (!cur->preference && cur->hasAtLeastOneValue()) {
697 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000698 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
699 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000700 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
701 if (CopyMI &&
702 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000703 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000704 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000705 Reg = SrcReg;
706 else if (vrm_->isAssignedReg(SrcReg))
707 Reg = vrm_->getPhys(SrcReg);
708 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
709 cur->preference = Reg;
710 }
711 }
712 }
713
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000714 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000715 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 for (IntervalPtrs::const_iterator i = inactive_.begin(),
717 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000718 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000719 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000720 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000721 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000722 // If this is not in a related reg class to the register we're allocating,
723 // don't check it.
724 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
725 cur->overlapsFrom(*i->first, i->second-1)) {
726 Reg = vrm_->getPhys(Reg);
727 prt_->addRegUse(Reg);
728 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000729 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000730 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000731
732 // Speculatively check to see if we can get a register right now. If not,
733 // we know we won't be able to by adding more constraints. If so, we can
734 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
735 // is very bad (it contains all callee clobbered registers for any functions
736 // with a call), so we want to avoid doing that if possible.
737 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000738 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000739 if (physReg) {
740 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000741 // conflict with it. Check to see if we conflict with it or any of its
742 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000743 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000744 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000745 RegAliases.insert(*AS);
746
Chris Lattnera411cbc2005-08-22 20:59:30 +0000747 bool ConflictsWithFixed = false;
748 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000749 IntervalPtr &IP = fixed_[i];
750 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000751 // Okay, this reg is on the fixed list. Check to see if we actually
752 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000753 LiveInterval *I = IP.first;
754 if (I->endNumber() > StartPosition) {
755 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
756 IP.second = II;
757 if (II != I->begin() && II->start > StartPosition)
758 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000759 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000760 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000761 break;
762 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000763 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000764 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000765 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000766
767 // Okay, the register picked by our speculative getFreePhysReg call turned
768 // out to be in use. Actually add all of the conflicting fixed registers to
769 // prt so we can do an accurate query.
770 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000771 // For every interval in fixed we overlap with, mark the register as not
772 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000773 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
774 IntervalPtr &IP = fixed_[i];
775 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000776
777 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
778 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
779 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000780 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
781 IP.second = II;
782 if (II != I->begin() && II->start > StartPosition)
783 --II;
784 if (cur->overlapsFrom(*I, II)) {
785 unsigned reg = I->reg;
786 prt_->addRegUse(reg);
787 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
788 }
789 }
790 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000791
Chris Lattnera411cbc2005-08-22 20:59:30 +0000792 // Using the newly updated prt_ object, which includes conflicts in the
793 // future, see if there are any registers available.
794 physReg = getFreePhysReg(cur);
795 }
796 }
797
Chris Lattnera6c17502005-08-22 20:20:42 +0000798 // Restore the physical register tracker, removing information about the
799 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000800 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000801
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000802 // if we find a free register, we are done: assign this virtual to
803 // the free physical register and add this interval to the active
804 // list.
805 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000806 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000807 vrm_->assignVirt2Phys(cur->reg, physReg);
808 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000809 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000810 handled_.push_back(cur);
811 return;
812 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000813 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000814
Chris Lattnera6c17502005-08-22 20:20:42 +0000815 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000816 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000817 for (std::vector<std::pair<unsigned, float> >::iterator
818 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000819 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000820
821 // for each interval in active, update spill weights.
822 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
823 i != e; ++i) {
824 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000825 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000826 "Can only allocate virtual registers!");
827 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000828 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000829 }
830
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000831 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000832
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000833 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000834 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000835 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
836
837 bool Found = false;
838 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000839 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
840 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
841 e = RC->allocation_order_end(*mf_); i != e; ++i) {
842 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000843 float regWeight = SpillWeights[reg];
844 if (minWeight > regWeight)
845 Found = true;
846 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000847 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000848
849 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000850 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000851 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
852 e = RC->allocation_order_end(*mf_); i != e; ++i) {
853 unsigned reg = *i;
854 // No need to worry about if the alias register size < regsize of RC.
855 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000856 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
857 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000858 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000859 }
Evan Cheng3e172252008-06-20 21:45:16 +0000860
861 // Sort all potential spill candidates by weight.
862 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
863 minReg = RegsWeights[0].first;
864 minWeight = RegsWeights[0].second;
865 if (minWeight == HUGE_VALF) {
866 // All registers must have inf weight. Just grab one!
867 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000868 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000869 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000870 // Spill a physical register around defs and uses.
871 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000872 assignRegOrStackSlotAtInterval(cur);
873 return;
874 }
Evan Cheng3e172252008-06-20 21:45:16 +0000875 }
876
877 // Find up to 3 registers to consider as spill candidates.
878 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
879 while (LastCandidate > 1) {
880 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
881 break;
882 --LastCandidate;
883 }
884
885 DOUT << "\t\tregister(s) with min weight(s): ";
886 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
887 DOUT << tri_->getName(RegsWeights[i].first)
888 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000889
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000890 // if the current has the minimum weight, we need to spill it and
891 // add any added intervals back to unhandled, and restart
892 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000893 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000894 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000895 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000896 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000897 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000898 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000899 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000900 if (added.empty())
901 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000902
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000903 // Merge added with unhandled. Note that we know that
904 // addIntervalsForSpills returns intervals sorted by their starting
905 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000906 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000907 unhandled_.push(added[i]);
908 return;
909 }
910
Chris Lattner19828d42004-11-18 03:49:30 +0000911 ++NumBacktracks;
912
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000913 // push the current interval back to unhandled since we are going
914 // to re-run at least this iteration. Since we didn't modify it it
915 // should go back right in the front of the list
916 unhandled_.push(cur);
917
Dan Gohman6f0d0242008-02-10 18:45:23 +0000918 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000919 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000920
Evan Cheng3e172252008-06-20 21:45:16 +0000921 // We spill all intervals aliasing the register with
922 // minimum weight, rollback to the interval with the earliest
923 // start point and let the linear scan algorithm run again
924 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000925
Evan Cheng3e172252008-06-20 21:45:16 +0000926 // Determine which intervals have to be spilled.
927 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
928
929 // Set of spilled vregs (used later to rollback properly)
930 SmallSet<unsigned, 8> spilled;
931
932 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000933 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000934 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000935
Evan Cheng3e172252008-06-20 21:45:16 +0000936 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000937 // want to clear (and its aliases). We only spill those that overlap with the
938 // current interval as the rest do not affect its allocation. we also keep
939 // track of the earliest start of all spilled live intervals since this will
940 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000941 std::vector<LiveInterval*> added;
942 while (!spillIs.empty()) {
943 LiveInterval *sli = spillIs.back();
944 spillIs.pop_back();
945 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
946 earliestStart = std::min(earliestStart, sli->beginNumber());
947 float SSWeight;
948 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000949 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000950 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
951 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
952 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000953 }
954
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000955 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000956
957 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000958 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000959 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000960 while (!handled_.empty()) {
961 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000962 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000963 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000964 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000965 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000966 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000967
968 // When undoing a live interval allocation we must know if it is active or
969 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000970 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000971 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000972 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000973 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000974 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000975 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000976 prt_->delRegUse(vrm_->getPhys(i->reg));
977 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000978 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000979 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000980 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000981 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000982 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000983 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000984 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000985 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000986 "Can only allocate virtual registers!");
987 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000988 unhandled_.push(i);
989 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000990
991 // It interval has a preference, it must be defined by a copy. Clear the
992 // preference now since the source interval allocation may have been undone
993 // as well.
994 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000995 }
996
Chris Lattner19828d42004-11-18 03:49:30 +0000997 // Rewind the iterators in the active, inactive, and fixed lists back to the
998 // point we reverted to.
999 RevertVectorIteratorsTo(active_, earliestStart);
1000 RevertVectorIteratorsTo(inactive_, earliestStart);
1001 RevertVectorIteratorsTo(fixed_, earliestStart);
1002
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001003 // scan the rest and undo each interval that expired after t and
1004 // insert it in active (the next iteration of the algorithm will
1005 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001006 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1007 LiveInterval *HI = handled_[i];
1008 if (!HI->expiredAt(earliestStart) &&
1009 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001010 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001011 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001012 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001013 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001014 }
1015 }
1016
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001017 // merge added with unhandled
1018 for (unsigned i = 0, e = added.size(); i != e; ++i)
1019 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001020}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001021
Chris Lattnercbb56252004-11-18 02:42:27 +00001022/// getFreePhysReg - return a free physical register for this virtual register
1023/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001024unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001025 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001026 unsigned MaxInactiveCount = 0;
1027
Evan Cheng841ee1a2008-09-18 22:38:47 +00001028 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001029 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1030
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001031 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1032 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001033 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001034 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001035 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001036
1037 // If this is not in a related reg class to the register we're allocating,
1038 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001039 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001040 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1041 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001042 if (inactiveCounts.size() <= reg)
1043 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001044 ++inactiveCounts[reg];
1045 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1046 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001047 }
1048
Chris Lattnerf8355d92005-08-22 16:55:22 +00001049 unsigned FreeReg = 0;
1050 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001051
1052 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001053 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001054 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001055 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001056 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001057 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001058 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001059 return cur->preference;
1060 } else
1061 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001062 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001063 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001064
Chris Lattnerf8355d92005-08-22 16:55:22 +00001065 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001066 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1067 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001068 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001069 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001070 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001071 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001072 if (FreeReg < inactiveCounts.size())
1073 FreeRegInactiveCount = inactiveCounts[FreeReg];
1074 else
1075 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001076 break;
1077 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001078
Chris Lattnerf8355d92005-08-22 16:55:22 +00001079 // If there are no free regs, or if this reg has the max inactive count,
1080 // return this register.
1081 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1082
1083 // Continue scanning the registers, looking for the one with the highest
1084 // inactive count. Alkis found that this reduced register pressure very
1085 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1086 // reevaluated now.
1087 for (; I != E; ++I) {
1088 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001089 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001090 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001091 FreeReg = Reg;
1092 FreeRegInactiveCount = inactiveCounts[Reg];
1093 if (FreeRegInactiveCount == MaxInactiveCount)
1094 break; // We found the one with the max inactive count.
1095 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001096 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001097
1098 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001099}
1100
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001101FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001102 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001103}