1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the RABasic function pass, which provides a minimal
10 // implementation of the basic register allocator.
12 //===----------------------------------------------------------------------===//
14 #include "AllocationOrder.h"
15 #include "LiveDebugVariables.h"
16 #include "RegAllocBase.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/CodeGen/CalcSpillWeights.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/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.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"
41 #define DEBUG_TYPE "regalloc"
43 static RegisterRegAlloc
basicRegAlloc("basic", "basic register allocator",
44 createBasicRegisterAllocator
);
47 struct CompSpillWeight
{
48 bool operator()(LiveInterval
*A
, LiveInterval
*B
) const {
49 return A
->weight
< B
->weight
;
55 /// RABasic provides a minimal implementation of the basic register allocation
56 /// algorithm. It prioritizes live virtual registers by spill weight and spills
57 /// whenever a register is unavailable. This is not practical in production but
58 /// provides a useful baseline both for measuring other allocators and comparing
59 /// the speed of the basic algorithm against other styles of allocators.
60 class RABasic
: public MachineFunctionPass
,
62 private LiveRangeEdit::Delegate
{
67 std::unique_ptr
<Spiller
> SpillerInstance
;
68 std::priority_queue
<LiveInterval
*, std::vector
<LiveInterval
*>,
69 CompSpillWeight
> Queue
;
71 // Scratch space. Allocated here to avoid repeated malloc calls in
75 bool LRE_CanEraseVirtReg(unsigned) override
;
76 void LRE_WillShrinkVirtReg(unsigned) override
;
81 /// Return the pass name.
82 StringRef
getPassName() const override
{ 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 MachineFunctionProperties
getRequiredProperties() const override
{
110 return MachineFunctionProperties().set(
111 MachineFunctionProperties::Property::NoPHIs
);
114 // Helper for spilling all live virtual registers currently unified under preg
115 // that interfere with the most recently queried lvr. Return true if spilling
116 // was successful, and append any new spilled/split intervals to splitLVRs.
117 bool spillInterferences(LiveInterval
&VirtReg
, unsigned PhysReg
,
118 SmallVectorImpl
<unsigned> &SplitVRegs
);
123 char RABasic::ID
= 0;
125 } // end anonymous namespace
127 char &llvm::RABasicID
= RABasic::ID
;
129 INITIALIZE_PASS_BEGIN(RABasic
, "regallocbasic", "Basic Register Allocator",
131 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables
)
132 INITIALIZE_PASS_DEPENDENCY(SlotIndexes
)
133 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
134 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer
)
135 INITIALIZE_PASS_DEPENDENCY(MachineScheduler
)
136 INITIALIZE_PASS_DEPENDENCY(LiveStacks
)
137 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
138 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
139 INITIALIZE_PASS_DEPENDENCY(VirtRegMap
)
140 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix
)
141 INITIALIZE_PASS_END(RABasic
, "regallocbasic", "Basic Register Allocator", false,
144 bool RABasic::LRE_CanEraseVirtReg(unsigned VirtReg
) {
145 LiveInterval
&LI
= LIS
->getInterval(VirtReg
);
146 if (VRM
->hasPhys(VirtReg
)) {
147 Matrix
->unassign(LI
);
148 aboutToRemoveInterval(LI
);
151 // Unassigned virtreg is probably in the priority queue.
152 // RegAllocBase will erase it after dequeueing.
153 // Nonetheless, clear the live-range so that the debug
154 // dump will show the right state for that VirtReg.
159 void RABasic::LRE_WillShrinkVirtReg(unsigned VirtReg
) {
160 if (!VRM
->hasPhys(VirtReg
))
163 // Register is assigned, put it back on the queue for reassignment.
164 LiveInterval
&LI
= LIS
->getInterval(VirtReg
);
165 Matrix
->unassign(LI
);
169 RABasic::RABasic(): MachineFunctionPass(ID
) {
172 void RABasic::getAnalysisUsage(AnalysisUsage
&AU
) const {
173 AU
.setPreservesCFG();
174 AU
.addRequired
<AAResultsWrapperPass
>();
175 AU
.addPreserved
<AAResultsWrapperPass
>();
176 AU
.addRequired
<LiveIntervals
>();
177 AU
.addPreserved
<LiveIntervals
>();
178 AU
.addPreserved
<SlotIndexes
>();
179 AU
.addRequired
<LiveDebugVariables
>();
180 AU
.addPreserved
<LiveDebugVariables
>();
181 AU
.addRequired
<LiveStacks
>();
182 AU
.addPreserved
<LiveStacks
>();
183 AU
.addRequired
<MachineBlockFrequencyInfo
>();
184 AU
.addPreserved
<MachineBlockFrequencyInfo
>();
185 AU
.addRequiredID(MachineDominatorsID
);
186 AU
.addPreservedID(MachineDominatorsID
);
187 AU
.addRequired
<MachineLoopInfo
>();
188 AU
.addPreserved
<MachineLoopInfo
>();
189 AU
.addRequired
<VirtRegMap
>();
190 AU
.addPreserved
<VirtRegMap
>();
191 AU
.addRequired
<LiveRegMatrix
>();
192 AU
.addPreserved
<LiveRegMatrix
>();
193 MachineFunctionPass::getAnalysisUsage(AU
);
196 void RABasic::releaseMemory() {
197 SpillerInstance
.reset();
201 // Spill or split all live virtual registers currently unified under PhysReg
202 // that interfere with VirtReg. The newly spilled or split live intervals are
203 // returned by appending them to SplitVRegs.
204 bool RABasic::spillInterferences(LiveInterval
&VirtReg
, unsigned PhysReg
,
205 SmallVectorImpl
<unsigned> &SplitVRegs
) {
206 // Record each interference and determine if all are spillable before mutating
207 // either the union or live intervals.
208 SmallVector
<LiveInterval
*, 8> Intfs
;
210 // Collect interferences assigned to any alias of the physical register.
211 for (MCRegUnitIterator
Units(PhysReg
, TRI
); Units
.isValid(); ++Units
) {
212 LiveIntervalUnion::Query
&Q
= Matrix
->query(VirtReg
, *Units
);
213 Q
.collectInterferingVRegs();
214 for (unsigned i
= Q
.interferingVRegs().size(); i
; --i
) {
215 LiveInterval
*Intf
= Q
.interferingVRegs()[i
- 1];
216 if (!Intf
->isSpillable() || Intf
->weight
> VirtReg
.weight
)
218 Intfs
.push_back(Intf
);
221 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg
, TRI
)
222 << " interferences with " << VirtReg
<< "\n");
223 assert(!Intfs
.empty() && "expected interference");
225 // Spill each interfering vreg allocated to PhysReg or an alias.
226 for (unsigned i
= 0, e
= Intfs
.size(); i
!= e
; ++i
) {
227 LiveInterval
&Spill
= *Intfs
[i
];
230 if (!VRM
->hasPhys(Spill
.reg
))
233 // Deallocate the interfering vreg by removing it from the union.
234 // A LiveInterval instance may not be in a union during modification!
235 Matrix
->unassign(Spill
);
237 // Spill the extracted interval.
238 LiveRangeEdit
LRE(&Spill
, SplitVRegs
, *MF
, *LIS
, VRM
, this, &DeadRemats
);
239 spiller().spill(LRE
);
244 // Driver for the register assignment and splitting heuristics.
245 // Manages iteration over the LiveIntervalUnions.
247 // This is a minimal implementation of register assignment and splitting that
248 // spills whenever we run out of registers.
250 // selectOrSplit can only be called once per live virtual register. We then do a
251 // single interference test for each register the correct class until we find an
252 // available register. So, the number of interference tests in the worst case is
253 // |vregs| * |machineregs|. And since the number of interference tests is
254 // minimal, there is no value in caching them outside the scope of
256 unsigned RABasic::selectOrSplit(LiveInterval
&VirtReg
,
257 SmallVectorImpl
<unsigned> &SplitVRegs
) {
258 // Populate a list of physical register spill candidates.
259 SmallVector
<unsigned, 8> PhysRegSpillCands
;
261 // Check for an available register in this class.
262 AllocationOrder
Order(VirtReg
.reg
, *VRM
, RegClassInfo
, Matrix
);
263 while (unsigned PhysReg
= Order
.next()) {
264 // Check for interference in PhysReg
265 switch (Matrix
->checkInterference(VirtReg
, PhysReg
)) {
266 case LiveRegMatrix::IK_Free
:
267 // PhysReg is available, allocate it.
270 case LiveRegMatrix::IK_VirtReg
:
271 // Only virtual registers in the way, we may be able to spill them.
272 PhysRegSpillCands
.push_back(PhysReg
);
276 // RegMask or RegUnit interference.
281 // Try to spill another interfering reg with less spill weight.
282 for (SmallVectorImpl
<unsigned>::iterator PhysRegI
= PhysRegSpillCands
.begin(),
283 PhysRegE
= PhysRegSpillCands
.end(); PhysRegI
!= PhysRegE
; ++PhysRegI
) {
284 if (!spillInterferences(VirtReg
, *PhysRegI
, SplitVRegs
))
287 assert(!Matrix
->checkInterference(VirtReg
, *PhysRegI
) &&
288 "Interference after spill.");
289 // Tell the caller to allocate to this newly freed physical register.
293 // No other spill candidates were found, so spill the current VirtReg.
294 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg
<< '\n');
295 if (!VirtReg
.isSpillable())
297 LiveRangeEdit
LRE(&VirtReg
, SplitVRegs
, *MF
, *LIS
, VRM
, this, &DeadRemats
);
298 spiller().spill(LRE
);
300 // The live virtual register requesting allocation was spilled, so tell
301 // the caller not to allocate anything during this round.
305 bool RABasic::runOnMachineFunction(MachineFunction
&mf
) {
306 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
307 << "********** Function: " << mf
.getName() << '\n');
310 RegAllocBase::init(getAnalysis
<VirtRegMap
>(),
311 getAnalysis
<LiveIntervals
>(),
312 getAnalysis
<LiveRegMatrix
>());
314 calculateSpillWeightsAndHints(*LIS
, *MF
, VRM
,
315 getAnalysis
<MachineLoopInfo
>(),
316 getAnalysis
<MachineBlockFrequencyInfo
>());
318 SpillerInstance
.reset(createInlineSpiller(*this, *MF
, *VRM
));
323 // Diagnostic output before rewriting
324 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM
<< "\n");
330 FunctionPass
* llvm::createBasicRegisterAllocator()
332 return new RABasic();