blob: f8eafe4200950878fd94fdf847225958d61a51e4 [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"
Andrew Tricke16eecc2010-10-26 18:34:01 +000016#include "LiveIntervalUnion.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000017#include "RegAllocBase.h"
18#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000021#include "VirtRegRewriter.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000022#include "llvm/ADT/OwningPtr.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000023#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000024#include "llvm/Function.h"
25#include "llvm/PassAnalysisSupport.h"
26#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000027#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000028#include "llvm/CodeGen/LiveStackAnalysis.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineLoopInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/CodeGen/RegAllocRegistry.h"
35#include "llvm/CodeGen/RegisterCoalescer.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000038#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000039#ifndef NDEBUG
40#include "llvm/ADT/SparseBitVector.h"
41#endif
Andrew Tricke141a492010-11-08 18:02:08 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000045
46#include <vector>
47#include <queue>
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000048#include <cstdlib>
Andrew Tricke16eecc2010-10-26 18:34:01 +000049
Andrew Trick14e8d712010-10-22 23:09:15 +000050using namespace llvm;
51
52static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
53 createBasicRegisterAllocator);
54
Andrew Trick071d1c02010-11-09 21:04:34 +000055// Temporary verification option until we can put verification inside
56// MachineVerifier.
57static cl::opt<bool>
58VerifyRegAlloc("verify-regalloc",
59 cl::desc("Verify live intervals before renaming"));
60
Benjamin Kramerc62feda2010-11-25 16:42:51 +000061namespace {
62
Andrew Trick071d1c02010-11-09 21:04:34 +000063class PhysicalRegisterDescription : public AbstractRegisterDescription {
Andrew Trick18c57a82010-11-30 23:18:47 +000064 const TargetRegisterInfo *TRI;
Andrew Trick071d1c02010-11-09 21:04:34 +000065public:
Andrew Trick18c57a82010-11-30 23:18:47 +000066 PhysicalRegisterDescription(const TargetRegisterInfo *T): TRI(T) {}
67 virtual const char *getName(unsigned Reg) const { return TRI->getName(Reg); }
Andrew Trick071d1c02010-11-09 21:04:34 +000068};
69
Andrew Trick14e8d712010-10-22 23:09:15 +000070/// RABasic provides a minimal implementation of the basic register allocation
71/// algorithm. It prioritizes live virtual registers by spill weight and spills
72/// whenever a register is unavailable. This is not practical in production but
73/// provides a useful baseline both for measuring other allocators and comparing
74/// the speed of the basic algorithm against other styles of allocators.
75class RABasic : public MachineFunctionPass, public RegAllocBase
76{
77 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000078 MachineFunction *MF;
79 const TargetMachine *TM;
80 MachineRegisterInfo *MRI;
81
82 BitVector ReservedRegs;
Andrew Trick14e8d712010-10-22 23:09:15 +000083
84 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000085 LiveStacks *LS;
86 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000087
88 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000089 std::auto_ptr<Spiller> SpillerInstance;
Andrew Trick14e8d712010-10-22 23:09:15 +000090
91public:
92 RABasic();
93
94 /// Return the pass name.
95 virtual const char* getPassName() const {
96 return "Basic Register Allocator";
97 }
98
99 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000100 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000101
102 virtual void releaseMemory();
103
Andrew Trick18c57a82010-11-30 23:18:47 +0000104 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000105
Andrew Trick18c57a82010-11-30 23:18:47 +0000106 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
107 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000108
109 /// Perform register allocation.
110 virtual bool runOnMachineFunction(MachineFunction &mf);
111
112 static char ID;
Andrew Trick316df4b2010-11-20 02:57:05 +0000113
114private:
115 void addMBBLiveIns();
Andrew Trick14e8d712010-10-22 23:09:15 +0000116};
117
118char RABasic::ID = 0;
119
120} // end anonymous namespace
121
Andrew Trick14e8d712010-10-22 23:09:15 +0000122RABasic::RABasic(): MachineFunctionPass(ID) {
123 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
124 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
125 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
126 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
127 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
128 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000129 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000130 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
131 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
132 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
133}
134
Andrew Trick18c57a82010-11-30 23:18:47 +0000135void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.setPreservesCFG();
137 AU.addRequired<AliasAnalysis>();
138 AU.addPreserved<AliasAnalysis>();
139 AU.addRequired<LiveIntervals>();
140 AU.addPreserved<SlotIndexes>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000141 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000142 AU.addRequiredID(StrongPHIEliminationID);
143 AU.addRequiredTransitive<RegisterCoalescer>();
144 AU.addRequired<CalculateSpillWeights>();
145 AU.addRequired<LiveStacks>();
146 AU.addPreserved<LiveStacks>();
147 AU.addRequiredID(MachineDominatorsID);
148 AU.addPreservedID(MachineDominatorsID);
149 AU.addRequired<MachineLoopInfo>();
150 AU.addPreserved<MachineLoopInfo>();
151 AU.addRequired<VirtRegMap>();
152 AU.addPreserved<VirtRegMap>();
153 DEBUG(AU.addRequired<RenderMachineFunction>());
154 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000155}
156
157void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000158 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000159 RegAllocBase::releaseMemory();
160}
161
Andrew Trick071d1c02010-11-09 21:04:34 +0000162#ifndef NDEBUG
163// Verify each LiveIntervalUnion.
164void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000165 LiveVirtRegBitSet VisitedVRegs;
166 OwningArrayPtr<LiveVirtRegBitSet>
167 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
168
Andrew Trick071d1c02010-11-09 21:04:34 +0000169 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000170 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
171 DEBUG(PhysicalRegisterDescription PRD(TRI);
172 PhysReg2LiveUnion[PhysReg].dump(&PRD));
173 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
174 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000175 // Union + intersection test could be done efficiently in one pass, but
176 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000177 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
178 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000179 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000180
Andrew Trick071d1c02010-11-09 21:04:34 +0000181 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000182 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000183 liItr != liEnd; ++liItr) {
184 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000185 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000186 if (!VRM->hasPhys(reg)) continue; // spilled?
187 unsigned PhysReg = VRM->getPhys(reg);
188 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000189 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000190 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000191 llvm_unreachable("unallocated live vreg");
192 }
193 }
194 // FIXME: I'm not sure how to verify spilled intervals.
195}
196#endif //!NDEBUG
197
Andrew Trick14e8d712010-10-22 23:09:15 +0000198//===----------------------------------------------------------------------===//
199// RegAllocBase Implementation
200//===----------------------------------------------------------------------===//
201
202// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000203void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
204 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000205 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000206 Array =
207 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
208 for (unsigned r = 0; r != NRegs; ++r)
209 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000210}
211
212void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
213 LiveIntervals &lis) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000214 TRI = &tri;
215 VRM = &vrm;
216 LIS = &lis;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000217 PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000218 // Cache an interferece query for each physical reg
Andrew Trick18c57a82010-11-30 23:18:47 +0000219 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000220}
221
Andrew Trick18c57a82010-11-30 23:18:47 +0000222void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000223 if (!Array)
224 return;
225 for (unsigned r = 0; r != NumRegs; ++r)
226 Array[r].~LiveIntervalUnion();
227 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000228 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000229 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000230}
231
232void RegAllocBase::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000233 PhysReg2LiveUnion.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000234}
235
Andrew Tricke16eecc2010-10-26 18:34:01 +0000236namespace llvm {
237/// This class defines a queue of live virtual registers prioritized by spill
238/// weight. The heaviest vreg is popped first.
239///
240/// Currently, this is trivial wrapper that gives us an opaque type in the
241/// header, but we may later give it a virtual interface for register allocators
242/// to override the priority queue comparator.
243class LiveVirtRegQueue {
244 typedef std::priority_queue
Andrew Trick18c57a82010-11-30 23:18:47 +0000245 <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority>
246 PriorityQ;
247 PriorityQ PQ;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000248
Andrew Tricke16eecc2010-10-26 18:34:01 +0000249public:
250 // Is the queue empty?
Andrew Trick18c57a82010-11-30 23:18:47 +0000251 bool empty() { return PQ.empty(); }
Andrew Trick13bdbb02010-11-20 02:43:55 +0000252
Andrew Tricke16eecc2010-10-26 18:34:01 +0000253 // Get the highest priority lvr (top + pop)
254 LiveInterval *get() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000255 LiveInterval *VirtReg = PQ.top();
256 PQ.pop();
257 return VirtReg;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000258 }
259 // Add this lvr to the queue
Andrew Trick18c57a82010-11-30 23:18:47 +0000260 void push(LiveInterval *VirtReg) {
261 PQ.push(VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000262 }
263};
264} // end namespace llvm
265
266// Visit all the live virtual registers. If they are already assigned to a
267// physical register, unify them with the corresponding LiveIntervalUnion,
268// otherwise push them on the priority queue for later assignment.
Andrew Trick18c57a82010-11-30 23:18:47 +0000269void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &VirtRegQ) {
270 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
271 unsigned RegNum = I->first;
272 LiveInterval &VirtReg = *I->second;
273 if (TargetRegisterInfo::isPhysicalRegister(RegNum)) {
274 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000275 }
276 else {
Andrew Trick18c57a82010-11-30 23:18:47 +0000277 VirtRegQ.push(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000278 }
279 }
280}
281
Andrew Trick18c57a82010-11-30 23:18:47 +0000282// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000283// selectOrSplit implementation.
284void RegAllocBase::allocatePhysRegs() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000285
286 // Push each vreg onto a queue or "precolor" by adding it to a physreg union.
287 LiveVirtRegQueue VirtRegQ;
288 seedLiveVirtRegs(VirtRegQ);
289
290 // Continue assigning vregs one at a time to available physical registers.
291 while (!VirtRegQ.empty()) {
292 // Pop the highest priority vreg.
293 LiveInterval *VirtReg = VirtRegQ.get();
294
295 // selectOrSplit requests the allocator to return an available physical
296 // register if possible and populate a list of new live intervals that
297 // result from splitting.
298 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
299 VirtRegVec SplitVRegs;
300 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
301
302 if (AvailablePhysReg) {
303 DEBUG(dbgs() << "allocating: " << TRI->getName(AvailablePhysReg) <<
304 " " << *VirtReg << '\n');
305 assert(!VRM->hasPhys(VirtReg->reg) && "duplicate vreg in union");
306 VRM->assignVirt2Phys(VirtReg->reg, AvailablePhysReg);
307 PhysReg2LiveUnion[AvailablePhysReg].unify(*VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000308 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000309 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
310 I != E; ++I) {
311 LiveInterval* SplitVirtReg = *I;
312 if (SplitVirtReg->empty()) continue;
313 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
314 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000315 "expect split value in virtual register");
Andrew Trick18c57a82010-11-30 23:18:47 +0000316 VirtRegQ.push(SplitVirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000317 }
318 }
319}
320
Andrew Trick18c57a82010-11-30 23:18:47 +0000321// Check if this live virtual register interferes with a physical register. If
322// not, then check for interference on each register that aliases with the
323// physical register. Return the interfering register.
324unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
325 unsigned PhysReg) {
326 if (query(VirtReg, PhysReg).checkInterference())
327 return PhysReg;
328 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
329 if (query(VirtReg, *AliasI).checkInterference())
330 return *AliasI;
Andrew Trick14e8d712010-10-22 23:09:15 +0000331 }
Andrew Tricke141a492010-11-08 18:02:08 +0000332 return 0;
333}
334
Andrew Trick18c57a82010-11-30 23:18:47 +0000335// Helper for spillInteferences() that spills all interfering vregs currently
336// assigned to this physical register.
337void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
338 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
339 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
340 assert(Q.seenAllInterferences() && "need collectInterferences()");
341 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000342
Andrew Trick18c57a82010-11-30 23:18:47 +0000343 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
344 E = PendingSpills.end(); I != E; ++I) {
345 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000346 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000347 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000348
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000349 // Deallocate the interfering vreg by removing it from the union.
350 // A LiveInterval instance may not be in a union during modification!
Andrew Trick18c57a82010-11-30 23:18:47 +0000351 PhysReg2LiveUnion[PhysReg].extract(SpilledVReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000352
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000353 // Clear the vreg assignment.
Andrew Trick18c57a82010-11-30 23:18:47 +0000354 VRM->clearVirt(SpilledVReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000355
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000356 // Spill the extracted interval.
Andrew Trick18c57a82010-11-30 23:18:47 +0000357 spiller().spill(&SpilledVReg, SplitVRegs, PendingSpills);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000358 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000359 // After extracting segments, the query's results are invalid. But keep the
360 // contents valid until we're done accessing pendingSpills.
361 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000362}
363
Andrew Trick18c57a82010-11-30 23:18:47 +0000364// Spill or split all live virtual registers currently unified under PhysReg
365// that interfere with VirtReg. The newly spilled or split live intervals are
366// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000367bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000368RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
369 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000370 // Record each interference and determine if all are spillable before mutating
371 // either the union or live intervals.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000372
Andrew Trick8a83d542010-11-11 17:46:29 +0000373 // Collect interferences assigned to the requested physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000374 LiveIntervalUnion::Query &QPreg = query(VirtReg, PhysReg);
375 unsigned NumInterferences = QPreg.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000376 if (QPreg.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000377 return false;
Andrew Tricke141a492010-11-08 18:02:08 +0000378 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000379 // Collect interferences assigned to any alias of the physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000380 for (const unsigned *asI = TRI->getAliasSet(PhysReg); *asI; ++asI) {
381 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
382 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000383 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000384 return false;
385 }
386 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000387 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
388 " interferences with " << VirtReg << "\n");
389 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000390
Andrew Trick18c57a82010-11-30 23:18:47 +0000391 // Spill each interfering vreg allocated to PhysReg or an alias.
392 spillReg(VirtReg, PhysReg, SplitVRegs);
393 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI)
394 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000395 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000396}
397
398//===----------------------------------------------------------------------===//
399// RABasic Implementation
400//===----------------------------------------------------------------------===//
401
402// Driver for the register assignment and splitting heuristics.
403// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000404//
Andrew Trick18c57a82010-11-30 23:18:47 +0000405// This is a minimal implementation of register assignment and splitting that
406// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000407//
408// selectOrSplit can only be called once per live virtual register. We then do a
409// single interference test for each register the correct class until we find an
410// available register. So, the number of interference tests in the worst case is
411// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000412// minimal, there is no value in caching them outside the scope of
413// selectOrSplit().
414unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
415 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000416 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000417 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000418
Andrew Trick13bdbb02010-11-20 02:43:55 +0000419 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000420 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
421 DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000422
Andrew Trick18c57a82010-11-30 23:18:47 +0000423 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
424 E = TRC->allocation_order_end(*MF);
425 I != E; ++I) {
426
427 unsigned PhysReg = *I;
428 if (ReservedRegs.test(PhysReg)) continue;
429
430 // Check interference and as a side effect, intialize queries for this
431 // VirtReg and its aliases.
432 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000433 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000434 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000435 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000436 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000437 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000438 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000439
Andrew Trick18c57a82010-11-30 23:18:47 +0000440 // The current VirtReg must either spillable, or one of its interferences
441 // must have less spill weight.
442 if (interferingVirtReg->weight < VirtReg.weight ) {
443 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000444 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000445 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000446 // Try to spill another interfering reg with less spill weight.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000447 //
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000448 // FIXME: RAGreedy will sort this list by spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000449 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
450 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000451
Andrew Trick18c57a82010-11-30 23:18:47 +0000452 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000453
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000454 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
455 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000456 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000457 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000458 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000459 // No other spill candidates were found, so spill the current VirtReg.
460 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000461 SmallVector<LiveInterval*, 1> pendingSpills;
Andrew Trick18c57a82010-11-30 23:18:47 +0000462
463 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000464
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000465 // The live virtual register requesting allocation was spilled, so tell
466 // the caller not to allocate anything during this round.
467 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000468}
Andrew Trick14e8d712010-10-22 23:09:15 +0000469
Andrew Trick18c57a82010-11-30 23:18:47 +0000470// Add newly allocated physical registers to the MBB live in sets.
Andrew Trick316df4b2010-11-20 02:57:05 +0000471void RABasic::addMBBLiveIns() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000472 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
473 MBBVec liveInMBBs;
474 MachineBasicBlock &entryMBB = *MF->begin();
Andrew Trick316df4b2010-11-20 02:57:05 +0000475
Andrew Trick18c57a82010-11-30 23:18:47 +0000476 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
477 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
478
479 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(),
480 SegEnd = LiveUnion.end();
481 SI != SegEnd; ++SI) {
482
Andrew Trick316df4b2010-11-20 02:57:05 +0000483 // Find the set of basic blocks which this range is live into...
Andrew Trick18c57a82010-11-30 23:18:47 +0000484 liveInMBBs.clear();
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000485 if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000486
487 // And add the physreg for this interval to their live-in sets.
488 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
489 I != E; ++I) {
490 MachineBasicBlock *MBB = *I;
491 if (MBB == &entryMBB) continue;
492 if (MBB->isLiveIn(PhysReg)) continue;
493 MBB->addLiveIn(PhysReg);
Andrew Trick316df4b2010-11-20 02:57:05 +0000494 }
495 }
496 }
497}
498
Andrew Trick14e8d712010-10-22 23:09:15 +0000499bool RABasic::runOnMachineFunction(MachineFunction &mf) {
500 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
501 << "********** Function: "
502 << ((Value*)mf.getFunction())->getName() << '\n');
503
Andrew Trick18c57a82010-11-30 23:18:47 +0000504 MF = &mf;
505 TM = &mf.getTarget();
506 MRI = &mf.getRegInfo();
Andrew Trick14e8d712010-10-22 23:09:15 +0000507
Andrew Trick18c57a82010-11-30 23:18:47 +0000508 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000509
Andrew Trick18c57a82010-11-30 23:18:47 +0000510 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Andrew Trick8a83d542010-11-11 17:46:29 +0000511 RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
Andrew Trick14e8d712010-10-22 23:09:15 +0000512 getAnalysis<LiveIntervals>());
513
Andrew Trick18c57a82010-11-30 23:18:47 +0000514 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000515
Andrew Trick18c57a82010-11-30 23:18:47 +0000516 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000517
Andrew Tricke16eecc2010-10-26 18:34:01 +0000518 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000519
Andrew Trick316df4b2010-11-20 02:57:05 +0000520 addMBBLiveIns();
521
Andrew Trick14e8d712010-10-22 23:09:15 +0000522 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000523 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000524
525 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000526 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000527
Andrew Trick071d1c02010-11-09 21:04:34 +0000528 // FIXME: Verification currently must run before VirtRegRewriter. We should
529 // make the rewriter a separate pass and override verifyAnalysis instead. When
530 // that happens, verification naturally falls under VerifyMachineCode.
531#ifndef NDEBUG
532 if (VerifyRegAlloc) {
533 // Verify accuracy of LiveIntervals. The standard machine code verifier
534 // ensures that each LiveIntervals covers all uses of the virtual reg.
535
Andrew Trick18c57a82010-11-30 23:18:47 +0000536 // FIXME: MachineVerifier is badly broken when using the standard
537 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
538 // inline spiller, some tests fail to verify because the coalescer does not
539 // always generate verifiable code.
540 MF->verify(this);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000541
Andrew Trick071d1c02010-11-09 21:04:34 +0000542 // Verify that LiveIntervals are partitioned into unions and disjoint within
543 // the unions.
544 verify();
545 }
546#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000547
Andrew Trick14e8d712010-10-22 23:09:15 +0000548 // Run rewriter
549 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
Andrew Trick18c57a82010-11-30 23:18:47 +0000550 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000551
552 // The pass output is in VirtRegMap. Release all the transient data.
553 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000554
Andrew Trick14e8d712010-10-22 23:09:15 +0000555 return true;
556}
557
Andrew Trick13bdbb02010-11-20 02:43:55 +0000558FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000559{
560 return new RABasic();
561}