blob: af7da53b89bae0dfd60f13c69471fa61064ce5a7 [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 Olesencfafc542011-04-05 21:40:37 +000016#include "LiveDebugVariables.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000017#include "LiveIntervalUnion.h"
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +000018#include "LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000019#include "RegAllocBase.h"
20#include "RenderMachineFunction.h"
21#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000022#include "VirtRegMap.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000023#include "llvm/ADT/OwningPtr.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000025#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000026#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000029#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000030#include "llvm/CodeGen/LiveStackAnalysis.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineLoopInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/Passes.h"
36#include "llvm/CodeGen/RegAllocRegistry.h"
37#include "llvm/CodeGen/RegisterCoalescer.h"
38#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 Trick18c57a82010-11-30 23:18:47 +000088 BitVector ReservedRegs;
Andrew Trick14e8d712010-10-22 23:09:15 +000089
90 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000091 LiveStacks *LS;
92 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000093
94 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000095 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000096 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
97 CompSpillWeight> Queue;
Andrew Trick14e8d712010-10-22 23:09:15 +000098public:
99 RABasic();
100
101 /// Return the pass name.
102 virtual const char* getPassName() const {
103 return "Basic Register Allocator";
104 }
105
106 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000107 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000108
109 virtual void releaseMemory();
110
Andrew Trick18c57a82010-11-30 23:18:47 +0000111 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000112
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000113 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
114
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000115 virtual void enqueue(LiveInterval *LI) {
116 Queue.push(LI);
117 }
118
119 virtual LiveInterval *dequeue() {
120 if (Queue.empty())
121 return 0;
122 LiveInterval *LI = Queue.top();
123 Queue.pop();
124 return LI;
125 }
126
Andrew Trick18c57a82010-11-30 23:18:47 +0000127 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
128 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000129
130 /// Perform register allocation.
131 virtual bool runOnMachineFunction(MachineFunction &mf);
132
133 static char ID;
134};
135
136char RABasic::ID = 0;
137
138} // end anonymous namespace
139
Andrew Trick14e8d712010-10-22 23:09:15 +0000140RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000141 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000142 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
143 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
144 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
145 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
146 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
147 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000148 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000149 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
150 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
151 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
152}
153
Andrew Trick18c57a82010-11-30 23:18:47 +0000154void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.setPreservesCFG();
156 AU.addRequired<AliasAnalysis>();
157 AU.addPreserved<AliasAnalysis>();
158 AU.addRequired<LiveIntervals>();
159 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000160 AU.addRequired<LiveDebugVariables>();
161 AU.addPreserved<LiveDebugVariables>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000162 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000163 AU.addRequiredID(StrongPHIEliminationID);
164 AU.addRequiredTransitive<RegisterCoalescer>();
165 AU.addRequired<CalculateSpillWeights>();
166 AU.addRequired<LiveStacks>();
167 AU.addPreserved<LiveStacks>();
168 AU.addRequiredID(MachineDominatorsID);
169 AU.addPreservedID(MachineDominatorsID);
170 AU.addRequired<MachineLoopInfo>();
171 AU.addPreserved<MachineLoopInfo>();
172 AU.addRequired<VirtRegMap>();
173 AU.addPreserved<VirtRegMap>();
174 DEBUG(AU.addRequired<RenderMachineFunction>());
175 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000176}
177
178void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000179 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000180 RegAllocBase::releaseMemory();
181}
182
Andrew Trick071d1c02010-11-09 21:04:34 +0000183#ifndef NDEBUG
184// Verify each LiveIntervalUnion.
185void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000186 LiveVirtRegBitSet VisitedVRegs;
187 OwningArrayPtr<LiveVirtRegBitSet>
188 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
189
Andrew Trick071d1c02010-11-09 21:04:34 +0000190 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000191 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000192 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000193 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
194 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000195 // Union + intersection test could be done efficiently in one pass, but
196 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000197 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
198 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000199 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000200
Andrew Trick071d1c02010-11-09 21:04:34 +0000201 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000202 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000203 liItr != liEnd; ++liItr) {
204 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000205 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000206 if (!VRM->hasPhys(reg)) continue; // spilled?
207 unsigned PhysReg = VRM->getPhys(reg);
208 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000209 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000210 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000211 llvm_unreachable("unallocated live vreg");
212 }
213 }
214 // FIXME: I'm not sure how to verify spilled intervals.
215}
216#endif //!NDEBUG
217
Andrew Trick14e8d712010-10-22 23:09:15 +0000218//===----------------------------------------------------------------------===//
219// RegAllocBase Implementation
220//===----------------------------------------------------------------------===//
221
222// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000223void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
224 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000225 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000226 Array =
227 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
228 for (unsigned r = 0; r != NRegs; ++r)
229 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000230}
231
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000232void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000233 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000234 TRI = &vrm.getTargetRegInfo();
235 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000236 VRM = &vrm;
237 LIS = &lis;
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000238 const unsigned NumRegs = TRI->getNumRegs();
239 if (NumRegs != PhysReg2LiveUnion.numRegs()) {
240 PhysReg2LiveUnion.init(UnionAllocator, NumRegs);
241 // Cache an interferece query for each physical reg
242 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
243 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000244}
245
Andrew Trick18c57a82010-11-30 23:18:47 +0000246void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000247 if (!Array)
248 return;
249 for (unsigned r = 0; r != NumRegs; ++r)
250 Array[r].~LiveIntervalUnion();
251 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000252 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000253 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000254}
255
256void RegAllocBase::releaseMemory() {
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000257 for (unsigned r = 0, e = PhysReg2LiveUnion.numRegs(); r != e; ++r)
258 PhysReg2LiveUnion[r].clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000259}
260
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000261// Visit all the live registers. If they are already assigned to a physical
262// register, unify them with the corresponding LiveIntervalUnion, otherwise push
263// them on the priority queue for later assignment.
264void RegAllocBase::seedLiveRegs() {
Jakob Stoklund Olesenbd1926d2011-04-11 15:00:42 +0000265 NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled);
Andrew Trick18c57a82010-11-30 23:18:47 +0000266 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
267 unsigned RegNum = I->first;
268 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000269 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000270 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000271 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000272 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000273 }
274}
275
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000276void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000277 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
278 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000279 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
280 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
281 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000282 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000283}
284
285void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000286 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
287 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000288 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
289 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
290 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000291 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000292}
293
Andrew Trick18c57a82010-11-30 23:18:47 +0000294// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000295// selectOrSplit implementation.
296void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000297 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000298
299 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000300 while (LiveInterval *VirtReg = dequeue()) {
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000301 assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned");
302
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000303 // Unused registers can appear when the spiller coalesces snippets.
304 if (MRI->reg_nodbg_empty(VirtReg->reg)) {
305 DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
306 LIS->removeInterval(VirtReg->reg);
307 continue;
308 }
309
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000310 // Invalidate all interference queries, live ranges could have changed.
311 ++UserTag;
312
Andrew Trick18c57a82010-11-30 23:18:47 +0000313 // selectOrSplit requests the allocator to return an available physical
314 // register if possible and populate a list of new live intervals that
315 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000316 DEBUG(dbgs() << "\nselectOrSplit "
317 << MRI->getRegClass(VirtReg->reg)->getName()
318 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000319 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
320 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000321 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000322
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000323 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000324 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000325
Andrew Trick18c57a82010-11-30 23:18:47 +0000326 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
327 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000328 LiveInterval *SplitVirtReg = *I;
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000329 assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned");
330 if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
331 DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
332 LIS->removeInterval(SplitVirtReg->reg);
333 continue;
334 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000335 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
336 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000337 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000338 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000339 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000340 }
341 }
342}
343
Andrew Trick18c57a82010-11-30 23:18:47 +0000344// Check if this live virtual register interferes with a physical register. If
345// not, then check for interference on each register that aliases with the
346// physical register. Return the interfering register.
347unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
348 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000349 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000350 if (query(VirtReg, *AliasI).checkInterference())
351 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000352 return 0;
353}
354
Andrew Trick18c57a82010-11-30 23:18:47 +0000355// Helper for spillInteferences() that spills all interfering vregs currently
356// assigned to this physical register.
357void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
358 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
359 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
360 assert(Q.seenAllInterferences() && "need collectInterferences()");
361 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000362
Andrew Trick18c57a82010-11-30 23:18:47 +0000363 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
364 E = PendingSpills.end(); I != E; ++I) {
365 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000366 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000367 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000368
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000369 // Deallocate the interfering vreg by removing it from the union.
370 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000371 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000372
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000373 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000374 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
375 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000376 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000377 // After extracting segments, the query's results are invalid. But keep the
378 // contents valid until we're done accessing pendingSpills.
379 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000380}
381
Andrew Trick18c57a82010-11-30 23:18:47 +0000382// Spill or split all live virtual registers currently unified under PhysReg
383// that interfere with VirtReg. The newly spilled or split live intervals are
384// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000385bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000386RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
387 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000388 // Record each interference and determine if all are spillable before mutating
389 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000390 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000391 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000392 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000393 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
394 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000395 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000396 return false;
397 }
398 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000399 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
400 " interferences with " << VirtReg << "\n");
401 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000402
Andrew Trick18c57a82010-11-30 23:18:47 +0000403 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000404 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000405 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000406 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000407}
408
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000409// Add newly allocated physical registers to the MBB live in sets.
410void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000411 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000412 SlotIndexes *Indexes = LIS->getSlotIndexes();
413 if (MF->size() <= 1)
414 return;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000415
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000416 LiveIntervalUnion::SegmentIter SI;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000417 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
418 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
419 if (LiveUnion.empty())
420 continue;
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000421 MachineFunction::iterator MBB = llvm::next(MF->begin());
422 MachineFunction::iterator MFE = MF->end();
423 SlotIndex Start, Stop;
424 tie(Start, Stop) = Indexes->getMBBRange(MBB);
425 SI.setMap(LiveUnion.getMap());
426 SI.find(Start);
427 while (SI.valid()) {
428 if (SI.start() <= Start) {
429 if (!MBB->isLiveIn(PhysReg))
430 MBB->addLiveIn(PhysReg);
431 } else if (SI.start() > Stop)
432 MBB = Indexes->getMBBFromIndex(SI.start());
433 if (++MBB == MFE)
434 break;
435 tie(Start, Stop) = Indexes->getMBBRange(MBB);
436 SI.advanceTo(Start);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000437 }
438 }
439}
440
441
Andrew Trick14e8d712010-10-22 23:09:15 +0000442//===----------------------------------------------------------------------===//
443// RABasic Implementation
444//===----------------------------------------------------------------------===//
445
446// Driver for the register assignment and splitting heuristics.
447// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000448//
Andrew Trick18c57a82010-11-30 23:18:47 +0000449// This is a minimal implementation of register assignment and splitting that
450// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000451//
452// selectOrSplit can only be called once per live virtual register. We then do a
453// single interference test for each register the correct class until we find an
454// available register. So, the number of interference tests in the worst case is
455// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000456// minimal, there is no value in caching them outside the scope of
457// selectOrSplit().
458unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
459 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000460 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000461 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000462
Andrew Trick13bdbb02010-11-20 02:43:55 +0000463 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000464 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000465
Andrew Trick18c57a82010-11-30 23:18:47 +0000466 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
467 E = TRC->allocation_order_end(*MF);
468 I != E; ++I) {
469
470 unsigned PhysReg = *I;
471 if (ReservedRegs.test(PhysReg)) continue;
472
473 // Check interference and as a side effect, intialize queries for this
474 // VirtReg and its aliases.
475 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000476 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000477 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000478 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000479 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000480 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000481 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000482
Andrew Trickb853e6c2010-12-09 18:15:21 +0000483 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000484 // must have less spill weight.
485 if (interferingVirtReg->weight < VirtReg.weight ) {
486 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000487 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000488 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000489 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000490 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
491 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000492
Andrew Trick18c57a82010-11-30 23:18:47 +0000493 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000494
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000495 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
496 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000497 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000498 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000499 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000500 // No other spill candidates were found, so spill the current VirtReg.
501 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000502 LiveRangeEdit LRE(VirtReg, SplitVRegs);
503 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000504
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000505 // The live virtual register requesting allocation was spilled, so tell
506 // the caller not to allocate anything during this round.
507 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000508}
Andrew Trick14e8d712010-10-22 23:09:15 +0000509
Andrew Trick14e8d712010-10-22 23:09:15 +0000510bool RABasic::runOnMachineFunction(MachineFunction &mf) {
511 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
512 << "********** Function: "
513 << ((Value*)mf.getFunction())->getName() << '\n');
514
Andrew Trick18c57a82010-11-30 23:18:47 +0000515 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000516 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000517
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000518 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Andrew Trick14e8d712010-10-22 23:09:15 +0000519
Andrew Trick18c57a82010-11-30 23:18:47 +0000520 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000521
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000522 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000523
Andrew Tricke16eecc2010-10-26 18:34:01 +0000524 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000525
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000526 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000527
Andrew Trick14e8d712010-10-22 23:09:15 +0000528 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000529 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000530
531 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000532 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000533
Andrew Trick071d1c02010-11-09 21:04:34 +0000534 // FIXME: Verification currently must run before VirtRegRewriter. We should
535 // make the rewriter a separate pass and override verifyAnalysis instead. When
536 // that happens, verification naturally falls under VerifyMachineCode.
537#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000538 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000539 // Verify accuracy of LiveIntervals. The standard machine code verifier
540 // ensures that each LiveIntervals covers all uses of the virtual reg.
541
Andrew Trick18c57a82010-11-30 23:18:47 +0000542 // FIXME: MachineVerifier is badly broken when using the standard
543 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
544 // inline spiller, some tests fail to verify because the coalescer does not
545 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000546 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000547
Andrew Trick071d1c02010-11-09 21:04:34 +0000548 // Verify that LiveIntervals are partitioned into unions and disjoint within
549 // the unions.
550 verify();
551 }
552#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000553
Andrew Trick14e8d712010-10-22 23:09:15 +0000554 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000555 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000556
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000557 // Write out new DBG_VALUE instructions.
558 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
559
Andrew Tricke16eecc2010-10-26 18:34:01 +0000560 // The pass output is in VirtRegMap. Release all the transient data.
561 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000562
Andrew Trick14e8d712010-10-22 23:09:15 +0000563 return true;
564}
565
Andrew Trick13bdbb02010-11-20 02:43:55 +0000566FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000567{
568 return new RABasic();
569}