blob: aab284805ea44e9cbbfb3d60c5bd0c0300e44bfa [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"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000038#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000039
40using namespace llvm;
41
42static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
43 createGreedyRegisterAllocator);
44
45namespace {
46class RAGreedy : public MachineFunctionPass, public RegAllocBase {
47 // context
48 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049 BitVector ReservedRegs;
50
51 // analyses
52 LiveStacks *LS;
53
54 // state
55 std::auto_ptr<Spiller> SpillerInstance;
56
57public:
58 RAGreedy();
59
60 /// Return the pass name.
61 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000062 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 }
64
65 /// RAGreedy analysis usage.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
67
68 virtual void releaseMemory();
69
70 virtual Spiller &spiller() { return *SpillerInstance; }
71
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +000072 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000073
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000074 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
75 SmallVectorImpl<LiveInterval*> &SplitVRegs);
76
77 /// Perform register allocation.
78 virtual bool runOnMachineFunction(MachineFunction &mf);
79
80 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +000081
82private:
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +000083 bool checkUncachedInterference(LiveInterval &, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +000084 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
85 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000086};
87} // end anonymous namespace
88
89char RAGreedy::ID = 0;
90
91FunctionPass* llvm::createGreedyRegisterAllocator() {
92 return new RAGreedy();
93}
94
95RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
97 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
98 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
99 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
100 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
101 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
102 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
103 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
104 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
105}
106
107void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.setPreservesCFG();
109 AU.addRequired<AliasAnalysis>();
110 AU.addPreserved<AliasAnalysis>();
111 AU.addRequired<LiveIntervals>();
112 AU.addPreserved<SlotIndexes>();
113 if (StrongPHIElim)
114 AU.addRequiredID(StrongPHIEliminationID);
115 AU.addRequiredTransitive<RegisterCoalescer>();
116 AU.addRequired<CalculateSpillWeights>();
117 AU.addRequired<LiveStacks>();
118 AU.addPreserved<LiveStacks>();
119 AU.addRequiredID(MachineDominatorsID);
120 AU.addPreservedID(MachineDominatorsID);
121 AU.addRequired<MachineLoopInfo>();
122 AU.addPreserved<MachineLoopInfo>();
123 AU.addRequired<VirtRegMap>();
124 AU.addPreserved<VirtRegMap>();
125 MachineFunctionPass::getAnalysisUsage(AU);
126}
127
128void RAGreedy::releaseMemory() {
129 SpillerInstance.reset(0);
130 RegAllocBase::releaseMemory();
131}
132
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000133float RAGreedy::getPriority(LiveInterval *LI) {
134 float Priority = LI->weight;
135
136 // Prioritize hinted registers so they are allocated first.
137 std::pair<unsigned, unsigned> Hint;
138 if (Hint.first || Hint.second) {
139 // The hint can be target specific, a virtual register, or a physreg.
140 Priority *= 2;
141
142 // Prefer physreg hints above anything else.
143 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
144 Priority *= 2;
145 }
146 return Priority;
147}
148
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000149// Check interference without using the cache.
150bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
151 unsigned PhysReg) {
152 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
153 if (subQ.checkInterference())
154 return true;
155 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
156 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
157 if (subQ.checkInterference())
158 return true;
159 }
160 return false;
161}
162
Andrew Trickb853e6c2010-12-09 18:15:21 +0000163// Attempt to reassign this virtual register to a different physical register.
164//
165// FIXME: we are not yet caching these "second-level" interferences discovered
166// in the sub-queries. These interferences can change with each call to
167// selectOrSplit. However, we could implement a "may-interfere" cache that
168// could be conservatively dirtied when we reassign or split.
169//
170// FIXME: This may result in a lot of alias queries. We could summarize alias
171// live intervals in their parent register's live union, but it's messy.
172bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
173 unsigned OldPhysReg) {
174 assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
175 "inconsistent phys reg assigment");
176
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000177 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
178 while (unsigned PhysReg = Order.next()) {
179 if (PhysReg == OldPhysReg)
Andrew Trickb853e6c2010-12-09 18:15:21 +0000180 continue;
181
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000182 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000183 continue;
184
Andrew Trickb853e6c2010-12-09 18:15:21 +0000185 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
186 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
187
188 // Reassign the interfering virtual reg to this physical reg.
189 PhysReg2LiveUnion[OldPhysReg].extract(InterferingVReg);
190 VRM->clearVirt(InterferingVReg.reg);
191 VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
192 PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
193
194 return true;
195 }
196 return false;
197}
198
199// Collect all virtual regs currently assigned to PhysReg that interfere with
200// VirtReg.
201//
202// Currently, for simplicity, we only attempt to reassign a single interference
203// within the same register class.
204bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
205 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
206
207 // Limit the interference search to one interference.
208 Q.collectInterferingVRegs(1);
209 assert(Q.interferingVRegs().size() == 1 &&
210 "expected at least one interference");
211
212 // Do not attempt reassignment unless we find only a single interference.
213 if (!Q.seenAllInterferences())
214 return false;
215
216 // Don't allow any interferences on aliases.
217 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
218 if (query(VirtReg, *AliasI).checkInterference())
219 return false;
220 }
221
222 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
223}
224
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000225unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
226 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
227 // Populate a list of physical register spill candidates.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000228 SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229
230 // Check for an available register in this class.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000231 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
232 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 // Check interference and as a side effect, intialize queries for this
234 // VirtReg and its aliases.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000235 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
236 if (InterfReg == 0) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 // Found an available register.
238 return PhysReg;
239 }
Jakob Stoklund Olesen9b0c4f82010-12-08 23:51:35 +0000240 assert(!VirtReg.empty() && "Empty VirtReg has interference");
Andrew Trickb853e6c2010-12-09 18:15:21 +0000241 LiveInterval *InterferingVirtReg =
242 Queries[InterfReg].firstInterference().liveUnionPos().value();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000243
Andrew Trickb853e6c2010-12-09 18:15:21 +0000244 // The current VirtReg must either be spillable, or one of its interferences
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000245 // must have less spill weight.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000246 if (InterferingVirtReg->weight < VirtReg.weight ) {
247 // For simplicity, only consider reassigning registers in the same class.
248 if (InterfReg == PhysReg)
249 ReassignCands.push_back(PhysReg);
250 else
251 PhysRegSpillCands.push_back(PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000252 }
253 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000254
255 // Try to reassign interfering physical register. Priority among
256 // PhysRegSpillCands does not matter yet, because the reassigned virtual
257 // registers will still be assigned to physical registers.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000258 {
259 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
260 for (SmallVectorImpl<unsigned>::iterator PhysRegI = ReassignCands.begin(),
261 PhysRegE = ReassignCands.end(); PhysRegI != PhysRegE; ++PhysRegI)
262 if (reassignInterferences(VirtReg, *PhysRegI))
263 // Reassignment successfull. Allocate now to this PhysReg.
264 return *PhysRegI;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000265 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000266 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
267 ReassignCands.end());
268
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000269 // Try to spill another interfering reg with less spill weight.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000270 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000271 //
Andrew Trickb853e6c2010-12-09 18:15:21 +0000272 // FIXME: do this in two steps: (1) check for unspillable interferences while
273 // accumulating spill weight; (2) spill the interferences with lowest
274 // aggregate spill weight.
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000275 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
276 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
277
278 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
279
280 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
281 "Interference after spill.");
282 // Tell the caller to allocate to this newly freed physical register.
283 return *PhysRegI;
284 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000285
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000286 // No other spill candidates were found, so spill the current VirtReg.
287 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
288 SmallVector<LiveInterval*, 1> pendingSpills;
289
290 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
291
292 // The live virtual register requesting allocation was spilled, so tell
293 // the caller not to allocate anything during this round.
294 return 0;
295}
296
297bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
298 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
299 << "********** Function: "
300 << ((Value*)mf.getFunction())->getName() << '\n');
301
302 MF = &mf;
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000303 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304
305 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +0000306 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000307 allocatePhysRegs();
308 addMBBLiveIns(MF);
309
310 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000311 {
312 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
313 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
314 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
315 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000316
317 // The pass output is in VirtRegMap. Release all the transient data.
318 releaseMemory();
319
320 return true;
321}