blob: bc9febff59a94a663564c09834de19608e997ac8 [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)) {
Bill Wendling5b8318a2007-11-15 02:06:30 +0000236 DOUT << "Coalescing: " << cur << " -> " << mri_->getName(SrcReg) << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000237 vrm_->clearVirt(cur.reg);
238 vrm_->assignVirt2Phys(cur.reg, SrcReg);
239 ++NumCoalesce;
240 return SrcReg;
241 }
242
243 return Reg;
244}
245
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000246bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000247 mf_ = &fn;
248 tm_ = &fn.getTarget();
249 mri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000250 tii_ = tm_->getInstrInfo();
251 regmap_ = mf_->getSSARegMap();
252 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000253 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000254
David Greene2c17c4d2007-09-06 16:18:45 +0000255 // We don't run the coalescer here because we have no reason to
256 // interact with it. If the coalescer requires interaction, it
257 // won't do anything. If it doesn't require interaction, we assume
258 // it was run as a separate pass.
259
Chris Lattnerb9805782005-08-23 22:27:31 +0000260 // If this is the first function compiled, compute the related reg classes.
261 if (RelatedRegClasses.empty())
262 ComputeRelatedRegClasses();
263
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000264 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
265 vrm_.reset(new VirtRegMap(*mf_));
266 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000267
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000269
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000270 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000271
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000272 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000273 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000274 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000275
Chris Lattnercbb56252004-11-18 02:42:27 +0000276 while (!unhandled_.empty()) unhandled_.pop();
277 fixed_.clear();
278 active_.clear();
279 inactive_.clear();
280 handled_.clear();
281
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000282 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000283}
284
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000285/// initIntervalSets - initialize the interval sets.
286///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000287void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000288{
289 assert(unhandled_.empty() && fixed_.empty() &&
290 active_.empty() && inactive_.empty() &&
291 "interval sets should be empty on initialization");
292
293 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000294 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000295 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000296 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000297 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000298 unhandled_.push(&i->second);
299 }
300}
301
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000302void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000303{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000304 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000305 DOUT << "********** LINEAR SCAN **********\n";
306 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000307
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000309
310 while (!unhandled_.empty()) {
311 // pick the interval with the earliest start point
312 LiveInterval* cur = unhandled_.top();
313 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000314 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000315 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316
Chris Lattnercbb56252004-11-18 02:42:27 +0000317 processActiveIntervals(cur->beginNumber());
318 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000319
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000320 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
321 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000322
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000323 // Allocating a virtual register. try to find a free
324 // physical register or spill an interval (possibly this one) in order to
325 // assign it one.
326 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000327
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000328 DEBUG(printIntervals("active", active_.begin(), active_.end()));
329 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000330 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000331
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000332 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000333 while (!active_.empty()) {
334 IntervalPtr &IP = active_.back();
335 unsigned reg = IP.first->reg;
336 DOUT << "\tinterval " << *IP.first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000337 assert(MRegisterInfo::isVirtualRegister(reg) &&
338 "Can only allocate virtual registers!");
339 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000340 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000341 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000342 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000343
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000344 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000345 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000346 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000347 DOUT << "\tinterval " << *i->first << " expired\n");
348 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000349
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000350 // Add live-ins to every BB except for entry.
351 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000352 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000353 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000354 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000355 unsigned Reg = 0;
356 if (MRegisterInfo::isPhysicalRegister(cur.reg))
357 Reg = i->second.reg;
358 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000359 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000360 if (!Reg)
361 continue;
362 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
363 I != E; ++I) {
364 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000365 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
366 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
367 if (LiveInMBBs[i] != EntryMBB)
368 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000369 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000370 }
371 }
372 }
373
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000374 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000375}
376
Chris Lattnercbb56252004-11-18 02:42:27 +0000377/// processActiveIntervals - expire old intervals and move non-overlapping ones
378/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000379void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000380{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000381 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000382
Chris Lattnercbb56252004-11-18 02:42:27 +0000383 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
384 LiveInterval *Interval = active_[i].first;
385 LiveInterval::iterator IntervalPos = active_[i].second;
386 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000387
Chris Lattnercbb56252004-11-18 02:42:27 +0000388 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
389
390 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000391 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000392 assert(MRegisterInfo::isVirtualRegister(reg) &&
393 "Can only allocate virtual registers!");
394 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000396
397 // Pop off the end of the list.
398 active_[i] = active_.back();
399 active_.pop_back();
400 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000401
Chris Lattnercbb56252004-11-18 02:42:27 +0000402 } else if (IntervalPos->start > CurPoint) {
403 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000404 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000405 assert(MRegisterInfo::isVirtualRegister(reg) &&
406 "Can only allocate virtual registers!");
407 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000409 // add to inactive.
410 inactive_.push_back(std::make_pair(Interval, IntervalPos));
411
412 // Pop off the end of the list.
413 active_[i] = active_.back();
414 active_.pop_back();
415 --i; --e;
416 } else {
417 // Otherwise, just update the iterator position.
418 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 }
420 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000421}
422
Chris Lattnercbb56252004-11-18 02:42:27 +0000423/// processInactiveIntervals - expire old intervals and move overlapping
424/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000425void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000426{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000427 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000428
Chris Lattnercbb56252004-11-18 02:42:27 +0000429 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
430 LiveInterval *Interval = inactive_[i].first;
431 LiveInterval::iterator IntervalPos = inactive_[i].second;
432 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000433
Chris Lattnercbb56252004-11-18 02:42:27 +0000434 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000435
Chris Lattnercbb56252004-11-18 02:42:27 +0000436 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000437 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000438
Chris Lattnercbb56252004-11-18 02:42:27 +0000439 // Pop off the end of the list.
440 inactive_[i] = inactive_.back();
441 inactive_.pop_back();
442 --i; --e;
443 } else if (IntervalPos->start <= CurPoint) {
444 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000445 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000446 assert(MRegisterInfo::isVirtualRegister(reg) &&
447 "Can only allocate virtual registers!");
448 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449 prt_->addRegUse(reg);
450 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000451 active_.push_back(std::make_pair(Interval, IntervalPos));
452
453 // Pop off the end of the list.
454 inactive_[i] = inactive_.back();
455 inactive_.pop_back();
456 --i; --e;
457 } else {
458 // Otherwise, just update the iterator position.
459 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 }
461 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000462}
463
Chris Lattnercbb56252004-11-18 02:42:27 +0000464/// updateSpillWeights - updates the spill weights of the specifed physical
465/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000466static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000467 unsigned reg, float weight,
468 const MRegisterInfo *MRI) {
469 Weights[reg] += weight;
470 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
471 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000472}
473
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000474static
475RALinScan::IntervalPtrs::iterator
476FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
477 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
478 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000479 if (I->first == LI) return I;
480 return IP.end();
481}
482
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000483static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000484 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000485 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000486 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
487 IP.second, Point);
488 if (I != IP.first->begin()) --I;
489 IP.second = I;
490 }
491}
Chris Lattnercbb56252004-11-18 02:42:27 +0000492
Chris Lattnercbb56252004-11-18 02:42:27 +0000493/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
494/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000495void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000496{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000497 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000498
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000499 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000500
Chris Lattnera6c17502005-08-22 20:20:42 +0000501 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000502 unsigned StartPosition = cur->beginNumber();
Evan Chengc92da382007-11-03 07:20:12 +0000503 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000504 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000505
506 // If this live interval is defined by a move instruction and its source is
507 // assigned a physical register that is compatible with the target register
508 // class, then we should try to assign it the same register.
509 // This can happen when the move is from a larger register class to a smaller
510 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
511 if (!cur->preference && cur->containsOneValue()) {
512 VNInfo *vni = cur->getValNumInfo(0);
513 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
514 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
515 unsigned SrcReg, DstReg;
516 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
517 unsigned Reg = 0;
518 if (MRegisterInfo::isPhysicalRegister(SrcReg))
519 Reg = SrcReg;
520 else if (vrm_->isAssignedReg(SrcReg))
521 Reg = vrm_->getPhys(SrcReg);
522 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
523 cur->preference = Reg;
524 }
525 }
526 }
527
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000528 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000529 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000530 for (IntervalPtrs::const_iterator i = inactive_.begin(),
531 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000532 unsigned Reg = i->first->reg;
533 assert(MRegisterInfo::isVirtualRegister(Reg) &&
534 "Can only allocate virtual registers!");
Evan Chengc92da382007-11-03 07:20:12 +0000535 const TargetRegisterClass *RegRC = regmap_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000536 // If this is not in a related reg class to the register we're allocating,
537 // don't check it.
538 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
539 cur->overlapsFrom(*i->first, i->second-1)) {
540 Reg = vrm_->getPhys(Reg);
541 prt_->addRegUse(Reg);
542 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000543 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000544 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000545
546 // Speculatively check to see if we can get a register right now. If not,
547 // we know we won't be able to by adding more constraints. If so, we can
548 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
549 // is very bad (it contains all callee clobbered registers for any functions
550 // with a call), so we want to avoid doing that if possible.
551 unsigned physReg = getFreePhysReg(cur);
552 if (physReg) {
553 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000554 // conflict with it. Check to see if we conflict with it or any of its
555 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000556 SmallSet<unsigned, 8> RegAliases;
Chris Lattnere836ad62005-08-30 21:03:36 +0000557 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
558 RegAliases.insert(*AS);
559
Chris Lattnera411cbc2005-08-22 20:59:30 +0000560 bool ConflictsWithFixed = false;
561 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000562 IntervalPtr &IP = fixed_[i];
563 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000564 // Okay, this reg is on the fixed list. Check to see if we actually
565 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000566 LiveInterval *I = IP.first;
567 if (I->endNumber() > StartPosition) {
568 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
569 IP.second = II;
570 if (II != I->begin() && II->start > StartPosition)
571 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000572 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000573 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000574 break;
575 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000576 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000577 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000578 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000579
580 // Okay, the register picked by our speculative getFreePhysReg call turned
581 // out to be in use. Actually add all of the conflicting fixed registers to
582 // prt so we can do an accurate query.
583 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000584 // For every interval in fixed we overlap with, mark the register as not
585 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000586 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
587 IntervalPtr &IP = fixed_[i];
588 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000589
590 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
591 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
592 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000593 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
594 IP.second = II;
595 if (II != I->begin() && II->start > StartPosition)
596 --II;
597 if (cur->overlapsFrom(*I, II)) {
598 unsigned reg = I->reg;
599 prt_->addRegUse(reg);
600 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
601 }
602 }
603 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000604
Chris Lattnera411cbc2005-08-22 20:59:30 +0000605 // Using the newly updated prt_ object, which includes conflicts in the
606 // future, see if there are any registers available.
607 physReg = getFreePhysReg(cur);
608 }
609 }
610
Chris Lattnera6c17502005-08-22 20:20:42 +0000611 // Restore the physical register tracker, removing information about the
612 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000614
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000615 // if we find a free register, we are done: assign this virtual to
616 // the free physical register and add this interval to the active
617 // list.
618 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000619 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000620 vrm_->assignVirt2Phys(cur->reg, physReg);
621 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000622 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623 handled_.push_back(cur);
624 return;
625 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000626 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000627
Chris Lattnera6c17502005-08-22 20:20:42 +0000628 // Compile the spill weights into an array that is better for scanning.
629 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
630 for (std::vector<std::pair<unsigned, float> >::iterator
631 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
632 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
633
634 // for each interval in active, update spill weights.
635 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
636 i != e; ++i) {
637 unsigned reg = i->first->reg;
638 assert(MRegisterInfo::isVirtualRegister(reg) &&
639 "Can only allocate virtual registers!");
640 reg = vrm_->getPhys(reg);
641 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
642 }
643
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000644 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000645
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000646 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000647 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000648 unsigned minReg = cur->preference; // Try the preferred register first.
649
650 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
651 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
652 e = RC->allocation_order_end(*mf_); i != e; ++i) {
653 unsigned reg = *i;
654 if (minWeight > SpillWeights[reg]) {
655 minWeight = SpillWeights[reg];
656 minReg = reg;
657 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000658 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000659
660 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000661 if (!minReg) {
662 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
663 e = RC->allocation_order_end(*mf_); i != e; ++i) {
664 unsigned reg = *i;
665 // No need to worry about if the alias register size < regsize of RC.
666 // We are going to spill all registers that alias it anyway.
667 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
668 if (minWeight > SpillWeights[*as]) {
669 minWeight = SpillWeights[*as];
670 minReg = *as;
671 }
672 }
673 }
674
675 // All registers must have inf weight. Just grab one!
676 if (!minReg)
677 minReg = *RC->allocation_order_begin(*mf_);
678 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000679
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000680 DOUT << "\t\tregister with min weight: "
681 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000682
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000683 // if the current has the minimum weight, we need to spill it and
684 // add any added intervals back to unhandled, and restart
685 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000686 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000687 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000688 std::vector<LiveInterval*> added =
Evan Chengf2fbca62007-11-12 06:35:08 +0000689 li_->addIntervalsForSpills(*cur, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000690 if (added.empty())
691 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000692
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000693 // Merge added with unhandled. Note that we know that
694 // addIntervalsForSpills returns intervals sorted by their starting
695 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000696 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000697 unhandled_.push(added[i]);
698 return;
699 }
700
Chris Lattner19828d42004-11-18 03:49:30 +0000701 ++NumBacktracks;
702
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000703 // push the current interval back to unhandled since we are going
704 // to re-run at least this iteration. Since we didn't modify it it
705 // should go back right in the front of the list
706 unhandled_.push(cur);
707
708 // otherwise we spill all intervals aliasing the register with
709 // minimum weight, rollback to the interval with the earliest
710 // start point and let the linear scan algorithm run again
711 std::vector<LiveInterval*> added;
712 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
713 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000714 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000715
716 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000717 toSpill[minReg] = true;
718 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
719 toSpill[*as] = true;
720
721 // the earliest start of a spilled interval indicates up to where
722 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000723 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000724
725 // set of spilled vregs (used later to rollback properly)
Evan Chengc92da382007-11-03 07:20:12 +0000726 SmallSet<unsigned, 32> spilled;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000727
Chris Lattner19828d42004-11-18 03:49:30 +0000728 // spill live intervals of virtual regs mapped to the physical register we
729 // want to clear (and its aliases). We only spill those that overlap with the
730 // current interval as the rest do not affect its allocation. we also keep
731 // track of the earliest start of all spilled live intervals since this will
732 // mark our rollback point.
733 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000734 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000735 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000736 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000737 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000738 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000739 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000740 std::vector<LiveInterval*> newIs =
Evan Chengf2fbca62007-11-12 06:35:08 +0000741 li_->addIntervalsForSpills(*i->first, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000742 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
743 spilled.insert(reg);
744 }
745 }
Chris Lattner19828d42004-11-18 03:49:30 +0000746 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000747 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000748 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000749 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000750 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000751 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000752 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000753 std::vector<LiveInterval*> newIs =
Evan Chengf2fbca62007-11-12 06:35:08 +0000754 li_->addIntervalsForSpills(*i->first, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000755 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
756 spilled.insert(reg);
757 }
758 }
759
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000760 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000761
762 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000763 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000764 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000765 while (!handled_.empty()) {
766 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000767 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000768 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000769 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000770 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000771 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000772
773 // When undoing a live interval allocation we must know if it is active or
774 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000775 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000776 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000777 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000778 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
779 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000780 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000781 prt_->delRegUse(vrm_->getPhys(i->reg));
782 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000783 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000784 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000785 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
786 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000787 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000788 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000789 } else {
790 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
791 "Can only allocate virtual registers!");
792 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000793 unhandled_.push(i);
794 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000795
796 // It interval has a preference, it must be defined by a copy. Clear the
797 // preference now since the source interval allocation may have been undone
798 // as well.
799 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000800 }
801
Chris Lattner19828d42004-11-18 03:49:30 +0000802 // Rewind the iterators in the active, inactive, and fixed lists back to the
803 // point we reverted to.
804 RevertVectorIteratorsTo(active_, earliestStart);
805 RevertVectorIteratorsTo(inactive_, earliestStart);
806 RevertVectorIteratorsTo(fixed_, earliestStart);
807
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000808 // scan the rest and undo each interval that expired after t and
809 // insert it in active (the next iteration of the algorithm will
810 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000811 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
812 LiveInterval *HI = handled_[i];
813 if (!HI->expiredAt(earliestStart) &&
814 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000815 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000816 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000817 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
818 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000819 }
820 }
821
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000822 // merge added with unhandled
823 for (unsigned i = 0, e = added.size(); i != e; ++i)
824 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000825}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000826
Chris Lattnercbb56252004-11-18 02:42:27 +0000827/// getFreePhysReg - return a free physical register for this virtual register
828/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000829unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000830 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000831 unsigned MaxInactiveCount = 0;
832
Evan Chengc92da382007-11-03 07:20:12 +0000833 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000834 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
835
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000836 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
837 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000838 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000839 assert(MRegisterInfo::isVirtualRegister(reg) &&
840 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000841
842 // If this is not in a related reg class to the register we're allocating,
843 // don't check it.
Evan Chengc92da382007-11-03 07:20:12 +0000844 const TargetRegisterClass *RegRC = regmap_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000845 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
846 reg = vrm_->getPhys(reg);
847 ++inactiveCounts[reg];
848 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
849 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000850 }
851
Chris Lattnerf8355d92005-08-22 16:55:22 +0000852 unsigned FreeReg = 0;
853 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000854
855 // If copy coalescer has assigned a "preferred" register, check if it's
856 // available first.
857 if (cur->preference)
858 if (prt_->isRegAvail(cur->preference)) {
859 DOUT << "\t\tassigned the preferred register: "
860 << mri_->getName(cur->preference) << "\n";
861 return cur->preference;
862 } else
863 DOUT << "\t\tunable to assign the preferred register: "
864 << mri_->getName(cur->preference) << "\n";
865
Chris Lattnerf8355d92005-08-22 16:55:22 +0000866 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000867 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
868 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000869 for (; I != E; ++I)
870 if (prt_->isRegAvail(*I)) {
871 FreeReg = *I;
872 FreeRegInactiveCount = inactiveCounts[FreeReg];
873 break;
874 }
875
876 // If there are no free regs, or if this reg has the max inactive count,
877 // return this register.
878 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
879
880 // Continue scanning the registers, looking for the one with the highest
881 // inactive count. Alkis found that this reduced register pressure very
882 // slightly on X86 (in rev 1.94 of this file), though this should probably be
883 // reevaluated now.
884 for (; I != E; ++I) {
885 unsigned Reg = *I;
886 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
887 FreeReg = Reg;
888 FreeRegInactiveCount = inactiveCounts[Reg];
889 if (FreeRegInactiveCount == MaxInactiveCount)
890 break; // We found the one with the max inactive count.
891 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000892 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000893
894 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000895}
896
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000897FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000898 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000899}