blob: ecdc4193558d2b739ffa08c6097f9d7f1bb8c1b8 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy 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 RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
16#include "LiveIntervalUnion.h"
17#include "RegAllocBase.h"
18#include "Spiller.h"
19#include "VirtRegMap.h"
20#include "VirtRegRewriter.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000021#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Function.h"
23#include "llvm/PassAnalysisSupport.h"
24#include "llvm/CodeGen/CalcSpillWeights.h"
25#include "llvm/CodeGen/LiveIntervalAnalysis.h"
26#include "llvm/CodeGen/LiveStackAnalysis.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/Passes.h"
31#include "llvm/CodeGen/RegAllocRegistry.h"
32#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
37
38using namespace llvm;
39
40static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
41 createGreedyRegisterAllocator);
42
43namespace {
44class RAGreedy : public MachineFunctionPass, public RegAllocBase {
45 // context
46 MachineFunction *MF;
47 const TargetMachine *TM;
48 MachineRegisterInfo *MRI;
49
50 BitVector ReservedRegs;
51
52 // analyses
53 LiveStacks *LS;
54
55 // state
56 std::auto_ptr<Spiller> SpillerInstance;
57
58public:
59 RAGreedy();
60
61 /// Return the pass name.
62 virtual const char* getPassName() const {
63 return "Basic Register Allocator";
64 }
65
66 /// RAGreedy analysis usage.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
68
69 virtual void releaseMemory();
70
71 virtual Spiller &spiller() { return *SpillerInstance; }
72
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +000073 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000074
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000075 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
76 SmallVectorImpl<LiveInterval*> &SplitVRegs);
77
78 /// Perform register allocation.
79 virtual bool runOnMachineFunction(MachineFunction &mf);
80
81 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +000082
83private:
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +000084 bool checkUncachedInterference(LiveInterval &, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +000085 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
86 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000087};
88} // end anonymous namespace
89
90char RAGreedy::ID = 0;
91
92FunctionPass* llvm::createGreedyRegisterAllocator() {
93 return new RAGreedy();
94}
95
96RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
97 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
98 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
99 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
100 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
101 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
102 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
103 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
104 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
105 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
106}
107
108void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.setPreservesCFG();
110 AU.addRequired<AliasAnalysis>();
111 AU.addPreserved<AliasAnalysis>();
112 AU.addRequired<LiveIntervals>();
113 AU.addPreserved<SlotIndexes>();
114 if (StrongPHIElim)
115 AU.addRequiredID(StrongPHIEliminationID);
116 AU.addRequiredTransitive<RegisterCoalescer>();
117 AU.addRequired<CalculateSpillWeights>();
118 AU.addRequired<LiveStacks>();
119 AU.addPreserved<LiveStacks>();
120 AU.addRequiredID(MachineDominatorsID);
121 AU.addPreservedID(MachineDominatorsID);
122 AU.addRequired<MachineLoopInfo>();
123 AU.addPreserved<MachineLoopInfo>();
124 AU.addRequired<VirtRegMap>();
125 AU.addPreserved<VirtRegMap>();
126 MachineFunctionPass::getAnalysisUsage(AU);
127}
128
129void RAGreedy::releaseMemory() {
130 SpillerInstance.reset(0);
131 RegAllocBase::releaseMemory();
132}
133
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000134float RAGreedy::getPriority(LiveInterval *LI) {
135 float Priority = LI->weight;
136
137 // Prioritize hinted registers so they are allocated first.
138 std::pair<unsigned, unsigned> Hint;
139 if (Hint.first || Hint.second) {
140 // The hint can be target specific, a virtual register, or a physreg.
141 Priority *= 2;
142
143 // Prefer physreg hints above anything else.
144 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
145 Priority *= 2;
146 }
147 return Priority;
148}
149
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000150// Check interference without using the cache.
151bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
152 unsigned PhysReg) {
153 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
154 if (subQ.checkInterference())
155 return true;
156 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
157 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
158 if (subQ.checkInterference())
159 return true;
160 }
161 return false;
162}
163
Andrew Trickb853e6c2010-12-09 18:15:21 +0000164// Attempt to reassign this virtual register to a different physical register.
165//
166// FIXME: we are not yet caching these "second-level" interferences discovered
167// in the sub-queries. These interferences can change with each call to
168// selectOrSplit. However, we could implement a "may-interfere" cache that
169// could be conservatively dirtied when we reassign or split.
170//
171// FIXME: This may result in a lot of alias queries. We could summarize alias
172// live intervals in their parent register's live union, but it's messy.
173bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
174 unsigned OldPhysReg) {
175 assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
176 "inconsistent phys reg assigment");
177
178 const TargetRegisterClass *TRC = MRI->getRegClass(InterferingVReg.reg);
179 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
180 E = TRC->allocation_order_end(*MF);
181 I != E; ++I) {
182 unsigned PhysReg = *I;
Jakob Stoklund Olesenff092fa2010-12-09 21:20:46 +0000183 if (PhysReg == OldPhysReg || ReservedRegs.test(PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000184 continue;
185
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000186 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000187 continue;
188
Andrew Trickb853e6c2010-12-09 18:15:21 +0000189 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
190 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
191
192 // Reassign the interfering virtual reg to this physical reg.
193 PhysReg2LiveUnion[OldPhysReg].extract(InterferingVReg);
194 VRM->clearVirt(InterferingVReg.reg);
195 VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
196 PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
197
198 return true;
199 }
200 return false;
201}
202
203// Collect all virtual regs currently assigned to PhysReg that interfere with
204// VirtReg.
205//
206// Currently, for simplicity, we only attempt to reassign a single interference
207// within the same register class.
208bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
209 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
210
211 // Limit the interference search to one interference.
212 Q.collectInterferingVRegs(1);
213 assert(Q.interferingVRegs().size() == 1 &&
214 "expected at least one interference");
215
216 // Do not attempt reassignment unless we find only a single interference.
217 if (!Q.seenAllInterferences())
218 return false;
219
220 // Don't allow any interferences on aliases.
221 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
222 if (query(VirtReg, *AliasI).checkInterference())
223 return false;
224 }
225
226 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
227}
228
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
230 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
231 // Populate a list of physical register spill candidates.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000232 SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233
234 // Check for an available register in this class.
235 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
236 DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
237
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000238 // Preferred physical register computed from hints.
239 unsigned Hint = VRM->getRegAllocPref(VirtReg.reg);
240
241 // Try a hinted allocation.
242 if (Hint && !ReservedRegs.test(Hint) && TRC->contains(Hint) &&
243 checkPhysRegInterference(VirtReg, Hint) == 0)
244 return Hint;
245
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
247 E = TRC->allocation_order_end(*MF);
248 I != E; ++I) {
249
250 unsigned PhysReg = *I;
251 if (ReservedRegs.test(PhysReg)) continue;
252
253 // Check interference and as a side effect, intialize queries for this
254 // VirtReg and its aliases.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000255 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
256 if (InterfReg == 0) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000257 // Found an available register.
258 return PhysReg;
259 }
Jakob Stoklund Olesen9b0c4f82010-12-08 23:51:35 +0000260 assert(!VirtReg.empty() && "Empty VirtReg has interference");
Andrew Trickb853e6c2010-12-09 18:15:21 +0000261 LiveInterval *InterferingVirtReg =
262 Queries[InterfReg].firstInterference().liveUnionPos().value();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000263
Andrew Trickb853e6c2010-12-09 18:15:21 +0000264 // The current VirtReg must either be spillable, or one of its interferences
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000265 // must have less spill weight.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000266 if (InterferingVirtReg->weight < VirtReg.weight ) {
267 // For simplicity, only consider reassigning registers in the same class.
268 if (InterfReg == PhysReg)
269 ReassignCands.push_back(PhysReg);
270 else
271 PhysRegSpillCands.push_back(PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000272 }
273 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000274
275 // Try to reassign interfering physical register. Priority among
276 // PhysRegSpillCands does not matter yet, because the reassigned virtual
277 // registers will still be assigned to physical registers.
278 for (SmallVectorImpl<unsigned>::iterator PhysRegI = ReassignCands.begin(),
279 PhysRegE = ReassignCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
280 if (reassignInterferences(VirtReg, *PhysRegI))
281 // Reassignment successfull. The caller may allocate now to this PhysReg.
282 return *PhysRegI;
283 }
284
285 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
286 ReassignCands.end());
287
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000288 // Try to spill another interfering reg with less spill weight.
289 //
Andrew Trickb853e6c2010-12-09 18:15:21 +0000290 // FIXME: do this in two steps: (1) check for unspillable interferences while
291 // accumulating spill weight; (2) spill the interferences with lowest
292 // aggregate spill weight.
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000293 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
294 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
295
296 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
297
298 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
299 "Interference after spill.");
300 // Tell the caller to allocate to this newly freed physical register.
301 return *PhysRegI;
302 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000303
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304 // No other spill candidates were found, so spill the current VirtReg.
305 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
306 SmallVector<LiveInterval*, 1> pendingSpills;
307
308 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
309
310 // The live virtual register requesting allocation was spilled, so tell
311 // the caller not to allocate anything during this round.
312 return 0;
313}
314
315bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
316 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
317 << "********** Function: "
318 << ((Value*)mf.getFunction())->getName() << '\n');
319
320 MF = &mf;
321 TM = &mf.getTarget();
322 MRI = &mf.getRegInfo();
323
324 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
325 RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
326 getAnalysis<LiveIntervals>());
327
328 ReservedRegs = TRI->getReservedRegs(*MF);
329 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
330 allocatePhysRegs();
331 addMBBLiveIns(MF);
332
333 // Run rewriter
334 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
335 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
336
337 // The pass output is in VirtRegMap. Release all the transient data.
338 releaseMemory();
339
340 return true;
341}
342