blob: 73059ec0ab3c54db898154cf1eafdd09a6ebcb2c [file] [log] [blame]
Jakob Stoklund Olesenccc95812012-01-11 22:28:30 +00001//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
Andrew Trick14e8d712010-10-22 23:09:15 +00002//
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 Olesen5f2316a2011-06-03 20:34:53 +000016#include "RegAllocBase.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000017#include "LiveDebugVariables.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000018#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000021#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000022#include "llvm/Function.h"
23#include "llvm/PassAnalysisSupport.h"
24#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000025#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000026#include "llvm/CodeGen/LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000027#include "llvm/CodeGen/LiveStackAnalysis.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineLoopInfo.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
32#include "llvm/CodeGen/Passes.h"
33#include "llvm/CodeGen/RegAllocRegistry.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000036#include "llvm/Target/TargetRegisterInfo.h"
Andrew Tricke141a492010-11-08 18:02:08 +000037#include "llvm/Support/Debug.h"
Andrew Tricke141a492010-11-08 18:02:08 +000038#include "llvm/Support/raw_ostream.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000039
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000040#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000041#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000042
Andrew Trick14e8d712010-10-22 23:09:15 +000043using namespace llvm;
44
45static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46 createBasicRegisterAllocator);
47
Benjamin Kramerc62feda2010-11-25 16:42:51 +000048namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000049 struct CompSpillWeight {
50 bool operator()(LiveInterval *A, LiveInterval *B) const {
51 return A->weight < B->weight;
52 }
53 };
54}
55
56namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000057/// RABasic provides a minimal implementation of the basic register allocation
58/// algorithm. It prioritizes live virtual registers by spill weight and spills
59/// whenever a register is unavailable. This is not practical in production but
60/// provides a useful baseline both for measuring other allocators and comparing
61/// the speed of the basic algorithm against other styles of allocators.
62class RABasic : public MachineFunctionPass, public RegAllocBase
63{
64 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000065 MachineFunction *MF;
Andrew Trick14e8d712010-10-22 23:09:15 +000066
Benjamin Kramera9783662012-06-16 21:48:13 +000067#ifndef NDEBUG
Andrew Trick14e8d712010-10-22 23:09:15 +000068 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000069 RenderMachineFunction *RMF;
Benjamin Kramera9783662012-06-16 21:48:13 +000070#endif
Andrew Trick14e8d712010-10-22 23:09:15 +000071
72 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000073 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000074 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
75 CompSpillWeight> Queue;
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +000076
77 // Scratch space. Allocated here to avoid repeated malloc calls in
78 // selectOrSplit().
79 BitVector UsableRegs;
80
Andrew Trick14e8d712010-10-22 23:09:15 +000081public:
82 RABasic();
83
84 /// Return the pass name.
85 virtual const char* getPassName() const {
86 return "Basic Register Allocator";
87 }
88
89 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +000090 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +000091
92 virtual void releaseMemory();
93
Andrew Trick18c57a82010-11-30 23:18:47 +000094 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +000095
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000096 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
97
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000098 virtual void enqueue(LiveInterval *LI) {
99 Queue.push(LI);
100 }
101
102 virtual LiveInterval *dequeue() {
103 if (Queue.empty())
104 return 0;
105 LiveInterval *LI = Queue.top();
106 Queue.pop();
107 return LI;
108 }
109
Andrew Trick18c57a82010-11-30 23:18:47 +0000110 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
111 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000112
113 /// Perform register allocation.
114 virtual bool runOnMachineFunction(MachineFunction &mf);
115
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000116 // Helper for spilling all live virtual registers currently unified under preg
117 // that interfere with the most recently queried lvr. Return true if spilling
118 // was successful, and append any new spilled/split intervals to splitLVRs.
119 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
120 SmallVectorImpl<LiveInterval*> &SplitVRegs);
121
122 void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
123 SmallVectorImpl<LiveInterval*> &SplitVRegs);
124
Andrew Trick14e8d712010-10-22 23:09:15 +0000125 static char ID;
126};
127
128char RABasic::ID = 0;
129
130} // end anonymous namespace
131
Andrew Trick14e8d712010-10-22 23:09:15 +0000132RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000133 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000134 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
135 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000136 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000137 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000138 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
139 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000140 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000141 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
142 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
143 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
144}
145
Andrew Trick18c57a82010-11-30 23:18:47 +0000146void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.setPreservesCFG();
148 AU.addRequired<AliasAnalysis>();
149 AU.addPreserved<AliasAnalysis>();
150 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000151 AU.addPreserved<LiveIntervals>();
Andrew Trick18c57a82010-11-30 23:18:47 +0000152 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000153 AU.addRequired<LiveDebugVariables>();
154 AU.addPreserved<LiveDebugVariables>();
Andrew Trick18c57a82010-11-30 23:18:47 +0000155 AU.addRequired<CalculateSpillWeights>();
156 AU.addRequired<LiveStacks>();
157 AU.addPreserved<LiveStacks>();
158 AU.addRequiredID(MachineDominatorsID);
159 AU.addPreservedID(MachineDominatorsID);
160 AU.addRequired<MachineLoopInfo>();
161 AU.addPreserved<MachineLoopInfo>();
162 AU.addRequired<VirtRegMap>();
163 AU.addPreserved<VirtRegMap>();
164 DEBUG(AU.addRequired<RenderMachineFunction>());
165 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000166}
167
168void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000169 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000170 RegAllocBase::releaseMemory();
171}
172
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000173// Helper for spillInterferences() that spills all interfering vregs currently
174// assigned to this physical register.
175void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
176 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
177 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
178 assert(Q.seenAllInterferences() && "need collectInterferences()");
179 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
180
181 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
182 E = PendingSpills.end(); I != E; ++I) {
183 LiveInterval &SpilledVReg = **I;
184 DEBUG(dbgs() << "extracting from " <<
185 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
186
187 // Deallocate the interfering vreg by removing it from the union.
188 // A LiveInterval instance may not be in a union during modification!
189 unassign(SpilledVReg, PhysReg);
190
191 // Spill the extracted interval.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +0000192 LiveRangeEdit LRE(&SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000193 spiller().spill(LRE);
194 }
195 // After extracting segments, the query's results are invalid. But keep the
196 // contents valid until we're done accessing pendingSpills.
197 Q.clear();
198}
199
200// Spill or split all live virtual registers currently unified under PhysReg
201// that interfere with VirtReg. The newly spilled or split live intervals are
202// returned by appending them to SplitVRegs.
203bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
204 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
205 // Record each interference and determine if all are spillable before mutating
206 // either the union or live intervals.
207 unsigned NumInterferences = 0;
208 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000209 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
210 LiveIntervalUnion::Query &QAlias = query(VirtReg, *AI);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000211 NumInterferences += QAlias.collectInterferingVRegs();
212 if (QAlias.seenUnspillableVReg()) {
213 return false;
214 }
215 }
216 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
217 " interferences with " << VirtReg << "\n");
218 assert(NumInterferences > 0 && "expect interference");
219
220 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000221 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
222 spillReg(VirtReg, *AI, SplitVRegs);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000223 return true;
224}
225
Andrew Trick14e8d712010-10-22 23:09:15 +0000226// Driver for the register assignment and splitting heuristics.
227// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000228//
Andrew Trick18c57a82010-11-30 23:18:47 +0000229// This is a minimal implementation of register assignment and splitting that
230// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000231//
232// selectOrSplit can only be called once per live virtual register. We then do a
233// single interference test for each register the correct class until we find an
234// available register. So, the number of interference tests in the worst case is
235// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000236// minimal, there is no value in caching them outside the scope of
237// selectOrSplit().
238unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
239 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +0000240 // Check for register mask interference. When live ranges cross calls, the
241 // set of usable registers is reduced to the callee-saved ones.
242 bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
243
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000244 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000245 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000246
Andrew Trick13bdbb02010-11-20 02:43:55 +0000247 // Check for an available register in this class.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000248 ArrayRef<unsigned> Order =
249 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
250 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
251 ++I) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000252 unsigned PhysReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000253
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +0000254 // If PhysReg is clobbered by a register mask, it isn't useful for
255 // allocation or spilling.
256 if (CrossRegMasks && !UsableRegs.test(PhysReg))
257 continue;
258
Andrew Trick18c57a82010-11-30 23:18:47 +0000259 // Check interference and as a side effect, intialize queries for this
260 // VirtReg and its aliases.
261 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000262 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000263 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000264 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000265 }
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +0000266 LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
267 IntfQ.collectInterferingVRegs(1);
268 LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000269
Andrew Trickb853e6c2010-12-09 18:15:21 +0000270 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000271 // must have less spill weight.
272 if (interferingVirtReg->weight < VirtReg.weight ) {
273 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000274 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000275 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000276 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000277 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
278 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000279
Andrew Trick18c57a82010-11-30 23:18:47 +0000280 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000281
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000282 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
283 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000284 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000285 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000286 }
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000287
Andrew Trick18c57a82010-11-30 23:18:47 +0000288 // No other spill candidates were found, so spill the current VirtReg.
289 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000290 if (!VirtReg.isSpillable())
291 return ~0u;
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +0000292 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000293 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000294
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000295 // The live virtual register requesting allocation was spilled, so tell
296 // the caller not to allocate anything during this round.
297 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000298}
Andrew Trick14e8d712010-10-22 23:09:15 +0000299
Andrew Trick14e8d712010-10-22 23:09:15 +0000300bool RABasic::runOnMachineFunction(MachineFunction &mf) {
301 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
302 << "********** Function: "
303 << ((Value*)mf.getFunction())->getName() << '\n');
304
Andrew Trick18c57a82010-11-30 23:18:47 +0000305 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000306 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000307
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000308 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000309 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000310
Andrew Tricke16eecc2010-10-26 18:34:01 +0000311 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000312
313 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000314 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000315
316 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000317 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000318
Andrew Tricke16eecc2010-10-26 18:34:01 +0000319 releaseMemory();
Andrew Trick14e8d712010-10-22 23:09:15 +0000320 return true;
321}
322
Andrew Trick13bdbb02010-11-20 02:43:55 +0000323FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000324{
325 return new RABasic();
326}