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 "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "LiveDebugVariables.h"
19 #include "RegAllocBase.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/CalcSpillWeights.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/LiveRangeEdit.h"
25 #include "llvm/CodeGen/LiveRegMatrix.h"
26 #include "llvm/CodeGen/LiveStackAnalysis.h"
27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.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/RegAllocRegistry.h"
33 #include "llvm/CodeGen/VirtRegMap.h"
34 #include "llvm/PassAnalysisSupport.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
44 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
45 createBasicRegisterAllocator);
48 struct CompSpillWeight {
49 bool operator()(LiveInterval *A, LiveInterval *B) const {
50 return A->weight < B->weight;
56 /// RABasic provides a minimal implementation of the basic register allocation
57 /// algorithm. It prioritizes live virtual registers by spill weight and spills
58 /// whenever a register is unavailable. This is not practical in production but
59 /// provides a useful baseline both for measuring other allocators and comparing
60 /// the speed of the basic algorithm against other styles of allocators.
61 class RABasic : public MachineFunctionPass, public RegAllocBase
67 OwningPtr<Spiller> SpillerInstance;
68 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
69 CompSpillWeight> Queue;
71 // Scratch space. Allocated here to avoid repeated malloc calls in
78 /// Return the pass name.
79 virtual const char* getPassName() const {
80 return "Basic Register Allocator";
83 /// RABasic analysis usage.
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
86 virtual void releaseMemory();
88 virtual Spiller &spiller() { return *SpillerInstance; }
90 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
92 virtual void enqueue(LiveInterval *LI) {
96 virtual LiveInterval *dequeue() {
99 LiveInterval *LI = Queue.top();
104 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
105 SmallVectorImpl<unsigned> &SplitVRegs);
107 /// Perform register allocation.
108 virtual bool runOnMachineFunction(MachineFunction &mf);
110 // Helper for spilling all live virtual registers currently unified under preg
111 // that interfere with the most recently queried lvr. Return true if spilling
112 // was successful, and append any new spilled/split intervals to splitLVRs.
113 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
114 SmallVectorImpl<unsigned> &SplitVRegs);
119 char RABasic::ID = 0;
121 } // end anonymous namespace
123 RABasic::RABasic(): MachineFunctionPass(ID) {
124 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
125 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
126 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
127 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
128 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
129 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
130 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
131 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
132 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
133 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
134 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
137 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
138 AU.setPreservesCFG();
139 AU.addRequired<AliasAnalysis>();
140 AU.addPreserved<AliasAnalysis>();
141 AU.addRequired<LiveIntervals>();
142 AU.addPreserved<LiveIntervals>();
143 AU.addPreserved<SlotIndexes>();
144 AU.addRequired<LiveDebugVariables>();
145 AU.addPreserved<LiveDebugVariables>();
146 AU.addRequired<CalculateSpillWeights>();
147 AU.addRequired<LiveStacks>();
148 AU.addPreserved<LiveStacks>();
149 AU.addRequired<MachineBlockFrequencyInfo>();
150 AU.addPreserved<MachineBlockFrequencyInfo>();
151 AU.addRequiredID(MachineDominatorsID);
152 AU.addPreservedID(MachineDominatorsID);
153 AU.addRequired<MachineLoopInfo>();
154 AU.addPreserved<MachineLoopInfo>();
155 AU.addRequired<VirtRegMap>();
156 AU.addPreserved<VirtRegMap>();
157 AU.addRequired<LiveRegMatrix>();
158 AU.addPreserved<LiveRegMatrix>();
159 MachineFunctionPass::getAnalysisUsage(AU);
162 void RABasic::releaseMemory() {
163 SpillerInstance.reset(0);
167 // Spill or split all live virtual registers currently unified under PhysReg
168 // that interfere with VirtReg. The newly spilled or split live intervals are
169 // returned by appending them to SplitVRegs.
170 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
171 SmallVectorImpl<unsigned> &SplitVRegs) {
172 // Record each interference and determine if all are spillable before mutating
173 // either the union or live intervals.
174 SmallVector<LiveInterval*, 8> Intfs;
176 // Collect interferences assigned to any alias of the physical register.
177 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
178 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
179 Q.collectInterferingVRegs();
180 if (Q.seenUnspillableVReg())
182 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
183 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
184 if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
186 Intfs.push_back(Intf);
189 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
190 " interferences with " << VirtReg << "\n");
191 assert(!Intfs.empty() && "expected interference");
193 // Spill each interfering vreg allocated to PhysReg or an alias.
194 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
195 LiveInterval &Spill = *Intfs[i];
198 if (!VRM->hasPhys(Spill.reg))
201 // Deallocate the interfering vreg by removing it from the union.
202 // A LiveInterval instance may not be in a union during modification!
203 Matrix->unassign(Spill);
205 // Spill the extracted interval.
206 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
207 spiller().spill(LRE);
212 // Driver for the register assignment and splitting heuristics.
213 // Manages iteration over the LiveIntervalUnions.
215 // This is a minimal implementation of register assignment and splitting that
216 // spills whenever we run out of registers.
218 // selectOrSplit can only be called once per live virtual register. We then do a
219 // single interference test for each register the correct class until we find an
220 // available register. So, the number of interference tests in the worst case is
221 // |vregs| * |machineregs|. And since the number of interference tests is
222 // minimal, there is no value in caching them outside the scope of
224 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
225 SmallVectorImpl<unsigned> &SplitVRegs) {
226 // Populate a list of physical register spill candidates.
227 SmallVector<unsigned, 8> PhysRegSpillCands;
229 // Check for an available register in this class.
230 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
231 while (unsigned PhysReg = Order.next()) {
232 // Check for interference in PhysReg
233 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
234 case LiveRegMatrix::IK_Free:
235 // PhysReg is available, allocate it.
238 case LiveRegMatrix::IK_VirtReg:
239 // Only virtual registers in the way, we may be able to spill them.
240 PhysRegSpillCands.push_back(PhysReg);
244 // RegMask or RegUnit interference.
249 // Try to spill another interfering reg with less spill weight.
250 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
251 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
252 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
255 assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
256 "Interference after spill.");
257 // Tell the caller to allocate to this newly freed physical register.
261 // No other spill candidates were found, so spill the current VirtReg.
262 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
263 if (!VirtReg.isSpillable())
265 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
266 spiller().spill(LRE);
268 // The live virtual register requesting allocation was spilled, so tell
269 // the caller not to allocate anything during this round.
273 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
274 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
275 << "********** Function: "
276 << mf.getName() << '\n');
279 RegAllocBase::init(getAnalysis<VirtRegMap>(),
280 getAnalysis<LiveIntervals>(),
281 getAnalysis<LiveRegMatrix>());
282 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
286 // Diagnostic output before rewriting
287 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
293 FunctionPass* llvm::createBasicRegisterAllocator()
295 return new RABasic();