LLVM 20.0.0git
RegUsageInfoCollector.cpp
Go to the documentation of this file.
1//===-- RegUsageInfoCollector.cpp - Register Usage Information Collector --===//
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 pass is required to take advantage of the interprocedural register
10/// allocation infrastructure.
11///
12/// This pass is simple MachineFunction pass which collects register usage
13/// details by iterating through each physical registers and checking
14/// MRI::isPhysRegUsed() then creates a RegMask based on this details.
15/// The pass then stores this RegMask in PhysicalRegisterUsageInfo.cpp
16///
17//===----------------------------------------------------------------------===//
18
20#include "llvm/ADT/Statistic.h"
25#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/Support/Debug.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "ip-regalloc"
35
36STATISTIC(NumCSROpt,
37 "Number of functions optimized for callee saved registers");
38
39namespace {
40
43
44public:
46 bool run(MachineFunction &MF);
47
48 // Call getCalleeSaves and then also set the bits for subregs and
49 // fully saved superregs.
50 static void computeCalleeSavedRegs(BitVector &SavedRegs, MachineFunction &MF);
51};
52
53class RegUsageInfoCollectorLegacy : public MachineFunctionPass {
54public:
55 static char ID;
56 RegUsageInfoCollectorLegacy() : MachineFunctionPass(ID) {
58 }
59
60 StringRef getPassName() const override {
61 return "Register Usage Information Collector Pass";
62 }
63
64 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesAll();
68 }
69
70 bool runOnMachineFunction(MachineFunction &MF) override;
71};
72} // end of anonymous namespace
73
74char RegUsageInfoCollectorLegacy::ID = 0;
75
76INITIALIZE_PASS_BEGIN(RegUsageInfoCollectorLegacy, "RegUsageInfoCollector",
77 "Register Usage Information Collector", false, false)
79INITIALIZE_PASS_END(RegUsageInfoCollectorLegacy, "RegUsageInfoCollector",
81
83 return new RegUsageInfoCollectorLegacy();
84}
85
86// TODO: Move to hook somwehere?
87
88// Return true if it is useful to track the used registers for IPRA / no CSR
89// optimizations. This is not useful for entry points, and computing the
90// register usage information is expensive.
91static bool isCallableFunction(const MachineFunction &MF) {
92 switch (MF.getFunction().getCallingConv()) {
101 return false;
102 default:
103 return true;
104 }
105}
106
110 Module &MFA = *MF.getFunction().getParent();
112 .getCachedResult<PhysicalRegisterUsageAnalysis>(MFA);
113 assert(PRUI && "PhysicalRegisterUsageAnalysis not available");
114 RegUsageInfoCollector(*PRUI).run(MF);
115 return PreservedAnalyses::all();
116}
117
118bool RegUsageInfoCollectorLegacy::runOnMachineFunction(MachineFunction &MF) {
120 getAnalysis<PhysicalRegisterUsageInfoWrapperLegacy>().getPRUI();
121 return RegUsageInfoCollector(PRUI).run(MF);
122}
123
124bool RegUsageInfoCollector::run(MachineFunction &MF) {
127 const TargetMachine &TM = MF.getTarget();
128
130 dbgs()
131 << " -------------------- Register Usage Information Collector Pass"
132 << " -------------------- \nFunction Name : " << MF.getName() << '\n');
133
134 // Analyzing the register usage may be expensive on some targets.
135 if (!isCallableFunction(MF)) {
136 LLVM_DEBUG(dbgs() << "Not analyzing non-callable function\n");
137 return false;
138 }
139
140 // If there are no callers, there's no point in computing more precise
141 // register usage here.
142 if (MF.getFunction().use_empty()) {
143 LLVM_DEBUG(dbgs() << "Not analyzing function with no callers\n");
144 return false;
145 }
146
147 std::vector<uint32_t> RegMask;
148
149 // Compute the size of the bit vector to represent all the registers.
150 // The bit vector is broken into 32-bit chunks, thus takes the ceil of
151 // the number of registers divided by 32 for the size.
152 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
153 RegMask.resize(RegMaskSize, ~((uint32_t)0));
154
155 const Function &F = MF.getFunction();
156
157 PRUI.setTargetMachine(TM);
158
159 LLVM_DEBUG(dbgs() << "Clobbered Registers: ");
160
161 BitVector SavedRegs;
162 computeCalleeSavedRegs(SavedRegs, MF);
163
164 const BitVector &UsedPhysRegsMask = MRI->getUsedPhysRegsMask();
165 auto SetRegAsDefined = [&RegMask] (unsigned Reg) {
166 RegMask[Reg / 32] &= ~(1u << Reg % 32);
167 };
168
169 // Don't include $noreg in any regmasks.
170 SetRegAsDefined(MCRegister::NoRegister);
171
172 // Some targets can clobber registers "inside" a call, typically in
173 // linker-generated code.
174 for (const MCPhysReg Reg : TRI->getIntraCallClobberedRegs(&MF))
175 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
176 SetRegAsDefined(*AI);
177
178 // Scan all the physical registers. When a register is defined in the current
179 // function set it and all the aliasing registers as defined in the regmask.
180 // FIXME: Rewrite to use regunits.
181 for (unsigned PReg = 1, PRegE = TRI->getNumRegs(); PReg < PRegE; ++PReg) {
182 // Don't count registers that are saved and restored.
183 if (SavedRegs.test(PReg))
184 continue;
185 // If a register is defined by an instruction mark it as defined together
186 // with all it's unsaved aliases.
187 if (!MRI->def_empty(PReg)) {
188 for (MCRegAliasIterator AI(PReg, TRI, true); AI.isValid(); ++AI)
189 if (!SavedRegs.test(*AI))
190 SetRegAsDefined(*AI);
191 continue;
192 }
193 // If a register is in the UsedPhysRegsMask set then mark it as defined.
194 // All clobbered aliases will also be in the set, so we can skip setting
195 // as defined all the aliases here.
196 if (UsedPhysRegsMask.test(PReg))
197 SetRegAsDefined(PReg);
198 }
199
202 ++NumCSROpt;
203 LLVM_DEBUG(dbgs() << MF.getName()
204 << " function optimized for not having CSR.\n");
205 }
206
208 for (unsigned PReg = 1, PRegE = TRI->getNumRegs(); PReg < PRegE; ++PReg) {
209 if (MachineOperand::clobbersPhysReg(&(RegMask[0]), PReg))
210 dbgs() << printReg(PReg, TRI) << " ";
211 }
212
213 dbgs() << " \n----------------------------------------\n";
214 );
215
216 PRUI.storeUpdateRegUsageInfo(F, RegMask);
217
218 return false;
219}
220
221void RegUsageInfoCollector::
222computeCalleeSavedRegs(BitVector &SavedRegs, MachineFunction &MF) {
225
226 // Target will return the set of registers that it saves/restores as needed.
227 SavedRegs.clear();
228 TFI.getCalleeSaves(MF, SavedRegs);
229 if (SavedRegs.none())
230 return;
231
232 // Insert subregs.
233 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
234 for (unsigned i = 0; CSRegs[i]; ++i) {
235 MCPhysReg Reg = CSRegs[i];
236 if (SavedRegs.test(Reg)) {
237 // Save subregisters
238 for (MCPhysReg SR : TRI.subregs(Reg))
239 SavedRegs.set(SR);
240 }
241 }
242}
unsigned const MachineRegisterInfo * MRI
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Natural Loop Information
Definition: LoopInfo.cpp:1209
#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
Register Usage Information Collector
RegUsageInfoCollector
static bool isCallableFunction(const MachineFunction &MF)
This pass is required to take advantage of the interprocedural register allocation infrastructure.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool test(unsigned Idx) const
Definition: BitVector.h:461
void clear()
clear - Removes all bits from the bitvector.
Definition: BitVector.h:335
BitVector & set()
Definition: BitVector.h:351
bool none() const
none - Returns true if none of the bits are set.
Definition: BitVector.h:188
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:277
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
MCRegAliasIterator enumerates all registers aliasing Reg.
static constexpr unsigned NoRegister
Definition: MCRegister.h:52
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
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...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
static unsigned getRegMaskSize(unsigned NumRegs)
Returns number of elements needed for a regmask array.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:692
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
void setTargetMachine(const TargetMachine &TM)
Set TargetMachine which is used to print analysis.
void storeUpdateRegUsageInfo(const Function &FP, ArrayRef< uint32_t > RegMask)
To store RegMask for given Function *.
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Information about stack frame layout on the target.
virtual void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
virtual bool isProfitableForNoCSROpt(const Function &F) const
Check if the no-CSR optimisation is profitable for the given function.
static bool isSafeForNoCSROpt(const Function &F)
Check if given function is safe for not having callee saved registers.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetFrameLowering * getFrameLowering() const
bool use_empty() const
Definition: Value.h:344
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
Definition: CallingConv.h:188
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
Definition: CallingConv.h:218
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:213
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Reg
All possible values of the reg field in the ModR/M byte.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createRegUsageInfoCollector()
This pass is executed POST-RA to collect which physical registers are preserved by given machine func...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void initializeRegUsageInfoCollectorLegacyPass(PassRegistry &)