1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RAGreedy function pass for register allocation in
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "LiveIntervalUnion.h"
17 #include "RegAllocBase.h"
19 #include "VirtRegMap.h"
20 #include "VirtRegRewriter.h"
21 #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"
28 #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"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
40 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
41 createGreedyRegisterAllocator);
44 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
47 const TargetMachine *TM;
48 MachineRegisterInfo *MRI;
50 BitVector ReservedRegs;
56 std::auto_ptr<Spiller> SpillerInstance;
61 /// Return the pass name.
62 virtual const char* getPassName() const {
63 return "Basic Register Allocator";
66 /// RAGreedy analysis usage.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
69 virtual void releaseMemory();
71 virtual Spiller &spiller() { return *SpillerInstance; }
73 virtual float getPriority(LiveInterval *LI);
75 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
76 SmallVectorImpl<LiveInterval*> &SplitVRegs);
78 /// Perform register allocation.
79 virtual bool runOnMachineFunction(MachineFunction &mf);
84 bool checkUncachedInterference(LiveInterval &, unsigned);
85 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
86 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
88 } // end anonymous namespace
90 char RAGreedy::ID = 0;
92 FunctionPass* llvm::createGreedyRegisterAllocator() {
93 return new RAGreedy();
96 RAGreedy::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());
108 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.setPreservesCFG();
110 AU.addRequired<AliasAnalysis>();
111 AU.addPreserved<AliasAnalysis>();
112 AU.addRequired<LiveIntervals>();
113 AU.addPreserved<SlotIndexes>();
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);
129 void RAGreedy::releaseMemory() {
130 SpillerInstance.reset(0);
131 RegAllocBase::releaseMemory();
134 float RAGreedy::getPriority(LiveInterval *LI) {
135 float Priority = LI->weight;
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.
143 // Prefer physreg hints above anything else.
144 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
150 // Check interference without using the cache.
151 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
153 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
154 if (subQ.checkInterference())
156 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
157 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
158 if (subQ.checkInterference())
164 // Attempt to reassign this virtual register to a different physical register.
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.
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.
173 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
174 unsigned OldPhysReg) {
175 assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
176 "inconsistent phys reg assigment");
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);
182 unsigned PhysReg = *I;
183 if (PhysReg == OldPhysReg || ReservedRegs.test(PhysReg))
186 if (checkUncachedInterference(InterferingVReg, PhysReg))
189 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
190 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
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);
203 // Collect all virtual regs currently assigned to PhysReg that interfere with
206 // Currently, for simplicity, we only attempt to reassign a single interference
207 // within the same register class.
208 bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
209 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
211 // Limit the interference search to one interference.
212 Q.collectInterferingVRegs(1);
213 assert(Q.interferingVRegs().size() == 1 &&
214 "expected at least one interference");
216 // Do not attempt reassignment unless we find only a single interference.
217 if (!Q.seenAllInterferences())
220 // Don't allow any interferences on aliases.
221 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
222 if (query(VirtReg, *AliasI).checkInterference())
226 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
229 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
230 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
231 // Populate a list of physical register spill candidates.
232 SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
234 // Check for an available register in this class.
235 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
236 DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
238 // Preferred physical register computed from hints.
239 unsigned Hint = VRM->getRegAllocPref(VirtReg.reg);
241 // Try a hinted allocation.
242 if (Hint && !ReservedRegs.test(Hint) && TRC->contains(Hint) &&
243 checkPhysRegInterference(VirtReg, Hint) == 0)
246 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
247 E = TRC->allocation_order_end(*MF);
250 unsigned PhysReg = *I;
251 if (ReservedRegs.test(PhysReg)) continue;
253 // Check interference and as a side effect, intialize queries for this
254 // VirtReg and its aliases.
255 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
256 if (InterfReg == 0) {
257 // Found an available register.
260 assert(!VirtReg.empty() && "Empty VirtReg has interference");
261 LiveInterval *InterferingVirtReg =
262 Queries[InterfReg].firstInterference().liveUnionPos().value();
264 // The current VirtReg must either be spillable, or one of its interferences
265 // must have less spill weight.
266 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);
271 PhysRegSpillCands.push_back(PhysReg);
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.
285 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
286 ReassignCands.end());
288 // Try to spill another interfering reg with less spill weight.
290 // 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.
293 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
294 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
296 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
298 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
299 "Interference after spill.");
300 // Tell the caller to allocate to this newly freed physical register.
304 // No other spill candidates were found, so spill the current VirtReg.
305 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
306 SmallVector<LiveInterval*, 1> pendingSpills;
308 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
310 // The live virtual register requesting allocation was spilled, so tell
311 // the caller not to allocate anything during this round.
315 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
316 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
317 << "********** Function: "
318 << ((Value*)mf.getFunction())->getName() << '\n');
321 TM = &mf.getTarget();
322 MRI = &mf.getRegInfo();
324 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
325 RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
326 getAnalysis<LiveIntervals>());
328 ReservedRegs = TRI->getReservedRegs(*MF);
329 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
334 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
335 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
337 // The pass output is in VirtRegMap. Release all the transient data.