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 "AllocationOrder.h"
17 #include "LiveIntervalUnion.h"
18 #include "RegAllocBase.h"
20 #include "VirtRegMap.h"
21 #include "VirtRegRewriter.h"
22 #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"
29 #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"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
41 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
42 createGreedyRegisterAllocator);
45 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
48 BitVector ReservedRegs;
54 std::auto_ptr<Spiller> SpillerInstance;
59 /// Return the pass name.
60 virtual const char* getPassName() const {
61 return "Basic Register Allocator";
64 /// RAGreedy analysis usage.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
67 virtual void releaseMemory();
69 virtual Spiller &spiller() { return *SpillerInstance; }
71 virtual float getPriority(LiveInterval *LI);
73 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
74 SmallVectorImpl<LiveInterval*> &SplitVRegs);
76 /// Perform register allocation.
77 virtual bool runOnMachineFunction(MachineFunction &mf);
82 bool checkUncachedInterference(LiveInterval &, unsigned);
83 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
84 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
86 } // end anonymous namespace
88 char RAGreedy::ID = 0;
90 FunctionPass* llvm::createGreedyRegisterAllocator() {
91 return new RAGreedy();
94 RAGreedy::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());
106 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
107 AU.setPreservesCFG();
108 AU.addRequired<AliasAnalysis>();
109 AU.addPreserved<AliasAnalysis>();
110 AU.addRequired<LiveIntervals>();
111 AU.addPreserved<SlotIndexes>();
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);
127 void RAGreedy::releaseMemory() {
128 SpillerInstance.reset(0);
129 RegAllocBase::releaseMemory();
132 float RAGreedy::getPriority(LiveInterval *LI) {
133 float Priority = LI->weight;
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.
141 // Prefer physreg hints above anything else.
142 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
148 // Check interference without using the cache.
149 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
151 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
152 if (subQ.checkInterference())
154 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
155 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
156 if (subQ.checkInterference())
162 // Attempt to reassign this virtual register to a different physical register.
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.
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.
171 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
172 unsigned OldPhysReg) {
173 assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
174 "inconsistent phys reg assigment");
176 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
177 while (unsigned PhysReg = Order.next()) {
178 if (PhysReg == OldPhysReg)
181 if (checkUncachedInterference(InterferingVReg, PhysReg))
184 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
185 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
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);
198 // Collect all virtual regs currently assigned to PhysReg that interfere with
201 // Currently, for simplicity, we only attempt to reassign a single interference
202 // within the same register class.
203 bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
204 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
206 // Limit the interference search to one interference.
207 Q.collectInterferingVRegs(1);
208 assert(Q.interferingVRegs().size() == 1 &&
209 "expected at least one interference");
211 // Do not attempt reassignment unless we find only a single interference.
212 if (!Q.seenAllInterferences())
215 // Don't allow any interferences on aliases.
216 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
217 if (query(VirtReg, *AliasI).checkInterference())
221 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
224 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
225 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
226 // Populate a list of physical register spill candidates.
227 SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
229 // Check for an available register in this class.
230 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
231 while (unsigned PhysReg = Order.next()) {
232 // Check interference and as a side effect, intialize queries for this
233 // VirtReg and its aliases.
234 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
235 if (InterfReg == 0) {
236 // Found an available register.
239 assert(!VirtReg.empty() && "Empty VirtReg has interference");
240 LiveInterval *InterferingVirtReg =
241 Queries[InterfReg].firstInterference().liveUnionPos().value();
243 // The current VirtReg must either be spillable, or one of its interferences
244 // must have less spill weight.
245 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);
250 PhysRegSpillCands.push_back(PhysReg);
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.
264 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
265 ReassignCands.end());
267 // Try to spill another interfering reg with less spill weight.
269 // 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.
272 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
273 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
275 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
277 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
278 "Interference after spill.");
279 // Tell the caller to allocate to this newly freed physical register.
283 // No other spill candidates were found, so spill the current VirtReg.
284 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
285 SmallVector<LiveInterval*, 1> pendingSpills;
287 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
289 // The live virtual register requesting allocation was spilled, so tell
290 // the caller not to allocate anything during this round.
294 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
295 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
296 << "********** Function: "
297 << ((Value*)mf.getFunction())->getName() << '\n');
300 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
302 ReservedRegs = TRI->getReservedRegs(*MF);
303 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
308 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
309 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
311 // The pass output is in VirtRegMap. Release all the transient data.