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 #include "llvm/CodeGen/Passes.h"
16 #include "AllocationOrder.h"
17 #include "LiveDebugVariables.h"
18 #include "RegAllocBase.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/CalcSpillWeights.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveRangeEdit.h"
24 #include "llvm/CodeGen/LiveRegMatrix.h"
25 #include "llvm/CodeGen/LiveStackAnalysis.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegAllocRegistry.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/PassAnalysisSupport.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
43 #define DEBUG_TYPE "regalloc"
45 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46 createBasicRegisterAllocator);
49 struct CompSpillWeight {
50 bool operator()(LiveInterval *A, LiveInterval *B) const {
51 return A->weight < B->weight;
57 /// 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.
62 class RABasic : public MachineFunctionPass, public RegAllocBase
68 std::unique_ptr<Spiller> SpillerInstance;
69 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
70 CompSpillWeight> Queue;
72 // Scratch space. Allocated here to avoid repeated malloc calls in
79 /// Return the pass name.
80 const char* getPassName() const override {
81 return "Basic Register Allocator";
84 /// RABasic analysis usage.
85 void getAnalysisUsage(AnalysisUsage &AU) const override;
87 void releaseMemory() override;
89 Spiller &spiller() override { return *SpillerInstance; }
91 void enqueue(LiveInterval *LI) override {
95 LiveInterval *dequeue() override {
98 LiveInterval *LI = Queue.top();
103 unsigned selectOrSplit(LiveInterval &VirtReg,
104 SmallVectorImpl<unsigned> &SplitVRegs) override;
106 /// Perform register allocation.
107 bool runOnMachineFunction(MachineFunction &mf) override;
109 // Helper for spilling all live virtual registers currently unified under preg
110 // that interfere with the most recently queried lvr. Return true if spilling
111 // was successful, and append any new spilled/split intervals to splitLVRs.
112 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
113 SmallVectorImpl<unsigned> &SplitVRegs);
118 char RABasic::ID = 0;
120 } // end anonymous namespace
122 RABasic::RABasic(): MachineFunctionPass(ID) {
123 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
124 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
125 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
126 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
127 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
128 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
129 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
130 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
131 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
132 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
135 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.setPreservesCFG();
137 AU.addRequired<AliasAnalysis>();
138 AU.addPreserved<AliasAnalysis>();
139 AU.addRequired<LiveIntervals>();
140 AU.addPreserved<LiveIntervals>();
141 AU.addPreserved<SlotIndexes>();
142 AU.addRequired<LiveDebugVariables>();
143 AU.addPreserved<LiveDebugVariables>();
144 AU.addRequired<LiveStacks>();
145 AU.addPreserved<LiveStacks>();
146 AU.addRequired<MachineBlockFrequencyInfo>();
147 AU.addPreserved<MachineBlockFrequencyInfo>();
148 AU.addRequiredID(MachineDominatorsID);
149 AU.addPreservedID(MachineDominatorsID);
150 AU.addRequired<MachineLoopInfo>();
151 AU.addPreserved<MachineLoopInfo>();
152 AU.addRequired<VirtRegMap>();
153 AU.addPreserved<VirtRegMap>();
154 AU.addRequired<LiveRegMatrix>();
155 AU.addPreserved<LiveRegMatrix>();
156 MachineFunctionPass::getAnalysisUsage(AU);
159 void RABasic::releaseMemory() {
160 SpillerInstance.reset(nullptr);
164 // Spill or split all live virtual registers currently unified under PhysReg
165 // that interfere with VirtReg. The newly spilled or split live intervals are
166 // returned by appending them to SplitVRegs.
167 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
168 SmallVectorImpl<unsigned> &SplitVRegs) {
169 // Record each interference and determine if all are spillable before mutating
170 // either the union or live intervals.
171 SmallVector<LiveInterval*, 8> Intfs;
173 // Collect interferences assigned to any alias of the physical register.
174 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
175 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
176 Q.collectInterferingVRegs();
177 if (Q.seenUnspillableVReg())
179 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
180 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
181 if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
183 Intfs.push_back(Intf);
186 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
187 " interferences with " << VirtReg << "\n");
188 assert(!Intfs.empty() && "expected interference");
190 // Spill each interfering vreg allocated to PhysReg or an alias.
191 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
192 LiveInterval &Spill = *Intfs[i];
195 if (!VRM->hasPhys(Spill.reg))
198 // Deallocate the interfering vreg by removing it from the union.
199 // A LiveInterval instance may not be in a union during modification!
200 Matrix->unassign(Spill);
202 // Spill the extracted interval.
203 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
204 spiller().spill(LRE);
209 // Driver for the register assignment and splitting heuristics.
210 // Manages iteration over the LiveIntervalUnions.
212 // This is a minimal implementation of register assignment and splitting that
213 // spills whenever we run out of registers.
215 // selectOrSplit can only be called once per live virtual register. We then do a
216 // single interference test for each register the correct class until we find an
217 // available register. So, the number of interference tests in the worst case is
218 // |vregs| * |machineregs|. And since the number of interference tests is
219 // minimal, there is no value in caching them outside the scope of
221 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
222 SmallVectorImpl<unsigned> &SplitVRegs) {
223 // Populate a list of physical register spill candidates.
224 SmallVector<unsigned, 8> PhysRegSpillCands;
226 // Check for an available register in this class.
227 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
228 while (unsigned PhysReg = Order.next()) {
229 // Check for interference in PhysReg
230 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
231 case LiveRegMatrix::IK_Free:
232 // PhysReg is available, allocate it.
235 case LiveRegMatrix::IK_VirtReg:
236 // Only virtual registers in the way, we may be able to spill them.
237 PhysRegSpillCands.push_back(PhysReg);
241 // RegMask or RegUnit interference.
246 // Try to spill another interfering reg with less spill weight.
247 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
248 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
249 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
252 assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
253 "Interference after spill.");
254 // Tell the caller to allocate to this newly freed physical register.
258 // No other spill candidates were found, so spill the current VirtReg.
259 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
260 if (!VirtReg.isSpillable())
262 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
263 spiller().spill(LRE);
265 // The live virtual register requesting allocation was spilled, so tell
266 // the caller not to allocate anything during this round.
270 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
271 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
272 << "********** Function: "
273 << mf.getName() << '\n');
276 RegAllocBase::init(getAnalysis<VirtRegMap>(),
277 getAnalysis<LiveIntervals>(),
278 getAnalysis<LiveRegMatrix>());
280 calculateSpillWeightsAndHints(*LIS, *MF,
281 getAnalysis<MachineLoopInfo>(),
282 getAnalysis<MachineBlockFrequencyInfo>());
284 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
288 // Diagnostic output before rewriting
289 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
295 FunctionPass* llvm::createBasicRegisterAllocator()
297 return new RABasic();