LLVM 20.0.0git
RegAllocBasic.cpp
Go to the documentation of this file.
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"
27#include "llvm/CodeGen/Passes.h"
32#include "llvm/Pass.h"
33#include "llvm/Support/Debug.h"
35#include <queue>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "regalloc"
40
41static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
43
44namespace {
45 struct CompSpillWeight {
46 bool operator()(const LiveInterval *A, const LiveInterval *B) const {
47 return A->weight() < B->weight();
48 }
49 };
50}
51
52namespace {
53/// RABasic provides a minimal implementation of the basic register allocation
54/// algorithm. It prioritizes live virtual registers by spill weight and spills
55/// whenever a register is unavailable. This is not practical in production but
56/// provides a useful baseline both for measuring other allocators and comparing
57/// the speed of the basic algorithm against other styles of allocators.
58class RABasic : public MachineFunctionPass,
59 public RegAllocBase,
61 // context
62 MachineFunction *MF = nullptr;
63
64 // state
65 std::unique_ptr<Spiller> SpillerInstance;
66 std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
67 CompSpillWeight>
68 Queue;
69
70 // Scratch space. Allocated here to avoid repeated malloc calls in
71 // selectOrSplit().
72 BitVector UsableRegs;
73
74 bool LRE_CanEraseVirtReg(Register) override;
75 void LRE_WillShrinkVirtReg(Register) override;
76
77public:
78 RABasic(const RegAllocFilterFunc F = nullptr);
79
80 /// Return the pass name.
81 StringRef getPassName() const override { return "Basic Register Allocator"; }
82
83 /// RABasic analysis usage.
84 void getAnalysisUsage(AnalysisUsage &AU) const override;
85
86 void releaseMemory() override;
87
88 Spiller &spiller() override { return *SpillerInstance; }
89
90 void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
91
92 const LiveInterval *dequeue() override {
93 if (Queue.empty())
94 return nullptr;
95 const LiveInterval *LI = Queue.top();
96 Queue.pop();
97 return LI;
98 }
99
101 SmallVectorImpl<Register> &SplitVRegs) override;
102
103 /// Perform register allocation.
104 bool runOnMachineFunction(MachineFunction &mf) override;
105
108 MachineFunctionProperties::Property::NoPHIs);
109 }
110
113 MachineFunctionProperties::Property::IsSSA);
114 }
115
116 // Helper for spilling all live virtual registers currently unified under preg
117 // that interfere with the most recently queried lvr. Return true if spilling
118 // was successful, and append any new spilled/split intervals to splitLVRs.
119 bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
120 SmallVectorImpl<Register> &SplitVRegs);
121
122 static char ID;
123};
124
125char RABasic::ID = 0;
126
127} // end anonymous namespace
128
129char &llvm::RABasicID = RABasic::ID;
130
131INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
132 false, false)
136INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
137INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
146 false)
147
148bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
149 LiveInterval &LI = LIS->getInterval(VirtReg);
150 if (VRM->hasPhys(VirtReg)) {
151 Matrix->unassign(LI);
152 aboutToRemoveInterval(LI);
153 return true;
154 }
155 // Unassigned virtreg is probably in the priority queue.
156 // RegAllocBase will erase it after dequeueing.
157 // Nonetheless, clear the live-range so that the debug
158 // dump will show the right state for that VirtReg.
159 LI.clear();
160 return false;
161}
162
163void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
164 if (!VRM->hasPhys(VirtReg))
165 return;
166
167 // Register is assigned, put it back on the queue for reassignment.
168 LiveInterval &LI = LIS->getInterval(VirtReg);
169 Matrix->unassign(LI);
170 enqueue(&LI);
171}
172
173RABasic::RABasic(RegAllocFilterFunc F)
175
176void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
177 AU.setPreservesCFG();
199}
200
201void RABasic::releaseMemory() {
202 SpillerInstance.reset();
203}
204
205
206// Spill or split all live virtual registers currently unified under PhysReg
207// that interfere with VirtReg. The newly spilled or split live intervals are
208// returned by appending them to SplitVRegs.
209bool RABasic::spillInterferences(const LiveInterval &VirtReg,
210 MCRegister PhysReg,
211 SmallVectorImpl<Register> &SplitVRegs) {
212 // Record each interference and determine if all are spillable before mutating
213 // either the union or live intervals.
215
216 // Collect interferences assigned to any alias of the physical register.
217 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
218 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
219 for (const auto *Intf : reverse(Q.interferingVRegs())) {
220 if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
221 return false;
222 Intfs.push_back(Intf);
223 }
224 }
225 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
226 << " interferences with " << VirtReg << "\n");
227 assert(!Intfs.empty() && "expected interference");
228
229 // Spill each interfering vreg allocated to PhysReg or an alias.
230 for (const LiveInterval *Spill : Intfs) {
231 // Skip duplicates.
232 if (!VRM->hasPhys(Spill->reg()))
233 continue;
234
235 // Deallocate the interfering vreg by removing it from the union.
236 // A LiveInterval instance may not be in a union during modification!
237 Matrix->unassign(*Spill);
238
239 // Spill the extracted interval.
240 LiveRangeEdit LRE(Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
241 spiller().spill(LRE);
242 }
243 return true;
244}
245
246// Driver for the register assignment and splitting heuristics.
247// Manages iteration over the LiveIntervalUnions.
248//
249// This is a minimal implementation of register assignment and splitting that
250// spills whenever we run out of registers.
251//
252// selectOrSplit can only be called once per live virtual register. We then do a
253// single interference test for each register the correct class until we find an
254// available register. So, the number of interference tests in the worst case is
255// |vregs| * |machineregs|. And since the number of interference tests is
256// minimal, there is no value in caching them outside the scope of
257// selectOrSplit().
258MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
259 SmallVectorImpl<Register> &SplitVRegs) {
260 // Populate a list of physical register spill candidates.
261 SmallVector<MCRegister, 8> PhysRegSpillCands;
262
263 // Check for an available register in this class.
264 auto Order =
265 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
266 for (MCRegister PhysReg : Order) {
267 assert(PhysReg.isValid());
268 // Check for interference in PhysReg
269 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
271 // PhysReg is available, allocate it.
272 return PhysReg;
273
275 // Only virtual registers in the way, we may be able to spill them.
276 PhysRegSpillCands.push_back(PhysReg);
277 continue;
278
279 default:
280 // RegMask or RegUnit interference.
281 continue;
282 }
283 }
284
285 // Try to spill another interfering reg with less spill weight.
286 for (MCRegister &PhysReg : PhysRegSpillCands) {
287 if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
288 continue;
289
290 assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
291 "Interference after spill.");
292 // Tell the caller to allocate to this newly freed physical register.
293 return PhysReg;
294 }
295
296 // No other spill candidates were found, so spill the current VirtReg.
297 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
298 if (!VirtReg.isSpillable())
299 return ~0u;
300 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
301 spiller().spill(LRE);
302
303 // The live virtual register requesting allocation was spilled, so tell
304 // the caller not to allocate anything during this round.
305 return 0;
306}
307
308bool RABasic::runOnMachineFunction(MachineFunction &mf) {
309 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
310 << "********** Function: " << mf.getName() << '\n');
311
312 MF = &mf;
313 RegAllocBase::init(getAnalysis<VirtRegMapWrapperLegacy>().getVRM(),
314 getAnalysis<LiveIntervalsWrapperPass>().getLIS(),
315 getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM());
316 VirtRegAuxInfo VRAI(
317 *MF, *LIS, *VRM, getAnalysis<MachineLoopInfoWrapperPass>().getLI(),
318 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(),
319 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
320 VRAI.calculateSpillWeightsAndHints();
321
322 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
323
324 allocatePhysRegs();
325 postOptimization();
326
327 // Diagnostic output before rewriting
328 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
329
330 releaseMemory();
331 return true;
332}
333
335 return new RABasic();
336}
337
339 return new RABasic(F);
340}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Live Register Matrix
#define F(x, y, z)
Definition: MD5.cpp:55
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
regallocbasic
Basic Register Allocator
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static AllocationOrder create(unsigned VirtReg, const VirtRegMap &VRM, const RegisterClassInfo &RegClassInfo, const LiveRegMatrix *Matrix)
Create a new AllocationOrder for VirtReg.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:270
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
Query interferences between a single live virtual register and a live interval union.
const SmallVectorImpl< const LiveInterval * > & interferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
float weight() const
Definition: LiveInterval.h:719
Register reg() const
Definition: LiveInterval.h:718
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:826
Callback methods for LiveRangeEdit owners.
Definition: LiveRangeEdit.h:45
virtual bool LRE_CanEraseVirtReg(Register)
Called when a virtual register is no longer used.
Definition: LiveRangeEdit.h:56
virtual void LRE_WillShrinkVirtReg(Register)
Called before shrinking the live range of a virtual register.
Definition: LiveRangeEdit.h:59
@ IK_VirtReg
Virtual register interference.
Definition: LiveRegMatrix.h:94
@ IK_Free
No interference, go ahead and assign.
Definition: LiveRegMatrix.h:89
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
constexpr bool isValid() const
Definition: MCRegister.h:81
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual MachineFunctionProperties getClearedProperties() const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
virtual void releaseMemory()
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: Pass.cpp:102
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:62
virtual MCRegister selectOrSplit(const LiveInterval &VirtReg, SmallVectorImpl< Register > &splitLVRs)=0
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
virtual Spiller & spiller()=0
virtual const LiveInterval * dequeue()=0
dequeue - Return the next unassigned register, or NULL.
virtual void enqueueImpl(const LiveInterval *LI)=0
enqueue - Add VirtReg to the priority queue of unassigned registers.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
bool empty() const
Definition: SmallVector.h:81
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
Spiller interface.
Definition: Spiller.h:27
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
Spiller * createInlineSpiller(MachineFunctionPass &Pass, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
char & RABasicID
Basic register allocator.