LLVM 24.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/// \file
10/// This file defines the RABasic function pass, which provides a minimal
11/// implementation of the basic register allocator.
12///
13//===----------------------------------------------------------------------===//
14
15#include "RegAllocBasic.h"
16#include "AllocationOrder.h"
27#include "llvm/CodeGen/Passes.h"
30#include "llvm/Pass.h"
31#include "llvm/Support/Debug.h"
33
34using namespace llvm;
35
36#define DEBUG_TYPE "regalloc"
37
38static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
40
41char RABasic::ID = 0;
42
44
45INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
46 false, false)
50INITIALIZE_PASS_DEPENDENCY(RegisterCoalescerLegacy)
51INITIALIZE_PASS_DEPENDENCY(MachineSchedulerLegacy)
59INITIALIZE_PASS_END(RABasic, "regallocbasic", "Basic Register Allocator", false,
60 false)
61
62bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
63 LiveInterval &LI = LIS->getInterval(VirtReg);
64 if (VRM->hasPhys(VirtReg)) {
65 Matrix->unassign(LI);
66 aboutToRemoveInterval(LI);
67 return true;
68 }
69 // Unassigned virtreg is probably in the priority queue.
70 // RegAllocBase will erase it after dequeueing.
71 // Nonetheless, clear the live-range so that the debug
72 // dump will show the right state for that VirtReg.
73 LI.clear();
74 return false;
75}
76
77void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
78 if (!VRM->hasPhys(VirtReg))
79 return;
80
81 // Register is assigned, put it back on the queue for reassignment.
82 LiveInterval &LI = LIS->getInterval(VirtReg);
83 Matrix->unassign(LI);
84 enqueue(&LI);
85}
86
89
112
114 SpillerInstance.reset();
115}
116
117
118// Spill or split all live virtual registers currently unified under PhysReg
119// that interfere with VirtReg. The newly spilled or split live intervals are
120// returned by appending them to SplitVRegs.
122 MCRegister PhysReg,
123 SmallVectorImpl<Register> &SplitVRegs) {
124 // Record each interference and determine if all are spillable before mutating
125 // either the union or live intervals.
127
128 // Collect interferences assigned to any alias of the physical register.
129 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
130 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
131 for (const auto *Intf : reverse(Q.interferingVRegs())) {
132 if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
133 return false;
134 Intfs.push_back(Intf);
135 }
136 }
137 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
138 << " interferences with " << VirtReg << "\n");
139 assert(!Intfs.empty() && "expected interference");
140
141 // Spill each interfering vreg allocated to PhysReg or an alias.
142 for (const LiveInterval *Spill : Intfs) {
143 // Skip duplicates.
144 if (!VRM->hasPhys(Spill->reg()))
145 continue;
146
147 // Deallocate the interfering vreg by removing it from the union.
148 // A LiveInterval instance may not be in a union during modification!
149 Matrix->unassign(*Spill);
150
151 // Spill the extracted interval.
152 LiveRangeEdit LRE(Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
153 spiller().spill(LRE);
154 }
155 return true;
156}
157
158// Driver for the register assignment and splitting heuristics.
159// Manages iteration over the LiveIntervalUnions.
160//
161// This is a minimal implementation of register assignment and splitting that
162// spills whenever we run out of registers.
163//
164// selectOrSplit can only be called once per live virtual register. We then do a
165// single interference test for each register the correct class until we find an
166// available register. So, the number of interference tests in the worst case is
167// |vregs| * |machineregs|. And since the number of interference tests is
168// minimal, there is no value in caching them outside the scope of
169// selectOrSplit().
171 SmallVectorImpl<Register> &SplitVRegs) {
172 // Populate a list of physical register spill candidates.
173 SmallVector<MCRegister, 8> PhysRegSpillCands;
174
175 // Check for an available register in this class.
176 auto Order =
178 for (MCRegister PhysReg : Order) {
179 assert(PhysReg.isValid());
180 // Check for interference in PhysReg
181 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
183 // PhysReg is available, allocate it.
184 return PhysReg;
185
187 // Only virtual registers in the way, we may be able to spill them.
188 PhysRegSpillCands.push_back(PhysReg);
189 continue;
190
191 default:
192 // RegMask or RegUnit interference.
193 continue;
194 }
195 }
196
197 // Try to spill another interfering reg with less spill weight.
198 for (MCRegister &PhysReg : PhysRegSpillCands) {
199 if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
200 continue;
201
202 assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
203 "Interference after spill.");
204 // Tell the caller to allocate to this newly freed physical register.
205 return PhysReg;
206 }
207
208 // No other spill candidates were found, so spill the current VirtReg.
209 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
210 if (!VirtReg.isSpillable())
211 return ~0u;
212 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
213 spiller().spill(LRE);
214
215 // The live virtual register requesting allocation was spilled, so tell
216 // the caller not to allocate anything during this round.
217 return 0;
218}
219
221 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
222 << "********** Function: " << mf.getName() << '\n');
223
224 MF = &mf;
226 auto &LiveStks = getAnalysis<LiveStacksWrapperLegacy>().getLS();
227 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
228
232 VirtRegAuxInfo VRAI(*MF, *LIS, *VRM,
236
237 SpillerInstance.reset(
238 createInlineSpiller({*LIS, LiveStks, MDT, MBFI}, *MF, *VRM, VRAI));
239
242
243 // Diagnostic output before rewriting
244 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
245
247 return true;
248}
249
253
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define F(x, y, z)
Definition MD5.cpp:54
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
This file declares the RABasic class, which provides a minimal implementation of the basic register a...
#define LLVM_DEBUG(...)
Definition Debug.h:119
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static AllocationOrder create(Register VirtReg, const VirtRegMap &VRM, const RegisterClassInfo &RegClassInfo, const LiveRegMatrix *Matrix)
Create a new AllocationOrder for VirtReg.
Represent the analysis usage information of a pass.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:289
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
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.
float weight() const
Register reg() const
bool isSpillable() const
isSpillable - Can this interval be spilled?
@ IK_VirtReg
Virtual register interference.
@ IK_Free
No interference, go ahead and assign.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Analysis pass which computes a MachineDominatorTree.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RABasic provides a minimal implementation of the basic register allocation algorithm.
void getAnalysisUsage(AnalysisUsage &AU) const override
RABasic analysis usage.
MCRegister selectOrSplit(const LiveInterval &VirtReg, SmallVectorImpl< Register > &SplitVRegs) override
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Spiller & spiller() override
RABasic(const RegAllocFilterFunc F=nullptr)
bool runOnMachineFunction(MachineFunction &mf) override
Perform register allocation.
bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg, SmallVectorImpl< Register > &SplitVRegs)
static char ID
RegAllocBase(const RegAllocFilterFunc F=nullptr)
void enqueue(const LiveInterval *LI)
enqueue - Add VirtReg to the priority queue of unassigned registers.
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
SmallPtrSet< MachineInstr *, 32 > DeadRemats
Inst which is a def of an original reg and whose defs are already all dead after remat is saved in De...
const TargetRegisterInfo * TRI
LiveIntervals * LIS
LiveRegMatrix * Matrix
virtual void postOptimization()
VirtRegMap * VRM
RegisterClassInfo RegClassInfo
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
virtual void spill(LiveRangeEdit &LRE, AllocationOrder *Order=nullptr)=0
spill - Spill the LRE.getParent() live interval.
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
LLVM_ABI void calculateSpillWeightsAndHints()
Compute spill weights and allocation hints for all virtual register live intervals.
This is an optimization pass for GlobalISel generic memory operations.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Spiller * createInlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix=nullptr)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
LLVM_ABI FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
LLVM_ABI 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.
LLVM_ABI char & RABasicID
Basic register allocator.