blob: 8bfa8680a7cb98359388b59ba3ef604eaf02fba4 [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 Lattnerb9805782005-08-23 22:27:31 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000017#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000025#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000029#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000030#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000035#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000036#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000037#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000038#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000040using namespace llvm;
41
Chris Lattnercd3245a2006-12-19 22:41:21 +000042STATISTIC(NumIters , "Number of iterations performed");
43STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000044STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000045
46static RegisterRegAlloc
47linearscanRegAlloc("linearscan", " linear scan register allocator",
48 createLinearScanRegisterAllocator);
49
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000050namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000051 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000052 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000053 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000054
Chris Lattnercbb56252004-11-18 02:42:27 +000055 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
56 typedef std::vector<IntervalPtr> IntervalPtrs;
57 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000058 /// RelatedRegClasses - This structure is built the first time a function is
59 /// compiled, and keeps track of which register classes have registers that
60 /// belong to multiple classes or have aliases that are in other classes.
61 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
62 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
63
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 MachineFunction* mf_;
65 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000066 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000067 const TargetInstrInfo* tii_;
Chris Lattner84bc5422007-12-31 04:13:23 +000068 MachineRegisterInfo *reginfo_;
Evan Chengc92da382007-11-03 07:20:12 +000069 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000071 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000072 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000073
74 /// handled_ - Intervals are added to the handled_ set in the order of their
75 /// start value. This is uses for backtracking.
76 std::vector<LiveInterval*> handled_;
77
78 /// fixed_ - Intervals that correspond to machine registers.
79 ///
80 IntervalPtrs fixed_;
81
82 /// active_ - Intervals that are currently being processed, and which have a
83 /// live range active for the current point.
84 IntervalPtrs active_;
85
86 /// inactive_ - Intervals that are currently being processed, but which have
87 /// a hold at the current point.
88 IntervalPtrs inactive_;
89
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000090 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000091 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000092 greater_ptr<LiveInterval> > IntervalHeap;
93 IntervalHeap unhandled_;
94 std::auto_ptr<PhysRegTracker> prt_;
95 std::auto_ptr<VirtRegMap> vrm_;
96 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000097
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000098 public:
99 virtual const char* getPassName() const {
100 return "Linear Scan Register Allocator";
101 }
102
103 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000105 // Make sure PassManager knows which analyses to make available
106 // to coalescing and which analyses coalescing invalidates.
107 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000108 AU.addRequired<LiveStacks>();
109 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000110 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000111 AU.addPreserved<MachineLoopInfo>();
112 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000113 MachineFunctionPass::getAnalysisUsage(AU);
114 }
115
116 /// runOnMachineFunction - register allocate the whole function
117 bool runOnMachineFunction(MachineFunction&);
118
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 private:
120 /// linearScan - the linear scan algorithm
121 void linearScan();
122
Chris Lattnercbb56252004-11-18 02:42:27 +0000123 /// initIntervalSets - initialize the interval sets.
124 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 void initIntervalSets();
126
Chris Lattnercbb56252004-11-18 02:42:27 +0000127 /// processActiveIntervals - expire old intervals and move non-overlapping
128 /// ones to the inactive list.
129 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130
Chris Lattnercbb56252004-11-18 02:42:27 +0000131 /// processInactiveIntervals - expire old intervals and move overlapping
132 /// ones to the active list.
133 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000134
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000135 /// assignRegOrStackSlotAtInterval - assign a register if one
136 /// is available, or spill.
137 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
138
Evan Chengc92da382007-11-03 07:20:12 +0000139 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
140 /// try allocate the definition the same register as the source register
141 /// if the register is not defined during live time of the interval. This
142 /// eliminate a copy. This is used to coalesce copies which were not
143 /// coalesced away before allocation either due to dest and src being in
144 /// different register classes or because the coalescer was overly
145 /// conservative.
146 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
147
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 ///
149 /// register handling helpers
150 ///
151
Chris Lattnercbb56252004-11-18 02:42:27 +0000152 /// getFreePhysReg - return a free physical register for this virtual
153 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000154 unsigned getFreePhysReg(LiveInterval* cur);
155
156 /// assignVirt2StackSlot - assigns this virtual register to a
157 /// stack slot. returns the stack slot
158 int assignVirt2StackSlot(unsigned virtReg);
159
Chris Lattnerb9805782005-08-23 22:27:31 +0000160 void ComputeRelatedRegClasses();
161
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000162 template <typename ItTy>
163 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000164 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000165 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000166 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000167 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000168 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000169 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000170 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000171 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000172 }
173 }
174 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000175 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000176}
177
Evan Cheng3f32d652008-06-04 09:18:41 +0000178static RegisterPass<RALinScan>
179X("linearscan-regalloc", "Linear Scan Register Allocator");
180
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000181void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000182 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000183
184 // First pass, add all reg classes to the union, and determine at least one
185 // reg class that each register is in.
186 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000187 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
188 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000189 RelatedRegClasses.insert(*RCI);
190 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
191 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000192 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000193
194 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
195 if (PRC) {
196 // Already processed this register. Just make sure we know that
197 // multiple register classes share a register.
198 RelatedRegClasses.unionSets(PRC, *RCI);
199 } else {
200 PRC = *RCI;
201 }
202 }
203 }
204
205 // Second pass, now that we know conservatively what register classes each reg
206 // belongs to, add info about aliases. We don't need to do this for targets
207 // without register aliases.
208 if (HasAliases)
209 for (std::map<unsigned, const TargetRegisterClass*>::iterator
210 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
211 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000212 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000213 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
214}
215
Evan Chengc92da382007-11-03 07:20:12 +0000216/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
217/// try allocate the definition the same register as the source register
218/// if the register is not defined during live time of the interval. This
219/// eliminate a copy. This is used to coalesce copies which were not
220/// coalesced away before allocation either due to dest and src being in
221/// different register classes or because the coalescer was overly
222/// conservative.
223unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000224 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000225 return Reg;
226
227 VNInfo *vni = cur.getValNumInfo(0);
228 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
229 return Reg;
230 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
231 unsigned SrcReg, DstReg;
232 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
233 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000234 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000235 if (!vrm_->isAssignedReg(SrcReg))
236 return Reg;
237 else
238 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000239 }
Evan Chengc92da382007-11-03 07:20:12 +0000240 if (Reg == SrcReg)
241 return Reg;
242
Chris Lattner84bc5422007-12-31 04:13:23 +0000243 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000244 if (!RC->contains(SrcReg))
245 return Reg;
246
247 // Try to coalesce.
248 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000249 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000250 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000251 vrm_->clearVirt(cur.reg);
252 vrm_->assignVirt2Phys(cur.reg, SrcReg);
253 ++NumCoalesce;
254 return SrcReg;
255 }
256
257 return Reg;
258}
259
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000260bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000261 mf_ = &fn;
262 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000263 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000264 tii_ = tm_->getInstrInfo();
Chris Lattner84bc5422007-12-31 04:13:23 +0000265 reginfo_ = &mf_->getRegInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000266 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000267 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000268 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000269 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000270
David Greene2c17c4d2007-09-06 16:18:45 +0000271 // We don't run the coalescer here because we have no reason to
272 // interact with it. If the coalescer requires interaction, it
273 // won't do anything. If it doesn't require interaction, we assume
274 // it was run as a separate pass.
275
Chris Lattnerb9805782005-08-23 22:27:31 +0000276 // If this is the first function compiled, compute the related reg classes.
277 if (RelatedRegClasses.empty())
278 ComputeRelatedRegClasses();
279
Dan Gohman6f0d0242008-02-10 18:45:23 +0000280 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 vrm_.reset(new VirtRegMap(*mf_));
282 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000283
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000284 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000285
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000287
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000288 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000290 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000291
Chris Lattnercbb56252004-11-18 02:42:27 +0000292 while (!unhandled_.empty()) unhandled_.pop();
293 fixed_.clear();
294 active_.clear();
295 inactive_.clear();
296 handled_.clear();
297
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000299}
300
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000301/// initIntervalSets - initialize the interval sets.
302///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000303void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000304{
305 assert(unhandled_.empty() && fixed_.empty() &&
306 active_.empty() && inactive_.empty() &&
307 "interval sets should be empty on initialization");
308
309 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000310 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000311 reginfo_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000312 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000313 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000314 unhandled_.push(&i->second);
315 }
316}
317
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000318void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000319{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000320 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000321 DOUT << "********** LINEAR SCAN **********\n";
322 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000323
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000324 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000325
326 while (!unhandled_.empty()) {
327 // pick the interval with the earliest start point
328 LiveInterval* cur = unhandled_.top();
329 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000330 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000331 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000332
Evan Chengf30a49d2008-04-03 16:40:27 +0000333 if (!cur->empty()) {
334 processActiveIntervals(cur->beginNumber());
335 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336
Evan Chengf30a49d2008-04-03 16:40:27 +0000337 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
338 "Can only allocate virtual registers!");
339 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000340
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000341 // Allocating a virtual register. try to find a free
342 // physical register or spill an interval (possibly this one) in order to
343 // assign it one.
344 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000345
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000346 DEBUG(printIntervals("active", active_.begin(), active_.end()));
347 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000349
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000351 while (!active_.empty()) {
352 IntervalPtr &IP = active_.back();
353 unsigned reg = IP.first->reg;
354 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000355 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000356 "Can only allocate virtual registers!");
357 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000358 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000359 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000360 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000361
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000363 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000364 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000365 DOUT << "\tinterval " << *i->first << " expired\n");
366 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000367
Evan Cheng81a03822007-11-17 00:40:40 +0000368 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000369 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000370 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000371 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000372 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000373 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000374 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000375 if (isPhys)
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000376 Reg = i->second.reg;
377 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000378 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000379 if (!Reg)
380 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000381 // Ignore splited live intervals.
382 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
383 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000384 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
385 I != E; ++I) {
386 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000387 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
388 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
389 if (LiveInMBBs[i] != EntryMBB)
390 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000391 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000392 }
393 }
394 }
395
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000396 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000397}
398
Chris Lattnercbb56252004-11-18 02:42:27 +0000399/// processActiveIntervals - expire old intervals and move non-overlapping ones
400/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000401void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000402{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000403 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000404
Chris Lattnercbb56252004-11-18 02:42:27 +0000405 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
406 LiveInterval *Interval = active_[i].first;
407 LiveInterval::iterator IntervalPos = active_[i].second;
408 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000409
Chris Lattnercbb56252004-11-18 02:42:27 +0000410 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
411
412 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000413 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000414 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000415 "Can only allocate virtual registers!");
416 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000417 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000418
419 // Pop off the end of the list.
420 active_[i] = active_.back();
421 active_.pop_back();
422 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000423
Chris Lattnercbb56252004-11-18 02:42:27 +0000424 } else if (IntervalPos->start > CurPoint) {
425 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000426 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000427 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000428 "Can only allocate virtual registers!");
429 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000431 // add to inactive.
432 inactive_.push_back(std::make_pair(Interval, IntervalPos));
433
434 // Pop off the end of the list.
435 active_[i] = active_.back();
436 active_.pop_back();
437 --i; --e;
438 } else {
439 // Otherwise, just update the iterator position.
440 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441 }
442 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000443}
444
Chris Lattnercbb56252004-11-18 02:42:27 +0000445/// processInactiveIntervals - expire old intervals and move overlapping
446/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000447void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000448{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000449 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000450
Chris Lattnercbb56252004-11-18 02:42:27 +0000451 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
452 LiveInterval *Interval = inactive_[i].first;
453 LiveInterval::iterator IntervalPos = inactive_[i].second;
454 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000455
Chris Lattnercbb56252004-11-18 02:42:27 +0000456 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000457
Chris Lattnercbb56252004-11-18 02:42:27 +0000458 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000459 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000460
Chris Lattnercbb56252004-11-18 02:42:27 +0000461 // Pop off the end of the list.
462 inactive_[i] = inactive_.back();
463 inactive_.pop_back();
464 --i; --e;
465 } else if (IntervalPos->start <= CurPoint) {
466 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000467 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000468 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000469 "Can only allocate virtual registers!");
470 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 prt_->addRegUse(reg);
472 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000473 active_.push_back(std::make_pair(Interval, IntervalPos));
474
475 // Pop off the end of the list.
476 inactive_[i] = inactive_.back();
477 inactive_.pop_back();
478 --i; --e;
479 } else {
480 // Otherwise, just update the iterator position.
481 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482 }
483 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000484}
485
Chris Lattnercbb56252004-11-18 02:42:27 +0000486/// updateSpillWeights - updates the spill weights of the specifed physical
487/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000488static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000489 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000490 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000491 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000492 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000493 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000494}
495
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000496static
497RALinScan::IntervalPtrs::iterator
498FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
499 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
500 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000501 if (I->first == LI) return I;
502 return IP.end();
503}
504
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000505static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000506 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000507 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000508 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
509 IP.second, Point);
510 if (I != IP.first->begin()) --I;
511 IP.second = I;
512 }
513}
Chris Lattnercbb56252004-11-18 02:42:27 +0000514
Evan Cheng3f32d652008-06-04 09:18:41 +0000515/// addStackInterval - Create a LiveInterval for stack if the specified live
516/// interval has been spilled.
517static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
518 LiveIntervals *li_, VirtRegMap &vrm_) {
519 int SS = vrm_.getStackSlot(cur->reg);
520 if (SS == VirtRegMap::NO_STACK_SLOT)
521 return;
522 LiveInterval &SI = ls_->getOrCreateInterval(SS);
523 VNInfo *VNI;
524 if (SI.getNumValNums())
525 VNI = SI.getValNumInfo(0);
526 else
527 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
528
529 LiveInterval &RI = li_->getInterval(cur->reg);
530 // FIXME: This may be overly conservative.
531 SI.MergeRangesInAsValue(RI, VNI);
532 SI.weight += RI.weight;
533}
534
Chris Lattnercbb56252004-11-18 02:42:27 +0000535/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
536/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000537void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000538{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000539 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000540
Evan Chengf30a49d2008-04-03 16:40:27 +0000541 // This is an implicitly defined live interval, just assign any register.
542 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
543 if (cur->empty()) {
544 unsigned physReg = cur->preference;
545 if (!physReg)
546 physReg = *RC->allocation_order_begin(*mf_);
547 DOUT << tri_->getName(physReg) << '\n';
548 // Note the register is not really in use.
549 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000550 return;
551 }
552
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000553 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000554
Chris Lattnera6c17502005-08-22 20:20:42 +0000555 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000556 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000557 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000558
559 // If this live interval is defined by a move instruction and its source is
560 // assigned a physical register that is compatible with the target register
561 // class, then we should try to assign it the same register.
562 // This can happen when the move is from a larger register class to a smaller
563 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
564 if (!cur->preference && cur->containsOneValue()) {
565 VNInfo *vni = cur->getValNumInfo(0);
566 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
567 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
568 unsigned SrcReg, DstReg;
Evan Chengf2b24ca2008-04-11 17:55:47 +0000569 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000570 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000571 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000572 Reg = SrcReg;
573 else if (vrm_->isAssignedReg(SrcReg))
574 Reg = vrm_->getPhys(SrcReg);
575 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
576 cur->preference = Reg;
577 }
578 }
579 }
580
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000581 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000582 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000583 for (IntervalPtrs::const_iterator i = inactive_.begin(),
584 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000585 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000586 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000587 "Can only allocate virtual registers!");
Chris Lattner84bc5422007-12-31 04:13:23 +0000588 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000589 // If this is not in a related reg class to the register we're allocating,
590 // don't check it.
591 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
592 cur->overlapsFrom(*i->first, i->second-1)) {
593 Reg = vrm_->getPhys(Reg);
594 prt_->addRegUse(Reg);
595 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000596 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000597 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000598
599 // Speculatively check to see if we can get a register right now. If not,
600 // we know we won't be able to by adding more constraints. If so, we can
601 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
602 // is very bad (it contains all callee clobbered registers for any functions
603 // with a call), so we want to avoid doing that if possible.
604 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000605 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000606 if (physReg) {
607 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000608 // conflict with it. Check to see if we conflict with it or any of its
609 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000610 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000611 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000612 RegAliases.insert(*AS);
613
Chris Lattnera411cbc2005-08-22 20:59:30 +0000614 bool ConflictsWithFixed = false;
615 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000616 IntervalPtr &IP = fixed_[i];
617 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000618 // Okay, this reg is on the fixed list. Check to see if we actually
619 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000620 LiveInterval *I = IP.first;
621 if (I->endNumber() > StartPosition) {
622 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
623 IP.second = II;
624 if (II != I->begin() && II->start > StartPosition)
625 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000626 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000627 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000628 break;
629 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000630 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000631 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000632 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000633
634 // Okay, the register picked by our speculative getFreePhysReg call turned
635 // out to be in use. Actually add all of the conflicting fixed registers to
636 // prt so we can do an accurate query.
637 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000638 // For every interval in fixed we overlap with, mark the register as not
639 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000640 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
641 IntervalPtr &IP = fixed_[i];
642 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000643
644 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
645 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
646 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000647 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
648 IP.second = II;
649 if (II != I->begin() && II->start > StartPosition)
650 --II;
651 if (cur->overlapsFrom(*I, II)) {
652 unsigned reg = I->reg;
653 prt_->addRegUse(reg);
654 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
655 }
656 }
657 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000658
Chris Lattnera411cbc2005-08-22 20:59:30 +0000659 // Using the newly updated prt_ object, which includes conflicts in the
660 // future, see if there are any registers available.
661 physReg = getFreePhysReg(cur);
662 }
663 }
664
Chris Lattnera6c17502005-08-22 20:20:42 +0000665 // Restore the physical register tracker, removing information about the
666 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000667 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000668
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000669 // if we find a free register, we are done: assign this virtual to
670 // the free physical register and add this interval to the active
671 // list.
672 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000673 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000674 vrm_->assignVirt2Phys(cur->reg, physReg);
675 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000676 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000677 handled_.push_back(cur);
678 return;
679 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000680 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000681
Chris Lattnera6c17502005-08-22 20:20:42 +0000682 // Compile the spill weights into an array that is better for scanning.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000683 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
Chris Lattnera6c17502005-08-22 20:20:42 +0000684 for (std::vector<std::pair<unsigned, float> >::iterator
685 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000686 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000687
688 // for each interval in active, update spill weights.
689 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
690 i != e; ++i) {
691 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000692 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000693 "Can only allocate virtual registers!");
694 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000695 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000696 }
697
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000698 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000699
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000700 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000701 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000702 unsigned minReg = cur->preference; // Try the preferred register first.
703
704 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
705 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
706 e = RC->allocation_order_end(*mf_); i != e; ++i) {
707 unsigned reg = *i;
708 if (minWeight > SpillWeights[reg]) {
709 minWeight = SpillWeights[reg];
710 minReg = reg;
711 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000712 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000713
714 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000715 if (!minReg) {
716 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
717 e = RC->allocation_order_end(*mf_); i != e; ++i) {
718 unsigned reg = *i;
719 // No need to worry about if the alias register size < regsize of RC.
720 // We are going to spill all registers that alias it anyway.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000721 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000722 if (minWeight > SpillWeights[*as]) {
723 minWeight = SpillWeights[*as];
724 minReg = *as;
725 }
726 }
727 }
728
729 // All registers must have inf weight. Just grab one!
Evan Cheng676dd7c2008-03-11 07:19:34 +0000730 if (!minReg) {
Evan Chengc438f352008-03-13 17:42:48 +0000731 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
732 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
733 // Spill a physical register around defs and uses.
734 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000735 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000736 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000737
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000738 DOUT << "\t\tregister with min weight: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000739 << tri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000740
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000741 // if the current has the minimum weight, we need to spill it and
742 // add any added intervals back to unhandled, and restart
743 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000744 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000745 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000746 std::vector<LiveInterval*> added =
Evan Cheng81a03822007-11-17 00:40:40 +0000747 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000748 addStackInterval(cur, ls_, li_, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000749 if (added.empty())
750 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000751
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000752 // Merge added with unhandled. Note that we know that
753 // addIntervalsForSpills returns intervals sorted by their starting
754 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000755 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000756 unhandled_.push(added[i]);
757 return;
758 }
759
Chris Lattner19828d42004-11-18 03:49:30 +0000760 ++NumBacktracks;
761
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000762 // push the current interval back to unhandled since we are going
763 // to re-run at least this iteration. Since we didn't modify it it
764 // should go back right in the front of the list
765 unhandled_.push(cur);
766
767 // otherwise we spill all intervals aliasing the register with
768 // minimum weight, rollback to the interval with the earliest
769 // start point and let the linear scan algorithm run again
770 std::vector<LiveInterval*> added;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000771 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000772 "did not choose a register to spill?");
Dan Gohman6f0d0242008-02-10 18:45:23 +0000773 BitVector toSpill(tri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000774
775 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000776 toSpill[minReg] = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000777 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000778 toSpill[*as] = true;
779
780 // the earliest start of a spilled interval indicates up to where
781 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000782 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000783
784 // set of spilled vregs (used later to rollback properly)
Evan Chengc92da382007-11-03 07:20:12 +0000785 SmallSet<unsigned, 32> spilled;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786
Chris Lattner19828d42004-11-18 03:49:30 +0000787 // spill live intervals of virtual regs mapped to the physical register we
788 // want to clear (and its aliases). We only spill those that overlap with the
789 // current interval as the rest do not affect its allocation. we also keep
790 // track of the earliest start of all spilled live intervals since this will
791 // mark our rollback point.
792 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000793 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000794 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000795 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000796 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000797 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000798 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000799 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000800 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000801 addStackInterval(i->first, ls_, li_, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000802 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
803 spilled.insert(reg);
804 }
805 }
Chris Lattner19828d42004-11-18 03:49:30 +0000806 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000807 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000808 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000809 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000810 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000811 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000812 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000813 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000814 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000815 addStackInterval(i->first, ls_, li_, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000816 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
817 spilled.insert(reg);
818 }
819 }
820
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000821 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000822
823 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000824 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000825 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000826 while (!handled_.empty()) {
827 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000828 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000829 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000830 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000831 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000832 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000833
834 // When undoing a live interval allocation we must know if it is active or
835 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000836 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000837 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000838 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000839 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000840 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000841 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000842 prt_->delRegUse(vrm_->getPhys(i->reg));
843 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000844 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000845 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000846 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000847 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000848 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000849 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000850 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000851 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000852 "Can only allocate virtual registers!");
853 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000854 unhandled_.push(i);
855 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000856
857 // It interval has a preference, it must be defined by a copy. Clear the
858 // preference now since the source interval allocation may have been undone
859 // as well.
860 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000861 }
862
Chris Lattner19828d42004-11-18 03:49:30 +0000863 // Rewind the iterators in the active, inactive, and fixed lists back to the
864 // point we reverted to.
865 RevertVectorIteratorsTo(active_, earliestStart);
866 RevertVectorIteratorsTo(inactive_, earliestStart);
867 RevertVectorIteratorsTo(fixed_, earliestStart);
868
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000869 // scan the rest and undo each interval that expired after t and
870 // insert it in active (the next iteration of the algorithm will
871 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000872 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
873 LiveInterval *HI = handled_[i];
874 if (!HI->expiredAt(earliestStart) &&
875 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000876 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000877 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +0000878 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000879 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000880 }
881 }
882
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000883 // merge added with unhandled
884 for (unsigned i = 0, e = added.size(); i != e; ++i)
885 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000886}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000887
Chris Lattnercbb56252004-11-18 02:42:27 +0000888/// getFreePhysReg - return a free physical register for this virtual register
889/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000890unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +0000891 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +0000892 unsigned MaxInactiveCount = 0;
893
Chris Lattner84bc5422007-12-31 04:13:23 +0000894 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000895 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
896
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000897 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
898 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000899 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000900 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000901 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000902
903 // If this is not in a related reg class to the register we're allocating,
904 // don't check it.
Chris Lattner84bc5422007-12-31 04:13:23 +0000905 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000906 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
907 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +0000908 if (inactiveCounts.size() <= reg)
909 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +0000910 ++inactiveCounts[reg];
911 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
912 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000913 }
914
Chris Lattnerf8355d92005-08-22 16:55:22 +0000915 unsigned FreeReg = 0;
916 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000917
918 // If copy coalescer has assigned a "preferred" register, check if it's
919 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000920 if (cur->preference) {
Evan Cheng20b0abc2007-04-17 20:32:26 +0000921 if (prt_->isRegAvail(cur->preference)) {
922 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000923 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +0000924 return cur->preference;
925 } else
926 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000927 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000928 }
Evan Cheng20b0abc2007-04-17 20:32:26 +0000929
Chris Lattnerf8355d92005-08-22 16:55:22 +0000930 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000931 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
932 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +0000933 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +0000934 for (; I != E; ++I)
935 if (prt_->isRegAvail(*I)) {
936 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +0000937 if (FreeReg < inactiveCounts.size())
938 FreeRegInactiveCount = inactiveCounts[FreeReg];
939 else
940 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +0000941 break;
942 }
Chris Lattnerfe424622008-02-26 22:08:41 +0000943
Chris Lattnerf8355d92005-08-22 16:55:22 +0000944 // If there are no free regs, or if this reg has the max inactive count,
945 // return this register.
946 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
947
948 // Continue scanning the registers, looking for the one with the highest
949 // inactive count. Alkis found that this reduced register pressure very
950 // slightly on X86 (in rev 1.94 of this file), though this should probably be
951 // reevaluated now.
952 for (; I != E; ++I) {
953 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +0000954 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
955 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +0000956 FreeReg = Reg;
957 FreeRegInactiveCount = inactiveCounts[Reg];
958 if (FreeRegInactiveCount == MaxInactiveCount)
959 break; // We found the one with the max inactive count.
960 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000961 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000962
963 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000964}
965
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000966FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000967 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000968}