blob: 919b94c5577b6ed1a5a0e2d52cc7f4844b947f1c [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "regalloc"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
17#include "llvm/Function.h"
Evan Cheng14f8a502008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng26d17df2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene1d80f1b2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Target/TargetMachine.h"
Owen Andersonbac9ae22008-10-07 20:22:28 +000029#include "llvm/Target/TargetOptions.h"
Evan Chengc4c75f52007-11-03 07:20:12 +000030#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/ADT/EquivalenceClasses.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Compiler.h"
36#include <algorithm>
37#include <set>
38#include <queue>
39#include <memory>
40#include <cmath>
41using namespace llvm;
42
43STATISTIC(NumIters , "Number of iterations performed");
44STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc4c75f52007-11-03 07:20:12 +000045STATISTIC(NumCoalesce, "Number of copies coalesced");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
Evan Chengc5952452008-06-20 21:45:16 +000047static cl::opt<bool>
48NewHeuristic("new-spilling-heuristic",
49 cl::desc("Use new spilling heuristic"),
50 cl::init(false), cl::Hidden);
51
Evan Cheng99dcc172008-10-23 20:43:13 +000052static cl::opt<bool>
53PreSplitIntervals("pre-alloc-split",
54 cl::desc("Pre-register allocation live interval splitting"),
55 cl::init(false), cl::Hidden);
56
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057static RegisterRegAlloc
Dan Gohman669b9bf2008-10-14 20:25:08 +000058linearscanRegAlloc("linearscan", "linear scan register allocator",
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 createLinearScanRegisterAllocator);
60
61namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
63 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +000064 RALinScan() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065
66 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersonba926a32008-08-15 18:49:41 +000067 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 private:
69 /// RelatedRegClasses - This structure is built the first time a function is
70 /// compiled, and keeps track of which register classes have registers that
71 /// belong to multiple classes or have aliases that are in other classes.
72 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson4a472712008-08-13 23:36:23 +000073 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074
75 MachineFunction* mf_;
Evan Chengc5952452008-06-20 21:45:16 +000076 MachineRegisterInfo* mri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 const TargetMachine* tm_;
Dan Gohman1e57df32008-02-10 18:45:23 +000078 const TargetRegisterInfo* tri_;
Evan Chengc4c75f52007-11-03 07:20:12 +000079 const TargetInstrInfo* tii_;
Evan Chengc4c75f52007-11-03 07:20:12 +000080 BitVector allocatableRegs_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 LiveIntervals* li_;
Evan Cheng14f8a502008-06-04 09:18:41 +000082 LiveStacks* ls_;
Evan Cheng26d17df2007-12-11 02:09:15 +000083 const MachineLoopInfo *loopInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// handled_ - Intervals are added to the handled_ set in the order of their
86 /// start value. This is uses for backtracking.
87 std::vector<LiveInterval*> handled_;
88
89 /// fixed_ - Intervals that correspond to machine registers.
90 ///
91 IntervalPtrs fixed_;
92
93 /// active_ - Intervals that are currently being processed, and which have a
94 /// live range active for the current point.
95 IntervalPtrs active_;
96
97 /// inactive_ - Intervals that are currently being processed, but which have
98 /// a hold at the current point.
99 IntervalPtrs inactive_;
100
101 typedef std::priority_queue<LiveInterval*,
Owen Andersonba926a32008-08-15 18:49:41 +0000102 SmallVector<LiveInterval*, 64>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 greater_ptr<LiveInterval> > IntervalHeap;
104 IntervalHeap unhandled_;
105 std::auto_ptr<PhysRegTracker> prt_;
106 std::auto_ptr<VirtRegMap> vrm_;
107 std::auto_ptr<Spiller> spiller_;
108
109 public:
110 virtual const char* getPassName() const {
111 return "Linear Scan Register Allocator";
112 }
113
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.addRequired<LiveIntervals>();
Owen Andersonbac9ae22008-10-07 20:22:28 +0000116 if (StrongPHIElim)
117 AU.addRequiredID(StrongPHIEliminationID);
David Greene1d80f1b2007-09-06 16:18:45 +0000118 // Make sure PassManager knows which analyses to make available
119 // to coalescing and which analyses coalescing invalidates.
120 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng99dcc172008-10-23 20:43:13 +0000121 if (PreSplitIntervals)
122 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng14f8a502008-06-04 09:18:41 +0000123 AU.addRequired<LiveStacks>();
124 AU.addPreserved<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000125 AU.addRequired<MachineLoopInfo>();
Bill Wendling62264362008-01-04 20:54:55 +0000126 AU.addPreserved<MachineLoopInfo>();
127 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 MachineFunctionPass::getAnalysisUsage(AU);
129 }
130
131 /// runOnMachineFunction - register allocate the whole function
132 bool runOnMachineFunction(MachineFunction&);
133
134 private:
135 /// linearScan - the linear scan algorithm
136 void linearScan();
137
138 /// initIntervalSets - initialize the interval sets.
139 ///
140 void initIntervalSets();
141
142 /// processActiveIntervals - expire old intervals and move non-overlapping
143 /// ones to the inactive list.
144 void processActiveIntervals(unsigned CurPoint);
145
146 /// processInactiveIntervals - expire old intervals and move overlapping
147 /// ones to the active list.
148 void processInactiveIntervals(unsigned CurPoint);
149
150 /// assignRegOrStackSlotAtInterval - assign a register if one
151 /// is available, or spill.
152 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
153
Evan Chengc5952452008-06-20 21:45:16 +0000154 /// findIntervalsToSpill - Determine the intervals to spill for the
155 /// specified interval. It's passed the physical registers whose spill
156 /// weight is the lowest among all the registers whose live intervals
157 /// conflict with the interval.
158 void findIntervalsToSpill(LiveInterval *cur,
159 std::vector<std::pair<unsigned,float> > &Candidates,
160 unsigned NumCands,
161 SmallVector<LiveInterval*, 8> &SpillIntervals);
162
Evan Chengc4c75f52007-11-03 07:20:12 +0000163 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
164 /// try allocate the definition the same register as the source register
165 /// if the register is not defined during live time of the interval. This
166 /// eliminate a copy. This is used to coalesce copies which were not
167 /// coalesced away before allocation either due to dest and src being in
168 /// different register classes or because the coalescer was overly
169 /// conservative.
170 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
171
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 ///
173 /// register handling helpers
174 ///
175
176 /// getFreePhysReg - return a free physical register for this virtual
177 /// register interval if we have one, otherwise return 0.
178 unsigned getFreePhysReg(LiveInterval* cur);
179
180 /// assignVirt2StackSlot - assigns this virtual register to a
181 /// stack slot. returns the stack slot
182 int assignVirt2StackSlot(unsigned virtReg);
183
184 void ComputeRelatedRegClasses();
185
186 template <typename ItTy>
187 void printIntervals(const char* const str, ItTy i, ItTy e) const {
188 if (str) DOUT << str << " intervals:\n";
189 for (; i != e; ++i) {
190 DOUT << "\t" << *i->first << " -> ";
191 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000192 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 reg = vrm_->getPhys(reg);
194 }
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000195 DOUT << tri_->getName(reg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 }
197 }
198 };
199 char RALinScan::ID = 0;
200}
201
Evan Cheng14f8a502008-06-04 09:18:41 +0000202static RegisterPass<RALinScan>
203X("linearscan-regalloc", "Linear Scan Register Allocator");
204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman1e57df32008-02-10 18:45:23 +0000206 const TargetRegisterInfo &TRI = *tri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207
208 // First pass, add all reg classes to the union, and determine at least one
209 // reg class that each register is in.
210 bool HasAliases = false;
Dan Gohman1e57df32008-02-10 18:45:23 +0000211 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
212 E = TRI.regclass_end(); RCI != E; ++RCI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 RelatedRegClasses.insert(*RCI);
214 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
215 I != E; ++I) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000216 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217
218 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
219 if (PRC) {
220 // Already processed this register. Just make sure we know that
221 // multiple register classes share a register.
222 RelatedRegClasses.unionSets(PRC, *RCI);
223 } else {
224 PRC = *RCI;
225 }
226 }
227 }
228
229 // Second pass, now that we know conservatively what register classes each reg
230 // belongs to, add info about aliases. We don't need to do this for targets
231 // without register aliases.
232 if (HasAliases)
Owen Anderson4a472712008-08-13 23:36:23 +0000233 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
235 I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000236 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
238}
239
Evan Chengc4c75f52007-11-03 07:20:12 +0000240/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
241/// try allocate the definition the same register as the source register
242/// if the register is not defined during live time of the interval. This
243/// eliminate a copy. This is used to coalesce copies which were not
244/// coalesced away before allocation either due to dest and src being in
245/// different register classes or because the coalescer was overly
246/// conservative.
247unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Chengb6aa6712007-11-04 08:32:21 +0000248 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc4c75f52007-11-03 07:20:12 +0000249 return Reg;
250
251 VNInfo *vni = cur.getValNumInfo(0);
252 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
253 return Reg;
254 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
255 unsigned SrcReg, DstReg;
256 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
257 return Reg;
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000258 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000259 if (!vrm_->isAssignedReg(SrcReg))
260 return Reg;
261 else
262 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000263 }
Evan Chengc4c75f52007-11-03 07:20:12 +0000264 if (Reg == SrcReg)
265 return Reg;
266
Evan Cheng06b74c52008-09-18 22:38:47 +0000267 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc4c75f52007-11-03 07:20:12 +0000268 if (!RC->contains(SrcReg))
269 return Reg;
270
271 // Try to coalesce.
272 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000273 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling8eeb9792008-02-26 21:11:01 +0000274 << '\n';
Evan Chengc4c75f52007-11-03 07:20:12 +0000275 vrm_->clearVirt(cur.reg);
276 vrm_->assignVirt2Phys(cur.reg, SrcReg);
277 ++NumCoalesce;
278 return SrcReg;
279 }
280
281 return Reg;
282}
283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
285 mf_ = &fn;
Evan Chengc5952452008-06-20 21:45:16 +0000286 mri_ = &fn.getRegInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 tm_ = &fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +0000288 tri_ = tm_->getRegisterInfo();
Evan Chengc4c75f52007-11-03 07:20:12 +0000289 tii_ = tm_->getInstrInfo();
Dan Gohman1e57df32008-02-10 18:45:23 +0000290 allocatableRegs_ = tri_->getAllocatableSet(fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000292 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000293 loopInfo = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
David Greene1d80f1b2007-09-06 16:18:45 +0000295 // We don't run the coalescer here because we have no reason to
296 // interact with it. If the coalescer requires interaction, it
297 // won't do anything. If it doesn't require interaction, we assume
298 // it was run as a separate pass.
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 // If this is the first function compiled, compute the related reg classes.
301 if (RelatedRegClasses.empty())
302 ComputeRelatedRegClasses();
303
Dan Gohman1e57df32008-02-10 18:45:23 +0000304 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 vrm_.reset(new VirtRegMap(*mf_));
306 if (!spiller_.get()) spiller_.reset(createSpiller());
307
308 initIntervalSets();
309
310 linearScan();
311
312 // Rewrite spill code and update the PhysRegsUsed set.
313 spiller_->runOnMachineFunction(*mf_, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 vrm_.reset(); // Free the VirtRegMap
315
Dan Gohman79a9f152008-06-23 23:51:16 +0000316 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 fixed_.clear();
318 active_.clear();
319 inactive_.clear();
320 handled_.clear();
321
322 return true;
323}
324
325/// initIntervalSets - initialize the interval sets.
326///
327void RALinScan::initIntervalSets()
328{
329 assert(unhandled_.empty() && fixed_.empty() &&
330 active_.empty() && inactive_.empty() &&
331 "interval sets should be empty on initialization");
332
Owen Andersonba926a32008-08-15 18:49:41 +0000333 handled_.reserve(li_->getNumIntervals());
334
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000336 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng06b74c52008-09-18 22:38:47 +0000337 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson348d1d82008-08-13 21:49:13 +0000338 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 } else
Owen Anderson348d1d82008-08-13 21:49:13 +0000340 unhandled_.push(i->second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 }
342}
343
344void RALinScan::linearScan()
345{
346 // linear scan algorithm
347 DOUT << "********** LINEAR SCAN **********\n";
348 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
349
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351
352 while (!unhandled_.empty()) {
353 // pick the interval with the earliest start point
354 LiveInterval* cur = unhandled_.top();
355 unhandled_.pop();
Evan Chengd48f2bc2007-10-16 21:09:14 +0000356 ++NumIters;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
358
Evan Chenga3186992008-04-03 16:40:27 +0000359 if (!cur->empty()) {
360 processActiveIntervals(cur->beginNumber());
361 processInactiveIntervals(cur->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
Evan Chenga3186992008-04-03 16:40:27 +0000363 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
364 "Can only allocate virtual registers!");
365 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366
367 // Allocating a virtual register. try to find a free
368 // physical register or spill an interval (possibly this one) in order to
369 // assign it one.
370 assignRegOrStackSlotAtInterval(cur);
371
372 DEBUG(printIntervals("active", active_.begin(), active_.end()));
373 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
374 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
376 // expire any remaining active intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000377 while (!active_.empty()) {
378 IntervalPtr &IP = active_.back();
379 unsigned reg = IP.first->reg;
380 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000381 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 "Can only allocate virtual registers!");
383 reg = vrm_->getPhys(reg);
384 prt_->delRegUse(reg);
Evan Chengd48f2bc2007-10-16 21:09:14 +0000385 active_.pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 }
387
388 // expire any remaining inactive intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000389 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling1817ab82007-11-15 00:40:48 +0000390 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Chengd48f2bc2007-10-16 21:09:14 +0000391 DOUT << "\tinterval " << *i->first << " expired\n");
392 inactive_.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
Evan Chengcecc8222007-11-17 00:40:40 +0000394 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Chengf5cdf122007-10-17 02:12:22 +0000395 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000396 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Chengf5cdf122007-10-17 02:12:22 +0000397 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000398 LiveInterval &cur = *i->second;
Evan Chengf5cdf122007-10-17 02:12:22 +0000399 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000400 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Chengcecc8222007-11-17 00:40:40 +0000401 if (isPhys)
Owen Anderson348d1d82008-08-13 21:49:13 +0000402 Reg = cur.reg;
Evan Chengf5cdf122007-10-17 02:12:22 +0000403 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000404 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Chengf5cdf122007-10-17 02:12:22 +0000405 if (!Reg)
406 continue;
Evan Chengcecc8222007-11-17 00:40:40 +0000407 // Ignore splited live intervals.
408 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
409 continue;
Evan Chengf5cdf122007-10-17 02:12:22 +0000410 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
411 I != E; ++I) {
412 const LiveRange &LR = *I;
Evan Cheng84f9fc22008-10-29 05:06:14 +0000413 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Chengf5cdf122007-10-17 02:12:22 +0000414 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
415 if (LiveInMBBs[i] != EntryMBB)
416 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000417 LiveInMBBs.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 }
419 }
420 }
421
422 DOUT << *vrm_;
423}
424
425/// processActiveIntervals - expire old intervals and move non-overlapping ones
426/// to the inactive list.
427void RALinScan::processActiveIntervals(unsigned CurPoint)
428{
429 DOUT << "\tprocessing active intervals:\n";
430
431 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
432 LiveInterval *Interval = active_[i].first;
433 LiveInterval::iterator IntervalPos = active_[i].second;
434 unsigned reg = Interval->reg;
435
436 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
437
438 if (IntervalPos == Interval->end()) { // Remove expired intervals.
439 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000440 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 "Can only allocate virtual registers!");
442 reg = vrm_->getPhys(reg);
443 prt_->delRegUse(reg);
444
445 // Pop off the end of the list.
446 active_[i] = active_.back();
447 active_.pop_back();
448 --i; --e;
449
450 } else if (IntervalPos->start > CurPoint) {
451 // Move inactive intervals to inactive list.
452 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000453 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 "Can only allocate virtual registers!");
455 reg = vrm_->getPhys(reg);
456 prt_->delRegUse(reg);
457 // add to inactive.
458 inactive_.push_back(std::make_pair(Interval, IntervalPos));
459
460 // Pop off the end of the list.
461 active_[i] = active_.back();
462 active_.pop_back();
463 --i; --e;
464 } else {
465 // Otherwise, just update the iterator position.
466 active_[i].second = IntervalPos;
467 }
468 }
469}
470
471/// processInactiveIntervals - expire old intervals and move overlapping
472/// ones to the active list.
473void RALinScan::processInactiveIntervals(unsigned CurPoint)
474{
475 DOUT << "\tprocessing inactive intervals:\n";
476
477 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
478 LiveInterval *Interval = inactive_[i].first;
479 LiveInterval::iterator IntervalPos = inactive_[i].second;
480 unsigned reg = Interval->reg;
481
482 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
483
484 if (IntervalPos == Interval->end()) { // remove expired intervals.
485 DOUT << "\t\tinterval " << *Interval << " expired\n";
486
487 // Pop off the end of the list.
488 inactive_[i] = inactive_.back();
489 inactive_.pop_back();
490 --i; --e;
491 } else if (IntervalPos->start <= CurPoint) {
492 // move re-activated intervals in active list
493 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000494 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 "Can only allocate virtual registers!");
496 reg = vrm_->getPhys(reg);
497 prt_->addRegUse(reg);
498 // add to active
499 active_.push_back(std::make_pair(Interval, IntervalPos));
500
501 // Pop off the end of the list.
502 inactive_[i] = inactive_.back();
503 inactive_.pop_back();
504 --i; --e;
505 } else {
506 // Otherwise, just update the iterator position.
507 inactive_[i].second = IntervalPos;
508 }
509 }
510}
511
512/// updateSpillWeights - updates the spill weights of the specifed physical
513/// register and its weight.
514static void updateSpillWeights(std::vector<float> &Weights,
515 unsigned reg, float weight,
Dan Gohman1e57df32008-02-10 18:45:23 +0000516 const TargetRegisterInfo *TRI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 Weights[reg] += weight;
Dan Gohman1e57df32008-02-10 18:45:23 +0000518 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 Weights[*as] += weight;
520}
521
522static
523RALinScan::IntervalPtrs::iterator
524FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
525 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
526 I != E; ++I)
527 if (I->first == LI) return I;
528 return IP.end();
529}
530
531static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
532 for (unsigned i = 0, e = V.size(); i != e; ++i) {
533 RALinScan::IntervalPtr &IP = V[i];
534 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
535 IP.second, Point);
536 if (I != IP.first->begin()) --I;
537 IP.second = I;
538 }
539}
540
Evan Cheng14f8a502008-06-04 09:18:41 +0000541/// addStackInterval - Create a LiveInterval for stack if the specified live
542/// interval has been spilled.
543static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengba221ca2008-06-06 07:54:39 +0000544 LiveIntervals *li_, float &Weight,
545 VirtRegMap &vrm_) {
Evan Cheng14f8a502008-06-04 09:18:41 +0000546 int SS = vrm_.getStackSlot(cur->reg);
547 if (SS == VirtRegMap::NO_STACK_SLOT)
548 return;
549 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Chengba221ca2008-06-06 07:54:39 +0000550 SI.weight += Weight;
551
Evan Cheng14f8a502008-06-04 09:18:41 +0000552 VNInfo *VNI;
Evan Cheng29f36f52008-10-29 08:39:34 +0000553 if (SI.hasAtLeastOneValue())
Evan Cheng14f8a502008-06-04 09:18:41 +0000554 VNI = SI.getValNumInfo(0);
555 else
556 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
557
558 LiveInterval &RI = li_->getInterval(cur->reg);
559 // FIXME: This may be overly conservative.
560 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng14f8a502008-06-04 09:18:41 +0000561}
562
Evan Chengc5952452008-06-20 21:45:16 +0000563/// getConflictWeight - Return the number of conflicts between cur
564/// live interval and defs and uses of Reg weighted by loop depthes.
565static float getConflictWeight(LiveInterval *cur, unsigned Reg,
566 LiveIntervals *li_,
567 MachineRegisterInfo *mri_,
568 const MachineLoopInfo *loopInfo) {
569 float Conflicts = 0;
570 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
571 E = mri_->reg_end(); I != E; ++I) {
572 MachineInstr *MI = &*I;
573 if (cur->liveAt(li_->getInstructionIndex(MI))) {
574 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
575 Conflicts += powf(10.0f, (float)loopDepth);
576 }
577 }
578 return Conflicts;
579}
580
581/// findIntervalsToSpill - Determine the intervals to spill for the
582/// specified interval. It's passed the physical registers whose spill
583/// weight is the lowest among all the registers whose live intervals
584/// conflict with the interval.
585void RALinScan::findIntervalsToSpill(LiveInterval *cur,
586 std::vector<std::pair<unsigned,float> > &Candidates,
587 unsigned NumCands,
588 SmallVector<LiveInterval*, 8> &SpillIntervals) {
589 // We have figured out the *best* register to spill. But there are other
590 // registers that are pretty good as well (spill weight within 3%). Spill
591 // the one that has fewest defs and uses that conflict with cur.
592 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
593 SmallVector<LiveInterval*, 8> SLIs[3];
594
595 DOUT << "\tConsidering " << NumCands << " candidates: ";
596 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
597 DOUT << tri_->getName(Candidates[i].first) << " ";
598 DOUT << "\n";);
599
600 // Calculate the number of conflicts of each candidate.
601 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
602 unsigned Reg = i->first->reg;
603 unsigned PhysReg = vrm_->getPhys(Reg);
604 if (!cur->overlapsFrom(*i->first, i->second))
605 continue;
606 for (unsigned j = 0; j < NumCands; ++j) {
607 unsigned Candidate = Candidates[j].first;
608 if (tri_->regsOverlap(PhysReg, Candidate)) {
609 if (NumCands > 1)
610 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
611 SLIs[j].push_back(i->first);
612 }
613 }
614 }
615
616 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
617 unsigned Reg = i->first->reg;
618 unsigned PhysReg = vrm_->getPhys(Reg);
619 if (!cur->overlapsFrom(*i->first, i->second-1))
620 continue;
621 for (unsigned j = 0; j < NumCands; ++j) {
622 unsigned Candidate = Candidates[j].first;
623 if (tri_->regsOverlap(PhysReg, Candidate)) {
624 if (NumCands > 1)
625 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
626 SLIs[j].push_back(i->first);
627 }
628 }
629 }
630
631 // Which is the best candidate?
632 unsigned BestCandidate = 0;
633 float MinConflicts = Conflicts[0];
634 for (unsigned i = 1; i != NumCands; ++i) {
635 if (Conflicts[i] < MinConflicts) {
636 BestCandidate = i;
637 MinConflicts = Conflicts[i];
638 }
639 }
640
641 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
642 std::back_inserter(SpillIntervals));
643}
644
645namespace {
646 struct WeightCompare {
647 typedef std::pair<unsigned, float> RegWeightPair;
648 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
649 return LHS.second < RHS.second;
650 }
651 };
652}
653
654static bool weightsAreClose(float w1, float w2) {
655 if (!NewHeuristic)
656 return false;
657
658 float diff = w1 - w2;
659 if (diff <= 0.02f) // Within 0.02f
660 return true;
661 return (diff / w2) <= 0.05f; // Within 5%.
662}
663
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
665/// spill.
666void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
667{
668 DOUT << "\tallocating current interval: ";
669
Evan Chenga3186992008-04-03 16:40:27 +0000670 // This is an implicitly defined live interval, just assign any register.
Evan Cheng06b74c52008-09-18 22:38:47 +0000671 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chenga3186992008-04-03 16:40:27 +0000672 if (cur->empty()) {
673 unsigned physReg = cur->preference;
674 if (!physReg)
675 physReg = *RC->allocation_order_begin(*mf_);
676 DOUT << tri_->getName(physReg) << '\n';
677 // Note the register is not really in use.
678 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chenga3186992008-04-03 16:40:27 +0000679 return;
680 }
681
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 PhysRegTracker backupPrt = *prt_;
683
684 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
685 unsigned StartPosition = cur->beginNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc4c75f52007-11-03 07:20:12 +0000687
688 // If this live interval is defined by a move instruction and its source is
689 // assigned a physical register that is compatible with the target register
690 // class, then we should try to assign it the same register.
691 // This can happen when the move is from a larger register class to a smaller
692 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
693 if (!cur->preference && cur->containsOneValue()) {
694 VNInfo *vni = cur->getValNumInfo(0);
695 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
696 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
697 unsigned SrcReg, DstReg;
Evan Cheng1fbf9c22008-04-11 17:55:47 +0000698 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000699 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000700 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000701 Reg = SrcReg;
702 else if (vrm_->isAssignedReg(SrcReg))
703 Reg = vrm_->getPhys(SrcReg);
704 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
705 cur->preference = Reg;
706 }
707 }
708 }
709
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 // for every interval in inactive we overlap with, mark the
711 // register as not free and update spill weights.
712 for (IntervalPtrs::const_iterator i = inactive_.begin(),
713 e = inactive_.end(); i != e; ++i) {
714 unsigned Reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000715 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 "Can only allocate virtual registers!");
Evan Cheng06b74c52008-09-18 22:38:47 +0000717 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 // If this is not in a related reg class to the register we're allocating,
719 // don't check it.
720 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
721 cur->overlapsFrom(*i->first, i->second-1)) {
722 Reg = vrm_->getPhys(Reg);
723 prt_->addRegUse(Reg);
724 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
725 }
726 }
727
728 // Speculatively check to see if we can get a register right now. If not,
729 // we know we won't be able to by adding more constraints. If so, we can
730 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
731 // is very bad (it contains all callee clobbered registers for any functions
732 // with a call), so we want to avoid doing that if possible.
733 unsigned physReg = getFreePhysReg(cur);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000734 unsigned BestPhysReg = physReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 if (physReg) {
736 // We got a register. However, if it's in the fixed_ list, we might
737 // conflict with it. Check to see if we conflict with it or any of its
738 // aliases.
Evan Chengc4c75f52007-11-03 07:20:12 +0000739 SmallSet<unsigned, 8> RegAliases;
Dan Gohman1e57df32008-02-10 18:45:23 +0000740 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 RegAliases.insert(*AS);
742
743 bool ConflictsWithFixed = false;
744 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
745 IntervalPtr &IP = fixed_[i];
746 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
747 // Okay, this reg is on the fixed list. Check to see if we actually
748 // conflict.
749 LiveInterval *I = IP.first;
750 if (I->endNumber() > StartPosition) {
751 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
752 IP.second = II;
753 if (II != I->begin() && II->start > StartPosition)
754 --II;
755 if (cur->overlapsFrom(*I, II)) {
756 ConflictsWithFixed = true;
757 break;
758 }
759 }
760 }
761 }
762
763 // Okay, the register picked by our speculative getFreePhysReg call turned
764 // out to be in use. Actually add all of the conflicting fixed registers to
765 // prt so we can do an accurate query.
766 if (ConflictsWithFixed) {
767 // For every interval in fixed we overlap with, mark the register as not
768 // free and update spill weights.
769 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
770 IntervalPtr &IP = fixed_[i];
771 LiveInterval *I = IP.first;
772
773 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
774 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
775 I->endNumber() > StartPosition) {
776 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
777 IP.second = II;
778 if (II != I->begin() && II->start > StartPosition)
779 --II;
780 if (cur->overlapsFrom(*I, II)) {
781 unsigned reg = I->reg;
782 prt_->addRegUse(reg);
783 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
784 }
785 }
786 }
787
788 // Using the newly updated prt_ object, which includes conflicts in the
789 // future, see if there are any registers available.
790 physReg = getFreePhysReg(cur);
791 }
792 }
793
794 // Restore the physical register tracker, removing information about the
795 // future.
796 *prt_ = backupPrt;
797
798 // if we find a free register, we are done: assign this virtual to
799 // the free physical register and add this interval to the active
800 // list.
801 if (physReg) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000802 DOUT << tri_->getName(physReg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 vrm_->assignVirt2Phys(cur->reg, physReg);
804 prt_->addRegUse(physReg);
805 active_.push_back(std::make_pair(cur, cur->begin()));
806 handled_.push_back(cur);
807 return;
808 }
809 DOUT << "no free registers\n";
810
811 // Compile the spill weights into an array that is better for scanning.
Evan Chengc5952452008-06-20 21:45:16 +0000812 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 for (std::vector<std::pair<unsigned, float> >::iterator
814 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000815 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816
817 // for each interval in active, update spill weights.
818 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
819 i != e; ++i) {
820 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000821 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 "Can only allocate virtual registers!");
823 reg = vrm_->getPhys(reg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000824 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
826
827 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
828
829 // Find a register to spill.
830 float minWeight = HUGE_VALF;
Evan Chengc5952452008-06-20 21:45:16 +0000831 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
832
833 bool Found = false;
834 std::vector<std::pair<unsigned,float> > RegsWeights;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
836 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
837 e = RC->allocation_order_end(*mf_); i != e; ++i) {
838 unsigned reg = *i;
Evan Chengc5952452008-06-20 21:45:16 +0000839 float regWeight = SpillWeights[reg];
840 if (minWeight > regWeight)
841 Found = true;
842 RegsWeights.push_back(std::make_pair(reg, regWeight));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 }
844
845 // If we didn't find a register that is spillable, try aliases?
Evan Chengc5952452008-06-20 21:45:16 +0000846 if (!Found) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
848 e = RC->allocation_order_end(*mf_); i != e; ++i) {
849 unsigned reg = *i;
850 // No need to worry about if the alias register size < regsize of RC.
851 // We are going to spill all registers that alias it anyway.
Evan Chengc5952452008-06-20 21:45:16 +0000852 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
853 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng14cc83f2008-03-11 07:19:34 +0000854 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 }
Evan Chengc5952452008-06-20 21:45:16 +0000856
857 // Sort all potential spill candidates by weight.
858 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
859 minReg = RegsWeights[0].first;
860 minWeight = RegsWeights[0].second;
861 if (minWeight == HUGE_VALF) {
862 // All registers must have inf weight. Just grab one!
863 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona0e65132008-07-22 22:46:49 +0000864 if (cur->weight == HUGE_VALF ||
Evan Chengaf3c4e32008-09-20 01:28:05 +0000865 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Chengc5952452008-06-20 21:45:16 +0000866 // Spill a physical register around defs and uses.
867 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Chengaf3c4e32008-09-20 01:28:05 +0000868 assignRegOrStackSlotAtInterval(cur);
869 return;
870 }
Evan Chengc5952452008-06-20 21:45:16 +0000871 }
872
873 // Find up to 3 registers to consider as spill candidates.
874 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
875 while (LastCandidate > 1) {
876 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
877 break;
878 --LastCandidate;
879 }
880
881 DOUT << "\t\tregister(s) with min weight(s): ";
882 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
883 DOUT << tri_->getName(RegsWeights[i].first)
884 << " (" << RegsWeights[i].second << ")\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885
886 // if the current has the minimum weight, we need to spill it and
887 // add any added intervals back to unhandled, and restart
888 // linearscan.
889 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
890 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengba221ca2008-06-06 07:54:39 +0000891 float SSWeight;
Evan Chengc84ea132008-09-30 15:44:16 +0000892 SmallVector<LiveInterval*, 8> spillIs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 std::vector<LiveInterval*> added =
Evan Chengc84ea132008-09-30 15:44:16 +0000894 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Chengba221ca2008-06-06 07:54:39 +0000895 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 if (added.empty())
897 return; // Early exit if all spills were folded.
898
899 // Merge added with unhandled. Note that we know that
900 // addIntervalsForSpills returns intervals sorted by their starting
901 // point.
902 for (unsigned i = 0, e = added.size(); i != e; ++i)
903 unhandled_.push(added[i]);
904 return;
905 }
906
907 ++NumBacktracks;
908
909 // push the current interval back to unhandled since we are going
910 // to re-run at least this iteration. Since we didn't modify it it
911 // should go back right in the front of the list
912 unhandled_.push(cur);
913
Dan Gohman1e57df32008-02-10 18:45:23 +0000914 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 "did not choose a register to spill?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916
Evan Chengc5952452008-06-20 21:45:16 +0000917 // We spill all intervals aliasing the register with
918 // minimum weight, rollback to the interval with the earliest
919 // start point and let the linear scan algorithm run again
920 SmallVector<LiveInterval*, 8> spillIs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921
Evan Chengc5952452008-06-20 21:45:16 +0000922 // Determine which intervals have to be spilled.
923 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
924
925 // Set of spilled vregs (used later to rollback properly)
926 SmallSet<unsigned, 8> spilled;
927
928 // The earliest start of a Spilled interval indicates up to where
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 // in handled we need to roll back
930 unsigned earliestStart = cur->beginNumber();
931
Evan Chengc5952452008-06-20 21:45:16 +0000932 // Spill live intervals of virtual regs mapped to the physical register we
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 // want to clear (and its aliases). We only spill those that overlap with the
934 // current interval as the rest do not affect its allocation. we also keep
935 // track of the earliest start of all spilled live intervals since this will
936 // mark our rollback point.
Evan Chengc5952452008-06-20 21:45:16 +0000937 std::vector<LiveInterval*> added;
938 while (!spillIs.empty()) {
939 LiveInterval *sli = spillIs.back();
940 spillIs.pop_back();
941 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
942 earliestStart = std::min(earliestStart, sli->beginNumber());
943 float SSWeight;
944 std::vector<LiveInterval*> newIs =
Evan Chengc84ea132008-09-30 15:44:16 +0000945 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Chengc5952452008-06-20 21:45:16 +0000946 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
947 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
948 spilled.insert(sli->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 }
950
951 DOUT << "\t\trolling back to: " << earliestStart << '\n';
952
953 // Scan handled in reverse order up to the earliest start of a
954 // spilled live interval and undo each one, restoring the state of
955 // unhandled.
956 while (!handled_.empty()) {
957 LiveInterval* i = handled_.back();
958 // If this interval starts before t we are done.
959 if (i->beginNumber() < earliestStart)
960 break;
961 DOUT << "\t\t\tundo changes for: " << *i << '\n';
962 handled_.pop_back();
963
964 // When undoing a live interval allocation we must know if it is active or
965 // inactive to properly update the PhysRegTracker and the VirtRegMap.
966 IntervalPtrs::iterator it;
967 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
968 active_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000969 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 if (!spilled.count(i->reg))
971 unhandled_.push(i);
972 prt_->delRegUse(vrm_->getPhys(i->reg));
973 vrm_->clearVirt(i->reg);
974 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
975 inactive_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000976 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 if (!spilled.count(i->reg))
978 unhandled_.push(i);
979 vrm_->clearVirt(i->reg);
980 } else {
Dan Gohman1e57df32008-02-10 18:45:23 +0000981 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 "Can only allocate virtual registers!");
983 vrm_->clearVirt(i->reg);
984 unhandled_.push(i);
985 }
Evan Chengb6aa6712007-11-04 08:32:21 +0000986
987 // It interval has a preference, it must be defined by a copy. Clear the
988 // preference now since the source interval allocation may have been undone
989 // as well.
990 i->preference = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 }
992
993 // Rewind the iterators in the active, inactive, and fixed lists back to the
994 // point we reverted to.
995 RevertVectorIteratorsTo(active_, earliestStart);
996 RevertVectorIteratorsTo(inactive_, earliestStart);
997 RevertVectorIteratorsTo(fixed_, earliestStart);
998
999 // scan the rest and undo each interval that expired after t and
1000 // insert it in active (the next iteration of the algorithm will
1001 // put it in inactive if required)
1002 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1003 LiveInterval *HI = handled_[i];
1004 if (!HI->expiredAt(earliestStart) &&
1005 HI->expiredAt(cur->beginNumber())) {
1006 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1007 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman1e57df32008-02-10 18:45:23 +00001008 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 prt_->addRegUse(vrm_->getPhys(HI->reg));
1010 }
1011 }
1012
1013 // merge added with unhandled
1014 for (unsigned i = 0, e = added.size(); i != e; ++i)
1015 unhandled_.push(added[i]);
1016}
1017
1018/// getFreePhysReg - return a free physical register for this virtual register
1019/// interval if we have one, otherwise return 0.
1020unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001021 SmallVector<unsigned, 256> inactiveCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 unsigned MaxInactiveCount = 0;
1023
Evan Cheng06b74c52008-09-18 22:38:47 +00001024 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1026
1027 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1028 i != e; ++i) {
1029 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001030 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 "Can only allocate virtual registers!");
1032
1033 // If this is not in a related reg class to the register we're allocating,
1034 // don't check it.
Evan Cheng06b74c52008-09-18 22:38:47 +00001035 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1037 reg = vrm_->getPhys(reg);
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001038 if (inactiveCounts.size() <= reg)
1039 inactiveCounts.resize(reg+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 ++inactiveCounts[reg];
1041 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1042 }
1043 }
1044
1045 unsigned FreeReg = 0;
1046 unsigned FreeRegInactiveCount = 0;
1047
1048 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen94464072008-09-24 01:07:17 +00001049 // available first.
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001050 if (cur->preference) {
Dale Johannesend9e4fd62008-09-20 02:03:04 +00001051 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen94464072008-09-24 01:07:17 +00001052 RC->contains(cur->preference)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 DOUT << "\t\tassigned the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001054 << tri_->getName(cur->preference) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 return cur->preference;
1056 } else
1057 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001058 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001059 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060
1061 // Scan for the first available register.
1062 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1063 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf091bd2008-03-24 23:28:21 +00001064 assert(I != E && "No allocatable register in this register class!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 for (; I != E; ++I)
Dale Johannesen94464072008-09-24 01:07:17 +00001066 if (prt_->isRegAvail(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 FreeReg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001068 if (FreeReg < inactiveCounts.size())
1069 FreeRegInactiveCount = inactiveCounts[FreeReg];
1070 else
1071 FreeRegInactiveCount = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 break;
1073 }
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001074
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 // If there are no free regs, or if this reg has the max inactive count,
1076 // return this register.
1077 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1078
1079 // Continue scanning the registers, looking for the one with the highest
1080 // inactive count. Alkis found that this reduced register pressure very
1081 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1082 // reevaluated now.
1083 for (; I != E; ++I) {
1084 unsigned Reg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001085 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen94464072008-09-24 01:07:17 +00001086 FreeRegInactiveCount < inactiveCounts[Reg]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 FreeReg = Reg;
1088 FreeRegInactiveCount = inactiveCounts[Reg];
1089 if (FreeRegInactiveCount == MaxInactiveCount)
1090 break; // We found the one with the max inactive count.
1091 }
1092 }
1093
1094 return FreeReg;
1095}
1096
1097FunctionPass* llvm::createLinearScanRegisterAllocator() {
1098 return new RALinScan();
1099}