blob: c7383154841502fe9f4a7adff6662d4ea12b5442 [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");
Evan Cheng206d1852009-04-20 08:01:12 +000048STATISTIC(NumDowngrade, "Number of registers downgraded");
Chris Lattnercd3245a2006-12-19 22:41:21 +000049
Evan Cheng3e172252008-06-20 21:45:16 +000050static cl::opt<bool>
51NewHeuristic("new-spilling-heuristic",
52 cl::desc("Use new spilling heuristic"),
53 cl::init(false), cl::Hidden);
54
Evan Chengf5cd4f02008-10-23 20:43:13 +000055static cl::opt<bool>
56PreSplitIntervals("pre-alloc-split",
57 cl::desc("Pre-register allocation live interval splitting"),
58 cl::init(false), cl::Hidden);
59
Chris Lattnercd3245a2006-12-19 22:41:21 +000060static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000061linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000062 createLinearScanRegisterAllocator);
63
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000064namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000065 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000066 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000068
Chris Lattnercbb56252004-11-18 02:42:27 +000069 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000070 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000071 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000072 /// RelatedRegClasses - This structure is built the first time a function is
73 /// compiled, and keeps track of which register classes have registers that
74 /// belong to multiple classes or have aliases that are in other classes.
75 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000076 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000077
Evan Cheng206d1852009-04-20 08:01:12 +000078 // NextReloadMap - For each register in the map, it maps to the another
79 // register which is defined by a reload from the same stack slot and
80 // both reloads are in the same basic block.
81 DenseMap<unsigned, unsigned> NextReloadMap;
82
83 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
84 // un-favored for allocation.
85 SmallSet<unsigned, 8> DowngradedRegs;
86
87 // DowngradeMap - A map from virtual registers to physical registers being
88 // downgraded for the virtual registers.
89 DenseMap<unsigned, unsigned> DowngradeMap;
90
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000091 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000092 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000093 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000094 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000095 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000096 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000097 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000098 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000099 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +0000100
101 /// handled_ - Intervals are added to the handled_ set in the order of their
102 /// start value. This is uses for backtracking.
103 std::vector<LiveInterval*> handled_;
104
105 /// fixed_ - Intervals that correspond to machine registers.
106 ///
107 IntervalPtrs fixed_;
108
109 /// active_ - Intervals that are currently being processed, and which have a
110 /// live range active for the current point.
111 IntervalPtrs active_;
112
113 /// inactive_ - Intervals that are currently being processed, but which have
114 /// a hold at the current point.
115 IntervalPtrs inactive_;
116
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000117 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000118 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 greater_ptr<LiveInterval> > IntervalHeap;
120 IntervalHeap unhandled_;
121 std::auto_ptr<PhysRegTracker> prt_;
Owen Anderson49c8aa02009-03-13 05:55:11 +0000122 VirtRegMap* vrm_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000123 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000124
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 public:
126 virtual const char* getPassName() const {
127 return "Linear Scan Register Allocator";
128 }
129
130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000132 if (StrongPHIElim)
133 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000134 // Make sure PassManager knows which analyses to make available
135 // to coalescing and which analyses coalescing invalidates.
136 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000137 if (PreSplitIntervals)
138 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000139 AU.addRequired<LiveStacks>();
140 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000141 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000142 AU.addPreserved<MachineLoopInfo>();
Owen Anderson49c8aa02009-03-13 05:55:11 +0000143 AU.addRequired<VirtRegMap>();
144 AU.addPreserved<VirtRegMap>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000145 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000146 MachineFunctionPass::getAnalysisUsage(AU);
147 }
148
149 /// runOnMachineFunction - register allocate the whole function
150 bool runOnMachineFunction(MachineFunction&);
151
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000152 private:
153 /// linearScan - the linear scan algorithm
154 void linearScan();
155
Chris Lattnercbb56252004-11-18 02:42:27 +0000156 /// initIntervalSets - initialize the interval sets.
157 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000158 void initIntervalSets();
159
Chris Lattnercbb56252004-11-18 02:42:27 +0000160 /// processActiveIntervals - expire old intervals and move non-overlapping
161 /// ones to the inactive list.
162 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000163
Chris Lattnercbb56252004-11-18 02:42:27 +0000164 /// processInactiveIntervals - expire old intervals and move overlapping
165 /// ones to the active list.
166 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000167
Evan Cheng206d1852009-04-20 08:01:12 +0000168 /// hasNextReloadInterval - Return the next liveinterval that's being
169 /// defined by a reload from the same SS as the specified one.
170 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
171
172 /// DowngradeRegister - Downgrade a register for allocation.
173 void DowngradeRegister(LiveInterval *li, unsigned Reg);
174
175 /// UpgradeRegister - Upgrade a register for allocation.
176 void UpgradeRegister(unsigned Reg);
177
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000178 /// assignRegOrStackSlotAtInterval - assign a register if one
179 /// is available, or spill.
180 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
181
Evan Cheng5d088fe2009-03-23 22:57:19 +0000182 void updateSpillWeights(std::vector<float> &Weights,
183 unsigned reg, float weight,
184 const TargetRegisterClass *RC);
185
Evan Cheng3e172252008-06-20 21:45:16 +0000186 /// findIntervalsToSpill - Determine the intervals to spill for the
187 /// specified interval. It's passed the physical registers whose spill
188 /// weight is the lowest among all the registers whose live intervals
189 /// conflict with the interval.
190 void findIntervalsToSpill(LiveInterval *cur,
191 std::vector<std::pair<unsigned,float> > &Candidates,
192 unsigned NumCands,
193 SmallVector<LiveInterval*, 8> &SpillIntervals);
194
Evan Chengc92da382007-11-03 07:20:12 +0000195 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
196 /// try allocate the definition the same register as the source register
197 /// if the register is not defined during live time of the interval. This
198 /// eliminate a copy. This is used to coalesce copies which were not
199 /// coalesced away before allocation either due to dest and src being in
200 /// different register classes or because the coalescer was overly
201 /// conservative.
202 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
203
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000204 ///
205 /// register handling helpers
206 ///
207
Chris Lattnercbb56252004-11-18 02:42:27 +0000208 /// getFreePhysReg - return a free physical register for this virtual
209 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000210 unsigned getFreePhysReg(LiveInterval* cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000211 unsigned getFreePhysReg(const TargetRegisterClass *RC,
212 unsigned MaxInactiveCount,
213 SmallVector<unsigned, 256> &inactiveCounts,
214 bool SkipDGRegs);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000215
216 /// assignVirt2StackSlot - assigns this virtual register to a
217 /// stack slot. returns the stack slot
218 int assignVirt2StackSlot(unsigned virtReg);
219
Chris Lattnerb9805782005-08-23 22:27:31 +0000220 void ComputeRelatedRegClasses();
221
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000222 template <typename ItTy>
223 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000224 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000225 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000226 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000227 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000228 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000229 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000230 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000231 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000232 }
233 }
234 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000235 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000236}
237
Evan Cheng3f32d652008-06-04 09:18:41 +0000238static RegisterPass<RALinScan>
239X("linearscan-regalloc", "Linear Scan Register Allocator");
240
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000241void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000242 // First pass, add all reg classes to the union, and determine at least one
243 // reg class that each register is in.
244 bool HasAliases = false;
Evan Cheng206d1852009-04-20 08:01:12 +0000245 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
246 E = tri_->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000247 RelatedRegClasses.insert(*RCI);
248 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
249 I != E; ++I) {
Evan Cheng206d1852009-04-20 08:01:12 +0000250 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000251
252 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
253 if (PRC) {
254 // Already processed this register. Just make sure we know that
255 // multiple register classes share a register.
256 RelatedRegClasses.unionSets(PRC, *RCI);
257 } else {
258 PRC = *RCI;
259 }
260 }
261 }
262
263 // Second pass, now that we know conservatively what register classes each reg
264 // belongs to, add info about aliases. We don't need to do this for targets
265 // without register aliases.
266 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000267 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000268 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
269 I != E; ++I)
Evan Cheng206d1852009-04-20 08:01:12 +0000270 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000271 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
272}
273
Evan Chengc92da382007-11-03 07:20:12 +0000274/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
275/// try allocate the definition the same register as the source register
276/// if the register is not defined during live time of the interval. This
277/// eliminate a copy. This is used to coalesce copies which were not
278/// coalesced away before allocation either due to dest and src being in
279/// different register classes or because the coalescer was overly
280/// conservative.
281unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000282 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000283 return Reg;
284
Evan Chengd0deec22009-01-20 00:16:18 +0000285 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000286 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
287 return Reg;
288 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000289 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
290 if (!CopyMI ||
291 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000292 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000293 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000294 if (!vrm_->isAssignedReg(SrcReg))
295 return Reg;
296 else
297 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000298 }
Evan Chengc92da382007-11-03 07:20:12 +0000299 if (Reg == SrcReg)
300 return Reg;
301
Evan Cheng841ee1a2008-09-18 22:38:47 +0000302 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000303 if (!RC->contains(SrcReg))
304 return Reg;
305
306 // Try to coalesce.
307 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000308 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000309 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000310 vrm_->clearVirt(cur.reg);
311 vrm_->assignVirt2Phys(cur.reg, SrcReg);
312 ++NumCoalesce;
313 return SrcReg;
314 }
315
316 return Reg;
317}
318
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000319bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000320 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000321 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000322 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000323 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000324 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000325 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000326 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000327 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000328 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000329
David Greene2c17c4d2007-09-06 16:18:45 +0000330 // We don't run the coalescer here because we have no reason to
331 // interact with it. If the coalescer requires interaction, it
332 // won't do anything. If it doesn't require interaction, we assume
333 // it was run as a separate pass.
334
Chris Lattnerb9805782005-08-23 22:27:31 +0000335 // If this is the first function compiled, compute the related reg classes.
336 if (RelatedRegClasses.empty())
337 ComputeRelatedRegClasses();
338
Dan Gohman6f0d0242008-02-10 18:45:23 +0000339 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Owen Anderson49c8aa02009-03-13 05:55:11 +0000340 vrm_ = &getAnalysis<VirtRegMap>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000341 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000342
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000344
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000345 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000346
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000347 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattnercbb56252004-11-18 02:42:27 +0000349
Dan Gohman51cd9d62008-06-23 23:51:16 +0000350 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000351 fixed_.clear();
352 active_.clear();
353 inactive_.clear();
354 handled_.clear();
Evan Cheng206d1852009-04-20 08:01:12 +0000355 NextReloadMap.clear();
356 DowngradedRegs.clear();
357 DowngradeMap.clear();
Chris Lattnercbb56252004-11-18 02:42:27 +0000358
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000360}
361
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000362/// initIntervalSets - initialize the interval sets.
363///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000364void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000365{
366 assert(unhandled_.empty() && fixed_.empty() &&
367 active_.empty() && inactive_.empty() &&
368 "interval sets should be empty on initialization");
369
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000370 handled_.reserve(li_->getNumIntervals());
371
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000372 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000373 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000374 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000375 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000376 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000377 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000378 }
379}
380
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000381void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000382{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000383 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000384 DOUT << "********** LINEAR SCAN **********\n";
385 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000386
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000387 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388
389 while (!unhandled_.empty()) {
390 // pick the interval with the earliest start point
391 LiveInterval* cur = unhandled_.top();
392 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000393 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000394 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395
Evan Chengf30a49d2008-04-03 16:40:27 +0000396 if (!cur->empty()) {
397 processActiveIntervals(cur->beginNumber());
398 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399
Evan Chengf30a49d2008-04-03 16:40:27 +0000400 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
401 "Can only allocate virtual registers!");
402 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000403
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000404 // Allocating a virtual register. try to find a free
405 // physical register or spill an interval (possibly this one) in order to
406 // assign it one.
407 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000409 DEBUG(printIntervals("active", active_.begin(), active_.end()));
410 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000411 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000412
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000413 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000414 while (!active_.empty()) {
415 IntervalPtr &IP = active_.back();
416 unsigned reg = IP.first->reg;
417 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000418 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000419 "Can only allocate virtual registers!");
420 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000422 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000423 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000424
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000425 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000426 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000427 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000428 DOUT << "\tinterval " << *i->first << " expired\n");
429 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000430
Evan Cheng81a03822007-11-17 00:40:40 +0000431 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000432 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000433 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000434 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000435 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000436 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000437 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000438 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000439 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000440 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000441 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000442 if (!Reg)
443 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000444 // Ignore splited live intervals.
445 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
446 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000447 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
448 I != E; ++I) {
449 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000450 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000451 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
452 if (LiveInMBBs[i] != EntryMBB)
453 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000454 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000455 }
456 }
457 }
458
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000459 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000460}
461
Chris Lattnercbb56252004-11-18 02:42:27 +0000462/// processActiveIntervals - expire old intervals and move non-overlapping ones
463/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000464void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000465{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000466 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000467
Chris Lattnercbb56252004-11-18 02:42:27 +0000468 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
469 LiveInterval *Interval = active_[i].first;
470 LiveInterval::iterator IntervalPos = active_[i].second;
471 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000472
Chris Lattnercbb56252004-11-18 02:42:27 +0000473 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
474
475 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000476 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000477 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000478 "Can only allocate virtual registers!");
479 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000481
482 // Pop off the end of the list.
483 active_[i] = active_.back();
484 active_.pop_back();
485 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000486
Chris Lattnercbb56252004-11-18 02:42:27 +0000487 } else if (IntervalPos->start > CurPoint) {
488 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000489 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000490 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000491 "Can only allocate virtual registers!");
492 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000493 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000494 // add to inactive.
495 inactive_.push_back(std::make_pair(Interval, IntervalPos));
496
497 // Pop off the end of the list.
498 active_[i] = active_.back();
499 active_.pop_back();
500 --i; --e;
501 } else {
502 // Otherwise, just update the iterator position.
503 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000504 }
505 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000506}
507
Chris Lattnercbb56252004-11-18 02:42:27 +0000508/// processInactiveIntervals - expire old intervals and move overlapping
509/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000510void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000511{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000512 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000513
Chris Lattnercbb56252004-11-18 02:42:27 +0000514 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
515 LiveInterval *Interval = inactive_[i].first;
516 LiveInterval::iterator IntervalPos = inactive_[i].second;
517 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000518
Chris Lattnercbb56252004-11-18 02:42:27 +0000519 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000520
Chris Lattnercbb56252004-11-18 02:42:27 +0000521 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000522 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000523
Chris Lattnercbb56252004-11-18 02:42:27 +0000524 // Pop off the end of the list.
525 inactive_[i] = inactive_.back();
526 inactive_.pop_back();
527 --i; --e;
528 } else if (IntervalPos->start <= CurPoint) {
529 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000530 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000531 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000532 "Can only allocate virtual registers!");
533 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000534 prt_->addRegUse(reg);
535 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000536 active_.push_back(std::make_pair(Interval, IntervalPos));
537
538 // Pop off the end of the list.
539 inactive_[i] = inactive_.back();
540 inactive_.pop_back();
541 --i; --e;
542 } else {
543 // Otherwise, just update the iterator position.
544 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 }
546 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000547}
548
Chris Lattnercbb56252004-11-18 02:42:27 +0000549/// updateSpillWeights - updates the spill weights of the specifed physical
550/// register and its weight.
Evan Cheng5d088fe2009-03-23 22:57:19 +0000551void RALinScan::updateSpillWeights(std::vector<float> &Weights,
552 unsigned reg, float weight,
553 const TargetRegisterClass *RC) {
554 SmallSet<unsigned, 4> Processed;
555 SmallSet<unsigned, 4> SuperAdded;
556 SmallVector<unsigned, 4> Supers;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000557 Weights[reg] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000558 Processed.insert(reg);
559 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000560 Weights[*as] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000561 Processed.insert(*as);
562 if (tri_->isSubRegister(*as, reg) &&
563 SuperAdded.insert(*as) &&
564 RC->contains(*as)) {
565 Supers.push_back(*as);
566 }
567 }
568
569 // If the alias is a super-register, and the super-register is in the
570 // register class we are trying to allocate. Then add the weight to all
571 // sub-registers of the super-register even if they are not aliases.
572 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
573 // bl should get the same spill weight otherwise it will be choosen
574 // as a spill candidate since spilling bh doesn't make ebx available.
575 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
576 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
577 if (!Processed.count(*sr))
578 Weights[*sr] += weight;
579 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000580}
581
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000582static
583RALinScan::IntervalPtrs::iterator
584FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
585 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
586 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000587 if (I->first == LI) return I;
588 return IP.end();
589}
590
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000591static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000592 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000593 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000594 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
595 IP.second, Point);
596 if (I != IP.first->begin()) --I;
597 IP.second = I;
598 }
599}
Chris Lattnercbb56252004-11-18 02:42:27 +0000600
Evan Cheng3f32d652008-06-04 09:18:41 +0000601/// addStackInterval - Create a LiveInterval for stack if the specified live
602/// interval has been spilled.
603static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000604 LiveIntervals *li_, float &Weight,
605 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000606 int SS = vrm_.getStackSlot(cur->reg);
607 if (SS == VirtRegMap::NO_STACK_SLOT)
608 return;
609 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000610 SI.weight += Weight;
611
Evan Cheng3f32d652008-06-04 09:18:41 +0000612 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000613 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000614 VNI = SI.getValNumInfo(0);
615 else
616 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
617
618 LiveInterval &RI = li_->getInterval(cur->reg);
619 // FIXME: This may be overly conservative.
620 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000621}
622
Evan Cheng3e172252008-06-20 21:45:16 +0000623/// getConflictWeight - Return the number of conflicts between cur
624/// live interval and defs and uses of Reg weighted by loop depthes.
625static float getConflictWeight(LiveInterval *cur, unsigned Reg,
626 LiveIntervals *li_,
627 MachineRegisterInfo *mri_,
628 const MachineLoopInfo *loopInfo) {
629 float Conflicts = 0;
630 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
631 E = mri_->reg_end(); I != E; ++I) {
632 MachineInstr *MI = &*I;
633 if (cur->liveAt(li_->getInstructionIndex(MI))) {
634 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
635 Conflicts += powf(10.0f, (float)loopDepth);
636 }
637 }
638 return Conflicts;
639}
640
641/// findIntervalsToSpill - Determine the intervals to spill for the
642/// specified interval. It's passed the physical registers whose spill
643/// weight is the lowest among all the registers whose live intervals
644/// conflict with the interval.
645void RALinScan::findIntervalsToSpill(LiveInterval *cur,
646 std::vector<std::pair<unsigned,float> > &Candidates,
647 unsigned NumCands,
648 SmallVector<LiveInterval*, 8> &SpillIntervals) {
649 // We have figured out the *best* register to spill. But there are other
650 // registers that are pretty good as well (spill weight within 3%). Spill
651 // the one that has fewest defs and uses that conflict with cur.
652 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
653 SmallVector<LiveInterval*, 8> SLIs[3];
654
655 DOUT << "\tConsidering " << NumCands << " candidates: ";
656 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
657 DOUT << tri_->getName(Candidates[i].first) << " ";
658 DOUT << "\n";);
659
660 // Calculate the number of conflicts of each candidate.
661 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
662 unsigned Reg = i->first->reg;
663 unsigned PhysReg = vrm_->getPhys(Reg);
664 if (!cur->overlapsFrom(*i->first, i->second))
665 continue;
666 for (unsigned j = 0; j < NumCands; ++j) {
667 unsigned Candidate = Candidates[j].first;
668 if (tri_->regsOverlap(PhysReg, Candidate)) {
669 if (NumCands > 1)
670 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
671 SLIs[j].push_back(i->first);
672 }
673 }
674 }
675
676 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
677 unsigned Reg = i->first->reg;
678 unsigned PhysReg = vrm_->getPhys(Reg);
679 if (!cur->overlapsFrom(*i->first, i->second-1))
680 continue;
681 for (unsigned j = 0; j < NumCands; ++j) {
682 unsigned Candidate = Candidates[j].first;
683 if (tri_->regsOverlap(PhysReg, Candidate)) {
684 if (NumCands > 1)
685 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
686 SLIs[j].push_back(i->first);
687 }
688 }
689 }
690
691 // Which is the best candidate?
692 unsigned BestCandidate = 0;
693 float MinConflicts = Conflicts[0];
694 for (unsigned i = 1; i != NumCands; ++i) {
695 if (Conflicts[i] < MinConflicts) {
696 BestCandidate = i;
697 MinConflicts = Conflicts[i];
698 }
699 }
700
701 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
702 std::back_inserter(SpillIntervals));
703}
704
705namespace {
706 struct WeightCompare {
707 typedef std::pair<unsigned, float> RegWeightPair;
708 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
709 return LHS.second < RHS.second;
710 }
711 };
712}
713
714static bool weightsAreClose(float w1, float w2) {
715 if (!NewHeuristic)
716 return false;
717
718 float diff = w1 - w2;
719 if (diff <= 0.02f) // Within 0.02f
720 return true;
721 return (diff / w2) <= 0.05f; // Within 5%.
722}
723
Evan Cheng206d1852009-04-20 08:01:12 +0000724LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
725 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
726 if (I == NextReloadMap.end())
727 return 0;
728 return &li_->getInterval(I->second);
729}
730
731void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
732 bool isNew = DowngradedRegs.insert(Reg);
733 isNew = isNew; // Silence compiler warning.
734 assert(isNew && "Multiple reloads holding the same register?");
735 DowngradeMap.insert(std::make_pair(li->reg, Reg));
736 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
737 isNew = DowngradedRegs.insert(*AS);
738 isNew = isNew; // Silence compiler warning.
739 assert(isNew && "Multiple reloads holding the same register?");
740 DowngradeMap.insert(std::make_pair(li->reg, *AS));
741 }
742 ++NumDowngrade;
743}
744
745void RALinScan::UpgradeRegister(unsigned Reg) {
746 if (Reg) {
747 DowngradedRegs.erase(Reg);
748 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
749 DowngradedRegs.erase(*AS);
750 }
751}
752
753namespace {
754 struct LISorter {
755 bool operator()(LiveInterval* A, LiveInterval* B) {
756 return A->beginNumber() < B->beginNumber();
757 }
758 };
759}
760
Chris Lattnercbb56252004-11-18 02:42:27 +0000761/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
762/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000763void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000764{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000765 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000766
Evan Chengf30a49d2008-04-03 16:40:27 +0000767 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000768 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000769 if (cur->empty()) {
770 unsigned physReg = cur->preference;
771 if (!physReg)
772 physReg = *RC->allocation_order_begin(*mf_);
773 DOUT << tri_->getName(physReg) << '\n';
774 // Note the register is not really in use.
775 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000776 return;
777 }
778
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000780
Chris Lattnera6c17502005-08-22 20:20:42 +0000781 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000782 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000783 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000784
Evan Chengd0deec22009-01-20 00:16:18 +0000785 // If start of this live interval is defined by a move instruction and its
786 // source is assigned a physical register that is compatible with the target
787 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000788 // This can happen when the move is from a larger register class to a smaller
789 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000790 if (!cur->preference && cur->hasAtLeastOneValue()) {
791 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000792 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
793 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000794 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
795 if (CopyMI &&
796 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000797 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000798 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000799 Reg = SrcReg;
800 else if (vrm_->isAssignedReg(SrcReg))
801 Reg = vrm_->getPhys(SrcReg);
802 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
803 cur->preference = Reg;
804 }
805 }
806 }
807
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000808 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000809 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000810 for (IntervalPtrs::const_iterator i = inactive_.begin(),
811 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000812 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000813 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000814 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000815 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000816 // If this is not in a related reg class to the register we're allocating,
817 // don't check it.
818 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
819 cur->overlapsFrom(*i->first, i->second-1)) {
820 Reg = vrm_->getPhys(Reg);
821 prt_->addRegUse(Reg);
822 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000823 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000824 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000825
826 // Speculatively check to see if we can get a register right now. If not,
827 // we know we won't be able to by adding more constraints. If so, we can
828 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
829 // is very bad (it contains all callee clobbered registers for any functions
830 // with a call), so we want to avoid doing that if possible.
831 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000832 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000833 if (physReg) {
834 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000835 // conflict with it. Check to see if we conflict with it or any of its
836 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000837 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000838 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000839 RegAliases.insert(*AS);
840
Chris Lattnera411cbc2005-08-22 20:59:30 +0000841 bool ConflictsWithFixed = false;
842 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000843 IntervalPtr &IP = fixed_[i];
844 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000845 // Okay, this reg is on the fixed list. Check to see if we actually
846 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000847 LiveInterval *I = IP.first;
848 if (I->endNumber() > StartPosition) {
849 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
850 IP.second = II;
851 if (II != I->begin() && II->start > StartPosition)
852 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000853 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000854 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000855 break;
856 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000857 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000858 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000859 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000860
861 // Okay, the register picked by our speculative getFreePhysReg call turned
862 // out to be in use. Actually add all of the conflicting fixed registers to
863 // prt so we can do an accurate query.
864 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000865 // For every interval in fixed we overlap with, mark the register as not
866 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000867 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
868 IntervalPtr &IP = fixed_[i];
869 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000870
871 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
872 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
873 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000874 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
875 IP.second = II;
876 if (II != I->begin() && II->start > StartPosition)
877 --II;
878 if (cur->overlapsFrom(*I, II)) {
879 unsigned reg = I->reg;
880 prt_->addRegUse(reg);
881 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
882 }
883 }
884 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000885
Chris Lattnera411cbc2005-08-22 20:59:30 +0000886 // Using the newly updated prt_ object, which includes conflicts in the
887 // future, see if there are any registers available.
888 physReg = getFreePhysReg(cur);
889 }
890 }
891
Chris Lattnera6c17502005-08-22 20:20:42 +0000892 // Restore the physical register tracker, removing information about the
893 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000894 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000895
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000896 // if we find a free register, we are done: assign this virtual to
897 // the free physical register and add this interval to the active
898 // list.
899 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000900 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000901 vrm_->assignVirt2Phys(cur->reg, physReg);
902 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000903 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000904 handled_.push_back(cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000905
906 // "Upgrade" the physical register since it has been allocated.
907 UpgradeRegister(physReg);
908 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
909 // "Downgrade" physReg to try to keep physReg from being allocated until
910 // the next reload from the same SS is allocated.
911 NextReloadLI->preference = physReg;
912 DowngradeRegister(cur, physReg);
913 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000914 return;
915 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000916 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000917
Chris Lattnera6c17502005-08-22 20:20:42 +0000918 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000919 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000920 for (std::vector<std::pair<unsigned, float> >::iterator
921 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Evan Cheng5d088fe2009-03-23 22:57:19 +0000922 updateSpillWeights(SpillWeights, I->first, I->second, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +0000923
924 // for each interval in active, update spill weights.
925 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
926 i != e; ++i) {
927 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000928 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000929 "Can only allocate virtual registers!");
930 reg = vrm_->getPhys(reg);
Evan Cheng5d088fe2009-03-23 22:57:19 +0000931 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +0000932 }
933
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000934 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000935
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000936 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000937 float minWeight = HUGE_VALF;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000938 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
Evan Cheng3e172252008-06-20 21:45:16 +0000939
940 bool Found = false;
941 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000942 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
943 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
944 e = RC->allocation_order_end(*mf_); i != e; ++i) {
945 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000946 float regWeight = SpillWeights[reg];
947 if (minWeight > regWeight)
948 Found = true;
949 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000950 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000951
952 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000953 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000954 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
955 e = RC->allocation_order_end(*mf_); i != e; ++i) {
956 unsigned reg = *i;
957 // No need to worry about if the alias register size < regsize of RC.
958 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000959 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
960 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000961 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000962 }
Evan Cheng3e172252008-06-20 21:45:16 +0000963
964 // Sort all potential spill candidates by weight.
965 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
966 minReg = RegsWeights[0].first;
967 minWeight = RegsWeights[0].second;
968 if (minWeight == HUGE_VALF) {
969 // All registers must have inf weight. Just grab one!
970 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000971 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000972 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000973 // Spill a physical register around defs and uses.
Evan Cheng206d1852009-04-20 08:01:12 +0000974 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
975 DowngradedRegs.clear();
Evan Cheng2824a652009-03-23 18:24:37 +0000976 assignRegOrStackSlotAtInterval(cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000977 } else {
Evan Cheng2824a652009-03-23 18:24:37 +0000978 cerr << "Ran out of registers during register allocation!\n";
979 exit(1);
980 }
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000981 return;
982 }
Evan Cheng3e172252008-06-20 21:45:16 +0000983 }
984
985 // Find up to 3 registers to consider as spill candidates.
986 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
987 while (LastCandidate > 1) {
988 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
989 break;
990 --LastCandidate;
991 }
992
993 DOUT << "\t\tregister(s) with min weight(s): ";
994 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
995 DOUT << tri_->getName(RegsWeights[i].first)
996 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000997
Evan Cheng206d1852009-04-20 08:01:12 +0000998 // If the current has the minimum weight, we need to spill it and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000999 // add any added intervals back to unhandled, and restart
1000 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +00001001 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001002 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +00001003 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +00001004 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001005 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +00001006 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng206d1852009-04-20 08:01:12 +00001007 std::sort(added.begin(), added.end(), LISorter());
Evan Cheng9c3c2212008-06-06 07:54:39 +00001008 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001009 if (added.empty())
1010 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001011
Evan Cheng206d1852009-04-20 08:01:12 +00001012 // Merge added with unhandled. Note that we have already sorted
1013 // intervals returned by addIntervalsForSpills by their starting
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001014 // point.
Evan Chengc4f718a2009-04-20 17:23:48 +00001015 // This also update the NextReloadMap. That is, it adds mapping from a
1016 // register defined by a reload from SS to the next reload from SS in the
1017 // same basic block.
1018 MachineBasicBlock *LastReloadMBB = 0;
1019 LiveInterval *LastReload = 0;
1020 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1021 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1022 LiveInterval *ReloadLi = added[i];
1023 if (ReloadLi->weight == HUGE_VALF &&
1024 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1025 unsigned ReloadIdx = ReloadLi->beginNumber();
1026 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1027 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1028 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1029 // Last reload of same SS is in the same MBB. We want to try to
1030 // allocate both reloads the same register and make sure the reg
1031 // isn't clobbered in between if at all possible.
1032 assert(LastReload->beginNumber() < ReloadIdx);
1033 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1034 }
1035 LastReloadMBB = ReloadMBB;
1036 LastReload = ReloadLi;
1037 LastReloadSS = ReloadSS;
1038 }
1039 unhandled_.push(ReloadLi);
1040 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001041 return;
1042 }
1043
Chris Lattner19828d42004-11-18 03:49:30 +00001044 ++NumBacktracks;
1045
Evan Cheng206d1852009-04-20 08:01:12 +00001046 // Push the current interval back to unhandled since we are going
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001047 // to re-run at least this iteration. Since we didn't modify it it
1048 // should go back right in the front of the list
1049 unhandled_.push(cur);
1050
Dan Gohman6f0d0242008-02-10 18:45:23 +00001051 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001052 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +00001053
Evan Cheng3e172252008-06-20 21:45:16 +00001054 // We spill all intervals aliasing the register with
1055 // minimum weight, rollback to the interval with the earliest
1056 // start point and let the linear scan algorithm run again
1057 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001058
Evan Cheng3e172252008-06-20 21:45:16 +00001059 // Determine which intervals have to be spilled.
1060 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1061
1062 // Set of spilled vregs (used later to rollback properly)
1063 SmallSet<unsigned, 8> spilled;
1064
1065 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001066 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +00001067 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001068
Evan Cheng3e172252008-06-20 21:45:16 +00001069 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +00001070 // want to clear (and its aliases). We only spill those that overlap with the
1071 // current interval as the rest do not affect its allocation. we also keep
1072 // track of the earliest start of all spilled live intervals since this will
1073 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +00001074 std::vector<LiveInterval*> added;
1075 while (!spillIs.empty()) {
1076 LiveInterval *sli = spillIs.back();
1077 spillIs.pop_back();
1078 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1079 earliestStart = std::min(earliestStart, sli->beginNumber());
1080 float SSWeight;
1081 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +00001082 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +00001083 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
1084 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1085 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001086 }
1087
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001088 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001089
1090 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001091 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +00001092 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001093 while (!handled_.empty()) {
1094 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001095 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +00001096 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001097 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001098 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001099 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001100
1101 // When undoing a live interval allocation we must know if it is active or
1102 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001103 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +00001104 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001105 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001106 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001107 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001108 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001109 prt_->delRegUse(vrm_->getPhys(i->reg));
1110 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +00001111 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001112 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001113 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001114 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001115 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001116 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001117 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001118 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001119 "Can only allocate virtual registers!");
1120 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001121 unhandled_.push(i);
1122 }
Evan Cheng9aeaf752007-11-04 08:32:21 +00001123
Evan Cheng206d1852009-04-20 08:01:12 +00001124 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1125 if (ii == DowngradeMap.end())
1126 // It interval has a preference, it must be defined by a copy. Clear the
1127 // preference now since the source interval allocation may have been
1128 // undone as well.
1129 i->preference = 0;
1130 else {
1131 UpgradeRegister(ii->second);
1132 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001133 }
1134
Chris Lattner19828d42004-11-18 03:49:30 +00001135 // Rewind the iterators in the active, inactive, and fixed lists back to the
1136 // point we reverted to.
1137 RevertVectorIteratorsTo(active_, earliestStart);
1138 RevertVectorIteratorsTo(inactive_, earliestStart);
1139 RevertVectorIteratorsTo(fixed_, earliestStart);
1140
Evan Cheng206d1852009-04-20 08:01:12 +00001141 // Scan the rest and undo each interval that expired after t and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001142 // insert it in active (the next iteration of the algorithm will
1143 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001144 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1145 LiveInterval *HI = handled_[i];
1146 if (!HI->expiredAt(earliestStart) &&
1147 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001148 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001149 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001150 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001151 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001152 }
1153 }
1154
Evan Cheng206d1852009-04-20 08:01:12 +00001155 // Merge added with unhandled.
1156 // This also update the NextReloadMap. That is, it adds mapping from a
1157 // register defined by a reload from SS to the next reload from SS in the
1158 // same basic block.
1159 MachineBasicBlock *LastReloadMBB = 0;
1160 LiveInterval *LastReload = 0;
1161 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1162 std::sort(added.begin(), added.end(), LISorter());
1163 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1164 LiveInterval *ReloadLi = added[i];
1165 if (ReloadLi->weight == HUGE_VALF &&
1166 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1167 unsigned ReloadIdx = ReloadLi->beginNumber();
1168 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1169 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1170 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1171 // Last reload of same SS is in the same MBB. We want to try to
1172 // allocate both reloads the same register and make sure the reg
1173 // isn't clobbered in between if at all possible.
1174 assert(LastReload->beginNumber() < ReloadIdx);
1175 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1176 }
1177 LastReloadMBB = ReloadMBB;
1178 LastReload = ReloadLi;
1179 LastReloadSS = ReloadSS;
1180 }
1181 unhandled_.push(ReloadLi);
1182 }
1183}
1184
1185unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1186 unsigned MaxInactiveCount,
1187 SmallVector<unsigned, 256> &inactiveCounts,
1188 bool SkipDGRegs) {
1189 unsigned FreeReg = 0;
1190 unsigned FreeRegInactiveCount = 0;
1191
1192 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1193 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1194 assert(I != E && "No allocatable register in this register class!");
1195
1196 // Scan for the first available register.
1197 for (; I != E; ++I) {
1198 unsigned Reg = *I;
1199 // Ignore "downgraded" registers.
1200 if (SkipDGRegs && DowngradedRegs.count(Reg))
1201 continue;
1202 if (prt_->isRegAvail(Reg)) {
1203 FreeReg = Reg;
1204 if (FreeReg < inactiveCounts.size())
1205 FreeRegInactiveCount = inactiveCounts[FreeReg];
1206 else
1207 FreeRegInactiveCount = 0;
1208 break;
1209 }
1210 }
1211
1212 // If there are no free regs, or if this reg has the max inactive count,
1213 // return this register.
1214 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1215 return FreeReg;
1216
1217 // Continue scanning the registers, looking for the one with the highest
1218 // inactive count. Alkis found that this reduced register pressure very
1219 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1220 // reevaluated now.
1221 for (; I != E; ++I) {
1222 unsigned Reg = *I;
1223 // Ignore "downgraded" registers.
1224 if (SkipDGRegs && DowngradedRegs.count(Reg))
1225 continue;
1226 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1227 FreeRegInactiveCount < inactiveCounts[Reg]) {
1228 FreeReg = Reg;
1229 FreeRegInactiveCount = inactiveCounts[Reg];
1230 if (FreeRegInactiveCount == MaxInactiveCount)
1231 break; // We found the one with the max inactive count.
1232 }
1233 }
1234
1235 return FreeReg;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001236}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001237
Chris Lattnercbb56252004-11-18 02:42:27 +00001238/// getFreePhysReg - return a free physical register for this virtual register
1239/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001240unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001241 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001242 unsigned MaxInactiveCount = 0;
1243
Evan Cheng841ee1a2008-09-18 22:38:47 +00001244 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001245 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1246
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001247 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1248 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001249 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001250 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001251 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001252
1253 // If this is not in a related reg class to the register we're allocating,
1254 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001255 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001256 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1257 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001258 if (inactiveCounts.size() <= reg)
1259 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001260 ++inactiveCounts[reg];
1261 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1262 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001263 }
1264
Evan Cheng20b0abc2007-04-17 20:32:26 +00001265 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001266 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001267 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001268 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001269 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001270 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001271 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001272 return cur->preference;
1273 } else
1274 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001275 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001276 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001277
Evan Cheng206d1852009-04-20 08:01:12 +00001278 if (!DowngradedRegs.empty()) {
1279 unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1280 true);
1281 if (FreeReg)
1282 return FreeReg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001283 }
Evan Cheng206d1852009-04-20 08:01:12 +00001284 return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001285}
1286
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001287FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001288 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001289}