blob: 912135a57f6cbedc1188ea0e0a7dac8cda111ffd [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +000013
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
Chris Lattnerb9805782005-08-23 22:27:31 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
Owen Anderson1ed5b712009-03-11 22:31:21 +000017#include "Spiller.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000027#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000030#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000031#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000032#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000033#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000036#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000037#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000038#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000039#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000040#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000041#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000042#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000043using namespace llvm;
44
Chris Lattnercd3245a2006-12-19 22:41:21 +000045STATISTIC(NumIters , "Number of iterations performed");
46STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000047STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000048
Evan Cheng3e172252008-06-20 21:45:16 +000049static cl::opt<bool>
50NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden);
53
Evan Chengf5cd4f02008-10-23 20:43:13 +000054static cl::opt<bool>
55PreSplitIntervals("pre-alloc-split",
56 cl::desc("Pre-register allocation live interval splitting"),
57 cl::init(false), cl::Hidden);
58
Chris Lattnercd3245a2006-12-19 22:41:21 +000059static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000060linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000061 createLinearScanRegisterAllocator);
62
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000063namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000064 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000065 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000066 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000067
Chris Lattnercbb56252004-11-18 02:42:27 +000068 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000069 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000070 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000071 /// RelatedRegClasses - This structure is built the first time a function is
72 /// compiled, and keeps track of which register classes have registers that
73 /// belong to multiple classes or have aliases that are in other classes.
74 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000075 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000076
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000078 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000079 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000080 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000081 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000082 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000084 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000085 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000086
87 /// handled_ - Intervals are added to the handled_ set in the order of their
88 /// start value. This is uses for backtracking.
89 std::vector<LiveInterval*> handled_;
90
91 /// fixed_ - Intervals that correspond to machine registers.
92 ///
93 IntervalPtrs fixed_;
94
95 /// active_ - Intervals that are currently being processed, and which have a
96 /// live range active for the current point.
97 IntervalPtrs active_;
98
99 /// inactive_ - Intervals that are currently being processed, but which have
100 /// a hold at the current point.
101 IntervalPtrs inactive_;
102
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000104 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 greater_ptr<LiveInterval> > IntervalHeap;
106 IntervalHeap unhandled_;
107 std::auto_ptr<PhysRegTracker> prt_;
Owen Anderson49c8aa02009-03-13 05:55:11 +0000108 VirtRegMap* vrm_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000110
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000111 public:
112 virtual const char* getPassName() const {
113 return "Linear Scan Register Allocator";
114 }
115
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000117 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000118 if (StrongPHIElim)
119 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000120 // Make sure PassManager knows which analyses to make available
121 // to coalescing and which analyses coalescing invalidates.
122 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000123 if (PreSplitIntervals)
124 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000125 AU.addRequired<LiveStacks>();
126 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000127 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000128 AU.addPreserved<MachineLoopInfo>();
Owen Anderson49c8aa02009-03-13 05:55:11 +0000129 AU.addRequired<VirtRegMap>();
130 AU.addPreserved<VirtRegMap>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000131 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000132 MachineFunctionPass::getAnalysisUsage(AU);
133 }
134
135 /// runOnMachineFunction - register allocate the whole function
136 bool runOnMachineFunction(MachineFunction&);
137
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000138 private:
139 /// linearScan - the linear scan algorithm
140 void linearScan();
141
Chris Lattnercbb56252004-11-18 02:42:27 +0000142 /// initIntervalSets - initialize the interval sets.
143 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000144 void initIntervalSets();
145
Chris Lattnercbb56252004-11-18 02:42:27 +0000146 /// processActiveIntervals - expire old intervals and move non-overlapping
147 /// ones to the inactive list.
148 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000149
Chris Lattnercbb56252004-11-18 02:42:27 +0000150 /// processInactiveIntervals - expire old intervals and move overlapping
151 /// ones to the active list.
152 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000153
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000154 /// assignRegOrStackSlotAtInterval - assign a register if one
155 /// is available, or spill.
156 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
157
Evan Cheng3e172252008-06-20 21:45:16 +0000158 /// findIntervalsToSpill - Determine the intervals to spill for the
159 /// specified interval. It's passed the physical registers whose spill
160 /// weight is the lowest among all the registers whose live intervals
161 /// conflict with the interval.
162 void findIntervalsToSpill(LiveInterval *cur,
163 std::vector<std::pair<unsigned,float> > &Candidates,
164 unsigned NumCands,
165 SmallVector<LiveInterval*, 8> &SpillIntervals);
166
Evan Chengc92da382007-11-03 07:20:12 +0000167 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
168 /// try allocate the definition the same register as the source register
169 /// if the register is not defined during live time of the interval. This
170 /// eliminate a copy. This is used to coalesce copies which were not
171 /// coalesced away before allocation either due to dest and src being in
172 /// different register classes or because the coalescer was overly
173 /// conservative.
174 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
175
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000176 ///
177 /// register handling helpers
178 ///
179
Chris Lattnercbb56252004-11-18 02:42:27 +0000180 /// getFreePhysReg - return a free physical register for this virtual
181 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000182 unsigned getFreePhysReg(LiveInterval* cur);
183
184 /// assignVirt2StackSlot - assigns this virtual register to a
185 /// stack slot. returns the stack slot
186 int assignVirt2StackSlot(unsigned virtReg);
187
Chris Lattnerb9805782005-08-23 22:27:31 +0000188 void ComputeRelatedRegClasses();
189
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000190 template <typename ItTy>
191 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000192 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000193 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000194 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000195 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000196 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000197 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000198 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000199 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000200 }
201 }
202 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000203 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000204}
205
Evan Cheng3f32d652008-06-04 09:18:41 +0000206static RegisterPass<RALinScan>
207X("linearscan-regalloc", "Linear Scan Register Allocator");
208
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000209void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000210 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000211
212 // First pass, add all reg classes to the union, and determine at least one
213 // reg class that each register is in.
214 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000215 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
216 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000217 RelatedRegClasses.insert(*RCI);
218 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
219 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000220 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000221
222 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
223 if (PRC) {
224 // Already processed this register. Just make sure we know that
225 // multiple register classes share a register.
226 RelatedRegClasses.unionSets(PRC, *RCI);
227 } else {
228 PRC = *RCI;
229 }
230 }
231 }
232
233 // Second pass, now that we know conservatively what register classes each reg
234 // belongs to, add info about aliases. We don't need to do this for targets
235 // without register aliases.
236 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000237 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000238 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
239 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000240 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000241 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
242}
243
Evan Chengc92da382007-11-03 07:20:12 +0000244/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
245/// try allocate the definition the same register as the source register
246/// if the register is not defined during live time of the interval. This
247/// eliminate a copy. This is used to coalesce copies which were not
248/// coalesced away before allocation either due to dest and src being in
249/// different register classes or because the coalescer was overly
250/// conservative.
251unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000252 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000253 return Reg;
254
Evan Chengd0deec22009-01-20 00:16:18 +0000255 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000256 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
257 return Reg;
258 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000259 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
260 if (!CopyMI ||
261 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000262 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000263 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000264 if (!vrm_->isAssignedReg(SrcReg))
265 return Reg;
266 else
267 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000268 }
Evan Chengc92da382007-11-03 07:20:12 +0000269 if (Reg == SrcReg)
270 return Reg;
271
Evan Cheng841ee1a2008-09-18 22:38:47 +0000272 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000273 if (!RC->contains(SrcReg))
274 return Reg;
275
276 // Try to coalesce.
277 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000278 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000279 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000280 vrm_->clearVirt(cur.reg);
281 vrm_->assignVirt2Phys(cur.reg, SrcReg);
282 ++NumCoalesce;
283 return SrcReg;
284 }
285
286 return Reg;
287}
288
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000289bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000290 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000291 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000292 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000293 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000294 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000295 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000297 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000298 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000299
David Greene2c17c4d2007-09-06 16:18:45 +0000300 // We don't run the coalescer here because we have no reason to
301 // interact with it. If the coalescer requires interaction, it
302 // won't do anything. If it doesn't require interaction, we assume
303 // it was run as a separate pass.
304
Chris Lattnerb9805782005-08-23 22:27:31 +0000305 // If this is the first function compiled, compute the related reg classes.
306 if (RelatedRegClasses.empty())
307 ComputeRelatedRegClasses();
308
Dan Gohman6f0d0242008-02-10 18:45:23 +0000309 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Owen Anderson49c8aa02009-03-13 05:55:11 +0000310 vrm_ = &getAnalysis<VirtRegMap>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000312
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000314
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000316
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000317 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000318 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattnercbb56252004-11-18 02:42:27 +0000319
Dan Gohman51cd9d62008-06-23 23:51:16 +0000320 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000321 fixed_.clear();
322 active_.clear();
323 inactive_.clear();
324 handled_.clear();
325
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000326 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000327}
328
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000329/// initIntervalSets - initialize the interval sets.
330///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000331void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000332{
333 assert(unhandled_.empty() && fixed_.empty() &&
334 active_.empty() && inactive_.empty() &&
335 "interval sets should be empty on initialization");
336
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000337 handled_.reserve(li_->getNumIntervals());
338
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000339 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000340 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000341 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000342 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000343 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000344 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000345 }
346}
347
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000348void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000349{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000351 DOUT << "********** LINEAR SCAN **********\n";
352 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000353
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000355
356 while (!unhandled_.empty()) {
357 // pick the interval with the earliest start point
358 LiveInterval* cur = unhandled_.top();
359 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000360 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000361 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362
Evan Chengf30a49d2008-04-03 16:40:27 +0000363 if (!cur->empty()) {
364 processActiveIntervals(cur->beginNumber());
365 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366
Evan Chengf30a49d2008-04-03 16:40:27 +0000367 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
368 "Can only allocate virtual registers!");
369 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000370
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000371 // Allocating a virtual register. try to find a free
372 // physical register or spill an interval (possibly this one) in order to
373 // assign it one.
374 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000375
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000376 DEBUG(printIntervals("active", active_.begin(), active_.end()));
377 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000379
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000381 while (!active_.empty()) {
382 IntervalPtr &IP = active_.back();
383 unsigned reg = IP.first->reg;
384 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000385 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000386 "Can only allocate virtual registers!");
387 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000389 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000391
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000393 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000394 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000395 DOUT << "\tinterval " << *i->first << " expired\n");
396 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000397
Evan Cheng81a03822007-11-17 00:40:40 +0000398 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000399 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000400 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000401 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000402 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000404 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000405 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000406 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000407 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000408 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000409 if (!Reg)
410 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000411 // Ignore splited live intervals.
412 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
413 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000414 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
415 I != E; ++I) {
416 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000417 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000418 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
419 if (LiveInMBBs[i] != EntryMBB)
420 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000421 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000422 }
423 }
424 }
425
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000426 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000427}
428
Chris Lattnercbb56252004-11-18 02:42:27 +0000429/// processActiveIntervals - expire old intervals and move non-overlapping ones
430/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000431void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000432{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000433 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000434
Chris Lattnercbb56252004-11-18 02:42:27 +0000435 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
436 LiveInterval *Interval = active_[i].first;
437 LiveInterval::iterator IntervalPos = active_[i].second;
438 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000439
Chris Lattnercbb56252004-11-18 02:42:27 +0000440 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
441
442 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000443 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000444 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000445 "Can only allocate virtual registers!");
446 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000447 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000448
449 // Pop off the end of the list.
450 active_[i] = active_.back();
451 active_.pop_back();
452 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000453
Chris Lattnercbb56252004-11-18 02:42:27 +0000454 } else if (IntervalPos->start > CurPoint) {
455 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000456 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000457 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000458 "Can only allocate virtual registers!");
459 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000461 // add to inactive.
462 inactive_.push_back(std::make_pair(Interval, IntervalPos));
463
464 // Pop off the end of the list.
465 active_[i] = active_.back();
466 active_.pop_back();
467 --i; --e;
468 } else {
469 // Otherwise, just update the iterator position.
470 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 }
472 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000473}
474
Chris Lattnercbb56252004-11-18 02:42:27 +0000475/// processInactiveIntervals - expire old intervals and move overlapping
476/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000477void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000478{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000479 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000480
Chris Lattnercbb56252004-11-18 02:42:27 +0000481 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
482 LiveInterval *Interval = inactive_[i].first;
483 LiveInterval::iterator IntervalPos = inactive_[i].second;
484 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000485
Chris Lattnercbb56252004-11-18 02:42:27 +0000486 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000487
Chris Lattnercbb56252004-11-18 02:42:27 +0000488 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000489 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000490
Chris Lattnercbb56252004-11-18 02:42:27 +0000491 // Pop off the end of the list.
492 inactive_[i] = inactive_.back();
493 inactive_.pop_back();
494 --i; --e;
495 } else if (IntervalPos->start <= CurPoint) {
496 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000497 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000498 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000499 "Can only allocate virtual registers!");
500 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000501 prt_->addRegUse(reg);
502 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000503 active_.push_back(std::make_pair(Interval, IntervalPos));
504
505 // Pop off the end of the list.
506 inactive_[i] = inactive_.back();
507 inactive_.pop_back();
508 --i; --e;
509 } else {
510 // Otherwise, just update the iterator position.
511 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000512 }
513 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000514}
515
Chris Lattnercbb56252004-11-18 02:42:27 +0000516/// updateSpillWeights - updates the spill weights of the specifed physical
517/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000518static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000519 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000520 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000521 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000522 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000523 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000524}
525
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000526static
527RALinScan::IntervalPtrs::iterator
528FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
529 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
530 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000531 if (I->first == LI) return I;
532 return IP.end();
533}
534
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000535static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000536 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000537 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000538 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
539 IP.second, Point);
540 if (I != IP.first->begin()) --I;
541 IP.second = I;
542 }
543}
Chris Lattnercbb56252004-11-18 02:42:27 +0000544
Evan Cheng3f32d652008-06-04 09:18:41 +0000545/// addStackInterval - Create a LiveInterval for stack if the specified live
546/// interval has been spilled.
547static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000548 LiveIntervals *li_, float &Weight,
549 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000550 int SS = vrm_.getStackSlot(cur->reg);
551 if (SS == VirtRegMap::NO_STACK_SLOT)
552 return;
553 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000554 SI.weight += Weight;
555
Evan Cheng3f32d652008-06-04 09:18:41 +0000556 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000557 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000558 VNI = SI.getValNumInfo(0);
559 else
560 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
561
562 LiveInterval &RI = li_->getInterval(cur->reg);
563 // FIXME: This may be overly conservative.
564 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000565}
566
Evan Cheng3e172252008-06-20 21:45:16 +0000567/// getConflictWeight - Return the number of conflicts between cur
568/// live interval and defs and uses of Reg weighted by loop depthes.
569static float getConflictWeight(LiveInterval *cur, unsigned Reg,
570 LiveIntervals *li_,
571 MachineRegisterInfo *mri_,
572 const MachineLoopInfo *loopInfo) {
573 float Conflicts = 0;
574 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
575 E = mri_->reg_end(); I != E; ++I) {
576 MachineInstr *MI = &*I;
577 if (cur->liveAt(li_->getInstructionIndex(MI))) {
578 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
579 Conflicts += powf(10.0f, (float)loopDepth);
580 }
581 }
582 return Conflicts;
583}
584
585/// findIntervalsToSpill - Determine the intervals to spill for the
586/// specified interval. It's passed the physical registers whose spill
587/// weight is the lowest among all the registers whose live intervals
588/// conflict with the interval.
589void RALinScan::findIntervalsToSpill(LiveInterval *cur,
590 std::vector<std::pair<unsigned,float> > &Candidates,
591 unsigned NumCands,
592 SmallVector<LiveInterval*, 8> &SpillIntervals) {
593 // We have figured out the *best* register to spill. But there are other
594 // registers that are pretty good as well (spill weight within 3%). Spill
595 // the one that has fewest defs and uses that conflict with cur.
596 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
597 SmallVector<LiveInterval*, 8> SLIs[3];
598
599 DOUT << "\tConsidering " << NumCands << " candidates: ";
600 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
601 DOUT << tri_->getName(Candidates[i].first) << " ";
602 DOUT << "\n";);
603
604 // Calculate the number of conflicts of each candidate.
605 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
606 unsigned Reg = i->first->reg;
607 unsigned PhysReg = vrm_->getPhys(Reg);
608 if (!cur->overlapsFrom(*i->first, i->second))
609 continue;
610 for (unsigned j = 0; j < NumCands; ++j) {
611 unsigned Candidate = Candidates[j].first;
612 if (tri_->regsOverlap(PhysReg, Candidate)) {
613 if (NumCands > 1)
614 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
615 SLIs[j].push_back(i->first);
616 }
617 }
618 }
619
620 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
621 unsigned Reg = i->first->reg;
622 unsigned PhysReg = vrm_->getPhys(Reg);
623 if (!cur->overlapsFrom(*i->first, i->second-1))
624 continue;
625 for (unsigned j = 0; j < NumCands; ++j) {
626 unsigned Candidate = Candidates[j].first;
627 if (tri_->regsOverlap(PhysReg, Candidate)) {
628 if (NumCands > 1)
629 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
630 SLIs[j].push_back(i->first);
631 }
632 }
633 }
634
635 // Which is the best candidate?
636 unsigned BestCandidate = 0;
637 float MinConflicts = Conflicts[0];
638 for (unsigned i = 1; i != NumCands; ++i) {
639 if (Conflicts[i] < MinConflicts) {
640 BestCandidate = i;
641 MinConflicts = Conflicts[i];
642 }
643 }
644
645 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
646 std::back_inserter(SpillIntervals));
647}
648
649namespace {
650 struct WeightCompare {
651 typedef std::pair<unsigned, float> RegWeightPair;
652 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
653 return LHS.second < RHS.second;
654 }
655 };
656}
657
658static bool weightsAreClose(float w1, float w2) {
659 if (!NewHeuristic)
660 return false;
661
662 float diff = w1 - w2;
663 if (diff <= 0.02f) // Within 0.02f
664 return true;
665 return (diff / w2) <= 0.05f; // Within 5%.
666}
667
Chris Lattnercbb56252004-11-18 02:42:27 +0000668/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
669/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000670void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000671{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000672 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000673
Evan Chengf30a49d2008-04-03 16:40:27 +0000674 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000675 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000676 if (cur->empty()) {
677 unsigned physReg = cur->preference;
678 if (!physReg)
679 physReg = *RC->allocation_order_begin(*mf_);
680 DOUT << tri_->getName(physReg) << '\n';
681 // Note the register is not really in use.
682 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000683 return;
684 }
685
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000686 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000687
Chris Lattnera6c17502005-08-22 20:20:42 +0000688 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000689 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000690 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000691
Evan Chengd0deec22009-01-20 00:16:18 +0000692 // If start of this live interval is defined by a move instruction and its
693 // source is assigned a physical register that is compatible with the target
694 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000695 // This can happen when the move is from a larger register class to a smaller
696 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000697 if (!cur->preference && cur->hasAtLeastOneValue()) {
698 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000699 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
700 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000701 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
702 if (CopyMI &&
703 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000704 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000705 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000706 Reg = SrcReg;
707 else if (vrm_->isAssignedReg(SrcReg))
708 Reg = vrm_->getPhys(SrcReg);
709 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
710 cur->preference = Reg;
711 }
712 }
713 }
714
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000715 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000716 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000717 for (IntervalPtrs::const_iterator i = inactive_.begin(),
718 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000719 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000720 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000721 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000722 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000723 // If this is not in a related reg class to the register we're allocating,
724 // don't check it.
725 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
726 cur->overlapsFrom(*i->first, i->second-1)) {
727 Reg = vrm_->getPhys(Reg);
728 prt_->addRegUse(Reg);
729 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000730 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000731 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000732
733 // Speculatively check to see if we can get a register right now. If not,
734 // we know we won't be able to by adding more constraints. If so, we can
735 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
736 // is very bad (it contains all callee clobbered registers for any functions
737 // with a call), so we want to avoid doing that if possible.
738 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000739 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000740 if (physReg) {
741 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000742 // conflict with it. Check to see if we conflict with it or any of its
743 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000744 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000745 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000746 RegAliases.insert(*AS);
747
Chris Lattnera411cbc2005-08-22 20:59:30 +0000748 bool ConflictsWithFixed = false;
749 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000750 IntervalPtr &IP = fixed_[i];
751 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000752 // Okay, this reg is on the fixed list. Check to see if we actually
753 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000754 LiveInterval *I = IP.first;
755 if (I->endNumber() > StartPosition) {
756 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
757 IP.second = II;
758 if (II != I->begin() && II->start > StartPosition)
759 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000760 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000761 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000762 break;
763 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000764 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000765 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000766 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000767
768 // Okay, the register picked by our speculative getFreePhysReg call turned
769 // out to be in use. Actually add all of the conflicting fixed registers to
770 // prt so we can do an accurate query.
771 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000772 // For every interval in fixed we overlap with, mark the register as not
773 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000774 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
775 IntervalPtr &IP = fixed_[i];
776 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000777
778 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
779 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
780 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000781 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
782 IP.second = II;
783 if (II != I->begin() && II->start > StartPosition)
784 --II;
785 if (cur->overlapsFrom(*I, II)) {
786 unsigned reg = I->reg;
787 prt_->addRegUse(reg);
788 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
789 }
790 }
791 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000792
Chris Lattnera411cbc2005-08-22 20:59:30 +0000793 // Using the newly updated prt_ object, which includes conflicts in the
794 // future, see if there are any registers available.
795 physReg = getFreePhysReg(cur);
796 }
797 }
798
Chris Lattnera6c17502005-08-22 20:20:42 +0000799 // Restore the physical register tracker, removing information about the
800 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000801 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000802
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000803 // if we find a free register, we are done: assign this virtual to
804 // the free physical register and add this interval to the active
805 // list.
806 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000807 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000808 vrm_->assignVirt2Phys(cur->reg, physReg);
809 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000810 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000811 handled_.push_back(cur);
812 return;
813 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000814 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000815
Chris Lattnera6c17502005-08-22 20:20:42 +0000816 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000817 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000818 for (std::vector<std::pair<unsigned, float> >::iterator
819 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000820 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000821
822 // for each interval in active, update spill weights.
823 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
824 i != e; ++i) {
825 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000826 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000827 "Can only allocate virtual registers!");
828 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000829 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000830 }
831
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000832 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000833
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000834 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000835 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000836 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
837
838 bool Found = false;
839 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000840 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
841 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
842 e = RC->allocation_order_end(*mf_); i != e; ++i) {
843 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000844 float regWeight = SpillWeights[reg];
845 if (minWeight > regWeight)
846 Found = true;
847 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000848 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000849
850 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000851 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000852 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
853 e = RC->allocation_order_end(*mf_); i != e; ++i) {
854 unsigned reg = *i;
855 // No need to worry about if the alias register size < regsize of RC.
856 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000857 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
858 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000859 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000860 }
Evan Cheng3e172252008-06-20 21:45:16 +0000861
862 // Sort all potential spill candidates by weight.
863 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
864 minReg = RegsWeights[0].first;
865 minWeight = RegsWeights[0].second;
866 if (minWeight == HUGE_VALF) {
867 // All registers must have inf weight. Just grab one!
868 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000869 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000870 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000871 // Spill a physical register around defs and uses.
Evan Cheng2824a652009-03-23 18:24:37 +0000872 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_))
873 assignRegOrStackSlotAtInterval(cur);
874 else {
875 cerr << "Ran out of registers during register allocation!\n";
876 exit(1);
877 }
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000878 return;
879 }
Evan Cheng3e172252008-06-20 21:45:16 +0000880 }
881
882 // Find up to 3 registers to consider as spill candidates.
883 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
884 while (LastCandidate > 1) {
885 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
886 break;
887 --LastCandidate;
888 }
889
890 DOUT << "\t\tregister(s) with min weight(s): ";
891 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
892 DOUT << tri_->getName(RegsWeights[i].first)
893 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000894
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000895 // if the current has the minimum weight, we need to spill it and
896 // add any added intervals back to unhandled, and restart
897 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000898 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000899 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000900 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000901 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000902 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000903 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000904 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000905 if (added.empty())
906 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000907
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000908 // Merge added with unhandled. Note that we know that
909 // addIntervalsForSpills returns intervals sorted by their starting
910 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000911 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000912 unhandled_.push(added[i]);
913 return;
914 }
915
Chris Lattner19828d42004-11-18 03:49:30 +0000916 ++NumBacktracks;
917
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000918 // push the current interval back to unhandled since we are going
919 // to re-run at least this iteration. Since we didn't modify it it
920 // should go back right in the front of the list
921 unhandled_.push(cur);
922
Dan Gohman6f0d0242008-02-10 18:45:23 +0000923 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000924 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000925
Evan Cheng3e172252008-06-20 21:45:16 +0000926 // We spill all intervals aliasing the register with
927 // minimum weight, rollback to the interval with the earliest
928 // start point and let the linear scan algorithm run again
929 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000930
Evan Cheng3e172252008-06-20 21:45:16 +0000931 // Determine which intervals have to be spilled.
932 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
933
934 // Set of spilled vregs (used later to rollback properly)
935 SmallSet<unsigned, 8> spilled;
936
937 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000938 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000939 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000940
Evan Cheng3e172252008-06-20 21:45:16 +0000941 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000942 // want to clear (and its aliases). We only spill those that overlap with the
943 // current interval as the rest do not affect its allocation. we also keep
944 // track of the earliest start of all spilled live intervals since this will
945 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000946 std::vector<LiveInterval*> added;
947 while (!spillIs.empty()) {
948 LiveInterval *sli = spillIs.back();
949 spillIs.pop_back();
950 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
951 earliestStart = std::min(earliestStart, sli->beginNumber());
952 float SSWeight;
953 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000954 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000955 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
956 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
957 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000958 }
959
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000960 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000961
962 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000963 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000964 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000965 while (!handled_.empty()) {
966 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000967 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000968 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000969 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000970 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000971 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000972
973 // When undoing a live interval allocation we must know if it is active or
974 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000975 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000976 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000977 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000978 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000979 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000980 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000981 prt_->delRegUse(vrm_->getPhys(i->reg));
982 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000983 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000984 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000985 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000986 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000987 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000988 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000989 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000990 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000991 "Can only allocate virtual registers!");
992 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000993 unhandled_.push(i);
994 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000995
996 // It interval has a preference, it must be defined by a copy. Clear the
997 // preference now since the source interval allocation may have been undone
998 // as well.
999 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001000 }
1001
Chris Lattner19828d42004-11-18 03:49:30 +00001002 // Rewind the iterators in the active, inactive, and fixed lists back to the
1003 // point we reverted to.
1004 RevertVectorIteratorsTo(active_, earliestStart);
1005 RevertVectorIteratorsTo(inactive_, earliestStart);
1006 RevertVectorIteratorsTo(fixed_, earliestStart);
1007
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001008 // scan the rest and undo each interval that expired after t and
1009 // insert it in active (the next iteration of the algorithm will
1010 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001011 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1012 LiveInterval *HI = handled_[i];
1013 if (!HI->expiredAt(earliestStart) &&
1014 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001015 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001016 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001017 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001018 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001019 }
1020 }
1021
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001022 // merge added with unhandled
1023 for (unsigned i = 0, e = added.size(); i != e; ++i)
1024 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001025}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001026
Chris Lattnercbb56252004-11-18 02:42:27 +00001027/// getFreePhysReg - return a free physical register for this virtual register
1028/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001029unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001030 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001031 unsigned MaxInactiveCount = 0;
1032
Evan Cheng841ee1a2008-09-18 22:38:47 +00001033 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001034 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1035
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001036 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1037 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001038 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001039 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001040 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001041
1042 // If this is not in a related reg class to the register we're allocating,
1043 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001044 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001045 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1046 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001047 if (inactiveCounts.size() <= reg)
1048 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001049 ++inactiveCounts[reg];
1050 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1051 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001052 }
1053
Chris Lattnerf8355d92005-08-22 16:55:22 +00001054 unsigned FreeReg = 0;
1055 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001056
1057 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001058 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001059 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001060 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001061 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001062 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001063 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001064 return cur->preference;
1065 } else
1066 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001067 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001068 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001069
Chris Lattnerf8355d92005-08-22 16:55:22 +00001070 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001071 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1072 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001073 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001074 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001075 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001076 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001077 if (FreeReg < inactiveCounts.size())
1078 FreeRegInactiveCount = inactiveCounts[FreeReg];
1079 else
1080 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001081 break;
1082 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001083
Chris Lattnerf8355d92005-08-22 16:55:22 +00001084 // If there are no free regs, or if this reg has the max inactive count,
1085 // return this register.
1086 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1087
1088 // Continue scanning the registers, looking for the one with the highest
1089 // inactive count. Alkis found that this reduced register pressure very
1090 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1091 // reevaluated now.
1092 for (; I != E; ++I) {
1093 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001094 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001095 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001096 FreeReg = Reg;
1097 FreeRegInactiveCount = inactiveCounts[Reg];
1098 if (FreeRegInactiveCount == MaxInactiveCount)
1099 break; // We found the one with the max inactive count.
1100 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001101 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001102
1103 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001104}
1105
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001106FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001107 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001108}