blob: f12424c6b33a7699782573540cfc12f3ab0b184e [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"
22#include "llvm/CodeGen/SSARegMap.h"
23#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/Target/TargetMachine.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000025#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000028#include "llvm/Support/Debug.h"
Chris Lattnerf8c68f62006-06-28 22:17:39 +000029#include "llvm/Support/Visibility.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000030#include <algorithm>
Alkis Evlogimenos880e8e42004-05-08 03:50:03 +000031#include <cmath>
Chris Lattner2c2c6c62006-01-22 23:41:00 +000032#include <iostream>
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>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000036using namespace llvm;
37
38namespace {
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000039
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000040 Statistic<double> efficiency
41 ("regalloc", "Ratio of intervals processed over total intervals");
Chris Lattner19828d42004-11-18 03:49:30 +000042 Statistic<> NumBacktracks("regalloc", "Number of times we had to backtrack");
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000043
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000044 static unsigned numIterations = 0;
45 static unsigned numIntervals = 0;
Alkis Evlogimenosc1560952004-07-04 17:23:35 +000046
Chris Lattnerf8c68f62006-06-28 22:17:39 +000047 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
Chris Lattnercbb56252004-11-18 02:42:27 +000048 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
49 typedef std::vector<IntervalPtr> IntervalPtrs;
50 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000051 /// RelatedRegClasses - This structure is built the first time a function is
52 /// compiled, and keeps track of which register classes have registers that
53 /// belong to multiple classes or have aliases that are in other classes.
54 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
55 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
56
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000057 MachineFunction* mf_;
58 const TargetMachine* tm_;
59 const MRegisterInfo* mri_;
60 LiveIntervals* li_;
Chris Lattnerb0f31bf2005-01-23 22:45:13 +000061 bool *PhysRegsUsed;
Chris Lattnercbb56252004-11-18 02:42:27 +000062
63 /// handled_ - Intervals are added to the handled_ set in the order of their
64 /// start value. This is uses for backtracking.
65 std::vector<LiveInterval*> handled_;
66
67 /// fixed_ - Intervals that correspond to machine registers.
68 ///
69 IntervalPtrs fixed_;
70
71 /// active_ - Intervals that are currently being processed, and which have a
72 /// live range active for the current point.
73 IntervalPtrs active_;
74
75 /// inactive_ - Intervals that are currently being processed, but which have
76 /// a hold at the current point.
77 IntervalPtrs inactive_;
78
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000079 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000080 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000081 greater_ptr<LiveInterval> > IntervalHeap;
82 IntervalHeap unhandled_;
83 std::auto_ptr<PhysRegTracker> prt_;
84 std::auto_ptr<VirtRegMap> vrm_;
85 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000086
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000087 public:
88 virtual const char* getPassName() const {
89 return "Linear Scan Register Allocator";
90 }
91
92 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000093 AU.addRequired<LiveIntervals>();
94 MachineFunctionPass::getAnalysisUsage(AU);
95 }
96
97 /// runOnMachineFunction - register allocate the whole function
98 bool runOnMachineFunction(MachineFunction&);
99
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000100 private:
101 /// linearScan - the linear scan algorithm
102 void linearScan();
103
Chris Lattnercbb56252004-11-18 02:42:27 +0000104 /// initIntervalSets - initialize the interval sets.
105 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000106 void initIntervalSets();
107
Chris Lattnercbb56252004-11-18 02:42:27 +0000108 /// processActiveIntervals - expire old intervals and move non-overlapping
109 /// ones to the inactive list.
110 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000111
Chris Lattnercbb56252004-11-18 02:42:27 +0000112 /// processInactiveIntervals - expire old intervals and move overlapping
113 /// ones to the active list.
114 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116 /// assignRegOrStackSlotAtInterval - assign a register if one
117 /// is available, or spill.
118 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
119
120 ///
121 /// register handling helpers
122 ///
123
Chris Lattnercbb56252004-11-18 02:42:27 +0000124 /// getFreePhysReg - return a free physical register for this virtual
125 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126 unsigned getFreePhysReg(LiveInterval* cur);
127
128 /// assignVirt2StackSlot - assigns this virtual register to a
129 /// stack slot. returns the stack slot
130 int assignVirt2StackSlot(unsigned virtReg);
131
Chris Lattnerb9805782005-08-23 22:27:31 +0000132 void ComputeRelatedRegClasses();
133
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000134 template <typename ItTy>
135 void printIntervals(const char* const str, ItTy i, ItTy e) const {
136 if (str) std::cerr << str << " intervals:\n";
137 for (; i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000138 std::cerr << "\t" << *i->first << " -> ";
139 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140 if (MRegisterInfo::isVirtualRegister(reg)) {
141 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000142 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000143 std::cerr << mri_->getName(reg) << '\n';
144 }
145 }
146 };
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000147}
148
Chris Lattnerb9805782005-08-23 22:27:31 +0000149void RA::ComputeRelatedRegClasses() {
150 const MRegisterInfo &MRI = *mri_;
151
152 // First pass, add all reg classes to the union, and determine at least one
153 // reg class that each register is in.
154 bool HasAliases = false;
155 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
156 E = MRI.regclass_end(); RCI != E; ++RCI) {
157 RelatedRegClasses.insert(*RCI);
158 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
159 I != E; ++I) {
160 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
161
162 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
163 if (PRC) {
164 // Already processed this register. Just make sure we know that
165 // multiple register classes share a register.
166 RelatedRegClasses.unionSets(PRC, *RCI);
167 } else {
168 PRC = *RCI;
169 }
170 }
171 }
172
173 // Second pass, now that we know conservatively what register classes each reg
174 // belongs to, add info about aliases. We don't need to do this for targets
175 // without register aliases.
176 if (HasAliases)
177 for (std::map<unsigned, const TargetRegisterClass*>::iterator
178 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
179 I != E; ++I)
180 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
181 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
182}
183
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000184bool RA::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000185 mf_ = &fn;
186 tm_ = &fn.getTarget();
187 mri_ = tm_->getRegisterInfo();
188 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000189
Chris Lattnerb9805782005-08-23 22:27:31 +0000190 // If this is the first function compiled, compute the related reg classes.
191 if (RelatedRegClasses.empty())
192 ComputeRelatedRegClasses();
193
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000194 PhysRegsUsed = new bool[mri_->getNumRegs()];
195 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
196 fn.setUsedPhysRegs(PhysRegsUsed);
197
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000198 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
199 vrm_.reset(new VirtRegMap(*mf_));
200 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000201
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000202 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000203
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000204 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000205
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000206 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000207 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000208
Chris Lattner510a3ea2004-09-30 02:02:33 +0000209 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000210
211
212 while (!unhandled_.empty()) unhandled_.pop();
213 fixed_.clear();
214 active_.clear();
215 inactive_.clear();
216 handled_.clear();
217
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000218 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000219}
220
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000221/// initIntervalSets - initialize the interval sets.
222///
223void RA::initIntervalSets()
224{
225 assert(unhandled_.empty() && fixed_.empty() &&
226 active_.empty() && inactive_.empty() &&
227 "interval sets should be empty on initialization");
228
229 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000230 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
231 PhysRegsUsed[i->second.reg] = true;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000232 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000233 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000234 unhandled_.push(&i->second);
235 }
236}
237
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000238void RA::linearScan()
239{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000240 // linear scan algorithm
241 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
242 DEBUG(std::cerr << "********** Function: "
243 << mf_->getFunction()->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000244
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
246 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
247 DEBUG(printIntervals("active", active_.begin(), active_.end()));
248 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
249
250 while (!unhandled_.empty()) {
251 // pick the interval with the earliest start point
252 LiveInterval* cur = unhandled_.top();
253 unhandled_.pop();
254 ++numIterations;
255 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
256
Chris Lattnercbb56252004-11-18 02:42:27 +0000257 processActiveIntervals(cur->beginNumber());
258 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000259
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000260 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
261 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000262
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000263 // Allocating a virtual register. try to find a free
264 // physical register or spill an interval (possibly this one) in order to
265 // assign it one.
266 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000267
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000268 DEBUG(printIntervals("active", active_.begin(), active_.end()));
269 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000270 }
271 numIntervals += li_->getNumIntervals();
272 efficiency = double(numIterations) / double(numIntervals);
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000273
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274 // expire any remaining active intervals
275 for (IntervalPtrs::reverse_iterator
276 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000277 unsigned reg = i->first->reg;
278 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000279 assert(MRegisterInfo::isVirtualRegister(reg) &&
280 "Can only allocate virtual registers!");
281 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000282 prt_->delRegUse(reg);
283 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
284 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000285
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 // expire any remaining inactive intervals
287 for (IntervalPtrs::reverse_iterator
288 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000289 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000290 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
291 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000292
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 DEBUG(std::cerr << *vrm_);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000294}
295
Chris Lattnercbb56252004-11-18 02:42:27 +0000296/// processActiveIntervals - expire old intervals and move non-overlapping ones
297/// to the inactive list.
298void RA::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000299{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 DEBUG(std::cerr << "\tprocessing active intervals:\n");
Chris Lattner23b71c12004-11-18 01:29:39 +0000301
Chris Lattnercbb56252004-11-18 02:42:27 +0000302 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
303 LiveInterval *Interval = active_[i].first;
304 LiveInterval::iterator IntervalPos = active_[i].second;
305 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000306
Chris Lattnercbb56252004-11-18 02:42:27 +0000307 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
308
309 if (IntervalPos == Interval->end()) { // Remove expired intervals.
310 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000311 assert(MRegisterInfo::isVirtualRegister(reg) &&
312 "Can only allocate virtual registers!");
313 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000314 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000315
316 // Pop off the end of the list.
317 active_[i] = active_.back();
318 active_.pop_back();
319 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000320
Chris Lattnercbb56252004-11-18 02:42:27 +0000321 } else if (IntervalPos->start > CurPoint) {
322 // Move inactive intervals to inactive list.
323 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000324 assert(MRegisterInfo::isVirtualRegister(reg) &&
325 "Can only allocate virtual registers!");
326 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000327 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000328 // add to inactive.
329 inactive_.push_back(std::make_pair(Interval, IntervalPos));
330
331 // Pop off the end of the list.
332 active_[i] = active_.back();
333 active_.pop_back();
334 --i; --e;
335 } else {
336 // Otherwise, just update the iterator position.
337 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000338 }
339 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000340}
341
Chris Lattnercbb56252004-11-18 02:42:27 +0000342/// processInactiveIntervals - expire old intervals and move overlapping
343/// ones to the active list.
344void RA::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000345{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000346 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
Chris Lattner365b95f2004-11-18 04:13:02 +0000347
Chris Lattnercbb56252004-11-18 02:42:27 +0000348 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
349 LiveInterval *Interval = inactive_[i].first;
350 LiveInterval::iterator IntervalPos = inactive_[i].second;
351 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000352
Chris Lattnercbb56252004-11-18 02:42:27 +0000353 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000354
Chris Lattnercbb56252004-11-18 02:42:27 +0000355 if (IntervalPos == Interval->end()) { // remove expired intervals.
356 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000357
Chris Lattnercbb56252004-11-18 02:42:27 +0000358 // Pop off the end of the list.
359 inactive_[i] = inactive_.back();
360 inactive_.pop_back();
361 --i; --e;
362 } else if (IntervalPos->start <= CurPoint) {
363 // move re-activated intervals in active list
364 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000365 assert(MRegisterInfo::isVirtualRegister(reg) &&
366 "Can only allocate virtual registers!");
367 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 prt_->addRegUse(reg);
369 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000370 active_.push_back(std::make_pair(Interval, IntervalPos));
371
372 // Pop off the end of the list.
373 inactive_[i] = inactive_.back();
374 inactive_.pop_back();
375 --i; --e;
376 } else {
377 // Otherwise, just update the iterator position.
378 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 }
380 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000381}
382
Chris Lattnercbb56252004-11-18 02:42:27 +0000383/// updateSpillWeights - updates the spill weights of the specifed physical
384/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000385static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000386 unsigned reg, float weight,
387 const MRegisterInfo *MRI) {
388 Weights[reg] += weight;
389 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
390 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000391}
392
Chris Lattnercbb56252004-11-18 02:42:27 +0000393static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
394 LiveInterval *LI) {
395 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
396 if (I->first == LI) return I;
397 return IP.end();
398}
399
Chris Lattner19828d42004-11-18 03:49:30 +0000400static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
401 for (unsigned i = 0, e = V.size(); i != e; ++i) {
402 RA::IntervalPtr &IP = V[i];
403 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
404 IP.second, Point);
405 if (I != IP.first->begin()) --I;
406 IP.second = I;
407 }
408}
Chris Lattnercbb56252004-11-18 02:42:27 +0000409
Chris Lattnercbb56252004-11-18 02:42:27 +0000410/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
411/// spill.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000412void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000413{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 DEBUG(std::cerr << "\tallocating current interval: ");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000415
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000416 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000417
Chris Lattnera6c17502005-08-22 20:20:42 +0000418 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000419 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000420 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
421 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
422
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000423 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000424 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000425 for (IntervalPtrs::const_iterator i = inactive_.begin(),
426 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000427 unsigned Reg = i->first->reg;
428 assert(MRegisterInfo::isVirtualRegister(Reg) &&
429 "Can only allocate virtual registers!");
430 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
431 // If this is not in a related reg class to the register we're allocating,
432 // don't check it.
433 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
434 cur->overlapsFrom(*i->first, i->second-1)) {
435 Reg = vrm_->getPhys(Reg);
436 prt_->addRegUse(Reg);
437 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000439 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000440
441 // Speculatively check to see if we can get a register right now. If not,
442 // we know we won't be able to by adding more constraints. If so, we can
443 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
444 // is very bad (it contains all callee clobbered registers for any functions
445 // with a call), so we want to avoid doing that if possible.
446 unsigned physReg = getFreePhysReg(cur);
447 if (physReg) {
448 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000449 // conflict with it. Check to see if we conflict with it or any of its
450 // aliases.
451 std::set<unsigned> RegAliases;
452 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
453 RegAliases.insert(*AS);
454
Chris Lattnera411cbc2005-08-22 20:59:30 +0000455 bool ConflictsWithFixed = false;
456 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Chris Lattnere836ad62005-08-30 21:03:36 +0000457 if (physReg == fixed_[i].first->reg ||
458 RegAliases.count(fixed_[i].first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000459 // Okay, this reg is on the fixed list. Check to see if we actually
460 // conflict.
461 IntervalPtr &IP = fixed_[i];
462 LiveInterval *I = IP.first;
463 if (I->endNumber() > StartPosition) {
464 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
465 IP.second = II;
466 if (II != I->begin() && II->start > StartPosition)
467 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000468 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000469 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000470 break;
471 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000472 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000473 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000474 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000475
476 // Okay, the register picked by our speculative getFreePhysReg call turned
477 // out to be in use. Actually add all of the conflicting fixed registers to
478 // prt so we can do an accurate query.
479 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000480 // For every interval in fixed we overlap with, mark the register as not
481 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000482 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
483 IntervalPtr &IP = fixed_[i];
484 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000485
486 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
487 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
488 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000489 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
490 IP.second = II;
491 if (II != I->begin() && II->start > StartPosition)
492 --II;
493 if (cur->overlapsFrom(*I, II)) {
494 unsigned reg = I->reg;
495 prt_->addRegUse(reg);
496 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
497 }
498 }
499 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000500
Chris Lattnera411cbc2005-08-22 20:59:30 +0000501 // Using the newly updated prt_ object, which includes conflicts in the
502 // future, see if there are any registers available.
503 physReg = getFreePhysReg(cur);
504 }
505 }
506
Chris Lattnera6c17502005-08-22 20:20:42 +0000507 // Restore the physical register tracker, removing information about the
508 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000510
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000511 // if we find a free register, we are done: assign this virtual to
512 // the free physical register and add this interval to the active
513 // list.
514 if (physReg) {
515 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
516 vrm_->assignVirt2Phys(cur->reg, physReg);
517 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000518 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000519 handled_.push_back(cur);
520 return;
521 }
522 DEBUG(std::cerr << "no free registers\n");
523
Chris Lattnera6c17502005-08-22 20:20:42 +0000524 // Compile the spill weights into an array that is better for scanning.
525 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
526 for (std::vector<std::pair<unsigned, float> >::iterator
527 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
528 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
529
530 // for each interval in active, update spill weights.
531 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
532 i != e; ++i) {
533 unsigned reg = i->first->reg;
534 assert(MRegisterInfo::isVirtualRegister(reg) &&
535 "Can only allocate virtual registers!");
536 reg = vrm_->getPhys(reg);
537 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
538 }
539
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
541
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000542 // Find a register to spill.
Chris Lattner5e5fb942005-01-08 19:53:50 +0000543 float minWeight = float(HUGE_VAL);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000544 unsigned minReg = 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000545 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
546 e = RC->allocation_order_end(*mf_); i != e; ++i) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000547 unsigned reg = *i;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000548 if (minWeight > SpillWeights[reg]) {
549 minWeight = SpillWeights[reg];
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000550 minReg = reg;
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000551 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000553
554 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000555 if (!minReg) {
556 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
557 e = RC->allocation_order_end(*mf_); i != e; ++i) {
558 unsigned reg = *i;
559 // No need to worry about if the alias register size < regsize of RC.
560 // We are going to spill all registers that alias it anyway.
561 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
562 if (minWeight > SpillWeights[*as]) {
563 minWeight = SpillWeights[*as];
564 minReg = *as;
565 }
566 }
567 }
568
569 // All registers must have inf weight. Just grab one!
570 if (!minReg)
571 minReg = *RC->allocation_order_begin(*mf_);
572 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000573
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000574 DEBUG(std::cerr << "\t\tregister with min weight: "
575 << mri_->getName(minReg) << " (" << minWeight << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000576
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000577 // if the current has the minimum weight, we need to spill it and
578 // add any added intervals back to unhandled, and restart
579 // linearscan.
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000580 if (cur->weight != float(HUGE_VAL) && cur->weight <= minWeight) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000581 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
582 int slot = vrm_->assignVirt2StackSlot(cur->reg);
583 std::vector<LiveInterval*> added =
584 li_->addIntervalsForSpills(*cur, *vrm_, slot);
585 if (added.empty())
586 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000587
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000588 // Merge added with unhandled. Note that we know that
589 // addIntervalsForSpills returns intervals sorted by their starting
590 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000591 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000592 unhandled_.push(added[i]);
593 return;
594 }
595
Chris Lattner19828d42004-11-18 03:49:30 +0000596 ++NumBacktracks;
597
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000598 // push the current interval back to unhandled since we are going
599 // to re-run at least this iteration. Since we didn't modify it it
600 // should go back right in the front of the list
601 unhandled_.push(cur);
602
603 // otherwise we spill all intervals aliasing the register with
604 // minimum weight, rollback to the interval with the earliest
605 // start point and let the linear scan algorithm run again
606 std::vector<LiveInterval*> added;
607 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
608 "did not choose a register to spill?");
609 std::vector<bool> toSpill(mri_->getNumRegs(), false);
Chris Lattner19828d42004-11-18 03:49:30 +0000610
611 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000612 toSpill[minReg] = true;
613 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
614 toSpill[*as] = true;
615
616 // the earliest start of a spilled interval indicates up to where
617 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000618 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000619
620 // set of spilled vregs (used later to rollback properly)
621 std::set<unsigned> spilled;
622
Chris Lattner19828d42004-11-18 03:49:30 +0000623 // spill live intervals of virtual regs mapped to the physical register we
624 // want to clear (and its aliases). We only spill those that overlap with the
625 // current interval as the rest do not affect its allocation. we also keep
626 // track of the earliest start of all spilled live intervals since this will
627 // mark our rollback point.
628 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000629 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000630 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000631 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000632 cur->overlapsFrom(*i->first, i->second)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000633 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
634 earliestStart = std::min(earliestStart, i->first->beginNumber());
635 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000636 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000637 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000638 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
639 spilled.insert(reg);
640 }
641 }
Chris Lattner19828d42004-11-18 03:49:30 +0000642 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000643 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000644 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000645 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000646 cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000647 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
648 earliestStart = std::min(earliestStart, i->first->beginNumber());
649 int slot = vrm_->assignVirt2StackSlot(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000650 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000651 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000652 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
653 spilled.insert(reg);
654 }
655 }
656
657 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
Chris Lattnercbb56252004-11-18 02:42:27 +0000658
659 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000660 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000661 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000662 while (!handled_.empty()) {
663 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000664 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000665 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000666 break;
667 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
668 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000669
670 // When undoing a live interval allocation we must know if it is active or
671 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000672 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000673 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000674 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000675 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
676 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000677 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000678 prt_->delRegUse(vrm_->getPhys(i->reg));
679 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000680 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000681 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000682 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
683 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000684 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000685 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000686 } else {
687 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
688 "Can only allocate virtual registers!");
689 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000690 unhandled_.push(i);
691 }
692 }
693
Chris Lattner19828d42004-11-18 03:49:30 +0000694 // Rewind the iterators in the active, inactive, and fixed lists back to the
695 // point we reverted to.
696 RevertVectorIteratorsTo(active_, earliestStart);
697 RevertVectorIteratorsTo(inactive_, earliestStart);
698 RevertVectorIteratorsTo(fixed_, earliestStart);
699
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 // scan the rest and undo each interval that expired after t and
701 // insert it in active (the next iteration of the algorithm will
702 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000703 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
704 LiveInterval *HI = handled_[i];
705 if (!HI->expiredAt(earliestStart) &&
706 HI->expiredAt(cur->beginNumber())) {
707 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
708 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000709 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
710 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000711 }
712 }
713
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000714 // merge added with unhandled
715 for (unsigned i = 0, e = added.size(); i != e; ++i)
716 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000717}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000718
Chris Lattnercbb56252004-11-18 02:42:27 +0000719/// getFreePhysReg - return a free physical register for this virtual register
720/// interval if we have one, otherwise return 0.
Chris Lattnerffab4222006-02-23 06:44:17 +0000721unsigned RA::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000722 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000723 unsigned MaxInactiveCount = 0;
724
Chris Lattnerb9805782005-08-23 22:27:31 +0000725 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
726 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
727
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000728 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
729 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000730 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000731 assert(MRegisterInfo::isVirtualRegister(reg) &&
732 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000733
734 // If this is not in a related reg class to the register we're allocating,
735 // don't check it.
736 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
737 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
738 reg = vrm_->getPhys(reg);
739 ++inactiveCounts[reg];
740 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
741 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000742 }
743
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000744 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Alkis Evlogimenos26bfc082003-12-28 17:58:18 +0000745
Chris Lattnerf8355d92005-08-22 16:55:22 +0000746 unsigned FreeReg = 0;
747 unsigned FreeRegInactiveCount = 0;
748
749 // Scan for the first available register.
750 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
751 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
752 for (; I != E; ++I)
753 if (prt_->isRegAvail(*I)) {
754 FreeReg = *I;
755 FreeRegInactiveCount = inactiveCounts[FreeReg];
756 break;
757 }
758
759 // If there are no free regs, or if this reg has the max inactive count,
760 // return this register.
761 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
762
763 // Continue scanning the registers, looking for the one with the highest
764 // inactive count. Alkis found that this reduced register pressure very
765 // slightly on X86 (in rev 1.94 of this file), though this should probably be
766 // reevaluated now.
767 for (; I != E; ++I) {
768 unsigned Reg = *I;
769 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
770 FreeReg = Reg;
771 FreeRegInactiveCount = inactiveCounts[Reg];
772 if (FreeRegInactiveCount == MaxInactiveCount)
773 break; // We found the one with the max inactive count.
774 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000775 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000776
777 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000778}
779
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000780FunctionPass* llvm::createLinearScanRegisterAllocator() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000781 return new RA();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000782}