blob: e74f3333d24531edb209b0dd40aaedf56a59ae7b [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"
Chris Lattnerb9805782005-08-23 22:27:31 +000027#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000030#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000031#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000032#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000033#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000034#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000035#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Chris Lattnercd3245a2006-12-19 22:41:21 +000039STATISTIC(NumIters , "Number of iterations performed");
40STATISTIC(NumBacktracks, "Number of times we had to backtrack");
41
42static RegisterRegAlloc
43linearscanRegAlloc("linearscan", " linear scan register allocator",
44 createLinearScanRegisterAllocator);
45
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000046namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000047 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000048 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000049 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000050
Chris Lattnercbb56252004-11-18 02:42:27 +000051 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
52 typedef std::vector<IntervalPtr> IntervalPtrs;
53 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000054 /// RelatedRegClasses - This structure is built the first time a function is
55 /// compiled, and keeps track of which register classes have registers that
56 /// belong to multiple classes or have aliases that are in other classes.
57 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
58 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
59
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000060 MachineFunction* mf_;
61 const TargetMachine* tm_;
62 const MRegisterInfo* mri_;
63 LiveIntervals* li_;
Chris Lattnercbb56252004-11-18 02:42:27 +000064
65 /// handled_ - Intervals are added to the handled_ set in the order of their
66 /// start value. This is uses for backtracking.
67 std::vector<LiveInterval*> handled_;
68
69 /// fixed_ - Intervals that correspond to machine registers.
70 ///
71 IntervalPtrs fixed_;
72
73 /// active_ - Intervals that are currently being processed, and which have a
74 /// live range active for the current point.
75 IntervalPtrs active_;
76
77 /// inactive_ - Intervals that are currently being processed, but which have
78 /// a hold at the current point.
79 IntervalPtrs inactive_;
80
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000081 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000082 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 greater_ptr<LiveInterval> > IntervalHeap;
84 IntervalHeap unhandled_;
85 std::auto_ptr<PhysRegTracker> prt_;
86 std::auto_ptr<VirtRegMap> vrm_;
87 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000088
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000089 public:
90 virtual const char* getPassName() const {
91 return "Linear Scan Register Allocator";
92 }
93
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000095 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +000096 // Make sure PassManager knows which analyses to make available
97 // to coalescing and which analyses coalescing invalidates.
98 AU.addRequiredTransitive<RegisterCoalescer>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000099 MachineFunctionPass::getAnalysisUsage(AU);
100 }
101
102 /// runOnMachineFunction - register allocate the whole function
103 bool runOnMachineFunction(MachineFunction&);
104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 private:
106 /// linearScan - the linear scan algorithm
107 void linearScan();
108
Chris Lattnercbb56252004-11-18 02:42:27 +0000109 /// initIntervalSets - initialize the interval sets.
110 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000111 void initIntervalSets();
112
Chris Lattnercbb56252004-11-18 02:42:27 +0000113 /// processActiveIntervals - expire old intervals and move non-overlapping
114 /// ones to the inactive list.
115 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116
Chris Lattnercbb56252004-11-18 02:42:27 +0000117 /// processInactiveIntervals - expire old intervals and move overlapping
118 /// ones to the active list.
119 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000120
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121 /// assignRegOrStackSlotAtInterval - assign a register if one
122 /// is available, or spill.
123 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
124
125 ///
126 /// register handling helpers
127 ///
128
Chris Lattnercbb56252004-11-18 02:42:27 +0000129 /// getFreePhysReg - return a free physical register for this virtual
130 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 unsigned getFreePhysReg(LiveInterval* cur);
132
133 /// assignVirt2StackSlot - assigns this virtual register to a
134 /// stack slot. returns the stack slot
135 int assignVirt2StackSlot(unsigned virtReg);
136
Chris Lattnerb9805782005-08-23 22:27:31 +0000137 void ComputeRelatedRegClasses();
138
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000139 template <typename ItTy>
140 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000141 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000143 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000144 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145 if (MRegisterInfo::isVirtualRegister(reg)) {
146 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000147 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000148 DOUT << mri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000149 }
150 }
151 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000152 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000153}
154
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000155void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000156 const MRegisterInfo &MRI = *mri_;
157
158 // First pass, add all reg classes to the union, and determine at least one
159 // reg class that each register is in.
160 bool HasAliases = false;
161 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
162 E = MRI.regclass_end(); RCI != E; ++RCI) {
163 RelatedRegClasses.insert(*RCI);
164 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
165 I != E; ++I) {
166 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
167
168 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
169 if (PRC) {
170 // Already processed this register. Just make sure we know that
171 // multiple register classes share a register.
172 RelatedRegClasses.unionSets(PRC, *RCI);
173 } else {
174 PRC = *RCI;
175 }
176 }
177 }
178
179 // Second pass, now that we know conservatively what register classes each reg
180 // belongs to, add info about aliases. We don't need to do this for targets
181 // without register aliases.
182 if (HasAliases)
183 for (std::map<unsigned, const TargetRegisterClass*>::iterator
184 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
185 I != E; ++I)
186 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
187 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
188}
189
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000190bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000191 mf_ = &fn;
192 tm_ = &fn.getTarget();
193 mri_ = tm_->getRegisterInfo();
194 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000195
David Greene2c17c4d2007-09-06 16:18:45 +0000196 // We don't run the coalescer here because we have no reason to
197 // interact with it. If the coalescer requires interaction, it
198 // won't do anything. If it doesn't require interaction, we assume
199 // it was run as a separate pass.
200
Chris Lattnerb9805782005-08-23 22:27:31 +0000201 // If this is the first function compiled, compute the related reg classes.
202 if (RelatedRegClasses.empty())
203 ComputeRelatedRegClasses();
204
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000205 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
206 vrm_.reset(new VirtRegMap(*mf_));
207 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000208
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000209 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000210
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000211 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000212
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000213 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000214 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000215 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000216
Chris Lattnercbb56252004-11-18 02:42:27 +0000217 while (!unhandled_.empty()) unhandled_.pop();
218 fixed_.clear();
219 active_.clear();
220 inactive_.clear();
221 handled_.clear();
222
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000223 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000224}
225
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000226/// initIntervalSets - initialize the interval sets.
227///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000228void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000229{
230 assert(unhandled_.empty() && fixed_.empty() &&
231 active_.empty() && inactive_.empty() &&
232 "interval sets should be empty on initialization");
233
234 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000235 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000236 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000237 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000238 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000239 unhandled_.push(&i->second);
240 }
241}
242
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000243void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000244{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000246 DOUT << "********** LINEAR SCAN **********\n";
247 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000248
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000249 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250
251 while (!unhandled_.empty()) {
252 // pick the interval with the earliest start point
253 LiveInterval* cur = unhandled_.top();
254 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000255 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000256 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000257
Chris Lattnercbb56252004-11-18 02:42:27 +0000258 processActiveIntervals(cur->beginNumber());
259 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000260
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000261 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
262 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000263
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000264 // Allocating a virtual register. try to find a free
265 // physical register or spill an interval (possibly this one) in order to
266 // assign it one.
267 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000269 DEBUG(printIntervals("active", active_.begin(), active_.end()));
270 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000271 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000272
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000273 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000274 while (!active_.empty()) {
275 IntervalPtr &IP = active_.back();
276 unsigned reg = IP.first->reg;
277 DOUT << "\tinterval " << *IP.first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000278 assert(MRegisterInfo::isVirtualRegister(reg) &&
279 "Can only allocate virtual registers!");
280 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000282 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000283 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000284
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000285 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000286 DEBUG(for (IntervalPtrs::reverse_iterator
287 i = inactive_.rbegin(); i != inactive_.rend(); )
288 DOUT << "\tinterval " << *i->first << " expired\n");
289 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000290
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000291 // Add live-ins to every BB except for entry.
292 MachineFunction::iterator EntryMBB = mf_->begin();
293 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
294 const LiveInterval &cur = i->second;
295 unsigned Reg = 0;
296 if (MRegisterInfo::isPhysicalRegister(cur.reg))
297 Reg = i->second.reg;
298 else if (vrm_->isAssignedReg(cur.reg))
299 Reg = vrm_->getPhys(cur.reg);
300 if (!Reg)
301 continue;
302 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
303 I != E; ++I) {
304 const LiveRange &LR = *I;
305 SmallVector<MachineBasicBlock*, 4> LiveInMBBs;
306 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
307 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
308 if (LiveInMBBs[i] != EntryMBB)
309 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng9fc508f2007-02-16 09:05:02 +0000310 }
311 }
312 }
313
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000314 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000315}
316
Chris Lattnercbb56252004-11-18 02:42:27 +0000317/// processActiveIntervals - expire old intervals and move non-overlapping ones
318/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000319void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000320{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000321 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000322
Chris Lattnercbb56252004-11-18 02:42:27 +0000323 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
324 LiveInterval *Interval = active_[i].first;
325 LiveInterval::iterator IntervalPos = active_[i].second;
326 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000327
Chris Lattnercbb56252004-11-18 02:42:27 +0000328 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
329
330 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000331 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000332 assert(MRegisterInfo::isVirtualRegister(reg) &&
333 "Can only allocate virtual registers!");
334 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000335 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000336
337 // Pop off the end of the list.
338 active_[i] = active_.back();
339 active_.pop_back();
340 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000341
Chris Lattnercbb56252004-11-18 02:42:27 +0000342 } else if (IntervalPos->start > CurPoint) {
343 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000344 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000345 assert(MRegisterInfo::isVirtualRegister(reg) &&
346 "Can only allocate virtual registers!");
347 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000349 // add to inactive.
350 inactive_.push_back(std::make_pair(Interval, IntervalPos));
351
352 // Pop off the end of the list.
353 active_[i] = active_.back();
354 active_.pop_back();
355 --i; --e;
356 } else {
357 // Otherwise, just update the iterator position.
358 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 }
360 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000361}
362
Chris Lattnercbb56252004-11-18 02:42:27 +0000363/// processInactiveIntervals - expire old intervals and move overlapping
364/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000365void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000366{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000367 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000368
Chris Lattnercbb56252004-11-18 02:42:27 +0000369 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
370 LiveInterval *Interval = inactive_[i].first;
371 LiveInterval::iterator IntervalPos = inactive_[i].second;
372 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000373
Chris Lattnercbb56252004-11-18 02:42:27 +0000374 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000375
Chris Lattnercbb56252004-11-18 02:42:27 +0000376 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000377 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000378
Chris Lattnercbb56252004-11-18 02:42:27 +0000379 // Pop off the end of the list.
380 inactive_[i] = inactive_.back();
381 inactive_.pop_back();
382 --i; --e;
383 } else if (IntervalPos->start <= CurPoint) {
384 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000385 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000386 assert(MRegisterInfo::isVirtualRegister(reg) &&
387 "Can only allocate virtual registers!");
388 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000389 prt_->addRegUse(reg);
390 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000391 active_.push_back(std::make_pair(Interval, IntervalPos));
392
393 // Pop off the end of the list.
394 inactive_[i] = inactive_.back();
395 inactive_.pop_back();
396 --i; --e;
397 } else {
398 // Otherwise, just update the iterator position.
399 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000400 }
401 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000402}
403
Chris Lattnercbb56252004-11-18 02:42:27 +0000404/// updateSpillWeights - updates the spill weights of the specifed physical
405/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000406static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000407 unsigned reg, float weight,
408 const MRegisterInfo *MRI) {
409 Weights[reg] += weight;
410 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
411 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000412}
413
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000414static
415RALinScan::IntervalPtrs::iterator
416FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
417 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
418 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000419 if (I->first == LI) return I;
420 return IP.end();
421}
422
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000423static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000424 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000425 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000426 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
427 IP.second, Point);
428 if (I != IP.first->begin()) --I;
429 IP.second = I;
430 }
431}
Chris Lattnercbb56252004-11-18 02:42:27 +0000432
Chris Lattnercbb56252004-11-18 02:42:27 +0000433/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
434/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000435void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000436{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000437 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000439 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000440
Chris Lattnera6c17502005-08-22 20:20:42 +0000441 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000442 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000443 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
444 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
445
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000447 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 for (IntervalPtrs::const_iterator i = inactive_.begin(),
449 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000450 unsigned Reg = i->first->reg;
451 assert(MRegisterInfo::isVirtualRegister(Reg) &&
452 "Can only allocate virtual registers!");
453 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
454 // If this is not in a related reg class to the register we're allocating,
455 // don't check it.
456 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
457 cur->overlapsFrom(*i->first, i->second-1)) {
458 Reg = vrm_->getPhys(Reg);
459 prt_->addRegUse(Reg);
460 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000461 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000463
464 // Speculatively check to see if we can get a register right now. If not,
465 // we know we won't be able to by adding more constraints. If so, we can
466 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
467 // is very bad (it contains all callee clobbered registers for any functions
468 // with a call), so we want to avoid doing that if possible.
469 unsigned physReg = getFreePhysReg(cur);
470 if (physReg) {
471 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000472 // conflict with it. Check to see if we conflict with it or any of its
473 // aliases.
474 std::set<unsigned> RegAliases;
475 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
476 RegAliases.insert(*AS);
477
Chris Lattnera411cbc2005-08-22 20:59:30 +0000478 bool ConflictsWithFixed = false;
479 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000480 IntervalPtr &IP = fixed_[i];
481 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000482 // Okay, this reg is on the fixed list. Check to see if we actually
483 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000484 LiveInterval *I = IP.first;
485 if (I->endNumber() > StartPosition) {
486 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
487 IP.second = II;
488 if (II != I->begin() && II->start > StartPosition)
489 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000490 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000491 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000492 break;
493 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000494 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000495 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000496 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000497
498 // Okay, the register picked by our speculative getFreePhysReg call turned
499 // out to be in use. Actually add all of the conflicting fixed registers to
500 // prt so we can do an accurate query.
501 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000502 // For every interval in fixed we overlap with, mark the register as not
503 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000504 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
505 IntervalPtr &IP = fixed_[i];
506 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000507
508 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
509 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
510 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000511 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
512 IP.second = II;
513 if (II != I->begin() && II->start > StartPosition)
514 --II;
515 if (cur->overlapsFrom(*I, II)) {
516 unsigned reg = I->reg;
517 prt_->addRegUse(reg);
518 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
519 }
520 }
521 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000522
Chris Lattnera411cbc2005-08-22 20:59:30 +0000523 // Using the newly updated prt_ object, which includes conflicts in the
524 // future, see if there are any registers available.
525 physReg = getFreePhysReg(cur);
526 }
527 }
528
Chris Lattnera6c17502005-08-22 20:20:42 +0000529 // Restore the physical register tracker, removing information about the
530 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000531 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000532
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000533 // if we find a free register, we are done: assign this virtual to
534 // the free physical register and add this interval to the active
535 // list.
536 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000537 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538 vrm_->assignVirt2Phys(cur->reg, physReg);
539 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000540 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000541 handled_.push_back(cur);
542 return;
543 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000544 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545
Chris Lattnera6c17502005-08-22 20:20:42 +0000546 // Compile the spill weights into an array that is better for scanning.
547 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
548 for (std::vector<std::pair<unsigned, float> >::iterator
549 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
550 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
551
552 // for each interval in active, update spill weights.
553 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
554 i != e; ++i) {
555 unsigned reg = i->first->reg;
556 assert(MRegisterInfo::isVirtualRegister(reg) &&
557 "Can only allocate virtual registers!");
558 reg = vrm_->getPhys(reg);
559 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
560 }
561
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000562 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000563
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000564 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000565 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000566 unsigned minReg = cur->preference; // Try the preferred register first.
567
568 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
569 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
570 e = RC->allocation_order_end(*mf_); i != e; ++i) {
571 unsigned reg = *i;
572 if (minWeight > SpillWeights[reg]) {
573 minWeight = SpillWeights[reg];
574 minReg = reg;
575 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000576 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000577
578 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000579 if (!minReg) {
580 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
581 e = RC->allocation_order_end(*mf_); i != e; ++i) {
582 unsigned reg = *i;
583 // No need to worry about if the alias register size < regsize of RC.
584 // We are going to spill all registers that alias it anyway.
585 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
586 if (minWeight > SpillWeights[*as]) {
587 minWeight = SpillWeights[*as];
588 minReg = *as;
589 }
590 }
591 }
592
593 // All registers must have inf weight. Just grab one!
594 if (!minReg)
595 minReg = *RC->allocation_order_begin(*mf_);
596 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000597
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000598 DOUT << "\t\tregister with min weight: "
599 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000600
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000601 // if the current has the minimum weight, we need to spill it and
602 // add any added intervals back to unhandled, and restart
603 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000604 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000605 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000606 std::vector<LiveInterval*> added =
Evan Cheng549f27d32007-08-13 23:45:17 +0000607 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000608 if (added.empty())
609 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000610
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000611 // Merge added with unhandled. Note that we know that
612 // addIntervalsForSpills returns intervals sorted by their starting
613 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000614 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000615 unhandled_.push(added[i]);
616 return;
617 }
618
Chris Lattner19828d42004-11-18 03:49:30 +0000619 ++NumBacktracks;
620
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000621 // push the current interval back to unhandled since we are going
622 // to re-run at least this iteration. Since we didn't modify it it
623 // should go back right in the front of the list
624 unhandled_.push(cur);
625
626 // otherwise we spill all intervals aliasing the register with
627 // minimum weight, rollback to the interval with the earliest
628 // start point and let the linear scan algorithm run again
629 std::vector<LiveInterval*> added;
630 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
631 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000632 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000633
634 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000635 toSpill[minReg] = true;
636 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
637 toSpill[*as] = true;
638
639 // the earliest start of a spilled interval indicates up to where
640 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000641 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000642
643 // set of spilled vregs (used later to rollback properly)
644 std::set<unsigned> spilled;
645
Chris Lattner19828d42004-11-18 03:49:30 +0000646 // spill live intervals of virtual regs mapped to the physical register we
647 // want to clear (and its aliases). We only spill those that overlap with the
648 // current interval as the rest do not affect its allocation. we also keep
649 // track of the earliest start of all spilled live intervals since this will
650 // mark our rollback point.
651 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000652 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000653 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000654 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000655 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000656 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000657 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000658 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000659 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000660 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
661 spilled.insert(reg);
662 }
663 }
Chris Lattner19828d42004-11-18 03:49:30 +0000664 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000665 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000666 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000667 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000668 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000669 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000670 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000671 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000672 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
674 spilled.insert(reg);
675 }
676 }
677
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000678 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000679
680 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000681 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000682 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000683 while (!handled_.empty()) {
684 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000685 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000686 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000687 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000688 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000689 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000690
691 // When undoing a live interval allocation we must know if it is active or
692 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000693 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000694 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000695 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000696 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
697 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000698 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000699 prt_->delRegUse(vrm_->getPhys(i->reg));
700 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000701 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000703 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
704 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000705 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000706 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000707 } else {
708 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
709 "Can only allocate virtual registers!");
710 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000711 unhandled_.push(i);
712 }
713 }
714
Chris Lattner19828d42004-11-18 03:49:30 +0000715 // Rewind the iterators in the active, inactive, and fixed lists back to the
716 // point we reverted to.
717 RevertVectorIteratorsTo(active_, earliestStart);
718 RevertVectorIteratorsTo(inactive_, earliestStart);
719 RevertVectorIteratorsTo(fixed_, earliestStart);
720
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000721 // scan the rest and undo each interval that expired after t and
722 // insert it in active (the next iteration of the algorithm will
723 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000724 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
725 LiveInterval *HI = handled_[i];
726 if (!HI->expiredAt(earliestStart) &&
727 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000728 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000729 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000730 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
731 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000732 }
733 }
734
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000735 // merge added with unhandled
736 for (unsigned i = 0, e = added.size(); i != e; ++i)
737 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000738}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000739
Chris Lattnercbb56252004-11-18 02:42:27 +0000740/// getFreePhysReg - return a free physical register for this virtual register
741/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000742unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000743 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000744 unsigned MaxInactiveCount = 0;
745
Chris Lattnerb9805782005-08-23 22:27:31 +0000746 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
747 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
748
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000749 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
750 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000751 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000752 assert(MRegisterInfo::isVirtualRegister(reg) &&
753 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000754
755 // If this is not in a related reg class to the register we're allocating,
756 // don't check it.
757 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
758 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
759 reg = vrm_->getPhys(reg);
760 ++inactiveCounts[reg];
761 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
762 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000763 }
764
Chris Lattnerf8355d92005-08-22 16:55:22 +0000765 unsigned FreeReg = 0;
766 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000767
768 // If copy coalescer has assigned a "preferred" register, check if it's
769 // available first.
770 if (cur->preference)
771 if (prt_->isRegAvail(cur->preference)) {
772 DOUT << "\t\tassigned the preferred register: "
773 << mri_->getName(cur->preference) << "\n";
774 return cur->preference;
775 } else
776 DOUT << "\t\tunable to assign the preferred register: "
777 << mri_->getName(cur->preference) << "\n";
778
Chris Lattnerf8355d92005-08-22 16:55:22 +0000779 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000780 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
781 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000782 for (; I != E; ++I)
783 if (prt_->isRegAvail(*I)) {
784 FreeReg = *I;
785 FreeRegInactiveCount = inactiveCounts[FreeReg];
786 break;
787 }
788
789 // If there are no free regs, or if this reg has the max inactive count,
790 // return this register.
791 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
792
793 // Continue scanning the registers, looking for the one with the highest
794 // inactive count. Alkis found that this reduced register pressure very
795 // slightly on X86 (in rev 1.94 of this file), though this should probably be
796 // reevaluated now.
797 for (; I != E; ++I) {
798 unsigned Reg = *I;
799 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
800 FreeReg = Reg;
801 FreeRegInactiveCount = inactiveCounts[Reg];
802 if (FreeRegInactiveCount == MaxInactiveCount)
803 break; // We found the one with the max inactive count.
804 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000805 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000806
807 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000808}
809
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000810FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000811 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000812}