blob: 6923908a32d920a7a8e957f575c4630da4cae66e [file] [log] [blame]
Andrew Trick14e8d712010-10-22 23:09:15 +00001//===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RABasic function pass, which provides a minimal
11// implementation of the basic register allocator.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Andrew Tricke16eecc2010-10-26 18:34:01 +000016#include "LiveIntervalUnion.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000017#include "RegAllocBase.h"
18#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000021#include "llvm/ADT/OwningPtr.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000022#include "llvm/ADT/Statistic.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000023#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000024#include "llvm/Function.h"
25#include "llvm/PassAnalysisSupport.h"
26#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000027#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000028#include "llvm/CodeGen/LiveStackAnalysis.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineLoopInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/CodeGen/RegAllocRegistry.h"
35#include "llvm/CodeGen/RegisterCoalescer.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000038#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000039#ifndef NDEBUG
40#include "llvm/ADT/SparseBitVector.h"
41#endif
Andrew Tricke141a492010-11-08 18:02:08 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000046
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000047#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000048#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000049
Andrew Trick14e8d712010-10-22 23:09:15 +000050using namespace llvm;
51
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumAssigned , "Number of registers assigned");
53STATISTIC(NumUnassigned , "Number of registers unassigned");
54STATISTIC(NumNewQueued , "Number of new live ranges queued");
55
Andrew Trick14e8d712010-10-22 23:09:15 +000056static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
57 createBasicRegisterAllocator);
58
Andrew Trick071d1c02010-11-09 21:04:34 +000059// Temporary verification option until we can put verification inside
60// MachineVerifier.
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000061static cl::opt<bool, true>
62VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled),
63 cl::desc("Verify during register allocation"));
Andrew Trick071d1c02010-11-09 21:04:34 +000064
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000065const char *RegAllocBase::TimerGroupName = "Register Allocation";
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000066bool RegAllocBase::VerifyEnabled = false;
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000067
Benjamin Kramerc62feda2010-11-25 16:42:51 +000068namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000069 struct CompSpillWeight {
70 bool operator()(LiveInterval *A, LiveInterval *B) const {
71 return A->weight < B->weight;
72 }
73 };
74}
75
76namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000077/// RABasic provides a minimal implementation of the basic register allocation
78/// algorithm. It prioritizes live virtual registers by spill weight and spills
79/// whenever a register is unavailable. This is not practical in production but
80/// provides a useful baseline both for measuring other allocators and comparing
81/// the speed of the basic algorithm against other styles of allocators.
82class RABasic : public MachineFunctionPass, public RegAllocBase
83{
84 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000085 MachineFunction *MF;
Andrew Trick18c57a82010-11-30 23:18:47 +000086 BitVector ReservedRegs;
Andrew Trick14e8d712010-10-22 23:09:15 +000087
88 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000089 LiveStacks *LS;
90 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000091
92 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000093 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000094 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
95 CompSpillWeight> Queue;
Andrew Trick14e8d712010-10-22 23:09:15 +000096public:
97 RABasic();
98
99 /// Return the pass name.
100 virtual const char* getPassName() const {
101 return "Basic Register Allocator";
102 }
103
104 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000105 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000106
107 virtual void releaseMemory();
108
Andrew Trick18c57a82010-11-30 23:18:47 +0000109 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000110
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000111 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
112
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000113 virtual void enqueue(LiveInterval *LI) {
114 Queue.push(LI);
115 }
116
117 virtual LiveInterval *dequeue() {
118 if (Queue.empty())
119 return 0;
120 LiveInterval *LI = Queue.top();
121 Queue.pop();
122 return LI;
123 }
124
Andrew Trick18c57a82010-11-30 23:18:47 +0000125 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
126 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000127
128 /// Perform register allocation.
129 virtual bool runOnMachineFunction(MachineFunction &mf);
130
131 static char ID;
132};
133
134char RABasic::ID = 0;
135
136} // end anonymous namespace
137
Andrew Trick14e8d712010-10-22 23:09:15 +0000138RABasic::RABasic(): MachineFunctionPass(ID) {
139 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
140 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
141 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
142 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
143 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
144 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000145 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000146 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
147 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
148 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
149}
150
Andrew Trick18c57a82010-11-30 23:18:47 +0000151void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
152 AU.setPreservesCFG();
153 AU.addRequired<AliasAnalysis>();
154 AU.addPreserved<AliasAnalysis>();
155 AU.addRequired<LiveIntervals>();
156 AU.addPreserved<SlotIndexes>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000157 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000158 AU.addRequiredID(StrongPHIEliminationID);
159 AU.addRequiredTransitive<RegisterCoalescer>();
160 AU.addRequired<CalculateSpillWeights>();
161 AU.addRequired<LiveStacks>();
162 AU.addPreserved<LiveStacks>();
163 AU.addRequiredID(MachineDominatorsID);
164 AU.addPreservedID(MachineDominatorsID);
165 AU.addRequired<MachineLoopInfo>();
166 AU.addPreserved<MachineLoopInfo>();
167 AU.addRequired<VirtRegMap>();
168 AU.addPreserved<VirtRegMap>();
169 DEBUG(AU.addRequired<RenderMachineFunction>());
170 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000171}
172
173void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000174 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000175 RegAllocBase::releaseMemory();
176}
177
Andrew Trick071d1c02010-11-09 21:04:34 +0000178#ifndef NDEBUG
179// Verify each LiveIntervalUnion.
180void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000181 LiveVirtRegBitSet VisitedVRegs;
182 OwningArrayPtr<LiveVirtRegBitSet>
183 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
184
Andrew Trick071d1c02010-11-09 21:04:34 +0000185 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000186 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000187 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000188 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
189 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000190 // Union + intersection test could be done efficiently in one pass, but
191 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000192 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
193 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000194 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000195
Andrew Trick071d1c02010-11-09 21:04:34 +0000196 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000197 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000198 liItr != liEnd; ++liItr) {
199 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000200 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000201 if (!VRM->hasPhys(reg)) continue; // spilled?
202 unsigned PhysReg = VRM->getPhys(reg);
203 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000204 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000205 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000206 llvm_unreachable("unallocated live vreg");
207 }
208 }
209 // FIXME: I'm not sure how to verify spilled intervals.
210}
211#endif //!NDEBUG
212
Andrew Trick14e8d712010-10-22 23:09:15 +0000213//===----------------------------------------------------------------------===//
214// RegAllocBase Implementation
215//===----------------------------------------------------------------------===//
216
217// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000218void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
219 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000220 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000221 Array =
222 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
223 for (unsigned r = 0; r != NRegs; ++r)
224 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000225}
226
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000227void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000228 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000229 TRI = &vrm.getTargetRegInfo();
230 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000231 VRM = &vrm;
232 LIS = &lis;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000233 PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000234 // Cache an interferece query for each physical reg
Andrew Trick18c57a82010-11-30 23:18:47 +0000235 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000236}
237
Andrew Trick18c57a82010-11-30 23:18:47 +0000238void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000239 if (!Array)
240 return;
241 for (unsigned r = 0; r != NumRegs; ++r)
242 Array[r].~LiveIntervalUnion();
243 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000244 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000245 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000246}
247
248void RegAllocBase::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000249 PhysReg2LiveUnion.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000250}
251
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000252// Visit all the live registers. If they are already assigned to a physical
253// register, unify them with the corresponding LiveIntervalUnion, otherwise push
254// them on the priority queue for later assignment.
255void RegAllocBase::seedLiveRegs() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000256 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
257 unsigned RegNum = I->first;
258 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000259 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000260 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000261 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000262 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000263 }
264}
265
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000266void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000267 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
268 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000269 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
270 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
271 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000272 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000273}
274
275void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000276 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
277 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000278 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
279 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
280 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000281 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000282}
283
Andrew Trick18c57a82010-11-30 23:18:47 +0000284// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000285// selectOrSplit implementation.
286void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000287 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000288
289 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000290 while (LiveInterval *VirtReg = dequeue()) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000291 // selectOrSplit requests the allocator to return an available physical
292 // register if possible and populate a list of new live intervals that
293 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000294 DEBUG(dbgs() << "\nselectOrSplit "
295 << MRI->getRegClass(VirtReg->reg)->getName()
296 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000297 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
298 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000299 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000300
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000301 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000302 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000303
Andrew Trick18c57a82010-11-30 23:18:47 +0000304 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
305 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000306 LiveInterval *SplitVirtReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000307 if (SplitVirtReg->empty()) continue;
308 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
309 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000310 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000311 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000312 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000313 }
314 }
315}
316
Andrew Trick18c57a82010-11-30 23:18:47 +0000317// Check if this live virtual register interferes with a physical register. If
318// not, then check for interference on each register that aliases with the
319// physical register. Return the interfering register.
320unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
321 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000322 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000323 if (query(VirtReg, *AliasI).checkInterference())
324 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000325 return 0;
326}
327
Andrew Trick18c57a82010-11-30 23:18:47 +0000328// Helper for spillInteferences() that spills all interfering vregs currently
329// assigned to this physical register.
330void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
331 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
332 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
333 assert(Q.seenAllInterferences() && "need collectInterferences()");
334 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000335
Andrew Trick18c57a82010-11-30 23:18:47 +0000336 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
337 E = PendingSpills.end(); I != E; ++I) {
338 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000339 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000340 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000341
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000342 // Deallocate the interfering vreg by removing it from the union.
343 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000344 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000345
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000346 // Spill the extracted interval.
Andrew Trick18c57a82010-11-30 23:18:47 +0000347 spiller().spill(&SpilledVReg, SplitVRegs, PendingSpills);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000348 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000349 // After extracting segments, the query's results are invalid. But keep the
350 // contents valid until we're done accessing pendingSpills.
351 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000352}
353
Andrew Trick18c57a82010-11-30 23:18:47 +0000354// Spill or split all live virtual registers currently unified under PhysReg
355// that interfere with VirtReg. The newly spilled or split live intervals are
356// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000357bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000358RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
359 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000360 // Record each interference and determine if all are spillable before mutating
361 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000362 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000363 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000364 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000365 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
366 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000367 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000368 return false;
369 }
370 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000371 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
372 " interferences with " << VirtReg << "\n");
373 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000374
Andrew Trick18c57a82010-11-30 23:18:47 +0000375 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000376 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000377 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000378 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000379}
380
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000381// Add newly allocated physical registers to the MBB live in sets.
382void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000383 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000384 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
385 MBBVec liveInMBBs;
386 MachineBasicBlock &entryMBB = *MF->begin();
387
388 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
389 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
390 if (LiveUnion.empty())
391 continue;
392 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(); SI.valid();
393 ++SI) {
394
395 // Find the set of basic blocks which this range is live into...
396 liveInMBBs.clear();
397 if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
398
399 // And add the physreg for this interval to their live-in sets.
400 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
401 I != E; ++I) {
402 MachineBasicBlock *MBB = *I;
403 if (MBB == &entryMBB) continue;
404 if (MBB->isLiveIn(PhysReg)) continue;
405 MBB->addLiveIn(PhysReg);
406 }
407 }
408 }
409}
410
411
Andrew Trick14e8d712010-10-22 23:09:15 +0000412//===----------------------------------------------------------------------===//
413// RABasic Implementation
414//===----------------------------------------------------------------------===//
415
416// Driver for the register assignment and splitting heuristics.
417// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000418//
Andrew Trick18c57a82010-11-30 23:18:47 +0000419// This is a minimal implementation of register assignment and splitting that
420// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000421//
422// selectOrSplit can only be called once per live virtual register. We then do a
423// single interference test for each register the correct class until we find an
424// available register. So, the number of interference tests in the worst case is
425// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000426// minimal, there is no value in caching them outside the scope of
427// selectOrSplit().
428unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
429 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000430 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000431 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000432
Andrew Trick13bdbb02010-11-20 02:43:55 +0000433 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000434 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000435
Andrew Trick18c57a82010-11-30 23:18:47 +0000436 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
437 E = TRC->allocation_order_end(*MF);
438 I != E; ++I) {
439
440 unsigned PhysReg = *I;
441 if (ReservedRegs.test(PhysReg)) continue;
442
443 // Check interference and as a side effect, intialize queries for this
444 // VirtReg and its aliases.
445 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000446 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000447 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000448 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000449 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000450 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000451 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000452
Andrew Trickb853e6c2010-12-09 18:15:21 +0000453 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000454 // must have less spill weight.
455 if (interferingVirtReg->weight < VirtReg.weight ) {
456 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000457 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000458 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000459 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000460 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
461 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000462
Andrew Trick18c57a82010-11-30 23:18:47 +0000463 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000464
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000465 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
466 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000467 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000468 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000469 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000470 // No other spill candidates were found, so spill the current VirtReg.
471 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000472 SmallVector<LiveInterval*, 1> pendingSpills;
Andrew Trick18c57a82010-11-30 23:18:47 +0000473
474 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000475
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000476 // The live virtual register requesting allocation was spilled, so tell
477 // the caller not to allocate anything during this round.
478 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000479}
Andrew Trick14e8d712010-10-22 23:09:15 +0000480
Andrew Trick14e8d712010-10-22 23:09:15 +0000481bool RABasic::runOnMachineFunction(MachineFunction &mf) {
482 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
483 << "********** Function: "
484 << ((Value*)mf.getFunction())->getName() << '\n');
485
Andrew Trick18c57a82010-11-30 23:18:47 +0000486 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000487 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000488
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000489 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Andrew Trick14e8d712010-10-22 23:09:15 +0000490
Andrew Trick18c57a82010-11-30 23:18:47 +0000491 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000492
Andrew Trick18c57a82010-11-30 23:18:47 +0000493 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000494
Andrew Tricke16eecc2010-10-26 18:34:01 +0000495 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000496
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000497 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000498
Andrew Trick14e8d712010-10-22 23:09:15 +0000499 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000500 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000501
502 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000503 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000504
Andrew Trick071d1c02010-11-09 21:04:34 +0000505 // FIXME: Verification currently must run before VirtRegRewriter. We should
506 // make the rewriter a separate pass and override verifyAnalysis instead. When
507 // that happens, verification naturally falls under VerifyMachineCode.
508#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000509 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000510 // Verify accuracy of LiveIntervals. The standard machine code verifier
511 // ensures that each LiveIntervals covers all uses of the virtual reg.
512
Andrew Trick18c57a82010-11-30 23:18:47 +0000513 // FIXME: MachineVerifier is badly broken when using the standard
514 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
515 // inline spiller, some tests fail to verify because the coalescer does not
516 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000517 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000518
Andrew Trick071d1c02010-11-09 21:04:34 +0000519 // Verify that LiveIntervals are partitioned into unions and disjoint within
520 // the unions.
521 verify();
522 }
523#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000524
Andrew Trick14e8d712010-10-22 23:09:15 +0000525 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000526 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000527
528 // The pass output is in VirtRegMap. Release all the transient data.
529 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000530
Andrew Trick14e8d712010-10-22 23:09:15 +0000531 return true;
532}
533
Andrew Trick13bdbb02010-11-20 02:43:55 +0000534FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000535{
536 return new RABasic();
537}