1 //===-- RegAllocBasic.cpp - Basic 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 RABasic function pass, which provides a minimal
11 // implementation of the basic register allocator.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "AllocationOrder.h"
17 #include "RegAllocBase.h"
18 #include "LiveDebugVariables.h"
19 #include "RenderMachineFunction.h"
21 #include "VirtRegMap.h"
22 #include "LiveRegMatrix.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Function.h"
25 #include "llvm/PassAnalysisSupport.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveRangeEdit.h"
29 #include "llvm/CodeGen/LiveStackAnalysis.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/RegAllocRegistry.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
47 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
48 createBasicRegisterAllocator);
51 struct CompSpillWeight {
52 bool operator()(LiveInterval *A, LiveInterval *B) const {
53 return A->weight < B->weight;
59 /// RABasic provides a minimal implementation of the basic register allocation
60 /// algorithm. It prioritizes live virtual registers by spill weight and spills
61 /// whenever a register is unavailable. This is not practical in production but
62 /// provides a useful baseline both for measuring other allocators and comparing
63 /// the speed of the basic algorithm against other styles of allocators.
64 class RABasic : public MachineFunctionPass, public RegAllocBase
71 RenderMachineFunction *RMF;
75 std::auto_ptr<Spiller> SpillerInstance;
76 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
77 CompSpillWeight> Queue;
79 // Scratch space. Allocated here to avoid repeated malloc calls in
86 /// Return the pass name.
87 virtual const char* getPassName() const {
88 return "Basic Register Allocator";
91 /// RABasic analysis usage.
92 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
94 virtual void releaseMemory();
96 virtual Spiller &spiller() { return *SpillerInstance; }
98 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
100 virtual void enqueue(LiveInterval *LI) {
104 virtual LiveInterval *dequeue() {
107 LiveInterval *LI = Queue.top();
112 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
113 SmallVectorImpl<LiveInterval*> &SplitVRegs);
115 /// Perform register allocation.
116 virtual bool runOnMachineFunction(MachineFunction &mf);
118 // Helper for spilling all live virtual registers currently unified under preg
119 // that interfere with the most recently queried lvr. Return true if spilling
120 // was successful, and append any new spilled/split intervals to splitLVRs.
121 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
122 SmallVectorImpl<LiveInterval*> &SplitVRegs);
127 char RABasic::ID = 0;
129 } // end anonymous namespace
131 RABasic::RABasic(): MachineFunctionPass(ID) {
132 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
133 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
134 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
135 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
136 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
137 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
138 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
139 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
140 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
141 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
142 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
143 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
146 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.setPreservesCFG();
148 AU.addRequired<AliasAnalysis>();
149 AU.addPreserved<AliasAnalysis>();
150 AU.addRequired<LiveIntervals>();
151 AU.addPreserved<LiveIntervals>();
152 AU.addPreserved<SlotIndexes>();
153 AU.addRequired<LiveDebugVariables>();
154 AU.addPreserved<LiveDebugVariables>();
155 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 AU.addRequired<LiveRegMatrix>();
165 AU.addPreserved<LiveRegMatrix>();
166 DEBUG(AU.addRequired<RenderMachineFunction>());
167 MachineFunctionPass::getAnalysisUsage(AU);
170 void RABasic::releaseMemory() {
171 SpillerInstance.reset(0);
175 // Spill or split all live virtual registers currently unified under PhysReg
176 // that interfere with VirtReg. The newly spilled or split live intervals are
177 // returned by appending them to SplitVRegs.
178 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
179 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
180 // Record each interference and determine if all are spillable before mutating
181 // either the union or live intervals.
182 SmallVector<LiveInterval*, 8> Intfs;
184 // Collect interferences assigned to any alias of the physical register.
185 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
186 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
187 Q.collectInterferingVRegs();
188 if (Q.seenUnspillableVReg())
190 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
191 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
192 if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
194 Intfs.push_back(Intf);
197 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
198 " interferences with " << VirtReg << "\n");
199 assert(!Intfs.empty() && "expected interference");
201 // Spill each interfering vreg allocated to PhysReg or an alias.
202 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
203 LiveInterval &Spill = *Intfs[i];
206 if (!VRM->hasPhys(Spill.reg))
209 // Deallocate the interfering vreg by removing it from the union.
210 // A LiveInterval instance may not be in a union during modification!
211 Matrix->unassign(Spill);
213 // Spill the extracted interval.
214 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
215 spiller().spill(LRE);
220 // Driver for the register assignment and splitting heuristics.
221 // Manages iteration over the LiveIntervalUnions.
223 // This is a minimal implementation of register assignment and splitting that
224 // spills whenever we run out of registers.
226 // selectOrSplit can only be called once per live virtual register. We then do a
227 // single interference test for each register the correct class until we find an
228 // available register. So, the number of interference tests in the worst case is
229 // |vregs| * |machineregs|. And since the number of interference tests is
230 // minimal, there is no value in caching them outside the scope of
232 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
233 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
234 // Populate a list of physical register spill candidates.
235 SmallVector<unsigned, 8> PhysRegSpillCands;
237 // Check for an available register in this class.
238 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
239 while (unsigned PhysReg = Order.next()) {
240 // Check for interference in PhysReg
241 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
242 case LiveRegMatrix::IK_Free:
243 // PhysReg is available, allocate it.
246 case LiveRegMatrix::IK_VirtReg:
247 // Only virtual registers in the way, we may be able to spill them.
248 PhysRegSpillCands.push_back(PhysReg);
252 // RegMask or RegUnit interference.
257 // Try to spill another interfering reg with less spill weight.
258 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
259 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
260 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
263 assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
264 "Interference after spill.");
265 // Tell the caller to allocate to this newly freed physical register.
269 // No other spill candidates were found, so spill the current VirtReg.
270 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
271 if (!VirtReg.isSpillable())
273 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
274 spiller().spill(LRE);
276 // The live virtual register requesting allocation was spilled, so tell
277 // the caller not to allocate anything during this round.
281 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
282 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
283 << "********** Function: "
284 << ((Value*)mf.getFunction())->getName() << '\n');
287 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
289 RegAllocBase::init(getAnalysis<VirtRegMap>(),
290 getAnalysis<LiveIntervals>(),
291 getAnalysis<LiveRegMatrix>());
292 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
296 // Diagnostic output before rewriting
297 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
299 // optional HTML output
300 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
306 FunctionPass* llvm::createBasicRegisterAllocator()
308 return new RABasic();