blob: e77a9e6839e8c029999f2e4041dd44751cb63046 [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Lattner3c3fe462005-09-21 04:19:09 +000015#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000016#include "PhysRegTracker.h"
17#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000019#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000022#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000023#include "llvm/CodeGen/RegisterCoalescer.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/SSARegMap.h"
25#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000026#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000027#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000028#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000031#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000032#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000033#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000034#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000035#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000036#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000037#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000038using namespace llvm;
39
Chris Lattnercd3245a2006-12-19 22:41:21 +000040STATISTIC(NumIters , "Number of iterations performed");
41STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000042STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000043
44static RegisterRegAlloc
45linearscanRegAlloc("linearscan", " linear scan register allocator",
46 createLinearScanRegisterAllocator);
47
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000048namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000049 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000050 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000051 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000052
Chris Lattnercbb56252004-11-18 02:42:27 +000053 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
54 typedef std::vector<IntervalPtr> IntervalPtrs;
55 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000056 /// RelatedRegClasses - This structure is built the first time a function is
57 /// compiled, and keeps track of which register classes have registers that
58 /// belong to multiple classes or have aliases that are in other classes.
59 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
60 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
61
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 MachineFunction* mf_;
63 const TargetMachine* tm_;
64 const MRegisterInfo* mri_;
Evan Chengc92da382007-11-03 07:20:12 +000065 const TargetInstrInfo* tii_;
66 SSARegMap *regmap_;
67 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 LiveIntervals* li_;
Chris Lattnercbb56252004-11-18 02:42:27 +000069
70 /// handled_ - Intervals are added to the handled_ set in the order of their
71 /// start value. This is uses for backtracking.
72 std::vector<LiveInterval*> handled_;
73
74 /// fixed_ - Intervals that correspond to machine registers.
75 ///
76 IntervalPtrs fixed_;
77
78 /// active_ - Intervals that are currently being processed, and which have a
79 /// live range active for the current point.
80 IntervalPtrs active_;
81
82 /// inactive_ - Intervals that are currently being processed, but which have
83 /// a hold at the current point.
84 IntervalPtrs inactive_;
85
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000086 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000087 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 greater_ptr<LiveInterval> > IntervalHeap;
89 IntervalHeap unhandled_;
90 std::auto_ptr<PhysRegTracker> prt_;
91 std::auto_ptr<VirtRegMap> vrm_;
92 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000093
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000094 public:
95 virtual const char* getPassName() const {
96 return "Linear Scan Register Allocator";
97 }
98
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000100 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000101 // Make sure PassManager knows which analyses to make available
102 // to coalescing and which analyses coalescing invalidates.
103 AU.addRequiredTransitive<RegisterCoalescer>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 MachineFunctionPass::getAnalysisUsage(AU);
105 }
106
107 /// runOnMachineFunction - register allocate the whole function
108 bool runOnMachineFunction(MachineFunction&);
109
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000110 private:
111 /// linearScan - the linear scan algorithm
112 void linearScan();
113
Chris Lattnercbb56252004-11-18 02:42:27 +0000114 /// initIntervalSets - initialize the interval sets.
115 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116 void initIntervalSets();
117
Chris Lattnercbb56252004-11-18 02:42:27 +0000118 /// processActiveIntervals - expire old intervals and move non-overlapping
119 /// ones to the inactive list.
120 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121
Chris Lattnercbb56252004-11-18 02:42:27 +0000122 /// processInactiveIntervals - expire old intervals and move overlapping
123 /// ones to the active list.
124 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126 /// assignRegOrStackSlotAtInterval - assign a register if one
127 /// is available, or spill.
128 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
129
Evan Chengc92da382007-11-03 07:20:12 +0000130 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
131 /// try allocate the definition the same register as the source register
132 /// if the register is not defined during live time of the interval. This
133 /// eliminate a copy. This is used to coalesce copies which were not
134 /// coalesced away before allocation either due to dest and src being in
135 /// different register classes or because the coalescer was overly
136 /// conservative.
137 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
138
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000139 ///
140 /// register handling helpers
141 ///
142
Chris Lattnercbb56252004-11-18 02:42:27 +0000143 /// getFreePhysReg - return a free physical register for this virtual
144 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145 unsigned getFreePhysReg(LiveInterval* cur);
146
147 /// assignVirt2StackSlot - assigns this virtual register to a
148 /// stack slot. returns the stack slot
149 int assignVirt2StackSlot(unsigned virtReg);
150
Chris Lattnerb9805782005-08-23 22:27:31 +0000151 void ComputeRelatedRegClasses();
152
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000153 template <typename ItTy>
154 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000155 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000156 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000157 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000158 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000159 if (MRegisterInfo::isVirtualRegister(reg)) {
160 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000161 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000162 DOUT << mri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000163 }
164 }
165 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000166 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000167}
168
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000169void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000170 const MRegisterInfo &MRI = *mri_;
171
172 // First pass, add all reg classes to the union, and determine at least one
173 // reg class that each register is in.
174 bool HasAliases = false;
175 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
176 E = MRI.regclass_end(); RCI != E; ++RCI) {
177 RelatedRegClasses.insert(*RCI);
178 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
179 I != E; ++I) {
180 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
181
182 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
183 if (PRC) {
184 // Already processed this register. Just make sure we know that
185 // multiple register classes share a register.
186 RelatedRegClasses.unionSets(PRC, *RCI);
187 } else {
188 PRC = *RCI;
189 }
190 }
191 }
192
193 // Second pass, now that we know conservatively what register classes each reg
194 // belongs to, add info about aliases. We don't need to do this for targets
195 // without register aliases.
196 if (HasAliases)
197 for (std::map<unsigned, const TargetRegisterClass*>::iterator
198 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
199 I != E; ++I)
200 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
201 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
202}
203
Evan Chengc92da382007-11-03 07:20:12 +0000204/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
205/// try allocate the definition the same register as the source register
206/// if the register is not defined during live time of the interval. This
207/// eliminate a copy. This is used to coalesce copies which were not
208/// coalesced away before allocation either due to dest and src being in
209/// different register classes or because the coalescer was overly
210/// conservative.
211unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000212 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000213 return Reg;
214
215 VNInfo *vni = cur.getValNumInfo(0);
216 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
217 return Reg;
218 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
219 unsigned SrcReg, DstReg;
220 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
221 return Reg;
222 if (MRegisterInfo::isVirtualRegister(SrcReg))
223 if (!vrm_->isAssignedReg(SrcReg))
224 return Reg;
225 else
226 SrcReg = vrm_->getPhys(SrcReg);
227 if (Reg == SrcReg)
228 return Reg;
229
230 const TargetRegisterClass *RC = regmap_->getRegClass(cur.reg);
231 if (!RC->contains(SrcReg))
232 return Reg;
233
234 // Try to coalesce.
235 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
236 vrm_->clearVirt(cur.reg);
237 vrm_->assignVirt2Phys(cur.reg, SrcReg);
238 ++NumCoalesce;
239 return SrcReg;
240 }
241
242 return Reg;
243}
244
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000245bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000246 mf_ = &fn;
247 tm_ = &fn.getTarget();
248 mri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000249 tii_ = tm_->getInstrInfo();
250 regmap_ = mf_->getSSARegMap();
251 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000253
David Greene2c17c4d2007-09-06 16:18:45 +0000254 // We don't run the coalescer here because we have no reason to
255 // interact with it. If the coalescer requires interaction, it
256 // won't do anything. If it doesn't require interaction, we assume
257 // it was run as a separate pass.
258
Chris Lattnerb9805782005-08-23 22:27:31 +0000259 // If this is the first function compiled, compute the related reg classes.
260 if (RelatedRegClasses.empty())
261 ComputeRelatedRegClasses();
262
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000263 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
264 vrm_.reset(new VirtRegMap(*mf_));
265 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000266
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000267 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000268
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000270
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000271 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000272 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000273 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000274
Chris Lattnercbb56252004-11-18 02:42:27 +0000275 while (!unhandled_.empty()) unhandled_.pop();
276 fixed_.clear();
277 active_.clear();
278 inactive_.clear();
279 handled_.clear();
280
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000282}
283
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000284/// initIntervalSets - initialize the interval sets.
285///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000286void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000287{
288 assert(unhandled_.empty() && fixed_.empty() &&
289 active_.empty() && inactive_.empty() &&
290 "interval sets should be empty on initialization");
291
292 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000293 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000294 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000295 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000296 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000297 unhandled_.push(&i->second);
298 }
299}
300
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000301void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000302{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000304 DOUT << "********** LINEAR SCAN **********\n";
305 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000306
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000307 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308
309 while (!unhandled_.empty()) {
310 // pick the interval with the earliest start point
311 LiveInterval* cur = unhandled_.top();
312 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000313 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000314 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315
Chris Lattnercbb56252004-11-18 02:42:27 +0000316 processActiveIntervals(cur->beginNumber());
317 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000318
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000319 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
320 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000321
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000322 // Allocating a virtual register. try to find a free
323 // physical register or spill an interval (possibly this one) in order to
324 // assign it one.
325 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000326
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000327 DEBUG(printIntervals("active", active_.begin(), active_.end()));
328 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000329 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000330
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000331 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000332 while (!active_.empty()) {
333 IntervalPtr &IP = active_.back();
334 unsigned reg = IP.first->reg;
335 DOUT << "\tinterval " << *IP.first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000336 assert(MRegisterInfo::isVirtualRegister(reg) &&
337 "Can only allocate virtual registers!");
338 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000339 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000340 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000341 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000342
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000344 DEBUG(for (IntervalPtrs::reverse_iterator
345 i = inactive_.rbegin(); i != inactive_.rend(); )
346 DOUT << "\tinterval " << *i->first << " expired\n");
347 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000348
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000349 // Add live-ins to every BB except for entry.
350 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000351 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000352 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000353 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000354 unsigned Reg = 0;
355 if (MRegisterInfo::isPhysicalRegister(cur.reg))
356 Reg = i->second.reg;
357 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000358 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000359 if (!Reg)
360 continue;
361 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
362 I != E; ++I) {
363 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000364 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
365 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
366 if (LiveInMBBs[i] != EntryMBB)
367 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000368 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000369 }
370 }
371 }
372
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000373 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000374}
375
Chris Lattnercbb56252004-11-18 02:42:27 +0000376/// processActiveIntervals - expire old intervals and move non-overlapping ones
377/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000378void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000379{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000380 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000381
Chris Lattnercbb56252004-11-18 02:42:27 +0000382 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
383 LiveInterval *Interval = active_[i].first;
384 LiveInterval::iterator IntervalPos = active_[i].second;
385 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000386
Chris Lattnercbb56252004-11-18 02:42:27 +0000387 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
388
389 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000390 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000391 assert(MRegisterInfo::isVirtualRegister(reg) &&
392 "Can only allocate virtual registers!");
393 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000394 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000395
396 // Pop off the end of the list.
397 active_[i] = active_.back();
398 active_.pop_back();
399 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000400
Chris Lattnercbb56252004-11-18 02:42:27 +0000401 } else if (IntervalPos->start > CurPoint) {
402 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000403 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000404 assert(MRegisterInfo::isVirtualRegister(reg) &&
405 "Can only allocate virtual registers!");
406 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000408 // add to inactive.
409 inactive_.push_back(std::make_pair(Interval, IntervalPos));
410
411 // Pop off the end of the list.
412 active_[i] = active_.back();
413 active_.pop_back();
414 --i; --e;
415 } else {
416 // Otherwise, just update the iterator position.
417 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000418 }
419 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000420}
421
Chris Lattnercbb56252004-11-18 02:42:27 +0000422/// processInactiveIntervals - expire old intervals and move overlapping
423/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000424void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000425{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000426 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000427
Chris Lattnercbb56252004-11-18 02:42:27 +0000428 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
429 LiveInterval *Interval = inactive_[i].first;
430 LiveInterval::iterator IntervalPos = inactive_[i].second;
431 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000432
Chris Lattnercbb56252004-11-18 02:42:27 +0000433 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000434
Chris Lattnercbb56252004-11-18 02:42:27 +0000435 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000436 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000437
Chris Lattnercbb56252004-11-18 02:42:27 +0000438 // Pop off the end of the list.
439 inactive_[i] = inactive_.back();
440 inactive_.pop_back();
441 --i; --e;
442 } else if (IntervalPos->start <= CurPoint) {
443 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000444 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000445 assert(MRegisterInfo::isVirtualRegister(reg) &&
446 "Can only allocate virtual registers!");
447 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 prt_->addRegUse(reg);
449 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000450 active_.push_back(std::make_pair(Interval, IntervalPos));
451
452 // Pop off the end of the list.
453 inactive_[i] = inactive_.back();
454 inactive_.pop_back();
455 --i; --e;
456 } else {
457 // Otherwise, just update the iterator position.
458 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 }
460 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000461}
462
Chris Lattnercbb56252004-11-18 02:42:27 +0000463/// updateSpillWeights - updates the spill weights of the specifed physical
464/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000465static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000466 unsigned reg, float weight,
467 const MRegisterInfo *MRI) {
468 Weights[reg] += weight;
469 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
470 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000471}
472
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000473static
474RALinScan::IntervalPtrs::iterator
475FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
476 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
477 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000478 if (I->first == LI) return I;
479 return IP.end();
480}
481
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000482static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000483 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000484 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000485 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
486 IP.second, Point);
487 if (I != IP.first->begin()) --I;
488 IP.second = I;
489 }
490}
Chris Lattnercbb56252004-11-18 02:42:27 +0000491
Chris Lattnercbb56252004-11-18 02:42:27 +0000492/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
493/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000494void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000495{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000496 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000497
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000499
Chris Lattnera6c17502005-08-22 20:20:42 +0000500 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000501 unsigned StartPosition = cur->beginNumber();
Evan Chengc92da382007-11-03 07:20:12 +0000502 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000503 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000504
505 // If this live interval is defined by a move instruction and its source is
506 // assigned a physical register that is compatible with the target register
507 // class, then we should try to assign it the same register.
508 // This can happen when the move is from a larger register class to a smaller
509 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
510 if (!cur->preference && cur->containsOneValue()) {
511 VNInfo *vni = cur->getValNumInfo(0);
512 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
513 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
514 unsigned SrcReg, DstReg;
515 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
516 unsigned Reg = 0;
517 if (MRegisterInfo::isPhysicalRegister(SrcReg))
518 Reg = SrcReg;
519 else if (vrm_->isAssignedReg(SrcReg))
520 Reg = vrm_->getPhys(SrcReg);
521 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
522 cur->preference = Reg;
523 }
524 }
525 }
526
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000528 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000529 for (IntervalPtrs::const_iterator i = inactive_.begin(),
530 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000531 unsigned Reg = i->first->reg;
532 assert(MRegisterInfo::isVirtualRegister(Reg) &&
533 "Can only allocate virtual registers!");
Evan Chengc92da382007-11-03 07:20:12 +0000534 const TargetRegisterClass *RegRC = regmap_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000535 // If this is not in a related reg class to the register we're allocating,
536 // don't check it.
537 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
538 cur->overlapsFrom(*i->first, i->second-1)) {
539 Reg = vrm_->getPhys(Reg);
540 prt_->addRegUse(Reg);
541 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000542 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000544
545 // Speculatively check to see if we can get a register right now. If not,
546 // we know we won't be able to by adding more constraints. If so, we can
547 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
548 // is very bad (it contains all callee clobbered registers for any functions
549 // with a call), so we want to avoid doing that if possible.
550 unsigned physReg = getFreePhysReg(cur);
551 if (physReg) {
552 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000553 // conflict with it. Check to see if we conflict with it or any of its
554 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000555 SmallSet<unsigned, 8> RegAliases;
Chris Lattnere836ad62005-08-30 21:03:36 +0000556 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
557 RegAliases.insert(*AS);
558
Chris Lattnera411cbc2005-08-22 20:59:30 +0000559 bool ConflictsWithFixed = false;
560 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000561 IntervalPtr &IP = fixed_[i];
562 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000563 // Okay, this reg is on the fixed list. Check to see if we actually
564 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000565 LiveInterval *I = IP.first;
566 if (I->endNumber() > StartPosition) {
567 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
568 IP.second = II;
569 if (II != I->begin() && II->start > StartPosition)
570 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000571 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000572 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000573 break;
574 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000575 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000576 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000577 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000578
579 // Okay, the register picked by our speculative getFreePhysReg call turned
580 // out to be in use. Actually add all of the conflicting fixed registers to
581 // prt so we can do an accurate query.
582 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000583 // For every interval in fixed we overlap with, mark the register as not
584 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000585 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
586 IntervalPtr &IP = fixed_[i];
587 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000588
589 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
590 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
591 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000592 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
593 IP.second = II;
594 if (II != I->begin() && II->start > StartPosition)
595 --II;
596 if (cur->overlapsFrom(*I, II)) {
597 unsigned reg = I->reg;
598 prt_->addRegUse(reg);
599 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
600 }
601 }
602 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000603
Chris Lattnera411cbc2005-08-22 20:59:30 +0000604 // Using the newly updated prt_ object, which includes conflicts in the
605 // future, see if there are any registers available.
606 physReg = getFreePhysReg(cur);
607 }
608 }
609
Chris Lattnera6c17502005-08-22 20:20:42 +0000610 // Restore the physical register tracker, removing information about the
611 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000612 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000613
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000614 // if we find a free register, we are done: assign this virtual to
615 // the free physical register and add this interval to the active
616 // list.
617 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000618 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000619 vrm_->assignVirt2Phys(cur->reg, physReg);
620 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000621 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000622 handled_.push_back(cur);
623 return;
624 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000625 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000626
Chris Lattnera6c17502005-08-22 20:20:42 +0000627 // Compile the spill weights into an array that is better for scanning.
628 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
629 for (std::vector<std::pair<unsigned, float> >::iterator
630 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
631 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
632
633 // for each interval in active, update spill weights.
634 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
635 i != e; ++i) {
636 unsigned reg = i->first->reg;
637 assert(MRegisterInfo::isVirtualRegister(reg) &&
638 "Can only allocate virtual registers!");
639 reg = vrm_->getPhys(reg);
640 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
641 }
642
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000643 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000644
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000645 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000646 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000647 unsigned minReg = cur->preference; // Try the preferred register first.
648
649 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
650 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
651 e = RC->allocation_order_end(*mf_); i != e; ++i) {
652 unsigned reg = *i;
653 if (minWeight > SpillWeights[reg]) {
654 minWeight = SpillWeights[reg];
655 minReg = reg;
656 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000657 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000658
659 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000660 if (!minReg) {
661 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
662 e = RC->allocation_order_end(*mf_); i != e; ++i) {
663 unsigned reg = *i;
664 // No need to worry about if the alias register size < regsize of RC.
665 // We are going to spill all registers that alias it anyway.
666 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
667 if (minWeight > SpillWeights[*as]) {
668 minWeight = SpillWeights[*as];
669 minReg = *as;
670 }
671 }
672 }
673
674 // All registers must have inf weight. Just grab one!
675 if (!minReg)
676 minReg = *RC->allocation_order_begin(*mf_);
677 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000678
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000679 DOUT << "\t\tregister with min weight: "
680 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000681
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 // if the current has the minimum weight, we need to spill it and
683 // add any added intervals back to unhandled, and restart
684 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000685 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000686 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000687 std::vector<LiveInterval*> added =
Evan Chengf2fbca62007-11-12 06:35:08 +0000688 li_->addIntervalsForSpills(*cur, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000689 if (added.empty())
690 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000691
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000692 // Merge added with unhandled. Note that we know that
693 // addIntervalsForSpills returns intervals sorted by their starting
694 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000695 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000696 unhandled_.push(added[i]);
697 return;
698 }
699
Chris Lattner19828d42004-11-18 03:49:30 +0000700 ++NumBacktracks;
701
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 // push the current interval back to unhandled since we are going
703 // to re-run at least this iteration. Since we didn't modify it it
704 // should go back right in the front of the list
705 unhandled_.push(cur);
706
707 // otherwise we spill all intervals aliasing the register with
708 // minimum weight, rollback to the interval with the earliest
709 // start point and let the linear scan algorithm run again
710 std::vector<LiveInterval*> added;
711 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
712 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000713 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000714
715 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 toSpill[minReg] = true;
717 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
718 toSpill[*as] = true;
719
720 // the earliest start of a spilled interval indicates up to where
721 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000722 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000723
724 // set of spilled vregs (used later to rollback properly)
Evan Chengc92da382007-11-03 07:20:12 +0000725 SmallSet<unsigned, 32> spilled;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000726
Chris Lattner19828d42004-11-18 03:49:30 +0000727 // spill live intervals of virtual regs mapped to the physical register we
728 // want to clear (and its aliases). We only spill those that overlap with the
729 // current interval as the rest do not affect its allocation. we also keep
730 // track of the earliest start of all spilled live intervals since this will
731 // mark our rollback point.
732 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000733 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000734 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000735 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000736 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000737 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000738 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000739 std::vector<LiveInterval*> newIs =
Evan Chengf2fbca62007-11-12 06:35:08 +0000740 li_->addIntervalsForSpills(*i->first, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000741 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
742 spilled.insert(reg);
743 }
744 }
Chris Lattner19828d42004-11-18 03:49:30 +0000745 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000746 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000747 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000748 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000749 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000750 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000751 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000752 std::vector<LiveInterval*> newIs =
Evan Chengf2fbca62007-11-12 06:35:08 +0000753 li_->addIntervalsForSpills(*i->first, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000754 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
755 spilled.insert(reg);
756 }
757 }
758
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000759 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000760
761 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000762 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000763 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000764 while (!handled_.empty()) {
765 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000766 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000767 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000768 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000769 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000770 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000771
772 // When undoing a live interval allocation we must know if it is active or
773 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000774 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000775 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000776 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000777 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
778 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000780 prt_->delRegUse(vrm_->getPhys(i->reg));
781 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000782 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000783 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000784 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
785 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000787 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000788 } else {
789 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
790 "Can only allocate virtual registers!");
791 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000792 unhandled_.push(i);
793 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000794
795 // It interval has a preference, it must be defined by a copy. Clear the
796 // preference now since the source interval allocation may have been undone
797 // as well.
798 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000799 }
800
Chris Lattner19828d42004-11-18 03:49:30 +0000801 // Rewind the iterators in the active, inactive, and fixed lists back to the
802 // point we reverted to.
803 RevertVectorIteratorsTo(active_, earliestStart);
804 RevertVectorIteratorsTo(inactive_, earliestStart);
805 RevertVectorIteratorsTo(fixed_, earliestStart);
806
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000807 // scan the rest and undo each interval that expired after t and
808 // insert it in active (the next iteration of the algorithm will
809 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000810 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
811 LiveInterval *HI = handled_[i];
812 if (!HI->expiredAt(earliestStart) &&
813 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000814 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000815 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000816 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
817 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000818 }
819 }
820
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000821 // merge added with unhandled
822 for (unsigned i = 0, e = added.size(); i != e; ++i)
823 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000824}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000825
Chris Lattnercbb56252004-11-18 02:42:27 +0000826/// getFreePhysReg - return a free physical register for this virtual register
827/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000828unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000829 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000830 unsigned MaxInactiveCount = 0;
831
Evan Chengc92da382007-11-03 07:20:12 +0000832 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000833 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
834
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000835 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
836 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000837 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000838 assert(MRegisterInfo::isVirtualRegister(reg) &&
839 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000840
841 // If this is not in a related reg class to the register we're allocating,
842 // don't check it.
Evan Chengc92da382007-11-03 07:20:12 +0000843 const TargetRegisterClass *RegRC = regmap_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000844 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
845 reg = vrm_->getPhys(reg);
846 ++inactiveCounts[reg];
847 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
848 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000849 }
850
Chris Lattnerf8355d92005-08-22 16:55:22 +0000851 unsigned FreeReg = 0;
852 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000853
854 // If copy coalescer has assigned a "preferred" register, check if it's
855 // available first.
856 if (cur->preference)
857 if (prt_->isRegAvail(cur->preference)) {
858 DOUT << "\t\tassigned the preferred register: "
859 << mri_->getName(cur->preference) << "\n";
860 return cur->preference;
861 } else
862 DOUT << "\t\tunable to assign the preferred register: "
863 << mri_->getName(cur->preference) << "\n";
864
Chris Lattnerf8355d92005-08-22 16:55:22 +0000865 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000866 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
867 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000868 for (; I != E; ++I)
869 if (prt_->isRegAvail(*I)) {
870 FreeReg = *I;
871 FreeRegInactiveCount = inactiveCounts[FreeReg];
872 break;
873 }
874
875 // If there are no free regs, or if this reg has the max inactive count,
876 // return this register.
877 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
878
879 // Continue scanning the registers, looking for the one with the highest
880 // inactive count. Alkis found that this reduced register pressure very
881 // slightly on X86 (in rev 1.94 of this file), though this should probably be
882 // reevaluated now.
883 for (; I != E; ++I) {
884 unsigned Reg = *I;
885 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
886 FreeReg = Reg;
887 FreeRegInactiveCount = inactiveCounts[Reg];
888 if (FreeRegInactiveCount == MaxInactiveCount)
889 break; // We found the one with the max inactive count.
890 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000891 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000892
893 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000894}
895
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000896FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000897 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000898}