xref: /llvm-project/llvm/lib/CodeGen/RegAllocBasic.cpp (revision 4f96fb5fb349b0030f9c14b4fe389cebc3069702)
1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RABasic function pass, which provides a minimal
10 // implementation of the basic register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AllocationOrder.h"
15 #include "RegAllocBase.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/ProfileSummaryInfo.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveDebugVariables.h"
20 #include "llvm/CodeGen/LiveIntervals.h"
21 #include "llvm/CodeGen/LiveRangeEdit.h"
22 #include "llvm/CodeGen/LiveRegMatrix.h"
23 #include "llvm/CodeGen/LiveStacks.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/Spiller.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <queue>
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "regalloc"
41 
42 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
43                                       createBasicRegisterAllocator);
44 
45 namespace {
46   struct CompSpillWeight {
47     bool operator()(const LiveInterval *A, const LiveInterval *B) const {
48       return A->weight() < B->weight();
49     }
50   };
51 }
52 
53 namespace {
54 /// RABasic provides a minimal implementation of the basic register allocation
55 /// algorithm. It prioritizes live virtual registers by spill weight and spills
56 /// whenever a register is unavailable. This is not practical in production but
57 /// provides a useful baseline both for measuring other allocators and comparing
58 /// the speed of the basic algorithm against other styles of allocators.
59 class RABasic : public MachineFunctionPass,
60                 public RegAllocBase,
61                 private LiveRangeEdit::Delegate {
62   // context
63   MachineFunction *MF = nullptr;
64 
65   // state
66   std::unique_ptr<Spiller> SpillerInstance;
67   std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
68                       CompSpillWeight>
69       Queue;
70 
71   // Scratch space.  Allocated here to avoid repeated malloc calls in
72   // selectOrSplit().
73   BitVector UsableRegs;
74 
75   bool LRE_CanEraseVirtReg(Register) override;
76   void LRE_WillShrinkVirtReg(Register) override;
77 
78 public:
79   RABasic(const RegAllocFilterFunc F = nullptr);
80 
81   /// Return the pass name.
82   StringRef getPassName() const override { return "Basic Register Allocator"; }
83 
84   /// RABasic analysis usage.
85   void getAnalysisUsage(AnalysisUsage &AU) const override;
86 
87   void releaseMemory() override;
88 
89   Spiller &spiller() override { return *SpillerInstance; }
90 
91   void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
92 
93   const LiveInterval *dequeue() override {
94     if (Queue.empty())
95       return nullptr;
96     const LiveInterval *LI = Queue.top();
97     Queue.pop();
98     return LI;
99   }
100 
101   MCRegister selectOrSplit(const LiveInterval &VirtReg,
102                            SmallVectorImpl<Register> &SplitVRegs) override;
103 
104   /// Perform register allocation.
105   bool runOnMachineFunction(MachineFunction &mf) override;
106 
107   MachineFunctionProperties getRequiredProperties() const override {
108     return MachineFunctionProperties().set(
109         MachineFunctionProperties::Property::NoPHIs);
110   }
111 
112   MachineFunctionProperties getClearedProperties() const override {
113     return MachineFunctionProperties().set(
114       MachineFunctionProperties::Property::IsSSA);
115   }
116 
117   // Helper for spilling all live virtual registers currently unified under preg
118   // that interfere with the most recently queried lvr.  Return true if spilling
119   // was successful, and append any new spilled/split intervals to splitLVRs.
120   bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
121                           SmallVectorImpl<Register> &SplitVRegs);
122 
123   static char ID;
124 };
125 
126 char RABasic::ID = 0;
127 
128 } // end anonymous namespace
129 
130 char &llvm::RABasicID = RABasic::ID;
131 
132 INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
133                       false, false)
134 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariablesWrapperLegacy)
135 INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
136 INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
137 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
138 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
139 INITIALIZE_PASS_DEPENDENCY(LiveStacksWrapperLegacy)
140 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
141 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
142 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
143 INITIALIZE_PASS_DEPENDENCY(VirtRegMapWrapperLegacy)
144 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrixWrapperLegacy)
145 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
146 INITIALIZE_PASS_END(RABasic, "regallocbasic", "Basic Register Allocator", false,
147                     false)
148 
149 bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
150   LiveInterval &LI = LIS->getInterval(VirtReg);
151   if (VRM->hasPhys(VirtReg)) {
152     Matrix->unassign(LI);
153     aboutToRemoveInterval(LI);
154     return true;
155   }
156   // Unassigned virtreg is probably in the priority queue.
157   // RegAllocBase will erase it after dequeueing.
158   // Nonetheless, clear the live-range so that the debug
159   // dump will show the right state for that VirtReg.
160   LI.clear();
161   return false;
162 }
163 
164 void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
165   if (!VRM->hasPhys(VirtReg))
166     return;
167 
168   // Register is assigned, put it back on the queue for reassignment.
169   LiveInterval &LI = LIS->getInterval(VirtReg);
170   Matrix->unassign(LI);
171   enqueue(&LI);
172 }
173 
174 RABasic::RABasic(RegAllocFilterFunc F)
175     : MachineFunctionPass(ID), RegAllocBase(F) {}
176 
177 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
178   AU.setPreservesCFG();
179   AU.addRequired<AAResultsWrapperPass>();
180   AU.addPreserved<AAResultsWrapperPass>();
181   AU.addRequired<LiveIntervalsWrapperPass>();
182   AU.addPreserved<LiveIntervalsWrapperPass>();
183   AU.addPreserved<SlotIndexesWrapperPass>();
184   AU.addRequired<LiveDebugVariablesWrapperLegacy>();
185   AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
186   AU.addRequired<LiveStacksWrapperLegacy>();
187   AU.addPreserved<LiveStacksWrapperLegacy>();
188   AU.addRequired<ProfileSummaryInfoWrapperPass>();
189   AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
190   AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
191   AU.addRequired<MachineDominatorTreeWrapperPass>();
192   AU.addRequiredID(MachineDominatorsID);
193   AU.addPreservedID(MachineDominatorsID);
194   AU.addRequired<MachineLoopInfoWrapperPass>();
195   AU.addPreserved<MachineLoopInfoWrapperPass>();
196   AU.addRequired<VirtRegMapWrapperLegacy>();
197   AU.addPreserved<VirtRegMapWrapperLegacy>();
198   AU.addRequired<LiveRegMatrixWrapperLegacy>();
199   AU.addPreserved<LiveRegMatrixWrapperLegacy>();
200   MachineFunctionPass::getAnalysisUsage(AU);
201 }
202 
203 void RABasic::releaseMemory() {
204   SpillerInstance.reset();
205 }
206 
207 
208 // Spill or split all live virtual registers currently unified under PhysReg
209 // that interfere with VirtReg. The newly spilled or split live intervals are
210 // returned by appending them to SplitVRegs.
211 bool RABasic::spillInterferences(const LiveInterval &VirtReg,
212                                  MCRegister PhysReg,
213                                  SmallVectorImpl<Register> &SplitVRegs) {
214   // Record each interference and determine if all are spillable before mutating
215   // either the union or live intervals.
216   SmallVector<const LiveInterval *, 8> Intfs;
217 
218   // Collect interferences assigned to any alias of the physical register.
219   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
220     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
221     for (const auto *Intf : reverse(Q.interferingVRegs())) {
222       if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
223         return false;
224       Intfs.push_back(Intf);
225     }
226   }
227   LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
228                     << " interferences with " << VirtReg << "\n");
229   assert(!Intfs.empty() && "expected interference");
230 
231   // Spill each interfering vreg allocated to PhysReg or an alias.
232   for (const LiveInterval *Spill : Intfs) {
233     // Skip duplicates.
234     if (!VRM->hasPhys(Spill->reg()))
235       continue;
236 
237     // Deallocate the interfering vreg by removing it from the union.
238     // A LiveInterval instance may not be in a union during modification!
239     Matrix->unassign(*Spill);
240 
241     // Spill the extracted interval.
242     LiveRangeEdit LRE(Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
243     spiller().spill(LRE);
244   }
245   return true;
246 }
247 
248 // Driver for the register assignment and splitting heuristics.
249 // Manages iteration over the LiveIntervalUnions.
250 //
251 // This is a minimal implementation of register assignment and splitting that
252 // spills whenever we run out of registers.
253 //
254 // selectOrSplit can only be called once per live virtual register. We then do a
255 // single interference test for each register the correct class until we find an
256 // available register. So, the number of interference tests in the worst case is
257 // |vregs| * |machineregs|. And since the number of interference tests is
258 // minimal, there is no value in caching them outside the scope of
259 // selectOrSplit().
260 MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
261                                   SmallVectorImpl<Register> &SplitVRegs) {
262   // Populate a list of physical register spill candidates.
263   SmallVector<MCRegister, 8> PhysRegSpillCands;
264 
265   // Check for an available register in this class.
266   auto Order =
267       AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
268   for (MCRegister PhysReg : Order) {
269     assert(PhysReg.isValid());
270     // Check for interference in PhysReg
271     switch (Matrix->checkInterference(VirtReg, PhysReg)) {
272     case LiveRegMatrix::IK_Free:
273       // PhysReg is available, allocate it.
274       return PhysReg;
275 
276     case LiveRegMatrix::IK_VirtReg:
277       // Only virtual registers in the way, we may be able to spill them.
278       PhysRegSpillCands.push_back(PhysReg);
279       continue;
280 
281     default:
282       // RegMask or RegUnit interference.
283       continue;
284     }
285   }
286 
287   // Try to spill another interfering reg with less spill weight.
288   for (MCRegister &PhysReg : PhysRegSpillCands) {
289     if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
290       continue;
291 
292     assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
293            "Interference after spill.");
294     // Tell the caller to allocate to this newly freed physical register.
295     return PhysReg;
296   }
297 
298   // No other spill candidates were found, so spill the current VirtReg.
299   LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
300   if (!VirtReg.isSpillable())
301     return ~0u;
302   LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
303   spiller().spill(LRE);
304 
305   // The live virtual register requesting allocation was spilled, so tell
306   // the caller not to allocate anything during this round.
307   return 0;
308 }
309 
310 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
311   LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
312                     << "********** Function: " << mf.getName() << '\n');
313 
314   MF = &mf;
315   auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
316   auto &LiveStks = getAnalysis<LiveStacksWrapperLegacy>().getLS();
317   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
318 
319   RegAllocBase::init(getAnalysis<VirtRegMapWrapperLegacy>().getVRM(),
320                      getAnalysis<LiveIntervalsWrapperPass>().getLIS(),
321                      getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM());
322   VirtRegAuxInfo VRAI(*MF, *LIS, *VRM,
323                       getAnalysis<MachineLoopInfoWrapperPass>().getLI(), MBFI,
324                       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
325   VRAI.calculateSpillWeightsAndHints();
326 
327   SpillerInstance.reset(
328       createInlineSpiller({*LIS, LiveStks, MDT, MBFI}, *MF, *VRM, VRAI));
329 
330   allocatePhysRegs();
331   postOptimization();
332 
333   // Diagnostic output before rewriting
334   LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
335 
336   releaseMemory();
337   return true;
338 }
339 
340 FunctionPass* llvm::createBasicRegisterAllocator() {
341   return new RABasic();
342 }
343 
344 FunctionPass *llvm::createBasicRegisterAllocator(RegAllocFilterFunc F) {
345   return new RABasic(F);
346 }
347