blob: ee118de4f49603e43c3daf48199fc3e243e9c7d2 [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"
Lang Hames87e3bca2009-05-06 02:36:21 +000016#include "VirtRegRewriter.h"
Lang Hamese2b201b2009-05-18 19:03:16 +000017#include "Spiller.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000027#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000030#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000031#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000032#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000033#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000036#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000037#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000038#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000039#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000040#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000041#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000042#include <cmath>
Lang Hamesf41538d2009-06-02 16:53:25 +000043#include <iostream>
44
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000045using namespace llvm;
46
Chris Lattnercd3245a2006-12-19 22:41:21 +000047STATISTIC(NumIters , "Number of iterations performed");
48STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000049STATISTIC(NumCoalesce, "Number of copies coalesced");
Evan Cheng206d1852009-04-20 08:01:12 +000050STATISTIC(NumDowngrade, "Number of registers downgraded");
Chris Lattnercd3245a2006-12-19 22:41:21 +000051
Evan Cheng3e172252008-06-20 21:45:16 +000052static cl::opt<bool>
53NewHeuristic("new-spilling-heuristic",
54 cl::desc("Use new spilling heuristic"),
55 cl::init(false), cl::Hidden);
56
Evan Chengf5cd4f02008-10-23 20:43:13 +000057static cl::opt<bool>
58PreSplitIntervals("pre-alloc-split",
59 cl::desc("Pre-register allocation live interval splitting"),
60 cl::init(false), cl::Hidden);
61
Lang Hamese2b201b2009-05-18 19:03:16 +000062static cl::opt<bool>
63NewSpillFramework("new-spill-framework",
64 cl::desc("New spilling framework"),
65 cl::init(false), cl::Hidden);
66
Chris Lattnercd3245a2006-12-19 22:41:21 +000067static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000068linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000069 createLinearScanRegisterAllocator);
70
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000072 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000073 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Chris Lattnercbb56252004-11-18 02:42:27 +000076 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000077 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000078 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000079 /// RelatedRegClasses - This structure is built the first time a function is
80 /// compiled, and keeps track of which register classes have registers that
81 /// belong to multiple classes or have aliases that are in other classes.
82 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000083 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000084
Evan Cheng206d1852009-04-20 08:01:12 +000085 // NextReloadMap - For each register in the map, it maps to the another
86 // register which is defined by a reload from the same stack slot and
87 // both reloads are in the same basic block.
88 DenseMap<unsigned, unsigned> NextReloadMap;
89
90 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
91 // un-favored for allocation.
92 SmallSet<unsigned, 8> DowngradedRegs;
93
94 // DowngradeMap - A map from virtual registers to physical registers being
95 // downgraded for the virtual registers.
96 DenseMap<unsigned, unsigned> DowngradeMap;
97
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000098 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000099 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000100 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000101 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +0000102 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +0000103 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +0000105 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000106 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +0000107
108 /// handled_ - Intervals are added to the handled_ set in the order of their
109 /// start value. This is uses for backtracking.
110 std::vector<LiveInterval*> handled_;
111
112 /// fixed_ - Intervals that correspond to machine registers.
113 ///
114 IntervalPtrs fixed_;
115
116 /// active_ - Intervals that are currently being processed, and which have a
117 /// live range active for the current point.
118 IntervalPtrs active_;
119
120 /// inactive_ - Intervals that are currently being processed, but which have
121 /// a hold at the current point.
122 IntervalPtrs inactive_;
123
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000124 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000125 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126 greater_ptr<LiveInterval> > IntervalHeap;
127 IntervalHeap unhandled_;
Evan Cheng5b16cd22009-05-01 01:03:49 +0000128
129 /// regUse_ - Tracks register usage.
130 SmallVector<unsigned, 32> regUse_;
131 SmallVector<unsigned, 32> regUseBackUp_;
132
133 /// vrm_ - Tracks register assignments.
Owen Anderson49c8aa02009-03-13 05:55:11 +0000134 VirtRegMap* vrm_;
Evan Cheng5b16cd22009-05-01 01:03:49 +0000135
Lang Hames87e3bca2009-05-06 02:36:21 +0000136 std::auto_ptr<VirtRegRewriter> rewriter_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000137
Lang Hamese2b201b2009-05-18 19:03:16 +0000138 std::auto_ptr<Spiller> spiller_;
139
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140 public:
141 virtual const char* getPassName() const {
142 return "Linear Scan Register Allocator";
143 }
144
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000146 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000147 if (StrongPHIElim)
148 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000149 // Make sure PassManager knows which analyses to make available
150 // to coalescing and which analyses coalescing invalidates.
151 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000152 if (PreSplitIntervals)
153 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000154 AU.addRequired<LiveStacks>();
155 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000156 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000157 AU.addPreserved<MachineLoopInfo>();
Owen Anderson49c8aa02009-03-13 05:55:11 +0000158 AU.addRequired<VirtRegMap>();
159 AU.addPreserved<VirtRegMap>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000160 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000161 MachineFunctionPass::getAnalysisUsage(AU);
162 }
163
164 /// runOnMachineFunction - register allocate the whole function
165 bool runOnMachineFunction(MachineFunction&);
166
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000167 private:
168 /// linearScan - the linear scan algorithm
169 void linearScan();
170
Chris Lattnercbb56252004-11-18 02:42:27 +0000171 /// initIntervalSets - initialize the interval sets.
172 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000173 void initIntervalSets();
174
Chris Lattnercbb56252004-11-18 02:42:27 +0000175 /// processActiveIntervals - expire old intervals and move non-overlapping
176 /// ones to the inactive list.
177 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000178
Chris Lattnercbb56252004-11-18 02:42:27 +0000179 /// processInactiveIntervals - expire old intervals and move overlapping
180 /// ones to the active list.
181 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000182
Evan Cheng206d1852009-04-20 08:01:12 +0000183 /// hasNextReloadInterval - Return the next liveinterval that's being
184 /// defined by a reload from the same SS as the specified one.
185 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
186
187 /// DowngradeRegister - Downgrade a register for allocation.
188 void DowngradeRegister(LiveInterval *li, unsigned Reg);
189
190 /// UpgradeRegister - Upgrade a register for allocation.
191 void UpgradeRegister(unsigned Reg);
192
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000193 /// assignRegOrStackSlotAtInterval - assign a register if one
194 /// is available, or spill.
195 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
196
Evan Cheng5d088fe2009-03-23 22:57:19 +0000197 void updateSpillWeights(std::vector<float> &Weights,
198 unsigned reg, float weight,
199 const TargetRegisterClass *RC);
200
Evan Cheng3e172252008-06-20 21:45:16 +0000201 /// findIntervalsToSpill - Determine the intervals to spill for the
202 /// specified interval. It's passed the physical registers whose spill
203 /// weight is the lowest among all the registers whose live intervals
204 /// conflict with the interval.
205 void findIntervalsToSpill(LiveInterval *cur,
206 std::vector<std::pair<unsigned,float> > &Candidates,
207 unsigned NumCands,
208 SmallVector<LiveInterval*, 8> &SpillIntervals);
209
Evan Chengc92da382007-11-03 07:20:12 +0000210 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
211 /// try allocate the definition the same register as the source register
212 /// if the register is not defined during live time of the interval. This
213 /// eliminate a copy. This is used to coalesce copies which were not
214 /// coalesced away before allocation either due to dest and src being in
215 /// different register classes or because the coalescer was overly
216 /// conservative.
217 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
218
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000219 ///
Evan Cheng5b16cd22009-05-01 01:03:49 +0000220 /// Register usage / availability tracking helpers.
221 ///
222
223 void initRegUses() {
224 regUse_.resize(tri_->getNumRegs(), 0);
225 regUseBackUp_.resize(tri_->getNumRegs(), 0);
226 }
227
228 void finalizeRegUses() {
Evan Chengc781a242009-05-03 18:32:42 +0000229#ifndef NDEBUG
230 // Verify all the registers are "freed".
231 bool Error = false;
232 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
233 if (regUse_[i] != 0) {
234 cerr << tri_->getName(i) << " is still in use!\n";
235 Error = true;
236 }
237 }
238 if (Error)
239 abort();
240#endif
Evan Cheng5b16cd22009-05-01 01:03:49 +0000241 regUse_.clear();
242 regUseBackUp_.clear();
243 }
244
245 void addRegUse(unsigned physReg) {
246 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
247 "should be physical register!");
248 ++regUse_[physReg];
249 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
250 ++regUse_[*as];
251 }
252
253 void delRegUse(unsigned physReg) {
254 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
255 "should be physical register!");
256 assert(regUse_[physReg] != 0);
257 --regUse_[physReg];
258 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
259 assert(regUse_[*as] != 0);
260 --regUse_[*as];
261 }
262 }
263
264 bool isRegAvail(unsigned physReg) const {
265 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
266 "should be physical register!");
267 return regUse_[physReg] == 0;
268 }
269
270 void backUpRegUses() {
271 regUseBackUp_ = regUse_;
272 }
273
274 void restoreRegUses() {
275 regUse_ = regUseBackUp_;
276 }
277
278 ///
279 /// Register handling helpers.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000280 ///
281
Chris Lattnercbb56252004-11-18 02:42:27 +0000282 /// getFreePhysReg - return a free physical register for this virtual
283 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000284 unsigned getFreePhysReg(LiveInterval* cur);
Evan Cheng206d1852009-04-20 08:01:12 +0000285 unsigned getFreePhysReg(const TargetRegisterClass *RC,
286 unsigned MaxInactiveCount,
287 SmallVector<unsigned, 256> &inactiveCounts,
288 bool SkipDGRegs);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289
290 /// assignVirt2StackSlot - assigns this virtual register to a
291 /// stack slot. returns the stack slot
292 int assignVirt2StackSlot(unsigned virtReg);
293
Chris Lattnerb9805782005-08-23 22:27:31 +0000294 void ComputeRelatedRegClasses();
295
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 template <typename ItTy>
297 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000298 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000299 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000300 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000301 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000302 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000304 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000305 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000306 }
307 }
308 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000309 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000310}
311
Evan Cheng3f32d652008-06-04 09:18:41 +0000312static RegisterPass<RALinScan>
313X("linearscan-regalloc", "Linear Scan Register Allocator");
314
Lang Hamesf41538d2009-06-02 16:53:25 +0000315bool validateRegAlloc(MachineFunction *mf, LiveIntervals *lis,
316 VirtRegMap *vrm) {
317
318 MachineRegisterInfo *mri = &mf->getRegInfo();
319 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
320 bool allocationValid = true;
321
322
323 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
324 itr != end; ++itr) {
325
326 LiveInterval *li = itr->second;
327
328 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
329 continue;
330 }
331
332 if (vrm->hasPhys(li->reg)) {
333 const TargetRegisterClass *trc = mri->getRegClass(li->reg);
334
335 if (lis->hasInterval(vrm->getPhys(li->reg))) {
336 if (li->overlaps(lis->getInterval(vrm->getPhys(li->reg)))) {
337 std::cerr << "vreg " << li->reg << " overlaps its assigned preg "
338 << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
339 }
340 }
341
342 TargetRegisterClass::iterator fReg =
343 std::find(trc->allocation_order_begin(*mf), trc->allocation_order_end(*mf),
344 vrm->getPhys(li->reg));
345
346 if (fReg == trc->allocation_order_end(*mf)) {
347 std::cerr << "preg " << vrm->getPhys(li->reg)
348 << "(" << tri->getName(vrm->getPhys(li->reg)) << ") is not in the allocation set for vreg "
349 << li->reg << "\n";
350 allocationValid &= false;
351 }
352 }
353 else {
354 std::cerr << "No preg for vreg " << li->reg << "\n";
355 // What about conflicting loads/stores?
356 continue;
357 }
358
359 for (LiveIntervals::iterator itr2 = next(itr); itr2 != end; ++itr2) {
360
361 LiveInterval *li2 = itr2->second;
362
363 if (li2->empty())
364 continue;
365
366 if (TargetRegisterInfo::isPhysicalRegister(li2->reg)) {
367 if (li->overlaps(*li2)) {
368 if (vrm->getPhys(li->reg) == li2->reg ||
369 tri->areAliases(vrm->getPhys(li->reg), li2->reg)) {
370 std::cerr << "vreg " << li->reg << " overlaps preg "
371 << li2->reg << "(" << tri->getName(li2->reg) << ") which aliases "
372 << vrm->getPhys(li->reg) << "(" << tri->getName(vrm->getPhys(li->reg)) << ")\n";
373 allocationValid &= false;
374 }
375 }
376 }
377 else {
378
379 if (!vrm->hasPhys(li2->reg)) {
380 continue;
381 }
382
383 if (li->overlaps(*li2)) {
384 if (vrm->getPhys(li->reg) == vrm->getPhys(li2->reg) ||
385 tri->areAliases(vrm->getPhys(li->reg), vrm->getPhys(li2->reg))) {
386 std::cerr << "vreg " << li->reg << " (preg " << vrm->getPhys(li->reg)
387 << ") overlaps vreg " << li2->reg << " (preg " << vrm->getPhys(li2->reg)
388 << ") and " << vrm->getPhys(li->reg) << " aliases " << vrm->getPhys(li2->reg) << "\n";
389 allocationValid &= false;
390 }
391 }
392 }
393 }
394
395 }
396
397 return allocationValid;
398
399}
400
401
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000402void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000403 // First pass, add all reg classes to the union, and determine at least one
404 // reg class that each register is in.
405 bool HasAliases = false;
Evan Cheng206d1852009-04-20 08:01:12 +0000406 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
407 E = tri_->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000408 RelatedRegClasses.insert(*RCI);
409 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
410 I != E; ++I) {
Evan Cheng206d1852009-04-20 08:01:12 +0000411 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000412
413 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
414 if (PRC) {
415 // Already processed this register. Just make sure we know that
416 // multiple register classes share a register.
417 RelatedRegClasses.unionSets(PRC, *RCI);
418 } else {
419 PRC = *RCI;
420 }
421 }
422 }
423
424 // Second pass, now that we know conservatively what register classes each reg
425 // belongs to, add info about aliases. We don't need to do this for targets
426 // without register aliases.
427 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000428 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000429 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
430 I != E; ++I)
Evan Cheng206d1852009-04-20 08:01:12 +0000431 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000432 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
433}
434
Evan Chengc92da382007-11-03 07:20:12 +0000435/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
436/// try allocate the definition the same register as the source register
437/// if the register is not defined during live time of the interval. This
438/// eliminate a copy. This is used to coalesce copies which were not
439/// coalesced away before allocation either due to dest and src being in
440/// different register classes or because the coalescer was overly
441/// conservative.
442unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000443 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000444 return Reg;
445
Evan Chengd0deec22009-01-20 00:16:18 +0000446 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000447 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
448 return Reg;
449 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Chengeca24fb2009-05-12 23:07:00 +0000450 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg, PhysReg;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000451 if (!CopyMI ||
452 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000453 return Reg;
Evan Chengeca24fb2009-05-12 23:07:00 +0000454 PhysReg = SrcReg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000455 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000456 if (!vrm_->isAssignedReg(SrcReg))
457 return Reg;
Evan Chengeca24fb2009-05-12 23:07:00 +0000458 PhysReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000459 }
Evan Chengeca24fb2009-05-12 23:07:00 +0000460 if (Reg == PhysReg)
Evan Chengc92da382007-11-03 07:20:12 +0000461 return Reg;
462
Evan Cheng841ee1a2008-09-18 22:38:47 +0000463 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengeca24fb2009-05-12 23:07:00 +0000464 if (!RC->contains(PhysReg))
Evan Chengc92da382007-11-03 07:20:12 +0000465 return Reg;
466
467 // Try to coalesce.
Evan Chengeca24fb2009-05-12 23:07:00 +0000468 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, PhysReg)) {
469 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(PhysReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000470 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000471 vrm_->clearVirt(cur.reg);
Evan Chengeca24fb2009-05-12 23:07:00 +0000472 vrm_->assignVirt2Phys(cur.reg, PhysReg);
473
474 // Remove unnecessary kills since a copy does not clobber the register.
475 if (li_->hasInterval(SrcReg)) {
476 LiveInterval &SrcLI = li_->getInterval(SrcReg);
477 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(cur.reg),
478 E = mri_->reg_end(); I != E; ++I) {
479 MachineOperand &O = I.getOperand();
480 if (!O.isUse() || !O.isKill())
481 continue;
482 MachineInstr *MI = &*I;
483 if (SrcLI.liveAt(li_->getDefIndex(li_->getInstructionIndex(MI))))
484 O.setIsKill(false);
485 }
486 }
487
Evan Chengc92da382007-11-03 07:20:12 +0000488 ++NumCoalesce;
489 return SrcReg;
490 }
491
492 return Reg;
493}
494
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000495bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000496 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000497 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000499 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000500 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000501 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000502 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000503 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000504 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000505
David Greene2c17c4d2007-09-06 16:18:45 +0000506 // We don't run the coalescer here because we have no reason to
507 // interact with it. If the coalescer requires interaction, it
508 // won't do anything. If it doesn't require interaction, we assume
509 // it was run as a separate pass.
510
Chris Lattnerb9805782005-08-23 22:27:31 +0000511 // If this is the first function compiled, compute the related reg classes.
512 if (RelatedRegClasses.empty())
513 ComputeRelatedRegClasses();
Evan Cheng5b16cd22009-05-01 01:03:49 +0000514
515 // Also resize register usage trackers.
516 initRegUses();
517
Owen Anderson49c8aa02009-03-13 05:55:11 +0000518 vrm_ = &getAnalysis<VirtRegMap>();
Lang Hames87e3bca2009-05-06 02:36:21 +0000519 if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
Lang Hamese2b201b2009-05-18 19:03:16 +0000520
521 if (NewSpillFramework) {
Lang Hamesf41538d2009-06-02 16:53:25 +0000522 spiller_.reset(createSpiller(mf_, li_, ls_, vrm_));
Lang Hamese2b201b2009-05-18 19:03:16 +0000523 }
Lang Hamesf41538d2009-06-02 16:53:25 +0000524
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000526
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000528
Lang Hamesf41538d2009-06-02 16:53:25 +0000529 if (NewSpillFramework) {
530 bool allocValid = validateRegAlloc(mf_, li_, vrm_);
531 }
532
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000533 // Rewrite spill code and update the PhysRegsUsed set.
Lang Hames87e3bca2009-05-06 02:36:21 +0000534 rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
Chris Lattnercbb56252004-11-18 02:42:27 +0000535
Dan Gohman51cd9d62008-06-23 23:51:16 +0000536 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Evan Cheng5b16cd22009-05-01 01:03:49 +0000537
538 finalizeRegUses();
539
Chris Lattnercbb56252004-11-18 02:42:27 +0000540 fixed_.clear();
541 active_.clear();
542 inactive_.clear();
543 handled_.clear();
Evan Cheng206d1852009-04-20 08:01:12 +0000544 NextReloadMap.clear();
545 DowngradedRegs.clear();
546 DowngradeMap.clear();
Lang Hamesf41538d2009-06-02 16:53:25 +0000547 spiller_.reset(0);
Chris Lattnercbb56252004-11-18 02:42:27 +0000548
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000549 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000550}
551
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000552/// initIntervalSets - initialize the interval sets.
553///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000554void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000555{
556 assert(unhandled_.empty() && fixed_.empty() &&
557 active_.empty() && inactive_.empty() &&
558 "interval sets should be empty on initialization");
559
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000560 handled_.reserve(li_->getNumIntervals());
561
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000562 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000563 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000564 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000565 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000566 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000567 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000568 }
569}
570
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000571void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000572{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000573 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000574 DOUT << "********** LINEAR SCAN **********\n";
575 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000576
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000577 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000578
579 while (!unhandled_.empty()) {
580 // pick the interval with the earliest start point
581 LiveInterval* cur = unhandled_.top();
582 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000583 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000584 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000585
Evan Chengf30a49d2008-04-03 16:40:27 +0000586 if (!cur->empty()) {
587 processActiveIntervals(cur->beginNumber());
588 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000589
Evan Chengf30a49d2008-04-03 16:40:27 +0000590 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
591 "Can only allocate virtual registers!");
592 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000593
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000594 // Allocating a virtual register. try to find a free
595 // physical register or spill an interval (possibly this one) in order to
596 // assign it one.
597 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000598
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000599 DEBUG(printIntervals("active", active_.begin(), active_.end()));
600 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000601 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000602
Evan Cheng5b16cd22009-05-01 01:03:49 +0000603 // Expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000604 while (!active_.empty()) {
605 IntervalPtr &IP = active_.back();
606 unsigned reg = IP.first->reg;
607 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000608 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000609 "Can only allocate virtual registers!");
610 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000611 delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000612 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000614
Evan Cheng5b16cd22009-05-01 01:03:49 +0000615 // Expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000616 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000617 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000618 DOUT << "\tinterval " << *i->first << " expired\n");
619 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000620
Evan Cheng81a03822007-11-17 00:40:40 +0000621 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000622 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000623 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000624 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000625 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000626 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000627 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000628 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000629 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000630 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000631 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000632 if (!Reg)
633 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000634 // Ignore splited live intervals.
635 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
636 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000637 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
638 I != E; ++I) {
639 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000640 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000641 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
642 if (LiveInMBBs[i] != EntryMBB)
643 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000644 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000645 }
646 }
647 }
648
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000649 DOUT << *vrm_;
Evan Chengc781a242009-05-03 18:32:42 +0000650
651 // Look for physical registers that end up not being allocated even though
652 // register allocator had to spill other registers in its register class.
653 if (ls_->getNumIntervals() == 0)
654 return;
655 if (!vrm_->FindUnusedRegisters(tri_, li_))
656 return;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000657}
658
Chris Lattnercbb56252004-11-18 02:42:27 +0000659/// processActiveIntervals - expire old intervals and move non-overlapping ones
660/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000661void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000662{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000663 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000664
Chris Lattnercbb56252004-11-18 02:42:27 +0000665 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
666 LiveInterval *Interval = active_[i].first;
667 LiveInterval::iterator IntervalPos = active_[i].second;
668 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000669
Chris Lattnercbb56252004-11-18 02:42:27 +0000670 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
671
672 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000673 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000674 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000675 "Can only allocate virtual registers!");
676 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000677 delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000678
679 // Pop off the end of the list.
680 active_[i] = active_.back();
681 active_.pop_back();
682 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000683
Chris Lattnercbb56252004-11-18 02:42:27 +0000684 } else if (IntervalPos->start > CurPoint) {
685 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000686 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000687 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000688 "Can only allocate virtual registers!");
689 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000690 delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000691 // add to inactive.
692 inactive_.push_back(std::make_pair(Interval, IntervalPos));
693
694 // Pop off the end of the list.
695 active_[i] = active_.back();
696 active_.pop_back();
697 --i; --e;
698 } else {
699 // Otherwise, just update the iterator position.
700 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000701 }
702 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000703}
704
Chris Lattnercbb56252004-11-18 02:42:27 +0000705/// processInactiveIntervals - expire old intervals and move overlapping
706/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000707void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000708{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000709 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000710
Chris Lattnercbb56252004-11-18 02:42:27 +0000711 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
712 LiveInterval *Interval = inactive_[i].first;
713 LiveInterval::iterator IntervalPos = inactive_[i].second;
714 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000715
Chris Lattnercbb56252004-11-18 02:42:27 +0000716 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000717
Chris Lattnercbb56252004-11-18 02:42:27 +0000718 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000719 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000720
Chris Lattnercbb56252004-11-18 02:42:27 +0000721 // Pop off the end of the list.
722 inactive_[i] = inactive_.back();
723 inactive_.pop_back();
724 --i; --e;
725 } else if (IntervalPos->start <= CurPoint) {
726 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000727 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000728 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000729 "Can only allocate virtual registers!");
730 reg = vrm_->getPhys(reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +0000731 addRegUse(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000732 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000733 active_.push_back(std::make_pair(Interval, IntervalPos));
734
735 // Pop off the end of the list.
736 inactive_[i] = inactive_.back();
737 inactive_.pop_back();
738 --i; --e;
739 } else {
740 // Otherwise, just update the iterator position.
741 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000742 }
743 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000744}
745
Chris Lattnercbb56252004-11-18 02:42:27 +0000746/// updateSpillWeights - updates the spill weights of the specifed physical
747/// register and its weight.
Evan Cheng5d088fe2009-03-23 22:57:19 +0000748void RALinScan::updateSpillWeights(std::vector<float> &Weights,
749 unsigned reg, float weight,
750 const TargetRegisterClass *RC) {
751 SmallSet<unsigned, 4> Processed;
752 SmallSet<unsigned, 4> SuperAdded;
753 SmallVector<unsigned, 4> Supers;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000754 Weights[reg] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000755 Processed.insert(reg);
756 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000757 Weights[*as] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000758 Processed.insert(*as);
759 if (tri_->isSubRegister(*as, reg) &&
760 SuperAdded.insert(*as) &&
761 RC->contains(*as)) {
762 Supers.push_back(*as);
763 }
764 }
765
766 // If the alias is a super-register, and the super-register is in the
767 // register class we are trying to allocate. Then add the weight to all
768 // sub-registers of the super-register even if they are not aliases.
769 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
770 // bl should get the same spill weight otherwise it will be choosen
771 // as a spill candidate since spilling bh doesn't make ebx available.
772 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
Evan Chengc781a242009-05-03 18:32:42 +0000773 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
774 if (!Processed.count(*sr))
775 Weights[*sr] += weight;
Evan Cheng5d088fe2009-03-23 22:57:19 +0000776 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000777}
778
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000779static
780RALinScan::IntervalPtrs::iterator
781FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
782 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
783 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000784 if (I->first == LI) return I;
785 return IP.end();
786}
787
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000788static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000789 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000790 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000791 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
792 IP.second, Point);
793 if (I != IP.first->begin()) --I;
794 IP.second = I;
795 }
796}
Chris Lattnercbb56252004-11-18 02:42:27 +0000797
Evan Cheng3f32d652008-06-04 09:18:41 +0000798/// addStackInterval - Create a LiveInterval for stack if the specified live
799/// interval has been spilled.
800static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengc781a242009-05-03 18:32:42 +0000801 LiveIntervals *li_,
802 MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000803 int SS = vrm_.getStackSlot(cur->reg);
804 if (SS == VirtRegMap::NO_STACK_SLOT)
805 return;
Evan Chengc781a242009-05-03 18:32:42 +0000806
807 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
808 LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000809
Evan Cheng3f32d652008-06-04 09:18:41 +0000810 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000811 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000812 VNI = SI.getValNumInfo(0);
813 else
814 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
815
816 LiveInterval &RI = li_->getInterval(cur->reg);
817 // FIXME: This may be overly conservative.
818 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000819}
820
Evan Cheng3e172252008-06-20 21:45:16 +0000821/// getConflictWeight - Return the number of conflicts between cur
822/// live interval and defs and uses of Reg weighted by loop depthes.
Evan Chengc781a242009-05-03 18:32:42 +0000823static
824float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
825 MachineRegisterInfo *mri_,
826 const MachineLoopInfo *loopInfo) {
Evan Cheng3e172252008-06-20 21:45:16 +0000827 float Conflicts = 0;
828 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
829 E = mri_->reg_end(); I != E; ++I) {
830 MachineInstr *MI = &*I;
831 if (cur->liveAt(li_->getInstructionIndex(MI))) {
832 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
833 Conflicts += powf(10.0f, (float)loopDepth);
834 }
835 }
836 return Conflicts;
837}
838
839/// findIntervalsToSpill - Determine the intervals to spill for the
840/// specified interval. It's passed the physical registers whose spill
841/// weight is the lowest among all the registers whose live intervals
842/// conflict with the interval.
843void RALinScan::findIntervalsToSpill(LiveInterval *cur,
844 std::vector<std::pair<unsigned,float> > &Candidates,
845 unsigned NumCands,
846 SmallVector<LiveInterval*, 8> &SpillIntervals) {
847 // We have figured out the *best* register to spill. But there are other
848 // registers that are pretty good as well (spill weight within 3%). Spill
849 // the one that has fewest defs and uses that conflict with cur.
850 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
851 SmallVector<LiveInterval*, 8> SLIs[3];
852
853 DOUT << "\tConsidering " << NumCands << " candidates: ";
854 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
855 DOUT << tri_->getName(Candidates[i].first) << " ";
856 DOUT << "\n";);
857
858 // Calculate the number of conflicts of each candidate.
859 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
860 unsigned Reg = i->first->reg;
861 unsigned PhysReg = vrm_->getPhys(Reg);
862 if (!cur->overlapsFrom(*i->first, i->second))
863 continue;
864 for (unsigned j = 0; j < NumCands; ++j) {
865 unsigned Candidate = Candidates[j].first;
866 if (tri_->regsOverlap(PhysReg, Candidate)) {
867 if (NumCands > 1)
868 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
869 SLIs[j].push_back(i->first);
870 }
871 }
872 }
873
874 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
875 unsigned Reg = i->first->reg;
876 unsigned PhysReg = vrm_->getPhys(Reg);
877 if (!cur->overlapsFrom(*i->first, i->second-1))
878 continue;
879 for (unsigned j = 0; j < NumCands; ++j) {
880 unsigned Candidate = Candidates[j].first;
881 if (tri_->regsOverlap(PhysReg, Candidate)) {
882 if (NumCands > 1)
883 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
884 SLIs[j].push_back(i->first);
885 }
886 }
887 }
888
889 // Which is the best candidate?
890 unsigned BestCandidate = 0;
891 float MinConflicts = Conflicts[0];
892 for (unsigned i = 1; i != NumCands; ++i) {
893 if (Conflicts[i] < MinConflicts) {
894 BestCandidate = i;
895 MinConflicts = Conflicts[i];
896 }
897 }
898
899 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
900 std::back_inserter(SpillIntervals));
901}
902
903namespace {
904 struct WeightCompare {
905 typedef std::pair<unsigned, float> RegWeightPair;
906 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
907 return LHS.second < RHS.second;
908 }
909 };
910}
911
912static bool weightsAreClose(float w1, float w2) {
913 if (!NewHeuristic)
914 return false;
915
916 float diff = w1 - w2;
917 if (diff <= 0.02f) // Within 0.02f
918 return true;
919 return (diff / w2) <= 0.05f; // Within 5%.
920}
921
Evan Cheng206d1852009-04-20 08:01:12 +0000922LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
923 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
924 if (I == NextReloadMap.end())
925 return 0;
926 return &li_->getInterval(I->second);
927}
928
929void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
930 bool isNew = DowngradedRegs.insert(Reg);
931 isNew = isNew; // Silence compiler warning.
932 assert(isNew && "Multiple reloads holding the same register?");
933 DowngradeMap.insert(std::make_pair(li->reg, Reg));
934 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
935 isNew = DowngradedRegs.insert(*AS);
936 isNew = isNew; // Silence compiler warning.
937 assert(isNew && "Multiple reloads holding the same register?");
938 DowngradeMap.insert(std::make_pair(li->reg, *AS));
939 }
940 ++NumDowngrade;
941}
942
943void RALinScan::UpgradeRegister(unsigned Reg) {
944 if (Reg) {
945 DowngradedRegs.erase(Reg);
946 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
947 DowngradedRegs.erase(*AS);
948 }
949}
950
951namespace {
952 struct LISorter {
953 bool operator()(LiveInterval* A, LiveInterval* B) {
954 return A->beginNumber() < B->beginNumber();
955 }
956 };
957}
958
Chris Lattnercbb56252004-11-18 02:42:27 +0000959/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
960/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000961void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000962{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000963 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000964
Evan Chengf30a49d2008-04-03 16:40:27 +0000965 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000966 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000967 if (cur->empty()) {
968 unsigned physReg = cur->preference;
969 if (!physReg)
970 physReg = *RC->allocation_order_begin(*mf_);
971 DOUT << tri_->getName(physReg) << '\n';
972 // Note the register is not really in use.
973 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000974 return;
975 }
976
Evan Cheng5b16cd22009-05-01 01:03:49 +0000977 backUpRegUses();
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000978
Chris Lattnera6c17502005-08-22 20:20:42 +0000979 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000980 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000981 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000982
Evan Chengd0deec22009-01-20 00:16:18 +0000983 // If start of this live interval is defined by a move instruction and its
984 // source is assigned a physical register that is compatible with the target
985 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000986 // This can happen when the move is from a larger register class to a smaller
987 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000988 if (!cur->preference && cur->hasAtLeastOneValue()) {
989 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000990 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
991 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000992 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
993 if (CopyMI &&
994 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000995 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000996 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000997 Reg = SrcReg;
998 else if (vrm_->isAssignedReg(SrcReg))
999 Reg = vrm_->getPhys(SrcReg);
Evan Cheng1c2f6da2009-04-29 00:42:27 +00001000 if (Reg) {
1001 if (SrcSubReg)
1002 Reg = tri_->getSubReg(Reg, SrcSubReg);
1003 if (DstSubReg)
1004 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1005 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1006 cur->preference = Reg;
1007 }
Evan Chengc92da382007-11-03 07:20:12 +00001008 }
1009 }
1010 }
1011
Evan Cheng5b16cd22009-05-01 01:03:49 +00001012 // For every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +00001013 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001014 for (IntervalPtrs::const_iterator i = inactive_.begin(),
1015 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +00001016 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001017 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +00001018 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +00001019 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001020 // If this is not in a related reg class to the register we're allocating,
1021 // don't check it.
1022 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1023 cur->overlapsFrom(*i->first, i->second-1)) {
1024 Reg = vrm_->getPhys(Reg);
Evan Cheng5b16cd22009-05-01 01:03:49 +00001025 addRegUse(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001026 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001027 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001028 }
Chris Lattnera411cbc2005-08-22 20:59:30 +00001029
1030 // Speculatively check to see if we can get a register right now. If not,
1031 // we know we won't be able to by adding more constraints. If so, we can
1032 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1033 // is very bad (it contains all callee clobbered registers for any functions
1034 // with a call), so we want to avoid doing that if possible.
1035 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +00001036 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +00001037 if (physReg) {
1038 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +00001039 // conflict with it. Check to see if we conflict with it or any of its
1040 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +00001041 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001042 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +00001043 RegAliases.insert(*AS);
1044
Chris Lattnera411cbc2005-08-22 20:59:30 +00001045 bool ConflictsWithFixed = false;
1046 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +00001047 IntervalPtr &IP = fixed_[i];
1048 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +00001049 // Okay, this reg is on the fixed list. Check to see if we actually
1050 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +00001051 LiveInterval *I = IP.first;
1052 if (I->endNumber() > StartPosition) {
1053 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1054 IP.second = II;
1055 if (II != I->begin() && II->start > StartPosition)
1056 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +00001057 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +00001058 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +00001059 break;
1060 }
Chris Lattnera411cbc2005-08-22 20:59:30 +00001061 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +00001062 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +00001063 }
Chris Lattnera411cbc2005-08-22 20:59:30 +00001064
1065 // Okay, the register picked by our speculative getFreePhysReg call turned
1066 // out to be in use. Actually add all of the conflicting fixed registers to
Evan Cheng5b16cd22009-05-01 01:03:49 +00001067 // regUse_ so we can do an accurate query.
Chris Lattnera411cbc2005-08-22 20:59:30 +00001068 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +00001069 // For every interval in fixed we overlap with, mark the register as not
1070 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +00001071 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1072 IntervalPtr &IP = fixed_[i];
1073 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +00001074
1075 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1076 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1077 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +00001078 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1079 IP.second = II;
1080 if (II != I->begin() && II->start > StartPosition)
1081 --II;
1082 if (cur->overlapsFrom(*I, II)) {
1083 unsigned reg = I->reg;
Evan Cheng5b16cd22009-05-01 01:03:49 +00001084 addRegUse(reg);
Chris Lattnera411cbc2005-08-22 20:59:30 +00001085 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1086 }
1087 }
1088 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +00001089
Evan Cheng5b16cd22009-05-01 01:03:49 +00001090 // Using the newly updated regUse_ object, which includes conflicts in the
Chris Lattnera411cbc2005-08-22 20:59:30 +00001091 // future, see if there are any registers available.
1092 physReg = getFreePhysReg(cur);
1093 }
1094 }
1095
Chris Lattnera6c17502005-08-22 20:20:42 +00001096 // Restore the physical register tracker, removing information about the
1097 // future.
Evan Cheng5b16cd22009-05-01 01:03:49 +00001098 restoreRegUses();
Chris Lattnera6c17502005-08-22 20:20:42 +00001099
Evan Cheng5b16cd22009-05-01 01:03:49 +00001100 // If we find a free register, we are done: assign this virtual to
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001101 // the free physical register and add this interval to the active
1102 // list.
1103 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001104 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001105 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Cheng5b16cd22009-05-01 01:03:49 +00001106 addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +00001107 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001108 handled_.push_back(cur);
Evan Cheng206d1852009-04-20 08:01:12 +00001109
1110 // "Upgrade" the physical register since it has been allocated.
1111 UpgradeRegister(physReg);
1112 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1113 // "Downgrade" physReg to try to keep physReg from being allocated until
1114 // the next reload from the same SS is allocated.
1115 NextReloadLI->preference = physReg;
1116 DowngradeRegister(cur, physReg);
1117 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001118 return;
1119 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001120 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001121
Chris Lattnera6c17502005-08-22 20:20:42 +00001122 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +00001123 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +00001124 for (std::vector<std::pair<unsigned, float> >::iterator
1125 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Evan Cheng5d088fe2009-03-23 22:57:19 +00001126 updateSpillWeights(SpillWeights, I->first, I->second, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +00001127
1128 // for each interval in active, update spill weights.
1129 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1130 i != e; ++i) {
1131 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001132 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +00001133 "Can only allocate virtual registers!");
1134 reg = vrm_->getPhys(reg);
Evan Cheng5d088fe2009-03-23 22:57:19 +00001135 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
Chris Lattnera6c17502005-08-22 20:20:42 +00001136 }
1137
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001138 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001139
Chris Lattnerc8e2c552006-03-25 23:00:56 +00001140 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +00001141 float minWeight = HUGE_VALF;
Evan Cheng5d088fe2009-03-23 22:57:19 +00001142 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
Evan Cheng3e172252008-06-20 21:45:16 +00001143
1144 bool Found = false;
1145 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001146 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1147 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1148 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1149 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +00001150 float regWeight = SpillWeights[reg];
1151 if (minWeight > regWeight)
1152 Found = true;
1153 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +00001154 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +00001155
1156 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +00001157 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +00001158 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1159 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1160 unsigned reg = *i;
1161 // No need to worry about if the alias register size < regsize of RC.
1162 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +00001163 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1164 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +00001165 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +00001166 }
Evan Cheng3e172252008-06-20 21:45:16 +00001167
1168 // Sort all potential spill candidates by weight.
1169 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1170 minReg = RegsWeights[0].first;
1171 minWeight = RegsWeights[0].second;
1172 if (minWeight == HUGE_VALF) {
1173 // All registers must have inf weight. Just grab one!
1174 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +00001175 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +00001176 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +00001177 // Spill a physical register around defs and uses.
Evan Cheng206d1852009-04-20 08:01:12 +00001178 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
Evan Cheng96f3fd92009-04-29 07:16:34 +00001179 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1180 // in fixed_. Reset them.
1181 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1182 IntervalPtr &IP = fixed_[i];
1183 LiveInterval *I = IP.first;
1184 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1185 IP.second = I->advanceTo(I->begin(), StartPosition);
1186 }
1187
Evan Cheng206d1852009-04-20 08:01:12 +00001188 DowngradedRegs.clear();
Evan Cheng2824a652009-03-23 18:24:37 +00001189 assignRegOrStackSlotAtInterval(cur);
Evan Cheng206d1852009-04-20 08:01:12 +00001190 } else {
Evan Cheng2824a652009-03-23 18:24:37 +00001191 cerr << "Ran out of registers during register allocation!\n";
1192 exit(1);
1193 }
Evan Cheng5e8d9de2008-09-20 01:28:05 +00001194 return;
1195 }
Evan Cheng3e172252008-06-20 21:45:16 +00001196 }
1197
1198 // Find up to 3 registers to consider as spill candidates.
1199 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1200 while (LastCandidate > 1) {
1201 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1202 break;
1203 --LastCandidate;
1204 }
1205
1206 DOUT << "\t\tregister(s) with min weight(s): ";
1207 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
1208 DOUT << tri_->getName(RegsWeights[i].first)
1209 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +00001210
Evan Cheng206d1852009-04-20 08:01:12 +00001211 // If the current has the minimum weight, we need to spill it and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001212 // add any added intervals back to unhandled, and restart
1213 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +00001214 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001215 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengdc377862008-09-30 15:44:16 +00001216 SmallVector<LiveInterval*, 8> spillIs;
Lang Hamese2b201b2009-05-18 19:03:16 +00001217 std::vector<LiveInterval*> added;
1218
1219 if (!NewSpillFramework) {
1220 added = li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_);
Lang Hamesf41538d2009-06-02 16:53:25 +00001221 } else {
Lang Hamese2b201b2009-05-18 19:03:16 +00001222 added = spiller_->spill(cur);
1223 }
1224
Evan Cheng206d1852009-04-20 08:01:12 +00001225 std::sort(added.begin(), added.end(), LISorter());
Evan Chengc781a242009-05-03 18:32:42 +00001226 addStackInterval(cur, ls_, li_, mri_, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001227 if (added.empty())
1228 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001229
Evan Cheng206d1852009-04-20 08:01:12 +00001230 // Merge added with unhandled. Note that we have already sorted
1231 // intervals returned by addIntervalsForSpills by their starting
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001232 // point.
Evan Chengc4f718a2009-04-20 17:23:48 +00001233 // This also update the NextReloadMap. That is, it adds mapping from a
1234 // register defined by a reload from SS to the next reload from SS in the
1235 // same basic block.
1236 MachineBasicBlock *LastReloadMBB = 0;
1237 LiveInterval *LastReload = 0;
1238 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1239 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1240 LiveInterval *ReloadLi = added[i];
1241 if (ReloadLi->weight == HUGE_VALF &&
1242 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1243 unsigned ReloadIdx = ReloadLi->beginNumber();
1244 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1245 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1246 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1247 // Last reload of same SS is in the same MBB. We want to try to
1248 // allocate both reloads the same register and make sure the reg
1249 // isn't clobbered in between if at all possible.
1250 assert(LastReload->beginNumber() < ReloadIdx);
1251 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1252 }
1253 LastReloadMBB = ReloadMBB;
1254 LastReload = ReloadLi;
1255 LastReloadSS = ReloadSS;
1256 }
1257 unhandled_.push(ReloadLi);
1258 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001259 return;
1260 }
1261
Chris Lattner19828d42004-11-18 03:49:30 +00001262 ++NumBacktracks;
1263
Evan Cheng206d1852009-04-20 08:01:12 +00001264 // Push the current interval back to unhandled since we are going
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001265 // to re-run at least this iteration. Since we didn't modify it it
1266 // should go back right in the front of the list
1267 unhandled_.push(cur);
1268
Dan Gohman6f0d0242008-02-10 18:45:23 +00001269 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001270 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +00001271
Evan Cheng3e172252008-06-20 21:45:16 +00001272 // We spill all intervals aliasing the register with
1273 // minimum weight, rollback to the interval with the earliest
1274 // start point and let the linear scan algorithm run again
1275 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001276
Evan Cheng3e172252008-06-20 21:45:16 +00001277 // Determine which intervals have to be spilled.
1278 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1279
1280 // Set of spilled vregs (used later to rollback properly)
1281 SmallSet<unsigned, 8> spilled;
1282
1283 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001284 // in handled we need to roll back
Lang Hamesf41538d2009-06-02 16:53:25 +00001285
Chris Lattner23b71c12004-11-18 01:29:39 +00001286 unsigned earliestStart = cur->beginNumber();
Lang Hamesf41538d2009-06-02 16:53:25 +00001287 LiveInterval *earliestStartInterval = cur;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001288
Evan Cheng3e172252008-06-20 21:45:16 +00001289 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +00001290 // want to clear (and its aliases). We only spill those that overlap with the
1291 // current interval as the rest do not affect its allocation. we also keep
1292 // track of the earliest start of all spilled live intervals since this will
1293 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +00001294 std::vector<LiveInterval*> added;
1295 while (!spillIs.empty()) {
Lang Hamesf41538d2009-06-02 16:53:25 +00001296 bool epicFail = false;
Evan Cheng3e172252008-06-20 21:45:16 +00001297 LiveInterval *sli = spillIs.back();
1298 spillIs.pop_back();
1299 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1300 earliestStart = std::min(earliestStart, sli->beginNumber());
Lang Hamesf41538d2009-06-02 16:53:25 +00001301 earliestStartInterval =
1302 (earliestStartInterval->beginNumber() < sli->beginNumber()) ?
1303 earliestStartInterval : sli;
1304
1305 if (earliestStartInterval->beginNumber()!=earliestStart) {
1306 epicFail |= true;
1307 std::cerr << "What the 1 - "
1308 << "earliestStart = " << earliestStart
1309 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1310 << "\n";
1311 }
1312
1313 std::vector<LiveInterval*> newIs;
1314 if (!NewSpillFramework) {
1315 newIs = li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_);
1316 } else {
1317 newIs = spiller_->spill(sli);
1318 }
Evan Chengc781a242009-05-03 18:32:42 +00001319 addStackInterval(sli, ls_, li_, mri_, *vrm_);
Evan Cheng3e172252008-06-20 21:45:16 +00001320 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1321 spilled.insert(sli->reg);
Lang Hamesf41538d2009-06-02 16:53:25 +00001322
1323 if (earliestStartInterval->beginNumber()!=earliestStart) {
1324 epicFail |= true;
1325 std::cerr << "What the 2 - "
1326 << "earliestStart = " << earliestStart
1327 << "earliestStartInterval = " << earliestStartInterval->beginNumber()
1328 << "\n";
1329 }
1330
1331 if (epicFail) {
1332 //abort();
1333 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001334 }
1335
Lang Hamesf41538d2009-06-02 16:53:25 +00001336 earliestStart = earliestStartInterval->beginNumber();
1337
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001338 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001339
1340 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001341 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +00001342 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001343 while (!handled_.empty()) {
1344 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001345 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +00001346 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001347 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001348 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001349 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +00001350
1351 // When undoing a live interval allocation we must know if it is active or
Evan Cheng5b16cd22009-05-01 01:03:49 +00001352 // inactive to properly update regUse_ and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001353 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +00001354 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001355 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001356 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001357 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001358 unhandled_.push(i);
Evan Cheng5b16cd22009-05-01 01:03:49 +00001359 delRegUse(vrm_->getPhys(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001360 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +00001361 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001362 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001363 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001364 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001365 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +00001366 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001367 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001368 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001369 "Can only allocate virtual registers!");
1370 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001371 unhandled_.push(i);
1372 }
Evan Cheng9aeaf752007-11-04 08:32:21 +00001373
Evan Cheng206d1852009-04-20 08:01:12 +00001374 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1375 if (ii == DowngradeMap.end())
1376 // It interval has a preference, it must be defined by a copy. Clear the
1377 // preference now since the source interval allocation may have been
1378 // undone as well.
1379 i->preference = 0;
1380 else {
1381 UpgradeRegister(ii->second);
1382 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001383 }
1384
Chris Lattner19828d42004-11-18 03:49:30 +00001385 // Rewind the iterators in the active, inactive, and fixed lists back to the
1386 // point we reverted to.
1387 RevertVectorIteratorsTo(active_, earliestStart);
1388 RevertVectorIteratorsTo(inactive_, earliestStart);
1389 RevertVectorIteratorsTo(fixed_, earliestStart);
1390
Evan Cheng206d1852009-04-20 08:01:12 +00001391 // Scan the rest and undo each interval that expired after t and
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001392 // insert it in active (the next iteration of the algorithm will
1393 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001394 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1395 LiveInterval *HI = handled_[i];
1396 if (!HI->expiredAt(earliestStart) &&
1397 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001398 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001399 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001400 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Evan Cheng5b16cd22009-05-01 01:03:49 +00001401 addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001402 }
1403 }
1404
Evan Cheng206d1852009-04-20 08:01:12 +00001405 // Merge added with unhandled.
1406 // This also update the NextReloadMap. That is, it adds mapping from a
1407 // register defined by a reload from SS to the next reload from SS in the
1408 // same basic block.
1409 MachineBasicBlock *LastReloadMBB = 0;
1410 LiveInterval *LastReload = 0;
1411 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1412 std::sort(added.begin(), added.end(), LISorter());
1413 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1414 LiveInterval *ReloadLi = added[i];
1415 if (ReloadLi->weight == HUGE_VALF &&
1416 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1417 unsigned ReloadIdx = ReloadLi->beginNumber();
1418 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1419 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1420 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1421 // Last reload of same SS is in the same MBB. We want to try to
1422 // allocate both reloads the same register and make sure the reg
1423 // isn't clobbered in between if at all possible.
1424 assert(LastReload->beginNumber() < ReloadIdx);
1425 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1426 }
1427 LastReloadMBB = ReloadMBB;
1428 LastReload = ReloadLi;
1429 LastReloadSS = ReloadSS;
1430 }
1431 unhandled_.push(ReloadLi);
1432 }
1433}
1434
1435unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1436 unsigned MaxInactiveCount,
1437 SmallVector<unsigned, 256> &inactiveCounts,
1438 bool SkipDGRegs) {
1439 unsigned FreeReg = 0;
1440 unsigned FreeRegInactiveCount = 0;
1441
1442 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1443 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1444 assert(I != E && "No allocatable register in this register class!");
1445
1446 // Scan for the first available register.
1447 for (; I != E; ++I) {
1448 unsigned Reg = *I;
1449 // Ignore "downgraded" registers.
1450 if (SkipDGRegs && DowngradedRegs.count(Reg))
1451 continue;
Evan Cheng5b16cd22009-05-01 01:03:49 +00001452 if (isRegAvail(Reg)) {
Evan Cheng206d1852009-04-20 08:01:12 +00001453 FreeReg = Reg;
1454 if (FreeReg < inactiveCounts.size())
1455 FreeRegInactiveCount = inactiveCounts[FreeReg];
1456 else
1457 FreeRegInactiveCount = 0;
1458 break;
1459 }
1460 }
1461
1462 // If there are no free regs, or if this reg has the max inactive count,
1463 // return this register.
1464 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1465 return FreeReg;
1466
1467 // Continue scanning the registers, looking for the one with the highest
1468 // inactive count. Alkis found that this reduced register pressure very
1469 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1470 // reevaluated now.
1471 for (; I != E; ++I) {
1472 unsigned Reg = *I;
1473 // Ignore "downgraded" registers.
1474 if (SkipDGRegs && DowngradedRegs.count(Reg))
1475 continue;
Evan Cheng5b16cd22009-05-01 01:03:49 +00001476 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Evan Cheng206d1852009-04-20 08:01:12 +00001477 FreeRegInactiveCount < inactiveCounts[Reg]) {
1478 FreeReg = Reg;
1479 FreeRegInactiveCount = inactiveCounts[Reg];
1480 if (FreeRegInactiveCount == MaxInactiveCount)
1481 break; // We found the one with the max inactive count.
1482 }
1483 }
1484
1485 return FreeReg;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001486}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001487
Chris Lattnercbb56252004-11-18 02:42:27 +00001488/// getFreePhysReg - return a free physical register for this virtual register
1489/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001490unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001491 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001492 unsigned MaxInactiveCount = 0;
1493
Evan Cheng841ee1a2008-09-18 22:38:47 +00001494 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001495 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1496
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001497 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1498 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001499 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001500 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001501 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001502
1503 // If this is not in a related reg class to the register we're allocating,
1504 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001505 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001506 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1507 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001508 if (inactiveCounts.size() <= reg)
1509 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001510 ++inactiveCounts[reg];
1511 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1512 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001513 }
1514
Evan Cheng20b0abc2007-04-17 20:32:26 +00001515 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001516 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001517 if (cur->preference) {
Evan Cheng1c2f6da2009-04-29 00:42:27 +00001518 DOUT << "(preferred: " << tri_->getName(cur->preference) << ") ";
Evan Cheng5b16cd22009-05-01 01:03:49 +00001519 if (isRegAvail(cur->preference) &&
Evan Cheng1c2f6da2009-04-29 00:42:27 +00001520 RC->contains(cur->preference))
Evan Cheng20b0abc2007-04-17 20:32:26 +00001521 return cur->preference;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001522 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001523
Evan Cheng206d1852009-04-20 08:01:12 +00001524 if (!DowngradedRegs.empty()) {
1525 unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1526 true);
1527 if (FreeReg)
1528 return FreeReg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001529 }
Evan Cheng206d1852009-04-20 08:01:12 +00001530 return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001531}
1532
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001533FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001534 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001535}