blob: 0e218a75d9944e83abc6e0f48b16a77c55565bd2 [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 Olesen953af2c2010-12-07 23:18:47 +0000238 PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000239 // Cache an interferece query for each physical reg
Andrew Trick18c57a82010-11-30 23:18:47 +0000240 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000241}
242
Andrew Trick18c57a82010-11-30 23:18:47 +0000243void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000244 if (!Array)
245 return;
246 for (unsigned r = 0; r != NumRegs; ++r)
247 Array[r].~LiveIntervalUnion();
248 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000249 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000250 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000251}
252
253void RegAllocBase::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000254 PhysReg2LiveUnion.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000255}
256
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000257// Visit all the live registers. If they are already assigned to a physical
258// register, unify them with the corresponding LiveIntervalUnion, otherwise push
259// them on the priority queue for later assignment.
260void RegAllocBase::seedLiveRegs() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000261 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
262 unsigned RegNum = I->first;
263 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000264 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000265 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000266 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000267 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000268 }
269}
270
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000271void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000272 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
273 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000274 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
275 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
276 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000277 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000278}
279
280void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000281 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
282 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000283 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
284 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
285 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000286 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000287}
288
Andrew Trick18c57a82010-11-30 23:18:47 +0000289// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000290// selectOrSplit implementation.
291void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000292 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000293
294 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000295 while (LiveInterval *VirtReg = dequeue()) {
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000296 assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned");
297
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000298 // Unused registers can appear when the spiller coalesces snippets.
299 if (MRI->reg_nodbg_empty(VirtReg->reg)) {
300 DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
301 LIS->removeInterval(VirtReg->reg);
302 continue;
303 }
304
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000305 // Invalidate all interference queries, live ranges could have changed.
306 ++UserTag;
307
Andrew Trick18c57a82010-11-30 23:18:47 +0000308 // selectOrSplit requests the allocator to return an available physical
309 // register if possible and populate a list of new live intervals that
310 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000311 DEBUG(dbgs() << "\nselectOrSplit "
312 << MRI->getRegClass(VirtReg->reg)->getName()
313 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000314 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
315 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000316 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000317
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000318 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000319 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000320
Andrew Trick18c57a82010-11-30 23:18:47 +0000321 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
322 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000323 LiveInterval *SplitVirtReg = *I;
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000324 assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned");
325 if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
326 DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
327 LIS->removeInterval(SplitVirtReg->reg);
328 continue;
329 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000330 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
331 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000332 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000333 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000334 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000335 }
336 }
337}
338
Andrew Trick18c57a82010-11-30 23:18:47 +0000339// Check if this live virtual register interferes with a physical register. If
340// not, then check for interference on each register that aliases with the
341// physical register. Return the interfering register.
342unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
343 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000344 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000345 if (query(VirtReg, *AliasI).checkInterference())
346 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000347 return 0;
348}
349
Andrew Trick18c57a82010-11-30 23:18:47 +0000350// Helper for spillInteferences() that spills all interfering vregs currently
351// assigned to this physical register.
352void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
353 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
354 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
355 assert(Q.seenAllInterferences() && "need collectInterferences()");
356 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000357
Andrew Trick18c57a82010-11-30 23:18:47 +0000358 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
359 E = PendingSpills.end(); I != E; ++I) {
360 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000361 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000362 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000363
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000364 // Deallocate the interfering vreg by removing it from the union.
365 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000366 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000367
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000368 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000369 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
370 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000371 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000372 // After extracting segments, the query's results are invalid. But keep the
373 // contents valid until we're done accessing pendingSpills.
374 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000375}
376
Andrew Trick18c57a82010-11-30 23:18:47 +0000377// Spill or split all live virtual registers currently unified under PhysReg
378// that interfere with VirtReg. The newly spilled or split live intervals are
379// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000380bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000381RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
382 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000383 // Record each interference and determine if all are spillable before mutating
384 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000385 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000386 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000387 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000388 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
389 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000390 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000391 return false;
392 }
393 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000394 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
395 " interferences with " << VirtReg << "\n");
396 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000397
Andrew Trick18c57a82010-11-30 23:18:47 +0000398 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000399 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000400 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000401 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000402}
403
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000404// Add newly allocated physical registers to the MBB live in sets.
405void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000406 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000407 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
408 MBBVec liveInMBBs;
409 MachineBasicBlock &entryMBB = *MF->begin();
410
411 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
412 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
413 if (LiveUnion.empty())
414 continue;
415 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(); SI.valid();
416 ++SI) {
417
418 // Find the set of basic blocks which this range is live into...
419 liveInMBBs.clear();
420 if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
421
422 // And add the physreg for this interval to their live-in sets.
423 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
424 I != E; ++I) {
425 MachineBasicBlock *MBB = *I;
426 if (MBB == &entryMBB) continue;
427 if (MBB->isLiveIn(PhysReg)) continue;
428 MBB->addLiveIn(PhysReg);
429 }
430 }
431 }
432}
433
434
Andrew Trick14e8d712010-10-22 23:09:15 +0000435//===----------------------------------------------------------------------===//
436// RABasic Implementation
437//===----------------------------------------------------------------------===//
438
439// Driver for the register assignment and splitting heuristics.
440// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000441//
Andrew Trick18c57a82010-11-30 23:18:47 +0000442// This is a minimal implementation of register assignment and splitting that
443// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000444//
445// selectOrSplit can only be called once per live virtual register. We then do a
446// single interference test for each register the correct class until we find an
447// available register. So, the number of interference tests in the worst case is
448// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000449// minimal, there is no value in caching them outside the scope of
450// selectOrSplit().
451unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
452 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000453 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000454 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000455
Andrew Trick13bdbb02010-11-20 02:43:55 +0000456 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000457 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000458
Andrew Trick18c57a82010-11-30 23:18:47 +0000459 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
460 E = TRC->allocation_order_end(*MF);
461 I != E; ++I) {
462
463 unsigned PhysReg = *I;
464 if (ReservedRegs.test(PhysReg)) continue;
465
466 // Check interference and as a side effect, intialize queries for this
467 // VirtReg and its aliases.
468 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000469 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000470 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000471 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000472 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000473 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000474 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000475
Andrew Trickb853e6c2010-12-09 18:15:21 +0000476 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000477 // must have less spill weight.
478 if (interferingVirtReg->weight < VirtReg.weight ) {
479 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000480 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000481 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000482 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000483 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
484 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000485
Andrew Trick18c57a82010-11-30 23:18:47 +0000486 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000487
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000488 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
489 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000490 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000491 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000492 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000493 // No other spill candidates were found, so spill the current VirtReg.
494 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000495 LiveRangeEdit LRE(VirtReg, SplitVRegs);
496 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000497
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000498 // The live virtual register requesting allocation was spilled, so tell
499 // the caller not to allocate anything during this round.
500 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000501}
Andrew Trick14e8d712010-10-22 23:09:15 +0000502
Andrew Trick14e8d712010-10-22 23:09:15 +0000503bool RABasic::runOnMachineFunction(MachineFunction &mf) {
504 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
505 << "********** Function: "
506 << ((Value*)mf.getFunction())->getName() << '\n');
507
Andrew Trick18c57a82010-11-30 23:18:47 +0000508 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000509 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000510
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000511 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Andrew Trick14e8d712010-10-22 23:09:15 +0000512
Andrew Trick18c57a82010-11-30 23:18:47 +0000513 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000514
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000515 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000516
Andrew Tricke16eecc2010-10-26 18:34:01 +0000517 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000518
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000519 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000520
Andrew Trick14e8d712010-10-22 23:09:15 +0000521 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000522 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000523
524 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000525 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000526
Andrew Trick071d1c02010-11-09 21:04:34 +0000527 // FIXME: Verification currently must run before VirtRegRewriter. We should
528 // make the rewriter a separate pass and override verifyAnalysis instead. When
529 // that happens, verification naturally falls under VerifyMachineCode.
530#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000531 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000532 // Verify accuracy of LiveIntervals. The standard machine code verifier
533 // ensures that each LiveIntervals covers all uses of the virtual reg.
534
Andrew Trick18c57a82010-11-30 23:18:47 +0000535 // FIXME: MachineVerifier is badly broken when using the standard
536 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
537 // inline spiller, some tests fail to verify because the coalescer does not
538 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000539 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000540
Andrew Trick071d1c02010-11-09 21:04:34 +0000541 // Verify that LiveIntervals are partitioned into unions and disjoint within
542 // the unions.
543 verify();
544 }
545#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000546
Andrew Trick14e8d712010-10-22 23:09:15 +0000547 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000548 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000549
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000550 // Write out new DBG_VALUE instructions.
551 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
552
Andrew Tricke16eecc2010-10-26 18:34:01 +0000553 // The pass output is in VirtRegMap. Release all the transient data.
554 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000555
Andrew Trick14e8d712010-10-22 23:09:15 +0000556 return true;
557}
558
Andrew Trick13bdbb02010-11-20 02:43:55 +0000559FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000560{
561 return new RABasic();
562}