blob: bcb38d7c35a9ce5b1725a18d80a1b54cf1522cfe [file] [log] [blame]
Andrew Trick14e8d712010-10-22 23:09:15 +00001//===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RABasic function pass, which provides a minimal
11// implementation of the basic register allocator.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +000016#include "RegAllocBase.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000017#include "LiveDebugVariables.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000018#include "LiveIntervalUnion.h"
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +000019#include "LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000020#include "RenderMachineFunction.h"
21#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000022#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000023#include "RegisterCoalescer.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000024#include "llvm/ADT/OwningPtr.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000026#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000027#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstr.h"
34#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/CodeGen/RegAllocRegistry.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000038#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000040#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000041#ifndef NDEBUG
42#include "llvm/ADT/SparseBitVector.h"
43#endif
Andrew Tricke141a492010-11-08 18:02:08 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000047#include "llvm/Support/Timer.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000048
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000049#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000050#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000051
Andrew Trick14e8d712010-10-22 23:09:15 +000052using namespace llvm;
53
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000054STATISTIC(NumAssigned , "Number of registers assigned");
55STATISTIC(NumUnassigned , "Number of registers unassigned");
56STATISTIC(NumNewQueued , "Number of new live ranges queued");
57
Andrew Trick14e8d712010-10-22 23:09:15 +000058static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
59 createBasicRegisterAllocator);
60
Andrew Trick071d1c02010-11-09 21:04:34 +000061// Temporary verification option until we can put verification inside
62// MachineVerifier.
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000063static cl::opt<bool, true>
64VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled),
65 cl::desc("Verify during register allocation"));
Andrew Trick071d1c02010-11-09 21:04:34 +000066
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000067const char *RegAllocBase::TimerGroupName = "Register Allocation";
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000068bool RegAllocBase::VerifyEnabled = false;
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000069
Benjamin Kramerc62feda2010-11-25 16:42:51 +000070namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000071 struct CompSpillWeight {
72 bool operator()(LiveInterval *A, LiveInterval *B) const {
73 return A->weight < B->weight;
74 }
75 };
76}
77
78namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000079/// RABasic provides a minimal implementation of the basic register allocation
80/// algorithm. It prioritizes live virtual registers by spill weight and spills
81/// whenever a register is unavailable. This is not practical in production but
82/// provides a useful baseline both for measuring other allocators and comparing
83/// the speed of the basic algorithm against other styles of allocators.
84class RABasic : public MachineFunctionPass, public RegAllocBase
85{
86 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000087 MachineFunction *MF;
Andrew Trick14e8d712010-10-22 23:09:15 +000088
89 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000090 LiveStacks *LS;
91 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000092
93 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000094 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000095 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
96 CompSpillWeight> Queue;
Andrew Trick14e8d712010-10-22 23:09:15 +000097public:
98 RABasic();
99
100 /// Return the pass name.
101 virtual const char* getPassName() const {
102 return "Basic Register Allocator";
103 }
104
105 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000106 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000107
108 virtual void releaseMemory();
109
Andrew Trick18c57a82010-11-30 23:18:47 +0000110 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000111
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000112 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
113
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000114 virtual void enqueue(LiveInterval *LI) {
115 Queue.push(LI);
116 }
117
118 virtual LiveInterval *dequeue() {
119 if (Queue.empty())
120 return 0;
121 LiveInterval *LI = Queue.top();
122 Queue.pop();
123 return LI;
124 }
125
Andrew Trick18c57a82010-11-30 23:18:47 +0000126 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
127 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000128
129 /// Perform register allocation.
130 virtual bool runOnMachineFunction(MachineFunction &mf);
131
132 static char ID;
133};
134
135char RABasic::ID = 0;
136
137} // end anonymous namespace
138
Andrew Trick14e8d712010-10-22 23:09:15 +0000139RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000140 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000141 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
142 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
143 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000144 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000145 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
146 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000147 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000148 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
149 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
150 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
151}
152
Andrew Trick18c57a82010-11-30 23:18:47 +0000153void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.setPreservesCFG();
155 AU.addRequired<AliasAnalysis>();
156 AU.addPreserved<AliasAnalysis>();
157 AU.addRequired<LiveIntervals>();
158 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000159 AU.addRequired<LiveDebugVariables>();
160 AU.addPreserved<LiveDebugVariables>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000161 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000162 AU.addRequiredID(StrongPHIEliminationID);
163 AU.addRequiredTransitive<RegisterCoalescer>();
164 AU.addRequired<CalculateSpillWeights>();
165 AU.addRequired<LiveStacks>();
166 AU.addPreserved<LiveStacks>();
167 AU.addRequiredID(MachineDominatorsID);
168 AU.addPreservedID(MachineDominatorsID);
169 AU.addRequired<MachineLoopInfo>();
170 AU.addPreserved<MachineLoopInfo>();
171 AU.addRequired<VirtRegMap>();
172 AU.addPreserved<VirtRegMap>();
173 DEBUG(AU.addRequired<RenderMachineFunction>());
174 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000175}
176
177void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000178 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000179 RegAllocBase::releaseMemory();
180}
181
Andrew Trick071d1c02010-11-09 21:04:34 +0000182#ifndef NDEBUG
183// Verify each LiveIntervalUnion.
184void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000185 LiveVirtRegBitSet VisitedVRegs;
186 OwningArrayPtr<LiveVirtRegBitSet>
187 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
188
Andrew Trick071d1c02010-11-09 21:04:34 +0000189 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000190 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000191 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000192 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
193 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000194 // Union + intersection test could be done efficiently in one pass, but
195 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000196 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
197 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000198 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000199
Andrew Trick071d1c02010-11-09 21:04:34 +0000200 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000201 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000202 liItr != liEnd; ++liItr) {
203 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000204 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000205 if (!VRM->hasPhys(reg)) continue; // spilled?
206 unsigned PhysReg = VRM->getPhys(reg);
207 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000208 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000209 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000210 llvm_unreachable("unallocated live vreg");
211 }
212 }
213 // FIXME: I'm not sure how to verify spilled intervals.
214}
215#endif //!NDEBUG
216
Andrew Trick14e8d712010-10-22 23:09:15 +0000217//===----------------------------------------------------------------------===//
218// RegAllocBase Implementation
219//===----------------------------------------------------------------------===//
220
221// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000222void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
223 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000224 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000225 Array =
226 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
227 for (unsigned r = 0; r != NRegs; ++r)
228 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000229}
230
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000231void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000232 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000233 TRI = &vrm.getTargetRegInfo();
234 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000235 VRM = &vrm;
236 LIS = &lis;
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000237 RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());
238
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000239 const unsigned NumRegs = TRI->getNumRegs();
240 if (NumRegs != PhysReg2LiveUnion.numRegs()) {
241 PhysReg2LiveUnion.init(UnionAllocator, NumRegs);
242 // Cache an interferece query for each physical reg
243 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
244 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000245}
246
Andrew Trick18c57a82010-11-30 23:18:47 +0000247void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000248 if (!Array)
249 return;
250 for (unsigned r = 0; r != NumRegs; ++r)
251 Array[r].~LiveIntervalUnion();
252 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000253 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000254 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000255}
256
257void RegAllocBase::releaseMemory() {
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000258 for (unsigned r = 0, e = PhysReg2LiveUnion.numRegs(); r != e; ++r)
259 PhysReg2LiveUnion[r].clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000260}
261
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000262// Visit all the live registers. If they are already assigned to a physical
263// register, unify them with the corresponding LiveIntervalUnion, otherwise push
264// them on the priority queue for later assignment.
265void RegAllocBase::seedLiveRegs() {
Jakob Stoklund Olesenbd1926d2011-04-11 15:00:42 +0000266 NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled);
Andrew Trick18c57a82010-11-30 23:18:47 +0000267 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
268 unsigned RegNum = I->first;
269 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000270 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000271 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000272 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000273 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000274 }
275}
276
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000277void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000278 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
279 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000280 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
281 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000282 MRI->setPhysRegUsed(PhysReg);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000283 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000284 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000285}
286
287void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000288 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
289 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000290 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
291 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
292 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000293 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000294}
295
Andrew Trick18c57a82010-11-30 23:18:47 +0000296// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000297// selectOrSplit implementation.
298void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000299 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000300
301 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000302 while (LiveInterval *VirtReg = dequeue()) {
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000303 assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned");
304
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000305 // Unused registers can appear when the spiller coalesces snippets.
306 if (MRI->reg_nodbg_empty(VirtReg->reg)) {
307 DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
308 LIS->removeInterval(VirtReg->reg);
309 continue;
310 }
311
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000312 // Invalidate all interference queries, live ranges could have changed.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +0000313 invalidateVirtRegs();
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000314
Andrew Trick18c57a82010-11-30 23:18:47 +0000315 // selectOrSplit requests the allocator to return an available physical
316 // register if possible and populate a list of new live intervals that
317 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000318 DEBUG(dbgs() << "\nselectOrSplit "
319 << MRI->getRegClass(VirtReg->reg)->getName()
320 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000321 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
322 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000323 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000324
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000325 if (AvailablePhysReg == ~0u) {
326 // selectOrSplit failed to find a register!
327 std::string msg;
328 raw_string_ostream Msg(msg);
329 Msg << "Ran out of registers during register allocation!"
330 "\nCannot allocate: " << *VirtReg;
331 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(VirtReg->reg);
332 MachineInstr *MI = I.skipInstruction();) {
333 if (!MI->isInlineAsm())
334 continue;
335 Msg << "\nPlease check your inline asm statement for "
336 "invalid constraints:\n";
337 MI->print(Msg, &VRM->getMachineFunction().getTarget());
338 }
339 report_fatal_error(Msg.str());
340 }
341
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000342 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000343 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000344
Andrew Trick18c57a82010-11-30 23:18:47 +0000345 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
346 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000347 LiveInterval *SplitVirtReg = *I;
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000348 assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned");
349 if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
350 DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
351 LIS->removeInterval(SplitVirtReg->reg);
352 continue;
353 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000354 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
355 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000356 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000357 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000358 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000359 }
360 }
361}
362
Andrew Trick18c57a82010-11-30 23:18:47 +0000363// Check if this live virtual register interferes with a physical register. If
364// not, then check for interference on each register that aliases with the
365// physical register. Return the interfering register.
366unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
367 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000368 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000369 if (query(VirtReg, *AliasI).checkInterference())
370 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000371 return 0;
372}
373
Andrew Trick18c57a82010-11-30 23:18:47 +0000374// Helper for spillInteferences() that spills all interfering vregs currently
375// assigned to this physical register.
376void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
377 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
378 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
379 assert(Q.seenAllInterferences() && "need collectInterferences()");
380 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000381
Andrew Trick18c57a82010-11-30 23:18:47 +0000382 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
383 E = PendingSpills.end(); I != E; ++I) {
384 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000385 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000386 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000387
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000388 // Deallocate the interfering vreg by removing it from the union.
389 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000390 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000391
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000392 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000393 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
394 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000395 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000396 // After extracting segments, the query's results are invalid. But keep the
397 // contents valid until we're done accessing pendingSpills.
398 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000399}
400
Andrew Trick18c57a82010-11-30 23:18:47 +0000401// Spill or split all live virtual registers currently unified under PhysReg
402// that interfere with VirtReg. The newly spilled or split live intervals are
403// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000404bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000405RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
406 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000407 // Record each interference and determine if all are spillable before mutating
408 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000409 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000410 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000411 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000412 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
413 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000414 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000415 return false;
416 }
417 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000418 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
419 " interferences with " << VirtReg << "\n");
420 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000421
Andrew Trick18c57a82010-11-30 23:18:47 +0000422 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000423 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000424 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000425 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000426}
427
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000428// Add newly allocated physical registers to the MBB live in sets.
429void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000430 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000431 SlotIndexes *Indexes = LIS->getSlotIndexes();
432 if (MF->size() <= 1)
433 return;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000434
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000435 LiveIntervalUnion::SegmentIter SI;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000436 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
437 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
438 if (LiveUnion.empty())
439 continue;
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000440 MachineFunction::iterator MBB = llvm::next(MF->begin());
441 MachineFunction::iterator MFE = MF->end();
442 SlotIndex Start, Stop;
443 tie(Start, Stop) = Indexes->getMBBRange(MBB);
444 SI.setMap(LiveUnion.getMap());
445 SI.find(Start);
446 while (SI.valid()) {
447 if (SI.start() <= Start) {
448 if (!MBB->isLiveIn(PhysReg))
449 MBB->addLiveIn(PhysReg);
450 } else if (SI.start() > Stop)
Jakob Stoklund Olesendfaf0e22011-04-12 18:11:28 +0000451 MBB = Indexes->getMBBFromIndex(SI.start().getPrevIndex());
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000452 if (++MBB == MFE)
453 break;
454 tie(Start, Stop) = Indexes->getMBBRange(MBB);
455 SI.advanceTo(Start);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000456 }
457 }
458}
459
460
Andrew Trick14e8d712010-10-22 23:09:15 +0000461//===----------------------------------------------------------------------===//
462// RABasic Implementation
463//===----------------------------------------------------------------------===//
464
465// Driver for the register assignment and splitting heuristics.
466// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000467//
Andrew Trick18c57a82010-11-30 23:18:47 +0000468// This is a minimal implementation of register assignment and splitting that
469// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000470//
471// selectOrSplit can only be called once per live virtual register. We then do a
472// single interference test for each register the correct class until we find an
473// available register. So, the number of interference tests in the worst case is
474// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000475// minimal, there is no value in caching them outside the scope of
476// selectOrSplit().
477unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
478 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000479 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000480 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000481
Andrew Trick13bdbb02010-11-20 02:43:55 +0000482 // Check for an available register in this class.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000483 ArrayRef<unsigned> Order =
484 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
485 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
486 ++I) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000487 unsigned PhysReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000488
489 // Check interference and as a side effect, intialize queries for this
490 // VirtReg and its aliases.
491 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000492 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000493 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000494 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000495 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000496 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000497 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000498
Andrew Trickb853e6c2010-12-09 18:15:21 +0000499 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000500 // must have less spill weight.
501 if (interferingVirtReg->weight < VirtReg.weight ) {
502 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000503 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000504 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000505 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000506 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
507 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000508
Andrew Trick18c57a82010-11-30 23:18:47 +0000509 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000510
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000511 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
512 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000513 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000514 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000515 }
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000516
Andrew Trick18c57a82010-11-30 23:18:47 +0000517 // No other spill candidates were found, so spill the current VirtReg.
518 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000519 if (!VirtReg.isSpillable())
520 return ~0u;
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000521 LiveRangeEdit LRE(VirtReg, SplitVRegs);
522 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000523
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000524 // The live virtual register requesting allocation was spilled, so tell
525 // the caller not to allocate anything during this round.
526 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000527}
Andrew Trick14e8d712010-10-22 23:09:15 +0000528
Andrew Trick14e8d712010-10-22 23:09:15 +0000529bool RABasic::runOnMachineFunction(MachineFunction &mf) {
530 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
531 << "********** Function: "
532 << ((Value*)mf.getFunction())->getName() << '\n');
533
Andrew Trick18c57a82010-11-30 23:18:47 +0000534 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000535 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000536
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000537 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000538 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000539
Andrew Tricke16eecc2010-10-26 18:34:01 +0000540 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000541
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000542 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000543
Andrew Trick14e8d712010-10-22 23:09:15 +0000544 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000545 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000546
547 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000548 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000549
Andrew Trick071d1c02010-11-09 21:04:34 +0000550 // FIXME: Verification currently must run before VirtRegRewriter. We should
551 // make the rewriter a separate pass and override verifyAnalysis instead. When
552 // that happens, verification naturally falls under VerifyMachineCode.
553#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000554 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000555 // Verify accuracy of LiveIntervals. The standard machine code verifier
556 // ensures that each LiveIntervals covers all uses of the virtual reg.
557
Andrew Trick18c57a82010-11-30 23:18:47 +0000558 // FIXME: MachineVerifier is badly broken when using the standard
559 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
560 // inline spiller, some tests fail to verify because the coalescer does not
561 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000562 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000563
Andrew Trick071d1c02010-11-09 21:04:34 +0000564 // Verify that LiveIntervals are partitioned into unions and disjoint within
565 // the unions.
566 verify();
567 }
568#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000569
Andrew Trick14e8d712010-10-22 23:09:15 +0000570 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000571 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000572
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000573 // Write out new DBG_VALUE instructions.
574 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
575
Andrew Tricke16eecc2010-10-26 18:34:01 +0000576 // The pass output is in VirtRegMap. Release all the transient data.
577 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000578
Andrew Trick14e8d712010-10-22 23:09:15 +0000579 return true;
580}
581
Andrew Trick13bdbb02010-11-20 02:43:55 +0000582FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000583{
584 return new RABasic();
585}