blob: d51be5202798b0f2dcd5ab29ea0995847cd552cd [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"
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +000017#include "LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000018#include "RegAllocBase.h"
19#include "RenderMachineFunction.h"
20#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000021#include "VirtRegMap.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000022#include "llvm/ADT/OwningPtr.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000023#include "llvm/ADT/Statistic.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000024#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000025#include "llvm/Function.h"
26#include "llvm/PassAnalysisSupport.h"
27#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000029#include "llvm/CodeGen/LiveStackAnalysis.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/CodeGen/MachineLoopInfo.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/Passes.h"
35#include "llvm/CodeGen/RegAllocRegistry.h"
36#include "llvm/CodeGen/RegisterCoalescer.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000039#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000040#ifndef NDEBUG
41#include "llvm/ADT/SparseBitVector.h"
42#endif
Andrew Tricke141a492010-11-08 18:02:08 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000046#include "llvm/Support/Timer.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000047
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000048#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000049#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000050
Andrew Trick14e8d712010-10-22 23:09:15 +000051using namespace llvm;
52
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumAssigned , "Number of registers assigned");
54STATISTIC(NumUnassigned , "Number of registers unassigned");
55STATISTIC(NumNewQueued , "Number of new live ranges queued");
56
Andrew Trick14e8d712010-10-22 23:09:15 +000057static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
58 createBasicRegisterAllocator);
59
Andrew Trick071d1c02010-11-09 21:04:34 +000060// Temporary verification option until we can put verification inside
61// MachineVerifier.
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000062static cl::opt<bool, true>
63VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled),
64 cl::desc("Verify during register allocation"));
Andrew Trick071d1c02010-11-09 21:04:34 +000065
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000066const char *RegAllocBase::TimerGroupName = "Register Allocation";
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000067bool RegAllocBase::VerifyEnabled = false;
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000068
Benjamin Kramerc62feda2010-11-25 16:42:51 +000069namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000070 struct CompSpillWeight {
71 bool operator()(LiveInterval *A, LiveInterval *B) const {
72 return A->weight < B->weight;
73 }
74 };
75}
76
77namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000078/// RABasic provides a minimal implementation of the basic register allocation
79/// algorithm. It prioritizes live virtual registers by spill weight and spills
80/// whenever a register is unavailable. This is not practical in production but
81/// provides a useful baseline both for measuring other allocators and comparing
82/// the speed of the basic algorithm against other styles of allocators.
83class RABasic : public MachineFunctionPass, public RegAllocBase
84{
85 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000086 MachineFunction *MF;
Andrew Trick18c57a82010-11-30 23:18:47 +000087 BitVector ReservedRegs;
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) {
140 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
141 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
142 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
143 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
144 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
145 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000146 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000147 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
148 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
149 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
150}
151
Andrew Trick18c57a82010-11-30 23:18:47 +0000152void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.setPreservesCFG();
154 AU.addRequired<AliasAnalysis>();
155 AU.addPreserved<AliasAnalysis>();
156 AU.addRequired<LiveIntervals>();
157 AU.addPreserved<SlotIndexes>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000158 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000159 AU.addRequiredID(StrongPHIEliminationID);
160 AU.addRequiredTransitive<RegisterCoalescer>();
161 AU.addRequired<CalculateSpillWeights>();
162 AU.addRequired<LiveStacks>();
163 AU.addPreserved<LiveStacks>();
164 AU.addRequiredID(MachineDominatorsID);
165 AU.addPreservedID(MachineDominatorsID);
166 AU.addRequired<MachineLoopInfo>();
167 AU.addPreserved<MachineLoopInfo>();
168 AU.addRequired<VirtRegMap>();
169 AU.addPreserved<VirtRegMap>();
170 DEBUG(AU.addRequired<RenderMachineFunction>());
171 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000172}
173
174void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000175 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000176 RegAllocBase::releaseMemory();
177}
178
Andrew Trick071d1c02010-11-09 21:04:34 +0000179#ifndef NDEBUG
180// Verify each LiveIntervalUnion.
181void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000182 LiveVirtRegBitSet VisitedVRegs;
183 OwningArrayPtr<LiveVirtRegBitSet>
184 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
185
Andrew Trick071d1c02010-11-09 21:04:34 +0000186 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000187 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000188 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000189 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
190 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000191 // Union + intersection test could be done efficiently in one pass, but
192 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000193 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
194 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000195 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000196
Andrew Trick071d1c02010-11-09 21:04:34 +0000197 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000198 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000199 liItr != liEnd; ++liItr) {
200 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000201 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000202 if (!VRM->hasPhys(reg)) continue; // spilled?
203 unsigned PhysReg = VRM->getPhys(reg);
204 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000205 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000206 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000207 llvm_unreachable("unallocated live vreg");
208 }
209 }
210 // FIXME: I'm not sure how to verify spilled intervals.
211}
212#endif //!NDEBUG
213
Andrew Trick14e8d712010-10-22 23:09:15 +0000214//===----------------------------------------------------------------------===//
215// RegAllocBase Implementation
216//===----------------------------------------------------------------------===//
217
218// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000219void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
220 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000221 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000222 Array =
223 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
224 for (unsigned r = 0; r != NRegs; ++r)
225 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000226}
227
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000228void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000229 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000230 TRI = &vrm.getTargetRegInfo();
231 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000232 VRM = &vrm;
233 LIS = &lis;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000234 PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000235 // Cache an interferece query for each physical reg
Andrew Trick18c57a82010-11-30 23:18:47 +0000236 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000237}
238
Andrew Trick18c57a82010-11-30 23:18:47 +0000239void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000240 if (!Array)
241 return;
242 for (unsigned r = 0; r != NumRegs; ++r)
243 Array[r].~LiveIntervalUnion();
244 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000245 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000246 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000247}
248
249void RegAllocBase::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000250 PhysReg2LiveUnion.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000251}
252
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000253// Visit all the live registers. If they are already assigned to a physical
254// register, unify them with the corresponding LiveIntervalUnion, otherwise push
255// them on the priority queue for later assignment.
256void RegAllocBase::seedLiveRegs() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000257 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
258 unsigned RegNum = I->first;
259 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000260 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000261 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000262 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000263 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000264 }
265}
266
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000267void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000268 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
269 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000270 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
271 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
272 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000273 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000274}
275
276void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000277 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
278 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000279 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
280 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
281 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000282 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000283}
284
Andrew Trick18c57a82010-11-30 23:18:47 +0000285// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000286// selectOrSplit implementation.
287void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000288 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000289
290 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000291 while (LiveInterval *VirtReg = dequeue()) {
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000292 // Unused registers can appear when the spiller coalesces snippets.
293 if (MRI->reg_nodbg_empty(VirtReg->reg)) {
294 DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
295 LIS->removeInterval(VirtReg->reg);
296 continue;
297 }
298
Andrew Trick18c57a82010-11-30 23:18:47 +0000299 // selectOrSplit requests the allocator to return an available physical
300 // register if possible and populate a list of new live intervals that
301 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000302 DEBUG(dbgs() << "\nselectOrSplit "
303 << MRI->getRegClass(VirtReg->reg)->getName()
304 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000305 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
306 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000307 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000308
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000309 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000310 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000311
Andrew Trick18c57a82010-11-30 23:18:47 +0000312 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
313 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000314 LiveInterval *SplitVirtReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000315 if (SplitVirtReg->empty()) continue;
316 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
317 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000318 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000319 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000320 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000321 }
322 }
323}
324
Andrew Trick18c57a82010-11-30 23:18:47 +0000325// Check if this live virtual register interferes with a physical register. If
326// not, then check for interference on each register that aliases with the
327// physical register. Return the interfering register.
328unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
329 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000330 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000331 if (query(VirtReg, *AliasI).checkInterference())
332 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000333 return 0;
334}
335
Andrew Trick18c57a82010-11-30 23:18:47 +0000336// Helper for spillInteferences() that spills all interfering vregs currently
337// assigned to this physical register.
338void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
339 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
340 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
341 assert(Q.seenAllInterferences() && "need collectInterferences()");
342 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000343
Andrew Trick18c57a82010-11-30 23:18:47 +0000344 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
345 E = PendingSpills.end(); I != E; ++I) {
346 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000347 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000348 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000349
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000350 // Deallocate the interfering vreg by removing it from the union.
351 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000352 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000353
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000354 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000355 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
356 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000357 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000358 // After extracting segments, the query's results are invalid. But keep the
359 // contents valid until we're done accessing pendingSpills.
360 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000361}
362
Andrew Trick18c57a82010-11-30 23:18:47 +0000363// Spill or split all live virtual registers currently unified under PhysReg
364// that interfere with VirtReg. The newly spilled or split live intervals are
365// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000366bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000367RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
368 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000369 // Record each interference and determine if all are spillable before mutating
370 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000371 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000372 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000373 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000374 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
375 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000376 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000377 return false;
378 }
379 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000380 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
381 " interferences with " << VirtReg << "\n");
382 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000383
Andrew Trick18c57a82010-11-30 23:18:47 +0000384 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000385 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000386 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000387 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000388}
389
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000390// Add newly allocated physical registers to the MBB live in sets.
391void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000392 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000393 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
394 MBBVec liveInMBBs;
395 MachineBasicBlock &entryMBB = *MF->begin();
396
397 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
398 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
399 if (LiveUnion.empty())
400 continue;
401 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(); SI.valid();
402 ++SI) {
403
404 // Find the set of basic blocks which this range is live into...
405 liveInMBBs.clear();
406 if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
407
408 // And add the physreg for this interval to their live-in sets.
409 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
410 I != E; ++I) {
411 MachineBasicBlock *MBB = *I;
412 if (MBB == &entryMBB) continue;
413 if (MBB->isLiveIn(PhysReg)) continue;
414 MBB->addLiveIn(PhysReg);
415 }
416 }
417 }
418}
419
420
Andrew Trick14e8d712010-10-22 23:09:15 +0000421//===----------------------------------------------------------------------===//
422// RABasic Implementation
423//===----------------------------------------------------------------------===//
424
425// Driver for the register assignment and splitting heuristics.
426// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000427//
Andrew Trick18c57a82010-11-30 23:18:47 +0000428// This is a minimal implementation of register assignment and splitting that
429// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000430//
431// selectOrSplit can only be called once per live virtual register. We then do a
432// single interference test for each register the correct class until we find an
433// available register. So, the number of interference tests in the worst case is
434// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000435// minimal, there is no value in caching them outside the scope of
436// selectOrSplit().
437unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
438 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000439 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000440 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000441
Andrew Trick13bdbb02010-11-20 02:43:55 +0000442 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000443 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000444
Andrew Trick18c57a82010-11-30 23:18:47 +0000445 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
446 E = TRC->allocation_order_end(*MF);
447 I != E; ++I) {
448
449 unsigned PhysReg = *I;
450 if (ReservedRegs.test(PhysReg)) continue;
451
452 // Check interference and as a side effect, intialize queries for this
453 // VirtReg and its aliases.
454 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000455 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000456 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000457 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000458 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000459 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000460 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000461
Andrew Trickb853e6c2010-12-09 18:15:21 +0000462 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000463 // must have less spill weight.
464 if (interferingVirtReg->weight < VirtReg.weight ) {
465 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000466 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000467 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000468 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000469 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
470 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000471
Andrew Trick18c57a82010-11-30 23:18:47 +0000472 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000473
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000474 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
475 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000476 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000477 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000478 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000479 // No other spill candidates were found, so spill the current VirtReg.
480 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000481 LiveRangeEdit LRE(VirtReg, SplitVRegs);
482 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000483
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000484 // The live virtual register requesting allocation was spilled, so tell
485 // the caller not to allocate anything during this round.
486 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000487}
Andrew Trick14e8d712010-10-22 23:09:15 +0000488
Andrew Trick14e8d712010-10-22 23:09:15 +0000489bool RABasic::runOnMachineFunction(MachineFunction &mf) {
490 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
491 << "********** Function: "
492 << ((Value*)mf.getFunction())->getName() << '\n');
493
Andrew Trick18c57a82010-11-30 23:18:47 +0000494 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000495 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000496
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000497 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Andrew Trick14e8d712010-10-22 23:09:15 +0000498
Andrew Trick18c57a82010-11-30 23:18:47 +0000499 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000500
Andrew Trick18c57a82010-11-30 23:18:47 +0000501 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000502
Andrew Tricke16eecc2010-10-26 18:34:01 +0000503 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000504
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000505 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000506
Andrew Trick14e8d712010-10-22 23:09:15 +0000507 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000508 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000509
510 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000511 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000512
Andrew Trick071d1c02010-11-09 21:04:34 +0000513 // FIXME: Verification currently must run before VirtRegRewriter. We should
514 // make the rewriter a separate pass and override verifyAnalysis instead. When
515 // that happens, verification naturally falls under VerifyMachineCode.
516#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000517 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000518 // Verify accuracy of LiveIntervals. The standard machine code verifier
519 // ensures that each LiveIntervals covers all uses of the virtual reg.
520
Andrew Trick18c57a82010-11-30 23:18:47 +0000521 // FIXME: MachineVerifier is badly broken when using the standard
522 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
523 // inline spiller, some tests fail to verify because the coalescer does not
524 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000525 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000526
Andrew Trick071d1c02010-11-09 21:04:34 +0000527 // Verify that LiveIntervals are partitioned into unions and disjoint within
528 // the unions.
529 verify();
530 }
531#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000532
Andrew Trick14e8d712010-10-22 23:09:15 +0000533 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000534 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000535
536 // The pass output is in VirtRegMap. Release all the transient data.
537 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000538
Andrew Trick14e8d712010-10-22 23:09:15 +0000539 return true;
540}
541
Andrew Trick13bdbb02010-11-20 02:43:55 +0000542FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000543{
544 return new RABasic();
545}