blob: b5f581cc59417b18157cc900805b7cc1d8a2c6a5 [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 "VirtRegMap.h"
Owen Anderson1ed5b712009-03-11 22:31:21 +000016#include "Spiller.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000017#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000025#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000029#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000030#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000031#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000032#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000035#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000036#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000037#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000038#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000039#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000040#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000041#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000042using namespace llvm;
43
Chris Lattnercd3245a2006-12-19 22:41:21 +000044STATISTIC(NumIters , "Number of iterations performed");
45STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000046STATISTIC(NumCoalesce, "Number of copies coalesced");
Evan Cheng206d1852009-04-20 08:01:12 +000047STATISTIC(NumDowngrade, "Number of registers downgraded");
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
Evan Cheng206d1852009-04-20 08:01:12 +000077 // NextReloadMap - For each register in the map, it maps to the another
78 // register which is defined by a reload from the same stack slot and
79 // both reloads are in the same basic block.
80 DenseMap<unsigned, unsigned> NextReloadMap;
81
82 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
83 // un-favored for allocation.
84 SmallSet<unsigned, 8> DowngradedRegs;
85
86 // DowngradeMap - A map from virtual registers to physical registers being
87 // downgraded for the virtual registers.
88 DenseMap<unsigned, unsigned> DowngradeMap;
89
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000090 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000091 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000092 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000093 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000094 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000095 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000097 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000098 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000099
100 /// handled_ - Intervals are added to the handled_ set in the order of their
101 /// start value. This is uses for backtracking.
102 std::vector<LiveInterval*> handled_;
103
104 /// fixed_ - Intervals that correspond to machine registers.
105 ///
106 IntervalPtrs fixed_;
107
108 /// active_ - Intervals that are currently being processed, and which have a
109 /// live range active for the current point.
110 IntervalPtrs active_;
111
112 /// inactive_ - Intervals that are currently being processed, but which have
113 /// a hold at the current point.
114 IntervalPtrs inactive_;
115
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000117 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000118 greater_ptr<LiveInterval> > IntervalHeap;
119 IntervalHeap unhandled_;
Evan Cheng5b16cd22009-05-01 01:03:49 +0000120
121 /// regUse_ - Tracks register usage.
122 SmallVector<unsigned, 32> regUse_;
123 SmallVector<unsigned, 32> regUseBackUp_;
124
125 /// vrm_ - Tracks register assignments.
Owen Anderson49c8aa02009-03-13 05:55:11 +0000126 VirtRegMap* vrm_;
Evan Cheng5b16cd22009-05-01 01:03:49 +0000127
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000129
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130 public:
131 virtual const char* getPassName() const {
132 return "Linear Scan Register Allocator";
133 }
134
135 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000136 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000137 if (StrongPHIElim)
138 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000139 // Make sure PassManager knows which analyses to make available
140 // to coalescing and which analyses coalescing invalidates.
141 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000142 if (PreSplitIntervals)
143 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000144 AU.addRequired<LiveStacks>();
145 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000146 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000147 AU.addPreserved<MachineLoopInfo>();
Owen Anderson49c8aa02009-03-13 05:55:11 +0000148 AU.addRequired<VirtRegMap>();
149 AU.addPreserved<VirtRegMap>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000150 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000151 MachineFunctionPass::getAnalysisUsage(AU);
152 }
153
154 /// runOnMachineFunction - register allocate the whole function
155 bool runOnMachineFunction(MachineFunction&);
156
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000157 private:
158 /// linearScan - the linear scan algorithm
159 void linearScan();
160
Chris Lattnercbb56252004-11-18 02:42:27 +0000161 /// initIntervalSets - initialize the interval sets.
162 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000163 void initIntervalSets();
164
Chris Lattnercbb56252004-11-18 02:42:27 +0000165 /// processActiveIntervals - expire old intervals and move non-overlapping
166 /// ones to the inactive list.
167 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000168
Chris Lattnercbb56252004-11-18 02:42:27 +0000169 /// processInactiveIntervals - expire old intervals and move overlapping
170 /// ones to the active list.
171 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000172
Evan Cheng206d1852009-04-20 08:01:12 +0000173 /// hasNextReloadInterval - Return the next liveinterval that's being
174 /// defined by a reload from the same SS as the specified one.
175 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
176
177 /// DowngradeRegister - Downgrade a register for allocation.
178 void DowngradeRegister(LiveInterval *li, unsigned Reg);
179
180 /// UpgradeRegister - Upgrade a register for allocation.
181 void UpgradeRegister(unsigned Reg);
182
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000183 /// assignRegOrStackSlotAtInterval - assign a register if one
184 /// is available, or spill.
185 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
186
Evan Cheng5d088fe2009-03-23 22:57:19 +0000187 void updateSpillWeights(std::vector<float> &Weights,
188 unsigned reg, float weight,
189 const TargetRegisterClass *RC);
190
Evan Cheng3e172252008-06-20 21:45:16 +0000191 /// findIntervalsToSpill - Determine the intervals to spill for the
192 /// specified interval. It's passed the physical registers whose spill
193 /// weight is the lowest among all the registers whose live intervals
194 /// conflict with the interval.
195 void findIntervalsToSpill(LiveInterval *cur,
196 std::vector<std::pair<unsigned,float> > &Candidates,
197 unsigned NumCands,
198 SmallVector<LiveInterval*, 8> &SpillIntervals);
199
Evan Chengc92da382007-11-03 07:20:12 +0000200 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
201 /// try allocate the definition the same register as the source register
202 /// if the register is not defined during live time of the interval. This
203 /// eliminate a copy. This is used to coalesce copies which were not
204 /// coalesced away before allocation either due to dest and src being in
205 /// different register classes or because the coalescer was overly
206 /// conservative.
207 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
208
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000209 ///
Evan Cheng5b16cd22009-05-01 01:03:49 +0000210 /// Register usage / availability tracking helpers.
211 ///
212
213 void initRegUses() {
214 regUse_.resize(tri_->getNumRegs(), 0);
215 regUseBackUp_.resize(tri_->getNumRegs(), 0);
216 }
217
218 void finalizeRegUses() {
Evan Chengc781a242009-05-03 18:32:42 +0000219#ifndef NDEBUG
220 // Verify all the registers are "freed".
221 bool Error = false;
222 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
223 if (regUse_[i] != 0) {
224 cerr << tri_->getName(i) << " is still in use!\n";
225 Error = true;
226 }
227 }
228 if (Error)
229 abort();
230#endif
Evan Cheng5b16cd22009-05-01 01:03:49 +0000231 regUse_.clear();
232 regUseBackUp_.clear();
233 }
234
235 void addRegUse(unsigned physReg) {
236 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
237 "should be physical register!");
238 ++regUse_[physReg];
239 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
240 ++regUse_[*as];
241 }
242
243 void delRegUse(unsigned physReg) {
244 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
245 "should be physical register!");
246 assert(regUse_[physReg] != 0);
247 --regUse_[physReg];
248 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
249 assert(regUse_[*as] != 0);
250 --regUse_[*as];
251 }
252 }
253
254 bool isRegAvail(unsigned physReg) const {
255 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
256 "should be physical register!");
257 return regUse_[physReg] == 0;
258 }
259
260 void backUpRegUses() {
261 regUseBackUp_ = regUse_;
262 }
263
264 void restoreRegUses() {
265 regUse_ = regUseBackUp_;
266 }
267
268 ///
269 /// Register handling helpers.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000270 ///
271
Chris Lattnercbb56252004-11-18 02:42:27 +0000272 /// getFreePhysReg - return a free physical register for this virtual
273 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274 unsigned getFreePhysReg(LiveInterval* cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000275 unsigned getFreePhysReg(const TargetRegisterClass *RC,
276 unsigned MaxInactiveCount,
277 SmallVector<unsigned, 256> &inactiveCounts,
278 bool SkipDGRegs);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279
280 /// assignVirt2StackSlot - assigns this virtual register to a
281 /// stack slot. returns the stack slot
282 int assignVirt2StackSlot(unsigned virtReg);
283
Chris Lattnerb9805782005-08-23 22:27:31 +0000284 void ComputeRelatedRegClasses();
285
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 template <typename ItTy>
287 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000288 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000290 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000291 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000292 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000294 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000295 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 }
297 }
298 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000299 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000300}
301
Evan Cheng3f32d652008-06-04 09:18:41 +0000302static RegisterPass<RALinScan>
303X("linearscan-regalloc", "Linear Scan Register Allocator");
304
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000305void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000306 // First pass, add all reg classes to the union, and determine at least one
307 // reg class that each register is in.
308 bool HasAliases = false;
Evan Cheng206d1852009-04-20 08:01:12 +0000309 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
310 E = tri_->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000311 RelatedRegClasses.insert(*RCI);
312 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
313 I != E; ++I) {
Evan Cheng206d1852009-04-20 08:01:12 +0000314 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000315
316 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
317 if (PRC) {
318 // Already processed this register. Just make sure we know that
319 // multiple register classes share a register.
320 RelatedRegClasses.unionSets(PRC, *RCI);
321 } else {
322 PRC = *RCI;
323 }
324 }
325 }
326
327 // Second pass, now that we know conservatively what register classes each reg
328 // belongs to, add info about aliases. We don't need to do this for targets
329 // without register aliases.
330 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000331 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000332 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
333 I != E; ++I)
Evan Cheng206d1852009-04-20 08:01:12 +0000334 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000335 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
336}
337
Evan Chengc92da382007-11-03 07:20:12 +0000338/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
339/// try allocate the definition the same register as the source register
340/// if the register is not defined during live time of the interval. This
341/// eliminate a copy. This is used to coalesce copies which were not
342/// coalesced away before allocation either due to dest and src being in
343/// different register classes or because the coalescer was overly
344/// conservative.
345unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000346 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000347 return Reg;
348
Evan Chengd0deec22009-01-20 00:16:18 +0000349 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000350 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
351 return Reg;
352 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000353 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
354 if (!CopyMI ||
355 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000356 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000357 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000358 if (!vrm_->isAssignedReg(SrcReg))
359 return Reg;
360 else
361 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000362 }
Evan Chengc92da382007-11-03 07:20:12 +0000363 if (Reg == SrcReg)
364 return Reg;
365
Evan Cheng841ee1a2008-09-18 22:38:47 +0000366 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000367 if (!RC->contains(SrcReg))
368 return Reg;
369
370 // Try to coalesce.
371 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000372 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000373 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000374 vrm_->clearVirt(cur.reg);
375 vrm_->assignVirt2Phys(cur.reg, SrcReg);
376 ++NumCoalesce;
377 return SrcReg;
378 }
379
380 return Reg;
381}
382
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000383bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000385 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000387 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000388 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000389 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000391 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000392 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000393
David Greene2c17c4d2007-09-06 16:18:45 +0000394 // We don't run the coalescer here because we have no reason to
395 // interact with it. If the coalescer requires interaction, it
396 // won't do anything. If it doesn't require interaction, we assume
397 // it was run as a separate pass.
398
Chris Lattnerb9805782005-08-23 22:27:31 +0000399 // If this is the first function compiled, compute the related reg classes.
400 if (RelatedRegClasses.empty())
401 ComputeRelatedRegClasses();
Evan Cheng5b16cd22009-05-01 01:03:49 +0000402
403 // Also resize register usage trackers.
404 initRegUses();
405
Owen Anderson49c8aa02009-03-13 05:55:11 +0000406 vrm_ = &getAnalysis<VirtRegMap>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000408
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000409 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000410
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000411 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000412
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000413 // Rewrite spill code and update the PhysRegsUsed set.
Evan Cheng5b69eba2009-04-21 22:46:52 +0000414 spiller_->runOnMachineFunction(*mf_, *vrm_, li_);
Chris Lattnercbb56252004-11-18 02:42:27 +0000415
Dan Gohman51cd9d62008-06-23 23:51:16 +0000416 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Evan Cheng5b16cd22009-05-01 01:03:49 +0000417
418 finalizeRegUses();
419
Chris Lattnercbb56252004-11-18 02:42:27 +0000420 fixed_.clear();
421 active_.clear();
422 inactive_.clear();
423 handled_.clear();
Evan Cheng206d1852009-04-20 08:01:12 +0000424 NextReloadMap.clear();
425 DowngradedRegs.clear();
426 DowngradeMap.clear();
Chris Lattnercbb56252004-11-18 02:42:27 +0000427
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000429}
430
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000431/// initIntervalSets - initialize the interval sets.
432///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000433void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000434{
435 assert(unhandled_.empty() && fixed_.empty() &&
436 active_.empty() && inactive_.empty() &&
437 "interval sets should be empty on initialization");
438
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000439 handled_.reserve(li_->getNumIntervals());
440
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000441 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000442 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000443 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000444 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000445 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000446 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000447 }
448}
449
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000450void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000451{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000452 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000453 DOUT << "********** LINEAR SCAN **********\n";
454 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000455
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000456 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457
458 while (!unhandled_.empty()) {
459 // pick the interval with the earliest start point
460 LiveInterval* cur = unhandled_.top();
461 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000462 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000463 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464
Evan Chengf30a49d2008-04-03 16:40:27 +0000465 if (!cur->empty()) {
466 processActiveIntervals(cur->beginNumber());
467 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468
Evan Chengf30a49d2008-04-03 16:40:27 +0000469 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
470 "Can only allocate virtual registers!");
471 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000472
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000473 // Allocating a virtual register. try to find a free
474 // physical register or spill an interval (possibly this one) in order to
475 // assign it one.
476 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000477
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000478 DEBUG(printIntervals("active", active_.begin(), active_.end()));
479 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000481
Evan Cheng5b16cd22009-05-01 01:03:49 +0000482 // Expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000483 while (!active_.empty()) {
484 IntervalPtr &IP = active_.back();
485 unsigned reg = IP.first->reg;
486 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000487 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000488 "Can only allocate virtual registers!");
489 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000490 delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000491 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000492 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000493
Evan Cheng5b16cd22009-05-01 01:03:49 +0000494 // Expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000495 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000496 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000497 DOUT << "\tinterval " << *i->first << " expired\n");
498 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000499
Evan Cheng81a03822007-11-17 00:40:40 +0000500 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000501 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000502 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000503 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000504 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000505 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000506 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000507 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000508 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000509 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000510 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000511 if (!Reg)
512 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000513 // Ignore splited live intervals.
514 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
515 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000516 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
517 I != E; ++I) {
518 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000519 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000520 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
521 if (LiveInMBBs[i] != EntryMBB)
522 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000523 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000524 }
525 }
526 }
527
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000528 DOUT << *vrm_;
Evan Chengc781a242009-05-03 18:32:42 +0000529
530 // Look for physical registers that end up not being allocated even though
531 // register allocator had to spill other registers in its register class.
532 if (ls_->getNumIntervals() == 0)
533 return;
534 if (!vrm_->FindUnusedRegisters(tri_, li_))
535 return;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000536}
537
Chris Lattnercbb56252004-11-18 02:42:27 +0000538/// processActiveIntervals - expire old intervals and move non-overlapping ones
539/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000540void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000541{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000542 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000543
Chris Lattnercbb56252004-11-18 02:42:27 +0000544 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
545 LiveInterval *Interval = active_[i].first;
546 LiveInterval::iterator IntervalPos = active_[i].second;
547 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000548
Chris Lattnercbb56252004-11-18 02:42:27 +0000549 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
550
551 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000552 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000553 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000554 "Can only allocate virtual registers!");
555 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000556 delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000557
558 // Pop off the end of the list.
559 active_[i] = active_.back();
560 active_.pop_back();
561 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000562
Chris Lattnercbb56252004-11-18 02:42:27 +0000563 } else if (IntervalPos->start > CurPoint) {
564 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000565 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000566 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000567 "Can only allocate virtual registers!");
568 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000569 delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000570 // add to inactive.
571 inactive_.push_back(std::make_pair(Interval, IntervalPos));
572
573 // Pop off the end of the list.
574 active_[i] = active_.back();
575 active_.pop_back();
576 --i; --e;
577 } else {
578 // Otherwise, just update the iterator position.
579 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000580 }
581 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000582}
583
Chris Lattnercbb56252004-11-18 02:42:27 +0000584/// processInactiveIntervals - expire old intervals and move overlapping
585/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000586void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000587{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000588 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000589
Chris Lattnercbb56252004-11-18 02:42:27 +0000590 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
591 LiveInterval *Interval = inactive_[i].first;
592 LiveInterval::iterator IntervalPos = inactive_[i].second;
593 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000594
Chris Lattnercbb56252004-11-18 02:42:27 +0000595 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000596
Chris Lattnercbb56252004-11-18 02:42:27 +0000597 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000598 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000599
Chris Lattnercbb56252004-11-18 02:42:27 +0000600 // Pop off the end of the list.
601 inactive_[i] = inactive_.back();
602 inactive_.pop_back();
603 --i; --e;
604 } else if (IntervalPos->start <= CurPoint) {
605 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000606 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000607 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000608 "Can only allocate virtual registers!");
609 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000610 addRegUse(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000611 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000612 active_.push_back(std::make_pair(Interval, IntervalPos));
613
614 // Pop off the end of the list.
615 inactive_[i] = inactive_.back();
616 inactive_.pop_back();
617 --i; --e;
618 } else {
619 // Otherwise, just update the iterator position.
620 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000621 }
622 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000623}
624
Chris Lattnercbb56252004-11-18 02:42:27 +0000625/// updateSpillWeights - updates the spill weights of the specifed physical
626/// register and its weight.
Evan Cheng5d088fe2009-03-23 22:57:19 +0000627void RALinScan::updateSpillWeights(std::vector<float> &Weights,
628 unsigned reg, float weight,
629 const TargetRegisterClass *RC) {
630 SmallSet<unsigned, 4> Processed;
631 SmallSet<unsigned, 4> SuperAdded;
632 SmallVector<unsigned, 4> Supers;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000633 Weights[reg] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000634 Processed.insert(reg);
635 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000636 Weights[*as] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000637 Processed.insert(*as);
638 if (tri_->isSubRegister(*as, reg) &&
639 SuperAdded.insert(*as) &&
640 RC->contains(*as)) {
641 Supers.push_back(*as);
642 }
643 }
644
645 // If the alias is a super-register, and the super-register is in the
646 // register class we are trying to allocate. Then add the weight to all
647 // sub-registers of the super-register even if they are not aliases.
648 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
649 // bl should get the same spill weight otherwise it will be choosen
650 // as a spill candidate since spilling bh doesn't make ebx available.
651 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
Evan Chengc781a242009-05-03 18:32:42 +0000652 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
653 if (!Processed.count(*sr))
654 Weights[*sr] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000655 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000656}
657
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000658static
659RALinScan::IntervalPtrs::iterator
660FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
661 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
662 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000663 if (I->first == LI) return I;
664 return IP.end();
665}
666
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000667static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000668 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000669 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000670 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
671 IP.second, Point);
672 if (I != IP.first->begin()) --I;
673 IP.second = I;
674 }
675}
Chris Lattnercbb56252004-11-18 02:42:27 +0000676
Evan Cheng3f32d652008-06-04 09:18:41 +0000677/// addStackInterval - Create a LiveInterval for stack if the specified live
678/// interval has been spilled.
679static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengc781a242009-05-03 18:32:42 +0000680 LiveIntervals *li_,
681 MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000682 int SS = vrm_.getStackSlot(cur->reg);
683 if (SS == VirtRegMap::NO_STACK_SLOT)
684 return;
Evan Chengc781a242009-05-03 18:32:42 +0000685
686 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
687 LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000688
Evan Cheng3f32d652008-06-04 09:18:41 +0000689 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000690 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000691 VNI = SI.getValNumInfo(0);
692 else
693 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
694
695 LiveInterval &RI = li_->getInterval(cur->reg);
696 // FIXME: This may be overly conservative.
697 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000698}
699
Evan Cheng3e172252008-06-20 21:45:16 +0000700/// getConflictWeight - Return the number of conflicts between cur
701/// live interval and defs and uses of Reg weighted by loop depthes.
Evan Chengc781a242009-05-03 18:32:42 +0000702static
703float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
704 MachineRegisterInfo *mri_,
705 const MachineLoopInfo *loopInfo) {
Evan Cheng3e172252008-06-20 21:45:16 +0000706 float Conflicts = 0;
707 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
708 E = mri_->reg_end(); I != E; ++I) {
709 MachineInstr *MI = &*I;
710 if (cur->liveAt(li_->getInstructionIndex(MI))) {
711 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
712 Conflicts += powf(10.0f, (float)loopDepth);
713 }
714 }
715 return Conflicts;
716}
717
718/// findIntervalsToSpill - Determine the intervals to spill for the
719/// specified interval. It's passed the physical registers whose spill
720/// weight is the lowest among all the registers whose live intervals
721/// conflict with the interval.
722void RALinScan::findIntervalsToSpill(LiveInterval *cur,
723 std::vector<std::pair<unsigned,float> > &Candidates,
724 unsigned NumCands,
725 SmallVector<LiveInterval*, 8> &SpillIntervals) {
726 // We have figured out the *best* register to spill. But there are other
727 // registers that are pretty good as well (spill weight within 3%). Spill
728 // the one that has fewest defs and uses that conflict with cur.
729 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
730 SmallVector<LiveInterval*, 8> SLIs[3];
731
732 DOUT << "\tConsidering " << NumCands << " candidates: ";
733 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
734 DOUT << tri_->getName(Candidates[i].first) << " ";
735 DOUT << "\n";);
736
737 // Calculate the number of conflicts of each candidate.
738 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
739 unsigned Reg = i->first->reg;
740 unsigned PhysReg = vrm_->getPhys(Reg);
741 if (!cur->overlapsFrom(*i->first, i->second))
742 continue;
743 for (unsigned j = 0; j < NumCands; ++j) {
744 unsigned Candidate = Candidates[j].first;
745 if (tri_->regsOverlap(PhysReg, Candidate)) {
746 if (NumCands > 1)
747 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
748 SLIs[j].push_back(i->first);
749 }
750 }
751 }
752
753 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
754 unsigned Reg = i->first->reg;
755 unsigned PhysReg = vrm_->getPhys(Reg);
756 if (!cur->overlapsFrom(*i->first, i->second-1))
757 continue;
758 for (unsigned j = 0; j < NumCands; ++j) {
759 unsigned Candidate = Candidates[j].first;
760 if (tri_->regsOverlap(PhysReg, Candidate)) {
761 if (NumCands > 1)
762 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
763 SLIs[j].push_back(i->first);
764 }
765 }
766 }
767
768 // Which is the best candidate?
769 unsigned BestCandidate = 0;
770 float MinConflicts = Conflicts[0];
771 for (unsigned i = 1; i != NumCands; ++i) {
772 if (Conflicts[i] < MinConflicts) {
773 BestCandidate = i;
774 MinConflicts = Conflicts[i];
775 }
776 }
777
778 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
779 std::back_inserter(SpillIntervals));
780}
781
782namespace {
783 struct WeightCompare {
784 typedef std::pair<unsigned, float> RegWeightPair;
785 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
786 return LHS.second < RHS.second;
787 }
788 };
789}
790
791static bool weightsAreClose(float w1, float w2) {
792 if (!NewHeuristic)
793 return false;
794
795 float diff = w1 - w2;
796 if (diff <= 0.02f) // Within 0.02f
797 return true;
798 return (diff / w2) <= 0.05f; // Within 5%.
799}
800
Evan Cheng206d1852009-04-20 08:01:12 +0000801LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
802 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
803 if (I == NextReloadMap.end())
804 return 0;
805 return &li_->getInterval(I->second);
806}
807
808void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
809 bool isNew = DowngradedRegs.insert(Reg);
810 isNew = isNew; // Silence compiler warning.
811 assert(isNew && "Multiple reloads holding the same register?");
812 DowngradeMap.insert(std::make_pair(li->reg, Reg));
813 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
814 isNew = DowngradedRegs.insert(*AS);
815 isNew = isNew; // Silence compiler warning.
816 assert(isNew && "Multiple reloads holding the same register?");
817 DowngradeMap.insert(std::make_pair(li->reg, *AS));
818 }
819 ++NumDowngrade;
820}
821
822void RALinScan::UpgradeRegister(unsigned Reg) {
823 if (Reg) {
824 DowngradedRegs.erase(Reg);
825 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
826 DowngradedRegs.erase(*AS);
827 }
828}
829
830namespace {
831 struct LISorter {
832 bool operator()(LiveInterval* A, LiveInterval* B) {
833 return A->beginNumber() < B->beginNumber();
834 }
835 };
836}
837
Chris Lattnercbb56252004-11-18 02:42:27 +0000838/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
839/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000840void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000841{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000842 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000843
Evan Chengf30a49d2008-04-03 16:40:27 +0000844 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000845 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000846 if (cur->empty()) {
847 unsigned physReg = cur->preference;
848 if (!physReg)
849 physReg = *RC->allocation_order_begin(*mf_);
850 DOUT << tri_->getName(physReg) << '\n';
851 // Note the register is not really in use.
852 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000853 return;
854 }
855
Evan Cheng5b16cd22009-05-01 01:03:49 +0000856 backUpRegUses();
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000857
Chris Lattnera6c17502005-08-22 20:20:42 +0000858 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000859 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000860 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000861
Evan Chengd0deec22009-01-20 00:16:18 +0000862 // If start of this live interval is defined by a move instruction and its
863 // source is assigned a physical register that is compatible with the target
864 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000865 // This can happen when the move is from a larger register class to a smaller
866 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000867 if (!cur->preference && cur->hasAtLeastOneValue()) {
868 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000869 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
870 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000871 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
872 if (CopyMI &&
873 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000874 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000875 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000876 Reg = SrcReg;
877 else if (vrm_->isAssignedReg(SrcReg))
878 Reg = vrm_->getPhys(SrcReg);
Evan Cheng1c2f6da2009-04-29 00:42:27 +0000879 if (Reg) {
880 if (SrcSubReg)
881 Reg = tri_->getSubReg(Reg, SrcSubReg);
882 if (DstSubReg)
883 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
884 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
885 cur->preference = Reg;
886 }
Evan Chengc92da382007-11-03 07:20:12 +0000887 }
888 }
889 }
890
Evan Cheng5b16cd22009-05-01 01:03:49 +0000891 // For every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000892 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000893 for (IntervalPtrs::const_iterator i = inactive_.begin(),
894 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000895 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000896 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000897 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000898 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000899 // If this is not in a related reg class to the register we're allocating,
900 // don't check it.
901 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
902 cur->overlapsFrom(*i->first, i->second-1)) {
903 Reg = vrm_->getPhys(Reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000904 addRegUse(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000905 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000906 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000907 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000908
909 // Speculatively check to see if we can get a register right now. If not,
910 // we know we won't be able to by adding more constraints. If so, we can
911 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
912 // is very bad (it contains all callee clobbered registers for any functions
913 // with a call), so we want to avoid doing that if possible.
914 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000915 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000916 if (physReg) {
917 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000918 // conflict with it. Check to see if we conflict with it or any of its
919 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000920 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000921 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000922 RegAliases.insert(*AS);
923
Chris Lattnera411cbc2005-08-22 20:59:30 +0000924 bool ConflictsWithFixed = false;
925 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000926 IntervalPtr &IP = fixed_[i];
927 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000928 // Okay, this reg is on the fixed list. Check to see if we actually
929 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000930 LiveInterval *I = IP.first;
931 if (I->endNumber() > StartPosition) {
932 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
933 IP.second = II;
934 if (II != I->begin() && II->start > StartPosition)
935 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000936 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000937 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000938 break;
939 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000940 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000941 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000942 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000943
944 // Okay, the register picked by our speculative getFreePhysReg call turned
945 // out to be in use. Actually add all of the conflicting fixed registers to
Evan Cheng5b16cd22009-05-01 01:03:49 +0000946 // regUse_ so we can do an accurate query.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000947 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000948 // For every interval in fixed we overlap with, mark the register as not
949 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000950 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
951 IntervalPtr &IP = fixed_[i];
952 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000953
954 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
955 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
956 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000957 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
958 IP.second = II;
959 if (II != I->begin() && II->start > StartPosition)
960 --II;
961 if (cur->overlapsFrom(*I, II)) {
962 unsigned reg = I->reg;
Evan Cheng5b16cd22009-05-01 01:03:49 +0000963 addRegUse(reg);
Chris Lattnera411cbc2005-08-22 20:59:30 +0000964 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
965 }
966 }
967 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000968
Evan Cheng5b16cd22009-05-01 01:03:49 +0000969 // Using the newly updated regUse_ object, which includes conflicts in the
Chris Lattnera411cbc2005-08-22 20:59:30 +0000970 // future, see if there are any registers available.
971 physReg = getFreePhysReg(cur);
972 }
973 }
974
Chris Lattnera6c17502005-08-22 20:20:42 +0000975 // Restore the physical register tracker, removing information about the
976 // future.
Evan Cheng5b16cd22009-05-01 01:03:49 +0000977 restoreRegUses();
Chris Lattnera6c17502005-08-22 20:20:42 +0000978
Evan Cheng5b16cd22009-05-01 01:03:49 +0000979 // If we find a free register, we are done: assign this virtual to
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000980 // the free physical register and add this interval to the active
981 // list.
982 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000983 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000984 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000985 addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000986 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000987 handled_.push_back(cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000988
989 // "Upgrade" the physical register since it has been allocated.
990 UpgradeRegister(physReg);
991 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
992 // "Downgrade" physReg to try to keep physReg from being allocated until
993 // the next reload from the same SS is allocated.
994 NextReloadLI->preference = physReg;
995 DowngradeRegister(cur, physReg);
996 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000997 return;
998 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000999 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001000
Chris Lattnera6c17502005-08-22 20:20:42 +00001001 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +00001002 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +00001003 for (std::vector<std::pair<unsigned, float> >::iterator
1004 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Evan Cheng5d088fe2009-03-23 22:57:19 +00001005 updateSpillWeights(SpillWeights, I->first, I->second, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +00001006
1007 // for each interval in active, update spill weights.
1008 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1009 i != e; ++i) {
1010 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001011 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +00001012 "Can only allocate virtual registers!");
1013 reg = vrm_->getPhys(reg);
Evan Cheng5d088fe2009-03-23 22:57:19 +00001014 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +00001015 }
1016
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001017 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001018
Chris Lattnerc8e2c552006-03-25 23:00:56 +00001019 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +00001020 float minWeight = HUGE_VALF;
Evan Cheng5d088fe2009-03-23 22:57:19 +00001021 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
Evan Cheng3e172252008-06-20 21:45:16 +00001022
1023 bool Found = false;
1024 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001025 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1026 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1027 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1028 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +00001029 float regWeight = SpillWeights[reg];
1030 if (minWeight > regWeight)
1031 Found = true;
1032 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +00001033 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +00001034
1035 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +00001036 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +00001037 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1038 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1039 unsigned reg = *i;
1040 // No need to worry about if the alias register size < regsize of RC.
1041 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +00001042 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1043 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +00001044 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +00001045 }
Evan Cheng3e172252008-06-20 21:45:16 +00001046
1047 // Sort all potential spill candidates by weight.
1048 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1049 minReg = RegsWeights[0].first;
1050 minWeight = RegsWeights[0].second;
1051 if (minWeight == HUGE_VALF) {
1052 // All registers must have inf weight. Just grab one!
1053 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +00001054 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +00001055 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +00001056 // Spill a physical register around defs and uses.
Evan Cheng206d1852009-04-20 08:01:12 +00001057 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
Evan Cheng96f3fd92009-04-29 07:16:34 +00001058 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1059 // in fixed_. Reset them.
1060 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1061 IntervalPtr &IP = fixed_[i];
1062 LiveInterval *I = IP.first;
1063 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1064 IP.second = I->advanceTo(I->begin(), StartPosition);
1065 }
1066
Evan Cheng206d1852009-04-20 08:01:12 +00001067 DowngradedRegs.clear();
Evan Cheng2824a652009-03-23 18:24:37 +00001068 assignRegOrStackSlotAtInterval(cur);
Evan Cheng206d1852009-04-20 08:01:12 +00001069 } else {
Evan Cheng2824a652009-03-23 18:24:37 +00001070 cerr << "Ran out of registers during register allocation!\n";
1071 exit(1);
1072 }
Evan Cheng5e8d9de2008-09-20 01:28:05 +00001073 return;
1074 }
Evan Cheng3e172252008-06-20 21:45:16 +00001075 }
1076
1077 // Find up to 3 registers to consider as spill candidates.
1078 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1079 while (LastCandidate > 1) {
1080 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1081 break;
1082 --LastCandidate;
1083 }
1084
1085 DOUT << "\t\tregister(s) with min weight(s): ";
1086 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
1087 DOUT << tri_->getName(RegsWeights[i].first)
1088 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +00001089
Evan Cheng206d1852009-04-20 08:01:12 +00001090 // If the current has the minimum weight, we need to spill it and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001091 // add any added intervals back to unhandled, and restart
1092 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +00001093 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001094 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengdc377862008-09-30 15:44:16 +00001095 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001096 std::vector<LiveInterval*> added =
Evan Chengc781a242009-05-03 18:32:42 +00001097 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_);
Evan Cheng206d1852009-04-20 08:01:12 +00001098 std::sort(added.begin(), added.end(), LISorter());
Evan Chengc781a242009-05-03 18:32:42 +00001099 addStackInterval(cur, ls_, li_, mri_, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001100 if (added.empty())
1101 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001102
Evan Cheng206d1852009-04-20 08:01:12 +00001103 // Merge added with unhandled. Note that we have already sorted
1104 // intervals returned by addIntervalsForSpills by their starting
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001105 // point.
Evan Chengc4f718a2009-04-20 17:23:48 +00001106 // This also update the NextReloadMap. That is, it adds mapping from a
1107 // register defined by a reload from SS to the next reload from SS in the
1108 // same basic block.
1109 MachineBasicBlock *LastReloadMBB = 0;
1110 LiveInterval *LastReload = 0;
1111 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1112 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1113 LiveInterval *ReloadLi = added[i];
1114 if (ReloadLi->weight == HUGE_VALF &&
1115 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1116 unsigned ReloadIdx = ReloadLi->beginNumber();
1117 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1118 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1119 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1120 // Last reload of same SS is in the same MBB. We want to try to
1121 // allocate both reloads the same register and make sure the reg
1122 // isn't clobbered in between if at all possible.
1123 assert(LastReload->beginNumber() < ReloadIdx);
1124 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1125 }
1126 LastReloadMBB = ReloadMBB;
1127 LastReload = ReloadLi;
1128 LastReloadSS = ReloadSS;
1129 }
1130 unhandled_.push(ReloadLi);
1131 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001132 return;
1133 }
1134
Chris Lattner19828d42004-11-18 03:49:30 +00001135 ++NumBacktracks;
1136
Evan Cheng206d1852009-04-20 08:01:12 +00001137 // Push the current interval back to unhandled since we are going
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001138 // to re-run at least this iteration. Since we didn't modify it it
1139 // should go back right in the front of the list
1140 unhandled_.push(cur);
1141
Dan Gohman6f0d0242008-02-10 18:45:23 +00001142 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001143 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +00001144
Evan Cheng3e172252008-06-20 21:45:16 +00001145 // We spill all intervals aliasing the register with
1146 // minimum weight, rollback to the interval with the earliest
1147 // start point and let the linear scan algorithm run again
1148 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001149
Evan Cheng3e172252008-06-20 21:45:16 +00001150 // Determine which intervals have to be spilled.
1151 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1152
1153 // Set of spilled vregs (used later to rollback properly)
1154 SmallSet<unsigned, 8> spilled;
1155
1156 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001157 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +00001158 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001159
Evan Cheng3e172252008-06-20 21:45:16 +00001160 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +00001161 // want to clear (and its aliases). We only spill those that overlap with the
1162 // current interval as the rest do not affect its allocation. we also keep
1163 // track of the earliest start of all spilled live intervals since this will
1164 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +00001165 std::vector<LiveInterval*> added;
1166 while (!spillIs.empty()) {
1167 LiveInterval *sli = spillIs.back();
1168 spillIs.pop_back();
1169 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1170 earliestStart = std::min(earliestStart, sli->beginNumber());
Evan Cheng3e172252008-06-20 21:45:16 +00001171 std::vector<LiveInterval*> newIs =
Evan Chengc781a242009-05-03 18:32:42 +00001172 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_);
1173 addStackInterval(sli, ls_, li_, mri_, *vrm_);
Evan Cheng3e172252008-06-20 21:45:16 +00001174 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1175 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001176 }
1177
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001178 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001179
1180 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001181 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +00001182 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001183 while (!handled_.empty()) {
1184 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001185 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +00001186 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001187 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001188 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001189 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001190
1191 // When undoing a live interval allocation we must know if it is active or
Evan Cheng5b16cd22009-05-01 01:03:49 +00001192 // inactive to properly update regUse_ and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001193 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +00001194 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001195 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001196 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001197 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001198 unhandled_.push(i);
Evan Cheng5b16cd22009-05-01 01:03:49 +00001199 delRegUse(vrm_->getPhys(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001200 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +00001201 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001202 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001203 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001204 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001205 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001206 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001207 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001208 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001209 "Can only allocate virtual registers!");
1210 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001211 unhandled_.push(i);
1212 }
Evan Cheng9aeaf752007-11-04 08:32:21 +00001213
Evan Cheng206d1852009-04-20 08:01:12 +00001214 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1215 if (ii == DowngradeMap.end())
1216 // It interval has a preference, it must be defined by a copy. Clear the
1217 // preference now since the source interval allocation may have been
1218 // undone as well.
1219 i->preference = 0;
1220 else {
1221 UpgradeRegister(ii->second);
1222 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001223 }
1224
Chris Lattner19828d42004-11-18 03:49:30 +00001225 // Rewind the iterators in the active, inactive, and fixed lists back to the
1226 // point we reverted to.
1227 RevertVectorIteratorsTo(active_, earliestStart);
1228 RevertVectorIteratorsTo(inactive_, earliestStart);
1229 RevertVectorIteratorsTo(fixed_, earliestStart);
1230
Evan Cheng206d1852009-04-20 08:01:12 +00001231 // Scan the rest and undo each interval that expired after t and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001232 // insert it in active (the next iteration of the algorithm will
1233 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001234 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1235 LiveInterval *HI = handled_[i];
1236 if (!HI->expiredAt(earliestStart) &&
1237 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001238 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001239 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001240 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Evan Cheng5b16cd22009-05-01 01:03:49 +00001241 addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001242 }
1243 }
1244
Evan Cheng206d1852009-04-20 08:01:12 +00001245 // Merge added with unhandled.
1246 // This also update the NextReloadMap. That is, it adds mapping from a
1247 // register defined by a reload from SS to the next reload from SS in the
1248 // same basic block.
1249 MachineBasicBlock *LastReloadMBB = 0;
1250 LiveInterval *LastReload = 0;
1251 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1252 std::sort(added.begin(), added.end(), LISorter());
1253 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1254 LiveInterval *ReloadLi = added[i];
1255 if (ReloadLi->weight == HUGE_VALF &&
1256 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1257 unsigned ReloadIdx = ReloadLi->beginNumber();
1258 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1259 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1260 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1261 // Last reload of same SS is in the same MBB. We want to try to
1262 // allocate both reloads the same register and make sure the reg
1263 // isn't clobbered in between if at all possible.
1264 assert(LastReload->beginNumber() < ReloadIdx);
1265 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1266 }
1267 LastReloadMBB = ReloadMBB;
1268 LastReload = ReloadLi;
1269 LastReloadSS = ReloadSS;
1270 }
1271 unhandled_.push(ReloadLi);
1272 }
1273}
1274
1275unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1276 unsigned MaxInactiveCount,
1277 SmallVector<unsigned, 256> &inactiveCounts,
1278 bool SkipDGRegs) {
1279 unsigned FreeReg = 0;
1280 unsigned FreeRegInactiveCount = 0;
1281
1282 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1283 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1284 assert(I != E && "No allocatable register in this register class!");
1285
1286 // Scan for the first available register.
1287 for (; I != E; ++I) {
1288 unsigned Reg = *I;
1289 // Ignore "downgraded" registers.
1290 if (SkipDGRegs && DowngradedRegs.count(Reg))
1291 continue;
Evan Cheng5b16cd22009-05-01 01:03:49 +00001292 if (isRegAvail(Reg)) {
Evan Cheng206d1852009-04-20 08:01:12 +00001293 FreeReg = Reg;
1294 if (FreeReg < inactiveCounts.size())
1295 FreeRegInactiveCount = inactiveCounts[FreeReg];
1296 else
1297 FreeRegInactiveCount = 0;
1298 break;
1299 }
1300 }
1301
1302 // If there are no free regs, or if this reg has the max inactive count,
1303 // return this register.
1304 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1305 return FreeReg;
1306
1307 // Continue scanning the registers, looking for the one with the highest
1308 // inactive count. Alkis found that this reduced register pressure very
1309 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1310 // reevaluated now.
1311 for (; I != E; ++I) {
1312 unsigned Reg = *I;
1313 // Ignore "downgraded" registers.
1314 if (SkipDGRegs && DowngradedRegs.count(Reg))
1315 continue;
Evan Cheng5b16cd22009-05-01 01:03:49 +00001316 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Evan Cheng206d1852009-04-20 08:01:12 +00001317 FreeRegInactiveCount < inactiveCounts[Reg]) {
1318 FreeReg = Reg;
1319 FreeRegInactiveCount = inactiveCounts[Reg];
1320 if (FreeRegInactiveCount == MaxInactiveCount)
1321 break; // We found the one with the max inactive count.
1322 }
1323 }
1324
1325 return FreeReg;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001326}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001327
Chris Lattnercbb56252004-11-18 02:42:27 +00001328/// getFreePhysReg - return a free physical register for this virtual register
1329/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001330unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001331 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001332 unsigned MaxInactiveCount = 0;
1333
Evan Cheng841ee1a2008-09-18 22:38:47 +00001334 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001335 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1336
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001337 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1338 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001339 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001340 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001341 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001342
1343 // If this is not in a related reg class to the register we're allocating,
1344 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001345 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001346 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1347 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001348 if (inactiveCounts.size() <= reg)
1349 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001350 ++inactiveCounts[reg];
1351 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1352 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001353 }
1354
Evan Cheng20b0abc2007-04-17 20:32:26 +00001355 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001356 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001357 if (cur->preference) {
Evan Cheng1c2f6da2009-04-29 00:42:27 +00001358 DOUT << "(preferred: " << tri_->getName(cur->preference) << ") ";
Evan Cheng5b16cd22009-05-01 01:03:49 +00001359 if (isRegAvail(cur->preference) &&
Evan Cheng1c2f6da2009-04-29 00:42:27 +00001360 RC->contains(cur->preference))
Evan Cheng20b0abc2007-04-17 20:32:26 +00001361 return cur->preference;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001362 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001363
Evan Cheng206d1852009-04-20 08:01:12 +00001364 if (!DowngradedRegs.empty()) {
1365 unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1366 true);
1367 if (FreeReg)
1368 return FreeReg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001369 }
Evan Cheng206d1852009-04-20 08:01:12 +00001370 return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001371}
1372
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001373FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001374 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001375}