blob: 7cf4ddf27daf42a463aa9c9652aaa24045991df6 [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +000013
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
Chris 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"
Evan Cheng22f07ff2007-12-11 02:09:15 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000022#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000023#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000024#include "llvm/CodeGen/RegisterCoalescer.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000028#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000029#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/Statistic.h"
31#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000032#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000033#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000034#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000035#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000036#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000037#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Chris Lattnercd3245a2006-12-19 22:41:21 +000041STATISTIC(NumIters , "Number of iterations performed");
42STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000043STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000044
45static RegisterRegAlloc
46linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
48
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000049namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000050 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000051 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000052 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000053
Chris Lattnercbb56252004-11-18 02:42:27 +000054 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
56 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000057 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
61 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000063 MachineFunction* mf_;
64 const TargetMachine* tm_;
65 const MRegisterInfo* mri_;
Evan Chengc92da382007-11-03 07:20:12 +000066 const TargetInstrInfo* tii_;
67 SSARegMap *regmap_;
68 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 LiveIntervals* li_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000070 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000071
72 /// handled_ - Intervals are added to the handled_ set in the order of their
73 /// start value. This is uses for backtracking.
74 std::vector<LiveInterval*> handled_;
75
76 /// fixed_ - Intervals that correspond to machine registers.
77 ///
78 IntervalPtrs fixed_;
79
80 /// active_ - Intervals that are currently being processed, and which have a
81 /// live range active for the current point.
82 IntervalPtrs active_;
83
84 /// inactive_ - Intervals that are currently being processed, but which have
85 /// a hold at the current point.
86 IntervalPtrs inactive_;
87
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000089 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000090 greater_ptr<LiveInterval> > IntervalHeap;
91 IntervalHeap unhandled_;
92 std::auto_ptr<PhysRegTracker> prt_;
93 std::auto_ptr<VirtRegMap> vrm_;
94 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000095
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 public:
97 virtual const char* getPassName() const {
98 return "Linear Scan Register Allocator";
99 }
100
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000102 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000103 // Make sure PassManager knows which analyses to make available
104 // to coalescing and which analyses coalescing invalidates.
105 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000106 AU.addRequired<MachineLoopInfo>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000107 MachineFunctionPass::getAnalysisUsage(AU);
108 }
109
110 /// runOnMachineFunction - register allocate the whole function
111 bool runOnMachineFunction(MachineFunction&);
112
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000113 private:
114 /// linearScan - the linear scan algorithm
115 void linearScan();
116
Chris Lattnercbb56252004-11-18 02:42:27 +0000117 /// initIntervalSets - initialize the interval sets.
118 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 void initIntervalSets();
120
Chris Lattnercbb56252004-11-18 02:42:27 +0000121 /// processActiveIntervals - expire old intervals and move non-overlapping
122 /// ones to the inactive list.
123 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000124
Chris Lattnercbb56252004-11-18 02:42:27 +0000125 /// processInactiveIntervals - expire old intervals and move overlapping
126 /// ones to the active list.
127 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000129 /// assignRegOrStackSlotAtInterval - assign a register if one
130 /// is available, or spill.
131 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
132
Evan Chengc92da382007-11-03 07:20:12 +0000133 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
134 /// try allocate the definition the same register as the source register
135 /// if the register is not defined during live time of the interval. This
136 /// eliminate a copy. This is used to coalesce copies which were not
137 /// coalesced away before allocation either due to dest and src being in
138 /// different register classes or because the coalescer was overly
139 /// conservative.
140 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
141
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142 ///
143 /// register handling helpers
144 ///
145
Chris Lattnercbb56252004-11-18 02:42:27 +0000146 /// getFreePhysReg - return a free physical register for this virtual
147 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 unsigned getFreePhysReg(LiveInterval* cur);
149
150 /// assignVirt2StackSlot - assigns this virtual register to a
151 /// stack slot. returns the stack slot
152 int assignVirt2StackSlot(unsigned virtReg);
153
Chris Lattnerb9805782005-08-23 22:27:31 +0000154 void ComputeRelatedRegClasses();
155
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000156 template <typename ItTy>
157 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000158 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000159 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000160 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000161 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000162 if (MRegisterInfo::isVirtualRegister(reg)) {
163 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000164 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000165 DOUT << mri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000166 }
167 }
168 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000169 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000170}
171
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000172void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000173 const MRegisterInfo &MRI = *mri_;
174
175 // First pass, add all reg classes to the union, and determine at least one
176 // reg class that each register is in.
177 bool HasAliases = false;
178 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
179 E = MRI.regclass_end(); RCI != E; ++RCI) {
180 RelatedRegClasses.insert(*RCI);
181 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
182 I != E; ++I) {
183 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
184
185 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
186 if (PRC) {
187 // Already processed this register. Just make sure we know that
188 // multiple register classes share a register.
189 RelatedRegClasses.unionSets(PRC, *RCI);
190 } else {
191 PRC = *RCI;
192 }
193 }
194 }
195
196 // Second pass, now that we know conservatively what register classes each reg
197 // belongs to, add info about aliases. We don't need to do this for targets
198 // without register aliases.
199 if (HasAliases)
200 for (std::map<unsigned, const TargetRegisterClass*>::iterator
201 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
202 I != E; ++I)
203 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
204 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
205}
206
Evan Chengc92da382007-11-03 07:20:12 +0000207/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
208/// try allocate the definition the same register as the source register
209/// if the register is not defined during live time of the interval. This
210/// eliminate a copy. This is used to coalesce copies which were not
211/// coalesced away before allocation either due to dest and src being in
212/// different register classes or because the coalescer was overly
213/// conservative.
214unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000215 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000216 return Reg;
217
218 VNInfo *vni = cur.getValNumInfo(0);
219 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
220 return Reg;
221 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
222 unsigned SrcReg, DstReg;
223 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
224 return Reg;
225 if (MRegisterInfo::isVirtualRegister(SrcReg))
226 if (!vrm_->isAssignedReg(SrcReg))
227 return Reg;
228 else
229 SrcReg = vrm_->getPhys(SrcReg);
230 if (Reg == SrcReg)
231 return Reg;
232
233 const TargetRegisterClass *RC = regmap_->getRegClass(cur.reg);
234 if (!RC->contains(SrcReg))
235 return Reg;
236
237 // Try to coalesce.
238 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling5b8318a2007-11-15 02:06:30 +0000239 DOUT << "Coalescing: " << cur << " -> " << mri_->getName(SrcReg) << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000240 vrm_->clearVirt(cur.reg);
241 vrm_->assignVirt2Phys(cur.reg, SrcReg);
242 ++NumCoalesce;
243 return SrcReg;
244 }
245
246 return Reg;
247}
248
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000249bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 mf_ = &fn;
251 tm_ = &fn.getTarget();
252 mri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000253 tii_ = tm_->getInstrInfo();
254 regmap_ = mf_->getSSARegMap();
255 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000256 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000257 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000258
David Greene2c17c4d2007-09-06 16:18:45 +0000259 // We don't run the coalescer here because we have no reason to
260 // interact with it. If the coalescer requires interaction, it
261 // won't do anything. If it doesn't require interaction, we assume
262 // it was run as a separate pass.
263
Chris Lattnerb9805782005-08-23 22:27:31 +0000264 // If this is the first function compiled, compute the related reg classes.
265 if (RelatedRegClasses.empty())
266 ComputeRelatedRegClasses();
267
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
269 vrm_.reset(new VirtRegMap(*mf_));
270 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000271
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000272 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000273
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000275
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000276 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000277 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000278 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000279
Chris Lattnercbb56252004-11-18 02:42:27 +0000280 while (!unhandled_.empty()) unhandled_.pop();
281 fixed_.clear();
282 active_.clear();
283 inactive_.clear();
284 handled_.clear();
285
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000287}
288
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000289/// initIntervalSets - initialize the interval sets.
290///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000291void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000292{
293 assert(unhandled_.empty() && fixed_.empty() &&
294 active_.empty() && inactive_.empty() &&
295 "interval sets should be empty on initialization");
296
297 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000298 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000299 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000300 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000301 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000302 unhandled_.push(&i->second);
303 }
304}
305
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000306void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000307{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000309 DOUT << "********** LINEAR SCAN **********\n";
310 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000311
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313
314 while (!unhandled_.empty()) {
315 // pick the interval with the earliest start point
316 LiveInterval* cur = unhandled_.top();
317 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000318 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000319 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000320
Chris Lattnercbb56252004-11-18 02:42:27 +0000321 processActiveIntervals(cur->beginNumber());
322 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000323
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000324 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
325 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000326
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000327 // Allocating a virtual register. try to find a free
328 // physical register or spill an interval (possibly this one) in order to
329 // assign it one.
330 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000331
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000332 DEBUG(printIntervals("active", active_.begin(), active_.end()));
333 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000334 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000335
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000337 while (!active_.empty()) {
338 IntervalPtr &IP = active_.back();
339 unsigned reg = IP.first->reg;
340 DOUT << "\tinterval " << *IP.first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000341 assert(MRegisterInfo::isVirtualRegister(reg) &&
342 "Can only allocate virtual registers!");
343 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000344 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000345 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000346 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000347
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000349 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000350 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000351 DOUT << "\tinterval " << *i->first << " expired\n");
352 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000353
Evan Cheng81a03822007-11-17 00:40:40 +0000354 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000355 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000356 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000357 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000358 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000359 unsigned Reg = 0;
Evan Cheng81a03822007-11-17 00:40:40 +0000360 bool isPhys = MRegisterInfo::isPhysicalRegister(cur.reg);
361 if (isPhys)
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000362 Reg = i->second.reg;
363 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000364 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000365 if (!Reg)
366 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000367 // Ignore splited live intervals.
368 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
369 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000370 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
371 I != E; ++I) {
372 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000373 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
374 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
375 if (LiveInMBBs[i] != EntryMBB)
376 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000377 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000378 }
379 }
380 }
381
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000382 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000383}
384
Chris Lattnercbb56252004-11-18 02:42:27 +0000385/// processActiveIntervals - expire old intervals and move non-overlapping ones
386/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000387void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000388{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000389 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000390
Chris Lattnercbb56252004-11-18 02:42:27 +0000391 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
392 LiveInterval *Interval = active_[i].first;
393 LiveInterval::iterator IntervalPos = active_[i].second;
394 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000395
Chris Lattnercbb56252004-11-18 02:42:27 +0000396 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
397
398 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000399 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000400 assert(MRegisterInfo::isVirtualRegister(reg) &&
401 "Can only allocate virtual registers!");
402 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000404
405 // Pop off the end of the list.
406 active_[i] = active_.back();
407 active_.pop_back();
408 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000409
Chris Lattnercbb56252004-11-18 02:42:27 +0000410 } else if (IntervalPos->start > CurPoint) {
411 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000412 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000413 assert(MRegisterInfo::isVirtualRegister(reg) &&
414 "Can only allocate virtual registers!");
415 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000416 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000417 // add to inactive.
418 inactive_.push_back(std::make_pair(Interval, IntervalPos));
419
420 // Pop off the end of the list.
421 active_[i] = active_.back();
422 active_.pop_back();
423 --i; --e;
424 } else {
425 // Otherwise, just update the iterator position.
426 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 }
428 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000429}
430
Chris Lattnercbb56252004-11-18 02:42:27 +0000431/// processInactiveIntervals - expire old intervals and move overlapping
432/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000433void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000434{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000435 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000436
Chris Lattnercbb56252004-11-18 02:42:27 +0000437 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
438 LiveInterval *Interval = inactive_[i].first;
439 LiveInterval::iterator IntervalPos = inactive_[i].second;
440 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000441
Chris Lattnercbb56252004-11-18 02:42:27 +0000442 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000443
Chris Lattnercbb56252004-11-18 02:42:27 +0000444 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000445 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000446
Chris Lattnercbb56252004-11-18 02:42:27 +0000447 // Pop off the end of the list.
448 inactive_[i] = inactive_.back();
449 inactive_.pop_back();
450 --i; --e;
451 } else if (IntervalPos->start <= CurPoint) {
452 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000453 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000454 assert(MRegisterInfo::isVirtualRegister(reg) &&
455 "Can only allocate virtual registers!");
456 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457 prt_->addRegUse(reg);
458 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000459 active_.push_back(std::make_pair(Interval, IntervalPos));
460
461 // Pop off the end of the list.
462 inactive_[i] = inactive_.back();
463 inactive_.pop_back();
464 --i; --e;
465 } else {
466 // Otherwise, just update the iterator position.
467 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468 }
469 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000470}
471
Chris Lattnercbb56252004-11-18 02:42:27 +0000472/// updateSpillWeights - updates the spill weights of the specifed physical
473/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000474static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000475 unsigned reg, float weight,
476 const MRegisterInfo *MRI) {
477 Weights[reg] += weight;
478 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
479 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000480}
481
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000482static
483RALinScan::IntervalPtrs::iterator
484FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
485 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
486 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000487 if (I->first == LI) return I;
488 return IP.end();
489}
490
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000491static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000492 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000493 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000494 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
495 IP.second, Point);
496 if (I != IP.first->begin()) --I;
497 IP.second = I;
498 }
499}
Chris Lattnercbb56252004-11-18 02:42:27 +0000500
Chris Lattnercbb56252004-11-18 02:42:27 +0000501/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
502/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000503void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000504{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000505 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000506
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000507 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000508
Chris Lattnera6c17502005-08-22 20:20:42 +0000509 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000510 unsigned StartPosition = cur->beginNumber();
Evan Chengc92da382007-11-03 07:20:12 +0000511 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000512 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000513
514 // If this live interval is defined by a move instruction and its source is
515 // assigned a physical register that is compatible with the target register
516 // class, then we should try to assign it the same register.
517 // This can happen when the move is from a larger register class to a smaller
518 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
519 if (!cur->preference && cur->containsOneValue()) {
520 VNInfo *vni = cur->getValNumInfo(0);
521 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
522 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
523 unsigned SrcReg, DstReg;
524 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
525 unsigned Reg = 0;
526 if (MRegisterInfo::isPhysicalRegister(SrcReg))
527 Reg = SrcReg;
528 else if (vrm_->isAssignedReg(SrcReg))
529 Reg = vrm_->getPhys(SrcReg);
530 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
531 cur->preference = Reg;
532 }
533 }
534 }
535
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000536 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000537 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538 for (IntervalPtrs::const_iterator i = inactive_.begin(),
539 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000540 unsigned Reg = i->first->reg;
541 assert(MRegisterInfo::isVirtualRegister(Reg) &&
542 "Can only allocate virtual registers!");
Evan Chengc92da382007-11-03 07:20:12 +0000543 const TargetRegisterClass *RegRC = regmap_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000544 // If this is not in a related reg class to the register we're allocating,
545 // don't check it.
546 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
547 cur->overlapsFrom(*i->first, i->second-1)) {
548 Reg = vrm_->getPhys(Reg);
549 prt_->addRegUse(Reg);
550 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000551 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000553
554 // Speculatively check to see if we can get a register right now. If not,
555 // we know we won't be able to by adding more constraints. If so, we can
556 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
557 // is very bad (it contains all callee clobbered registers for any functions
558 // with a call), so we want to avoid doing that if possible.
559 unsigned physReg = getFreePhysReg(cur);
560 if (physReg) {
561 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000562 // conflict with it. Check to see if we conflict with it or any of its
563 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000564 SmallSet<unsigned, 8> RegAliases;
Chris Lattnere836ad62005-08-30 21:03:36 +0000565 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
566 RegAliases.insert(*AS);
567
Chris Lattnera411cbc2005-08-22 20:59:30 +0000568 bool ConflictsWithFixed = false;
569 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000570 IntervalPtr &IP = fixed_[i];
571 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000572 // Okay, this reg is on the fixed list. Check to see if we actually
573 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000574 LiveInterval *I = IP.first;
575 if (I->endNumber() > StartPosition) {
576 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
577 IP.second = II;
578 if (II != I->begin() && II->start > StartPosition)
579 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000580 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000581 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000582 break;
583 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000584 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000585 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000586 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000587
588 // Okay, the register picked by our speculative getFreePhysReg call turned
589 // out to be in use. Actually add all of the conflicting fixed registers to
590 // prt so we can do an accurate query.
591 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000592 // For every interval in fixed we overlap with, mark the register as not
593 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000594 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
595 IntervalPtr &IP = fixed_[i];
596 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000597
598 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
599 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
600 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000601 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
602 IP.second = II;
603 if (II != I->begin() && II->start > StartPosition)
604 --II;
605 if (cur->overlapsFrom(*I, II)) {
606 unsigned reg = I->reg;
607 prt_->addRegUse(reg);
608 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
609 }
610 }
611 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000612
Chris Lattnera411cbc2005-08-22 20:59:30 +0000613 // Using the newly updated prt_ object, which includes conflicts in the
614 // future, see if there are any registers available.
615 physReg = getFreePhysReg(cur);
616 }
617 }
618
Chris Lattnera6c17502005-08-22 20:20:42 +0000619 // Restore the physical register tracker, removing information about the
620 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000621 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000622
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623 // if we find a free register, we are done: assign this virtual to
624 // the free physical register and add this interval to the active
625 // list.
626 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000627 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000628 vrm_->assignVirt2Phys(cur->reg, physReg);
629 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000630 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000631 handled_.push_back(cur);
632 return;
633 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000634 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000635
Chris Lattnera6c17502005-08-22 20:20:42 +0000636 // Compile the spill weights into an array that is better for scanning.
637 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
638 for (std::vector<std::pair<unsigned, float> >::iterator
639 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
640 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
641
642 // for each interval in active, update spill weights.
643 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
644 i != e; ++i) {
645 unsigned reg = i->first->reg;
646 assert(MRegisterInfo::isVirtualRegister(reg) &&
647 "Can only allocate virtual registers!");
648 reg = vrm_->getPhys(reg);
649 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
650 }
651
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000652 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000653
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000654 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000655 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000656 unsigned minReg = cur->preference; // Try the preferred register first.
657
658 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
659 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
660 e = RC->allocation_order_end(*mf_); i != e; ++i) {
661 unsigned reg = *i;
662 if (minWeight > SpillWeights[reg]) {
663 minWeight = SpillWeights[reg];
664 minReg = reg;
665 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000666 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000667
668 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000669 if (!minReg) {
670 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
671 e = RC->allocation_order_end(*mf_); i != e; ++i) {
672 unsigned reg = *i;
673 // No need to worry about if the alias register size < regsize of RC.
674 // We are going to spill all registers that alias it anyway.
675 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
676 if (minWeight > SpillWeights[*as]) {
677 minWeight = SpillWeights[*as];
678 minReg = *as;
679 }
680 }
681 }
682
683 // All registers must have inf weight. Just grab one!
684 if (!minReg)
685 minReg = *RC->allocation_order_begin(*mf_);
686 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000687
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000688 DOUT << "\t\tregister with min weight: "
689 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000690
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000691 // if the current has the minimum weight, we need to spill it and
692 // add any added intervals back to unhandled, and restart
693 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000694 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000695 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000696 std::vector<LiveInterval*> added =
Evan Cheng81a03822007-11-17 00:40:40 +0000697 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000698 if (added.empty())
699 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000700
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000701 // Merge added with unhandled. Note that we know that
702 // addIntervalsForSpills returns intervals sorted by their starting
703 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000704 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000705 unhandled_.push(added[i]);
706 return;
707 }
708
Chris Lattner19828d42004-11-18 03:49:30 +0000709 ++NumBacktracks;
710
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000711 // push the current interval back to unhandled since we are going
712 // to re-run at least this iteration. Since we didn't modify it it
713 // should go back right in the front of the list
714 unhandled_.push(cur);
715
716 // otherwise we spill all intervals aliasing the register with
717 // minimum weight, rollback to the interval with the earliest
718 // start point and let the linear scan algorithm run again
719 std::vector<LiveInterval*> added;
720 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
721 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000722 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000723
724 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000725 toSpill[minReg] = true;
726 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
727 toSpill[*as] = true;
728
729 // the earliest start of a spilled interval indicates up to where
730 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000731 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000732
733 // set of spilled vregs (used later to rollback properly)
Evan Chengc92da382007-11-03 07:20:12 +0000734 SmallSet<unsigned, 32> spilled;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000735
Chris Lattner19828d42004-11-18 03:49:30 +0000736 // spill live intervals of virtual regs mapped to the physical register we
737 // want to clear (and its aliases). We only spill those that overlap with the
738 // current interval as the rest do not affect its allocation. we also keep
739 // track of the earliest start of all spilled live intervals since this will
740 // mark our rollback point.
741 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000742 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000743 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000744 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000745 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000746 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000747 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000748 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000749 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000750 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
751 spilled.insert(reg);
752 }
753 }
Chris Lattner19828d42004-11-18 03:49:30 +0000754 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000755 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000756 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000757 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000758 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000759 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000760 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000761 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000762 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000763 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
764 spilled.insert(reg);
765 }
766 }
767
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000768 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000769
770 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000771 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000772 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000773 while (!handled_.empty()) {
774 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000775 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000776 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000777 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000778 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000780
781 // When undoing a live interval allocation we must know if it is active or
782 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000783 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000784 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000785 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000786 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
787 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000788 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000789 prt_->delRegUse(vrm_->getPhys(i->reg));
790 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000791 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000792 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000793 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
794 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000795 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000796 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000797 } else {
798 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
799 "Can only allocate virtual registers!");
800 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000801 unhandled_.push(i);
802 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000803
804 // It interval has a preference, it must be defined by a copy. Clear the
805 // preference now since the source interval allocation may have been undone
806 // as well.
807 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000808 }
809
Chris Lattner19828d42004-11-18 03:49:30 +0000810 // Rewind the iterators in the active, inactive, and fixed lists back to the
811 // point we reverted to.
812 RevertVectorIteratorsTo(active_, earliestStart);
813 RevertVectorIteratorsTo(inactive_, earliestStart);
814 RevertVectorIteratorsTo(fixed_, earliestStart);
815
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000816 // scan the rest and undo each interval that expired after t and
817 // insert it in active (the next iteration of the algorithm will
818 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000819 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
820 LiveInterval *HI = handled_[i];
821 if (!HI->expiredAt(earliestStart) &&
822 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000823 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000824 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000825 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
826 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000827 }
828 }
829
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000830 // merge added with unhandled
831 for (unsigned i = 0, e = added.size(); i != e; ++i)
832 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000833}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000834
Chris Lattnercbb56252004-11-18 02:42:27 +0000835/// getFreePhysReg - return a free physical register for this virtual register
836/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000837unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000838 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000839 unsigned MaxInactiveCount = 0;
840
Evan Chengc92da382007-11-03 07:20:12 +0000841 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000842 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
843
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000844 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
845 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000846 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000847 assert(MRegisterInfo::isVirtualRegister(reg) &&
848 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000849
850 // If this is not in a related reg class to the register we're allocating,
851 // don't check it.
Evan Chengc92da382007-11-03 07:20:12 +0000852 const TargetRegisterClass *RegRC = regmap_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000853 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
854 reg = vrm_->getPhys(reg);
855 ++inactiveCounts[reg];
856 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
857 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000858 }
859
Chris Lattnerf8355d92005-08-22 16:55:22 +0000860 unsigned FreeReg = 0;
861 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000862
863 // If copy coalescer has assigned a "preferred" register, check if it's
864 // available first.
865 if (cur->preference)
866 if (prt_->isRegAvail(cur->preference)) {
867 DOUT << "\t\tassigned the preferred register: "
868 << mri_->getName(cur->preference) << "\n";
869 return cur->preference;
870 } else
871 DOUT << "\t\tunable to assign the preferred register: "
872 << mri_->getName(cur->preference) << "\n";
873
Chris Lattnerf8355d92005-08-22 16:55:22 +0000874 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000875 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
876 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000877 for (; I != E; ++I)
878 if (prt_->isRegAvail(*I)) {
879 FreeReg = *I;
880 FreeRegInactiveCount = inactiveCounts[FreeReg];
881 break;
882 }
883
884 // If there are no free regs, or if this reg has the max inactive count,
885 // return this register.
886 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
887
888 // Continue scanning the registers, looking for the one with the highest
889 // inactive count. Alkis found that this reduced register pressure very
890 // slightly on X86 (in rev 1.94 of this file), though this should probably be
891 // reevaluated now.
892 for (; I != E; ++I) {
893 unsigned Reg = *I;
894 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
895 FreeReg = Reg;
896 FreeRegInactiveCount = inactiveCounts[Reg];
897 if (FreeRegInactiveCount == MaxInactiveCount)
898 break; // We found the one with the max inactive count.
899 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000900 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000901
902 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000903}
904
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000905FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000906 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000907}