blob: 01946c0db4a1c12c3c3574b3ee2520255af93def [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"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000017#include "LiveIntervalUnion.h"
18#include "RegAllocBase.h"
19#include "Spiller.h"
20#include "VirtRegMap.h"
21#include "VirtRegRewriter.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Function.h"
24#include "llvm/PassAnalysisSupport.h"
25#include "llvm/CodeGen/CalcSpillWeights.h"
26#include "llvm/CodeGen/LiveIntervalAnalysis.h"
27#include "llvm/CodeGen/LiveStackAnalysis.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000029#include "llvm/CodeGen/MachineLoopInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/CodeGen/RegAllocRegistry.h"
33#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace llvm;
40
41static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
42 createGreedyRegisterAllocator);
43
44namespace {
45class RAGreedy : public MachineFunctionPass, public RegAllocBase {
46 // context
47 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048 BitVector ReservedRegs;
49
50 // analyses
51 LiveStacks *LS;
52
53 // state
54 std::auto_ptr<Spiller> SpillerInstance;
55
56public:
57 RAGreedy();
58
59 /// Return the pass name.
60 virtual const char* getPassName() const {
61 return "Basic Register Allocator";
62 }
63
64 /// RAGreedy analysis usage.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
66
67 virtual void releaseMemory();
68
69 virtual Spiller &spiller() { return *SpillerInstance; }
70
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +000071 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000072
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
74 SmallVectorImpl<LiveInterval*> &SplitVRegs);
75
76 /// Perform register allocation.
77 virtual bool runOnMachineFunction(MachineFunction &mf);
78
79 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +000080
81private:
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +000082 bool checkUncachedInterference(LiveInterval &, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +000083 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
84 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000085};
86} // end anonymous namespace
87
88char RAGreedy::ID = 0;
89
90FunctionPass* llvm::createGreedyRegisterAllocator() {
91 return new RAGreedy();
92}
93
94RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
97 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
98 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
99 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
100 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
101 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
102 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
103 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
104}
105
106void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
107 AU.setPreservesCFG();
108 AU.addRequired<AliasAnalysis>();
109 AU.addPreserved<AliasAnalysis>();
110 AU.addRequired<LiveIntervals>();
111 AU.addPreserved<SlotIndexes>();
112 if (StrongPHIElim)
113 AU.addRequiredID(StrongPHIEliminationID);
114 AU.addRequiredTransitive<RegisterCoalescer>();
115 AU.addRequired<CalculateSpillWeights>();
116 AU.addRequired<LiveStacks>();
117 AU.addPreserved<LiveStacks>();
118 AU.addRequiredID(MachineDominatorsID);
119 AU.addPreservedID(MachineDominatorsID);
120 AU.addRequired<MachineLoopInfo>();
121 AU.addPreserved<MachineLoopInfo>();
122 AU.addRequired<VirtRegMap>();
123 AU.addPreserved<VirtRegMap>();
124 MachineFunctionPass::getAnalysisUsage(AU);
125}
126
127void RAGreedy::releaseMemory() {
128 SpillerInstance.reset(0);
129 RegAllocBase::releaseMemory();
130}
131
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000132float RAGreedy::getPriority(LiveInterval *LI) {
133 float Priority = LI->weight;
134
135 // Prioritize hinted registers so they are allocated first.
136 std::pair<unsigned, unsigned> Hint;
137 if (Hint.first || Hint.second) {
138 // The hint can be target specific, a virtual register, or a physreg.
139 Priority *= 2;
140
141 // Prefer physreg hints above anything else.
142 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
143 Priority *= 2;
144 }
145 return Priority;
146}
147
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000148// Check interference without using the cache.
149bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
150 unsigned PhysReg) {
151 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
152 if (subQ.checkInterference())
153 return true;
154 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
155 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
156 if (subQ.checkInterference())
157 return true;
158 }
159 return false;
160}
161
Andrew Trickb853e6c2010-12-09 18:15:21 +0000162// Attempt to reassign this virtual register to a different physical register.
163//
164// FIXME: we are not yet caching these "second-level" interferences discovered
165// in the sub-queries. These interferences can change with each call to
166// selectOrSplit. However, we could implement a "may-interfere" cache that
167// could be conservatively dirtied when we reassign or split.
168//
169// FIXME: This may result in a lot of alias queries. We could summarize alias
170// live intervals in their parent register's live union, but it's messy.
171bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
172 unsigned OldPhysReg) {
173 assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
174 "inconsistent phys reg assigment");
175
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000176 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
177 while (unsigned PhysReg = Order.next()) {
178 if (PhysReg == OldPhysReg)
Andrew Trickb853e6c2010-12-09 18:15:21 +0000179 continue;
180
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000181 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000182 continue;
183
Andrew Trickb853e6c2010-12-09 18:15:21 +0000184 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
185 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
186
187 // Reassign the interfering virtual reg to this physical reg.
188 PhysReg2LiveUnion[OldPhysReg].extract(InterferingVReg);
189 VRM->clearVirt(InterferingVReg.reg);
190 VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
191 PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
192
193 return true;
194 }
195 return false;
196}
197
198// Collect all virtual regs currently assigned to PhysReg that interfere with
199// VirtReg.
200//
201// Currently, for simplicity, we only attempt to reassign a single interference
202// within the same register class.
203bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
204 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
205
206 // Limit the interference search to one interference.
207 Q.collectInterferingVRegs(1);
208 assert(Q.interferingVRegs().size() == 1 &&
209 "expected at least one interference");
210
211 // Do not attempt reassignment unless we find only a single interference.
212 if (!Q.seenAllInterferences())
213 return false;
214
215 // Don't allow any interferences on aliases.
216 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
217 if (query(VirtReg, *AliasI).checkInterference())
218 return false;
219 }
220
221 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
222}
223
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000224unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
225 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
226 // Populate a list of physical register spill candidates.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000227 SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228
229 // Check for an available register in this class.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000230 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
231 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000232 // Check interference and as a side effect, intialize queries for this
233 // VirtReg and its aliases.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000234 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
235 if (InterfReg == 0) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000236 // Found an available register.
237 return PhysReg;
238 }
Jakob Stoklund Olesen9b0c4f82010-12-08 23:51:35 +0000239 assert(!VirtReg.empty() && "Empty VirtReg has interference");
Andrew Trickb853e6c2010-12-09 18:15:21 +0000240 LiveInterval *InterferingVirtReg =
241 Queries[InterfReg].firstInterference().liveUnionPos().value();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000242
Andrew Trickb853e6c2010-12-09 18:15:21 +0000243 // The current VirtReg must either be spillable, or one of its interferences
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000244 // must have less spill weight.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000245 if (InterferingVirtReg->weight < VirtReg.weight ) {
246 // For simplicity, only consider reassigning registers in the same class.
247 if (InterfReg == PhysReg)
248 ReassignCands.push_back(PhysReg);
249 else
250 PhysRegSpillCands.push_back(PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000251 }
252 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000253
254 // Try to reassign interfering physical register. Priority among
255 // PhysRegSpillCands does not matter yet, because the reassigned virtual
256 // registers will still be assigned to physical registers.
257 for (SmallVectorImpl<unsigned>::iterator PhysRegI = ReassignCands.begin(),
258 PhysRegE = ReassignCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
259 if (reassignInterferences(VirtReg, *PhysRegI))
260 // Reassignment successfull. The caller may allocate now to this PhysReg.
261 return *PhysRegI;
262 }
263
264 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
265 ReassignCands.end());
266
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000267 // Try to spill another interfering reg with less spill weight.
268 //
Andrew Trickb853e6c2010-12-09 18:15:21 +0000269 // FIXME: do this in two steps: (1) check for unspillable interferences while
270 // accumulating spill weight; (2) spill the interferences with lowest
271 // aggregate spill weight.
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000272 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
273 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
274
275 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
276
277 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
278 "Interference after spill.");
279 // Tell the caller to allocate to this newly freed physical register.
280 return *PhysRegI;
281 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000282
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000283 // No other spill candidates were found, so spill the current VirtReg.
284 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
285 SmallVector<LiveInterval*, 1> pendingSpills;
286
287 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
288
289 // The live virtual register requesting allocation was spilled, so tell
290 // the caller not to allocate anything during this round.
291 return 0;
292}
293
294bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
295 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
296 << "********** Function: "
297 << ((Value*)mf.getFunction())->getName() << '\n');
298
299 MF = &mf;
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000300 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000301
302 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +0000303 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304 allocatePhysRegs();
305 addMBBLiveIns(MF);
306
307 // Run rewriter
308 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
309 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
310
311 // The pass output is in VirtRegMap. Release all the transient data.
312 releaseMemory();
313
314 return true;
315}