blob: 26af53ef83223aff385b85ab289c851ac10ef72d [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_;
Owen Anderson49c8aa02009-03-13 05:55:11 +0000108 VirtRegMap* vrm_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 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>();
Owen Anderson49c8aa02009-03-13 05:55:11 +0000129 AU.addRequired<VirtRegMap>();
130 AU.addPreserved<VirtRegMap>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000131 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000132 MachineFunctionPass::getAnalysisUsage(AU);
133 }
134
135 /// runOnMachineFunction - register allocate the whole function
136 bool runOnMachineFunction(MachineFunction&);
137
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000138 private:
139 /// linearScan - the linear scan algorithm
140 void linearScan();
141
Chris Lattnercbb56252004-11-18 02:42:27 +0000142 /// initIntervalSets - initialize the interval sets.
143 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000144 void initIntervalSets();
145
Chris Lattnercbb56252004-11-18 02:42:27 +0000146 /// processActiveIntervals - expire old intervals and move non-overlapping
147 /// ones to the inactive list.
148 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000149
Chris Lattnercbb56252004-11-18 02:42:27 +0000150 /// processInactiveIntervals - expire old intervals and move overlapping
151 /// ones to the active list.
152 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000153
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000154 /// assignRegOrStackSlotAtInterval - assign a register if one
155 /// is available, or spill.
156 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
157
Evan Cheng5d088fe2009-03-23 22:57:19 +0000158 void updateSpillWeights(std::vector<float> &Weights,
159 unsigned reg, float weight,
160 const TargetRegisterClass *RC);
161
Evan Cheng3e172252008-06-20 21:45:16 +0000162 /// findIntervalsToSpill - Determine the intervals to spill for the
163 /// specified interval. It's passed the physical registers whose spill
164 /// weight is the lowest among all the registers whose live intervals
165 /// conflict with the interval.
166 void findIntervalsToSpill(LiveInterval *cur,
167 std::vector<std::pair<unsigned,float> > &Candidates,
168 unsigned NumCands,
169 SmallVector<LiveInterval*, 8> &SpillIntervals);
170
Evan Chengc92da382007-11-03 07:20:12 +0000171 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
172 /// try allocate the definition the same register as the source register
173 /// if the register is not defined during live time of the interval. This
174 /// eliminate a copy. This is used to coalesce copies which were not
175 /// coalesced away before allocation either due to dest and src being in
176 /// different register classes or because the coalescer was overly
177 /// conservative.
178 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
179
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000180 ///
181 /// register handling helpers
182 ///
183
Chris Lattnercbb56252004-11-18 02:42:27 +0000184 /// getFreePhysReg - return a free physical register for this virtual
185 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 unsigned getFreePhysReg(LiveInterval* cur);
187
188 /// assignVirt2StackSlot - assigns this virtual register to a
189 /// stack slot. returns the stack slot
190 int assignVirt2StackSlot(unsigned virtReg);
191
Chris Lattnerb9805782005-08-23 22:27:31 +0000192 void ComputeRelatedRegClasses();
193
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000194 template <typename ItTy>
195 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000196 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000197 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000198 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000199 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000200 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000201 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000202 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000203 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000204 }
205 }
206 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000207 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000208}
209
Evan Cheng3f32d652008-06-04 09:18:41 +0000210static RegisterPass<RALinScan>
211X("linearscan-regalloc", "Linear Scan Register Allocator");
212
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000213void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000214 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000215
216 // First pass, add all reg classes to the union, and determine at least one
217 // reg class that each register is in.
218 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000219 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
220 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000221 RelatedRegClasses.insert(*RCI);
222 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
223 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000224 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000225
226 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
227 if (PRC) {
228 // Already processed this register. Just make sure we know that
229 // multiple register classes share a register.
230 RelatedRegClasses.unionSets(PRC, *RCI);
231 } else {
232 PRC = *RCI;
233 }
234 }
235 }
236
237 // Second pass, now that we know conservatively what register classes each reg
238 // belongs to, add info about aliases. We don't need to do this for targets
239 // without register aliases.
240 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000241 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000242 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
243 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000244 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000245 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
246}
247
Evan Chengc92da382007-11-03 07:20:12 +0000248/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
249/// try allocate the definition the same register as the source register
250/// if the register is not defined during live time of the interval. This
251/// eliminate a copy. This is used to coalesce copies which were not
252/// coalesced away before allocation either due to dest and src being in
253/// different register classes or because the coalescer was overly
254/// conservative.
255unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000256 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000257 return Reg;
258
Evan Chengd0deec22009-01-20 00:16:18 +0000259 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000260 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
261 return Reg;
262 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000263 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
264 if (!CopyMI ||
265 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000266 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000267 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000268 if (!vrm_->isAssignedReg(SrcReg))
269 return Reg;
270 else
271 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000272 }
Evan Chengc92da382007-11-03 07:20:12 +0000273 if (Reg == SrcReg)
274 return Reg;
275
Evan Cheng841ee1a2008-09-18 22:38:47 +0000276 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000277 if (!RC->contains(SrcReg))
278 return Reg;
279
280 // Try to coalesce.
281 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000282 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000283 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000284 vrm_->clearVirt(cur.reg);
285 vrm_->assignVirt2Phys(cur.reg, SrcReg);
286 ++NumCoalesce;
287 return SrcReg;
288 }
289
290 return Reg;
291}
292
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000293bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000294 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000295 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000297 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000298 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000299 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000301 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000302 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000303
David Greene2c17c4d2007-09-06 16:18:45 +0000304 // We don't run the coalescer here because we have no reason to
305 // interact with it. If the coalescer requires interaction, it
306 // won't do anything. If it doesn't require interaction, we assume
307 // it was run as a separate pass.
308
Chris Lattnerb9805782005-08-23 22:27:31 +0000309 // If this is the first function compiled, compute the related reg classes.
310 if (RelatedRegClasses.empty())
311 ComputeRelatedRegClasses();
312
Dan Gohman6f0d0242008-02-10 18:45:23 +0000313 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Owen Anderson49c8aa02009-03-13 05:55:11 +0000314 vrm_ = &getAnalysis<VirtRegMap>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000316
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000317 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000318
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000319 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000320
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000321 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000322 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattnercbb56252004-11-18 02:42:27 +0000323
Dan Gohman51cd9d62008-06-23 23:51:16 +0000324 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000325 fixed_.clear();
326 active_.clear();
327 inactive_.clear();
328 handled_.clear();
329
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000330 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000331}
332
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000333/// initIntervalSets - initialize the interval sets.
334///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000335void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000336{
337 assert(unhandled_.empty() && fixed_.empty() &&
338 active_.empty() && inactive_.empty() &&
339 "interval sets should be empty on initialization");
340
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000341 handled_.reserve(li_->getNumIntervals());
342
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000343 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000344 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000345 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000346 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000347 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000348 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000349 }
350}
351
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000352void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000353{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000355 DOUT << "********** LINEAR SCAN **********\n";
356 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000357
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000358 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359
360 while (!unhandled_.empty()) {
361 // pick the interval with the earliest start point
362 LiveInterval* cur = unhandled_.top();
363 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000364 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000365 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366
Evan Chengf30a49d2008-04-03 16:40:27 +0000367 if (!cur->empty()) {
368 processActiveIntervals(cur->beginNumber());
369 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000370
Evan Chengf30a49d2008-04-03 16:40:27 +0000371 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
372 "Can only allocate virtual registers!");
373 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000374
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000375 // Allocating a virtual register. try to find a free
376 // physical register or spill an interval (possibly this one) in order to
377 // assign it one.
378 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000380 DEBUG(printIntervals("active", active_.begin(), active_.end()));
381 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000382 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000383
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000385 while (!active_.empty()) {
386 IntervalPtr &IP = active_.back();
387 unsigned reg = IP.first->reg;
388 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000389 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000390 "Can only allocate virtual registers!");
391 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000393 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000394 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000395
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000397 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000398 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000399 DOUT << "\tinterval " << *i->first << " expired\n");
400 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000401
Evan Cheng81a03822007-11-17 00:40:40 +0000402 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000404 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000405 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000406 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000407 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000408 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000409 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000410 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000411 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000412 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000413 if (!Reg)
414 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000415 // Ignore splited live intervals.
416 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
417 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000418 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
419 I != E; ++I) {
420 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000421 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000422 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
423 if (LiveInMBBs[i] != EntryMBB)
424 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000425 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000426 }
427 }
428 }
429
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000430 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000431}
432
Chris Lattnercbb56252004-11-18 02:42:27 +0000433/// processActiveIntervals - expire old intervals and move non-overlapping ones
434/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000435void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000436{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000437 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000438
Chris Lattnercbb56252004-11-18 02:42:27 +0000439 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
440 LiveInterval *Interval = active_[i].first;
441 LiveInterval::iterator IntervalPos = active_[i].second;
442 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000443
Chris Lattnercbb56252004-11-18 02:42:27 +0000444 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
445
446 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000447 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000448 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000449 "Can only allocate virtual registers!");
450 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000451 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000452
453 // Pop off the end of the list.
454 active_[i] = active_.back();
455 active_.pop_back();
456 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000457
Chris Lattnercbb56252004-11-18 02:42:27 +0000458 } else if (IntervalPos->start > CurPoint) {
459 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000460 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000461 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000462 "Can only allocate virtual registers!");
463 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000465 // add to inactive.
466 inactive_.push_back(std::make_pair(Interval, IntervalPos));
467
468 // Pop off the end of the list.
469 active_[i] = active_.back();
470 active_.pop_back();
471 --i; --e;
472 } else {
473 // Otherwise, just update the iterator position.
474 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475 }
476 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000477}
478
Chris Lattnercbb56252004-11-18 02:42:27 +0000479/// processInactiveIntervals - expire old intervals and move overlapping
480/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000481void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000482{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000483 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000484
Chris Lattnercbb56252004-11-18 02:42:27 +0000485 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
486 LiveInterval *Interval = inactive_[i].first;
487 LiveInterval::iterator IntervalPos = inactive_[i].second;
488 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000489
Chris Lattnercbb56252004-11-18 02:42:27 +0000490 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000491
Chris Lattnercbb56252004-11-18 02:42:27 +0000492 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000493 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000494
Chris Lattnercbb56252004-11-18 02:42:27 +0000495 // Pop off the end of the list.
496 inactive_[i] = inactive_.back();
497 inactive_.pop_back();
498 --i; --e;
499 } else if (IntervalPos->start <= CurPoint) {
500 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000501 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000502 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000503 "Can only allocate virtual registers!");
504 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 prt_->addRegUse(reg);
506 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000507 active_.push_back(std::make_pair(Interval, IntervalPos));
508
509 // Pop off the end of the list.
510 inactive_[i] = inactive_.back();
511 inactive_.pop_back();
512 --i; --e;
513 } else {
514 // Otherwise, just update the iterator position.
515 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000516 }
517 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000518}
519
Chris Lattnercbb56252004-11-18 02:42:27 +0000520/// updateSpillWeights - updates the spill weights of the specifed physical
521/// register and its weight.
Evan Cheng5d088fe2009-03-23 22:57:19 +0000522void RALinScan::updateSpillWeights(std::vector<float> &Weights,
523 unsigned reg, float weight,
524 const TargetRegisterClass *RC) {
525 SmallSet<unsigned, 4> Processed;
526 SmallSet<unsigned, 4> SuperAdded;
527 SmallVector<unsigned, 4> Supers;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000528 Weights[reg] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000529 Processed.insert(reg);
530 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000531 Weights[*as] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000532 Processed.insert(*as);
533 if (tri_->isSubRegister(*as, reg) &&
534 SuperAdded.insert(*as) &&
535 RC->contains(*as)) {
536 Supers.push_back(*as);
537 }
538 }
539
540 // If the alias is a super-register, and the super-register is in the
541 // register class we are trying to allocate. Then add the weight to all
542 // sub-registers of the super-register even if they are not aliases.
543 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
544 // bl should get the same spill weight otherwise it will be choosen
545 // as a spill candidate since spilling bh doesn't make ebx available.
546 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
547 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
548 if (!Processed.count(*sr))
549 Weights[*sr] += weight;
550 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000551}
552
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000553static
554RALinScan::IntervalPtrs::iterator
555FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
556 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
557 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000558 if (I->first == LI) return I;
559 return IP.end();
560}
561
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000562static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000563 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000564 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000565 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
566 IP.second, Point);
567 if (I != IP.first->begin()) --I;
568 IP.second = I;
569 }
570}
Chris Lattnercbb56252004-11-18 02:42:27 +0000571
Evan Cheng3f32d652008-06-04 09:18:41 +0000572/// addStackInterval - Create a LiveInterval for stack if the specified live
573/// interval has been spilled.
574static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000575 LiveIntervals *li_, float &Weight,
576 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000577 int SS = vrm_.getStackSlot(cur->reg);
578 if (SS == VirtRegMap::NO_STACK_SLOT)
579 return;
580 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000581 SI.weight += Weight;
582
Evan Cheng3f32d652008-06-04 09:18:41 +0000583 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000584 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000585 VNI = SI.getValNumInfo(0);
586 else
587 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
588
589 LiveInterval &RI = li_->getInterval(cur->reg);
590 // FIXME: This may be overly conservative.
591 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000592}
593
Evan Cheng3e172252008-06-20 21:45:16 +0000594/// getConflictWeight - Return the number of conflicts between cur
595/// live interval and defs and uses of Reg weighted by loop depthes.
596static float getConflictWeight(LiveInterval *cur, unsigned Reg,
597 LiveIntervals *li_,
598 MachineRegisterInfo *mri_,
599 const MachineLoopInfo *loopInfo) {
600 float Conflicts = 0;
601 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
602 E = mri_->reg_end(); I != E; ++I) {
603 MachineInstr *MI = &*I;
604 if (cur->liveAt(li_->getInstructionIndex(MI))) {
605 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
606 Conflicts += powf(10.0f, (float)loopDepth);
607 }
608 }
609 return Conflicts;
610}
611
612/// findIntervalsToSpill - Determine the intervals to spill for the
613/// specified interval. It's passed the physical registers whose spill
614/// weight is the lowest among all the registers whose live intervals
615/// conflict with the interval.
616void RALinScan::findIntervalsToSpill(LiveInterval *cur,
617 std::vector<std::pair<unsigned,float> > &Candidates,
618 unsigned NumCands,
619 SmallVector<LiveInterval*, 8> &SpillIntervals) {
620 // We have figured out the *best* register to spill. But there are other
621 // registers that are pretty good as well (spill weight within 3%). Spill
622 // the one that has fewest defs and uses that conflict with cur.
623 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
624 SmallVector<LiveInterval*, 8> SLIs[3];
625
626 DOUT << "\tConsidering " << NumCands << " candidates: ";
627 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
628 DOUT << tri_->getName(Candidates[i].first) << " ";
629 DOUT << "\n";);
630
631 // Calculate the number of conflicts of each candidate.
632 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
633 unsigned Reg = i->first->reg;
634 unsigned PhysReg = vrm_->getPhys(Reg);
635 if (!cur->overlapsFrom(*i->first, i->second))
636 continue;
637 for (unsigned j = 0; j < NumCands; ++j) {
638 unsigned Candidate = Candidates[j].first;
639 if (tri_->regsOverlap(PhysReg, Candidate)) {
640 if (NumCands > 1)
641 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
642 SLIs[j].push_back(i->first);
643 }
644 }
645 }
646
647 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
648 unsigned Reg = i->first->reg;
649 unsigned PhysReg = vrm_->getPhys(Reg);
650 if (!cur->overlapsFrom(*i->first, i->second-1))
651 continue;
652 for (unsigned j = 0; j < NumCands; ++j) {
653 unsigned Candidate = Candidates[j].first;
654 if (tri_->regsOverlap(PhysReg, Candidate)) {
655 if (NumCands > 1)
656 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
657 SLIs[j].push_back(i->first);
658 }
659 }
660 }
661
662 // Which is the best candidate?
663 unsigned BestCandidate = 0;
664 float MinConflicts = Conflicts[0];
665 for (unsigned i = 1; i != NumCands; ++i) {
666 if (Conflicts[i] < MinConflicts) {
667 BestCandidate = i;
668 MinConflicts = Conflicts[i];
669 }
670 }
671
672 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
673 std::back_inserter(SpillIntervals));
674}
675
676namespace {
677 struct WeightCompare {
678 typedef std::pair<unsigned, float> RegWeightPair;
679 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
680 return LHS.second < RHS.second;
681 }
682 };
683}
684
685static bool weightsAreClose(float w1, float w2) {
686 if (!NewHeuristic)
687 return false;
688
689 float diff = w1 - w2;
690 if (diff <= 0.02f) // Within 0.02f
691 return true;
692 return (diff / w2) <= 0.05f; // Within 5%.
693}
694
Chris Lattnercbb56252004-11-18 02:42:27 +0000695/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
696/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000697void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000698{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000699 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000700
Evan Chengf30a49d2008-04-03 16:40:27 +0000701 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000702 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000703 if (cur->empty()) {
704 unsigned physReg = cur->preference;
705 if (!physReg)
706 physReg = *RC->allocation_order_begin(*mf_);
707 DOUT << tri_->getName(physReg) << '\n';
708 // Note the register is not really in use.
709 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000710 return;
711 }
712
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000713 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000714
Chris Lattnera6c17502005-08-22 20:20:42 +0000715 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000716 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000717 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000718
Evan Chengd0deec22009-01-20 00:16:18 +0000719 // If start of this live interval is defined by a move instruction and its
720 // source is assigned a physical register that is compatible with the target
721 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000722 // This can happen when the move is from a larger register class to a smaller
723 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000724 if (!cur->preference && cur->hasAtLeastOneValue()) {
725 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000726 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
727 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000728 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
729 if (CopyMI &&
730 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000731 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000732 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000733 Reg = SrcReg;
734 else if (vrm_->isAssignedReg(SrcReg))
735 Reg = vrm_->getPhys(SrcReg);
736 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
737 cur->preference = Reg;
738 }
739 }
740 }
741
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000742 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000743 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000744 for (IntervalPtrs::const_iterator i = inactive_.begin(),
745 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000746 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000747 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000748 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000749 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000750 // If this is not in a related reg class to the register we're allocating,
751 // don't check it.
752 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
753 cur->overlapsFrom(*i->first, i->second-1)) {
754 Reg = vrm_->getPhys(Reg);
755 prt_->addRegUse(Reg);
756 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000757 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000758 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000759
760 // Speculatively check to see if we can get a register right now. If not,
761 // we know we won't be able to by adding more constraints. If so, we can
762 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
763 // is very bad (it contains all callee clobbered registers for any functions
764 // with a call), so we want to avoid doing that if possible.
765 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000766 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000767 if (physReg) {
768 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000769 // conflict with it. Check to see if we conflict with it or any of its
770 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000771 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000772 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000773 RegAliases.insert(*AS);
774
Chris Lattnera411cbc2005-08-22 20:59:30 +0000775 bool ConflictsWithFixed = false;
776 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000777 IntervalPtr &IP = fixed_[i];
778 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000779 // Okay, this reg is on the fixed list. Check to see if we actually
780 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000781 LiveInterval *I = IP.first;
782 if (I->endNumber() > StartPosition) {
783 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
784 IP.second = II;
785 if (II != I->begin() && II->start > StartPosition)
786 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000787 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000788 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000789 break;
790 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000791 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000792 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000793 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000794
795 // Okay, the register picked by our speculative getFreePhysReg call turned
796 // out to be in use. Actually add all of the conflicting fixed registers to
797 // prt so we can do an accurate query.
798 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000799 // For every interval in fixed we overlap with, mark the register as not
800 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000801 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
802 IntervalPtr &IP = fixed_[i];
803 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000804
805 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
806 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
807 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000808 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
809 IP.second = II;
810 if (II != I->begin() && II->start > StartPosition)
811 --II;
812 if (cur->overlapsFrom(*I, II)) {
813 unsigned reg = I->reg;
814 prt_->addRegUse(reg);
815 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
816 }
817 }
818 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000819
Chris Lattnera411cbc2005-08-22 20:59:30 +0000820 // Using the newly updated prt_ object, which includes conflicts in the
821 // future, see if there are any registers available.
822 physReg = getFreePhysReg(cur);
823 }
824 }
825
Chris Lattnera6c17502005-08-22 20:20:42 +0000826 // Restore the physical register tracker, removing information about the
827 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000828 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000829
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000830 // if we find a free register, we are done: assign this virtual to
831 // the free physical register and add this interval to the active
832 // list.
833 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000834 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000835 vrm_->assignVirt2Phys(cur->reg, physReg);
836 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000837 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000838 handled_.push_back(cur);
839 return;
840 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000841 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000842
Chris Lattnera6c17502005-08-22 20:20:42 +0000843 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000844 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000845 for (std::vector<std::pair<unsigned, float> >::iterator
846 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Evan Cheng5d088fe2009-03-23 22:57:19 +0000847 updateSpillWeights(SpillWeights, I->first, I->second, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +0000848
849 // for each interval in active, update spill weights.
850 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
851 i != e; ++i) {
852 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000853 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000854 "Can only allocate virtual registers!");
855 reg = vrm_->getPhys(reg);
Evan Cheng5d088fe2009-03-23 22:57:19 +0000856 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +0000857 }
858
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000859 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000860
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000861 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000862 float minWeight = HUGE_VALF;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000863 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
Evan Cheng3e172252008-06-20 21:45:16 +0000864
865 bool Found = false;
866 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000867 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
868 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
869 e = RC->allocation_order_end(*mf_); i != e; ++i) {
870 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000871 float regWeight = SpillWeights[reg];
872 if (minWeight > regWeight)
873 Found = true;
874 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000875 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000876
877 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000878 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000879 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
880 e = RC->allocation_order_end(*mf_); i != e; ++i) {
881 unsigned reg = *i;
882 // No need to worry about if the alias register size < regsize of RC.
883 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000884 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
885 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000886 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000887 }
Evan Cheng3e172252008-06-20 21:45:16 +0000888
889 // Sort all potential spill candidates by weight.
890 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
891 minReg = RegsWeights[0].first;
892 minWeight = RegsWeights[0].second;
893 if (minWeight == HUGE_VALF) {
894 // All registers must have inf weight. Just grab one!
895 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000896 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000897 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000898 // Spill a physical register around defs and uses.
Evan Cheng2824a652009-03-23 18:24:37 +0000899 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_))
900 assignRegOrStackSlotAtInterval(cur);
901 else {
902 cerr << "Ran out of registers during register allocation!\n";
903 exit(1);
904 }
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000905 return;
906 }
Evan Cheng3e172252008-06-20 21:45:16 +0000907 }
908
909 // Find up to 3 registers to consider as spill candidates.
910 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
911 while (LastCandidate > 1) {
912 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
913 break;
914 --LastCandidate;
915 }
916
917 DOUT << "\t\tregister(s) with min weight(s): ";
918 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
919 DOUT << tri_->getName(RegsWeights[i].first)
920 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000921
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000922 // if the current has the minimum weight, we need to spill it and
923 // add any added intervals back to unhandled, and restart
924 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000925 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000926 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000927 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000928 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000929 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000930 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000931 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000932 if (added.empty())
933 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000934
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000935 // Merge added with unhandled. Note that we know that
936 // addIntervalsForSpills returns intervals sorted by their starting
937 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000938 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000939 unhandled_.push(added[i]);
940 return;
941 }
942
Chris Lattner19828d42004-11-18 03:49:30 +0000943 ++NumBacktracks;
944
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000945 // push the current interval back to unhandled since we are going
946 // to re-run at least this iteration. Since we didn't modify it it
947 // should go back right in the front of the list
948 unhandled_.push(cur);
949
Dan Gohman6f0d0242008-02-10 18:45:23 +0000950 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000951 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000952
Evan Cheng3e172252008-06-20 21:45:16 +0000953 // We spill all intervals aliasing the register with
954 // minimum weight, rollback to the interval with the earliest
955 // start point and let the linear scan algorithm run again
956 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000957
Evan Cheng3e172252008-06-20 21:45:16 +0000958 // Determine which intervals have to be spilled.
959 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
960
961 // Set of spilled vregs (used later to rollback properly)
962 SmallSet<unsigned, 8> spilled;
963
964 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000965 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000966 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000967
Evan Cheng3e172252008-06-20 21:45:16 +0000968 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000969 // want to clear (and its aliases). We only spill those that overlap with the
970 // current interval as the rest do not affect its allocation. we also keep
971 // track of the earliest start of all spilled live intervals since this will
972 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000973 std::vector<LiveInterval*> added;
974 while (!spillIs.empty()) {
975 LiveInterval *sli = spillIs.back();
976 spillIs.pop_back();
977 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
978 earliestStart = std::min(earliestStart, sli->beginNumber());
979 float SSWeight;
980 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000981 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000982 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
983 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
984 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000985 }
986
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000987 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000988
989 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000990 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000991 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000992 while (!handled_.empty()) {
993 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000994 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000995 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000996 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000997 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000998 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000999
1000 // When undoing a live interval allocation we must know if it is active or
1001 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001002 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +00001003 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001004 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001005 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001006 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001007 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001008 prt_->delRegUse(vrm_->getPhys(i->reg));
1009 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +00001010 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001011 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001012 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001013 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001014 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001015 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001016 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001017 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001018 "Can only allocate virtual registers!");
1019 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001020 unhandled_.push(i);
1021 }
Evan Cheng9aeaf752007-11-04 08:32:21 +00001022
1023 // It interval has a preference, it must be defined by a copy. Clear the
1024 // preference now since the source interval allocation may have been undone
1025 // as well.
1026 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001027 }
1028
Chris Lattner19828d42004-11-18 03:49:30 +00001029 // Rewind the iterators in the active, inactive, and fixed lists back to the
1030 // point we reverted to.
1031 RevertVectorIteratorsTo(active_, earliestStart);
1032 RevertVectorIteratorsTo(inactive_, earliestStart);
1033 RevertVectorIteratorsTo(fixed_, earliestStart);
1034
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001035 // scan the rest and undo each interval that expired after t and
1036 // insert it in active (the next iteration of the algorithm will
1037 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001038 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1039 LiveInterval *HI = handled_[i];
1040 if (!HI->expiredAt(earliestStart) &&
1041 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001042 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001043 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001044 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001045 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001046 }
1047 }
1048
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001049 // merge added with unhandled
1050 for (unsigned i = 0, e = added.size(); i != e; ++i)
1051 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001052}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001053
Chris Lattnercbb56252004-11-18 02:42:27 +00001054/// getFreePhysReg - return a free physical register for this virtual register
1055/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001056unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001057 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001058 unsigned MaxInactiveCount = 0;
1059
Evan Cheng841ee1a2008-09-18 22:38:47 +00001060 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001061 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1062
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001063 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1064 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001065 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001066 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001067 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001068
1069 // If this is not in a related reg class to the register we're allocating,
1070 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001071 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001072 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1073 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001074 if (inactiveCounts.size() <= reg)
1075 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001076 ++inactiveCounts[reg];
1077 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1078 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001079 }
1080
Chris Lattnerf8355d92005-08-22 16:55:22 +00001081 unsigned FreeReg = 0;
1082 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001083
1084 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001085 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001086 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001087 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001088 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001089 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001090 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001091 return cur->preference;
1092 } else
1093 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001094 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001095 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001096
Chris Lattnerf8355d92005-08-22 16:55:22 +00001097 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001098 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1099 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001100 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001101 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001102 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001103 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001104 if (FreeReg < inactiveCounts.size())
1105 FreeRegInactiveCount = inactiveCounts[FreeReg];
1106 else
1107 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001108 break;
1109 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001110
Chris Lattnerf8355d92005-08-22 16:55:22 +00001111 // If there are no free regs, or if this reg has the max inactive count,
1112 // return this register.
1113 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1114
1115 // Continue scanning the registers, looking for the one with the highest
1116 // inactive count. Alkis found that this reduced register pressure very
1117 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1118 // reevaluated now.
1119 for (; I != E; ++I) {
1120 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001121 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001122 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001123 FreeReg = Reg;
1124 FreeRegInactiveCount = inactiveCounts[Reg];
1125 if (FreeRegInactiveCount == MaxInactiveCount)
1126 break; // We found the one with the max inactive count.
1127 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001128 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001129
1130 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001131}
1132
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001133FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001134 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001135}