26#include "llvm/IR/IntrinsicsAMDGPU.h"
32#define DEBUG_TYPE "amdgpu-preload-kernel-arguments"
38class AMDGPUPreloadKernelArgumentsLegacy :
public ModulePass {
43 explicit AMDGPUPreloadKernelArgumentsLegacy(
47 return "AMDGPU Preload Kernel Arguments";
50 bool runOnModule(
Module &M)
override;
53class PreloadKernelArgInfo {
57 unsigned NumFreeUserSGPRs;
59 enum HiddenArg :
unsigned {
73 struct HiddenArgInfo {
83 static constexpr HiddenArgInfo HiddenArgs[END_HIDDEN_ARGS] = {
84 {0, 4,
"_hidden_block_count_x"}, {4, 4,
"_hidden_block_count_y"},
85 {8, 4,
"_hidden_block_count_z"}, {12, 2,
"_hidden_group_size_x"},
86 {14, 2,
"_hidden_group_size_y"}, {16, 2,
"_hidden_group_size_z"},
87 {18, 2,
"_hidden_remainder_x"}, {20, 2,
"_hidden_remainder_y"},
88 {22, 2,
"_hidden_remainder_z"}};
90 static HiddenArg getHiddenArgFromOffset(
unsigned Offset) {
91 for (
unsigned I = 0;
I < END_HIDDEN_ARGS; ++
I)
93 return static_cast<HiddenArg
>(
I);
95 return END_HIDDEN_ARGS;
99 if (HA < END_HIDDEN_ARGS)
105 static const char *getHiddenArgName(HiddenArg HA) {
106 if (HA < END_HIDDEN_ARGS)
107 return HiddenArgs[HA].Name;
119 Function *cloneFunctionWithPreloadImplicitArgs(
unsigned LastPreloadIndex) {
123 for (
unsigned I = 0;
I <= LastPreloadIndex; ++
I)
124 FTypes.
push_back(getHiddenArgType(Ctx, HiddenArg(
I)));
134 F.getParent()->getFunctionList().insert(
F.getIterator(), NF);
140 Arg.replaceAllUsesWith(&*NFArg);
146 AB.addAttribute(Attribute::InReg);
147 AB.addAttribute(
"amdgpu-hidden-argument");
149 for (
unsigned I = 0;
I <= LastPreloadIndex; ++
I) {
150 AL = AL.addParamAttributes(Ctx, NFArg->
getArgNo(), AB);
151 NFArg++->
setName(getHiddenArgName(HiddenArg(
I)));
155 F.replaceAllUsesWith(NF);
162 setInitialFreeUserSGPRsCount();
167 void setInitialFreeUserSGPRsCount() {
172 bool canPreloadKernArgAtOffset(
uint64_t ExplicitArgOffset) {
173 return ExplicitArgOffset <= NumFreeUserSGPRs * 4;
178 tryAllocHiddenArgPreloadSGPRs(
uint64_t ImplicitArgsBaseOffset,
181 F.getParent(), Intrinsic::amdgcn_implicitarg_ptr);
188 for (
auto *U : ImplicitArgPtr->
users()) {
193 for (
auto *U : CI->
users()) {
197 if (U->user_empty() ||
210 HiddenArg HA = getHiddenArgFromOffset(
Offset);
211 if (HA == END_HIDDEN_ARGS || LoadTy != getHiddenArgType(Ctx, HA))
218 if (ImplicitArgLoads.
empty())
229 ImplicitArgLoads, [&](
const std::pair<LoadInst *, unsigned> &
Load) {
230 unsigned LoadSize =
DL.getTypeStoreSize(
Load.first->getType());
231 unsigned LoadOffset =
Load.second;
232 if (!canPreloadKernArgAtOffset(LoadOffset + LoadSize +
233 ImplicitArgsBaseOffset))
239 if (PreloadEnd == ImplicitArgLoads.
begin())
242 unsigned LastHiddenArgIndex = getHiddenArgFromOffset(PreloadEnd[-1].second);
243 Function *NF = cloneFunctionWithPreloadImplicitArgs(LastHiddenArgIndex);
246 for (
const auto *
I = ImplicitArgLoads.
begin();
I != PreloadEnd; ++
I) {
248 unsigned LoadOffset =
I->second;
249 unsigned HiddenArgIndex = getHiddenArgFromOffset(LoadOffset);
250 unsigned Index = NF->
arg_size() - LastHiddenArgIndex + HiddenArgIndex - 1;
259char AMDGPUPreloadKernelArgumentsLegacy::ID = 0;
262 "AMDGPU Preload Kernel Arguments",
false,
false)
266 return new AMDGPUPreloadKernelArgumentsLegacy(
270AMDGPUPreloadKernelArgumentsLegacy::AMDGPUPreloadKernelArgumentsLegacy(
275 const AMDGPUOptions &CLOpts =
277 if (!CLOpts.kernarg_preload)
284 if (!ST.hasKernargPreload() ||
288 PreloadKernelArgInfo PreloadInfo(
F, ST);
291 const uint64_t BaseOffset = ST.getExplicitKernelArgOffset();
292 unsigned NumPreloadsRequested = CLOpts.kernarg_preload_count;
293 unsigned NumPreloadedExplicitArgs = 0;
299 if (Arg.hasByRefAttr() || Arg.hasNestAttr() ||
300 Arg.hasAttribute(
"amdgpu-hidden-argument"))
304 if (NumPreloadsRequested == 0 && !Arg.hasInRegAttr())
308 if (Arg.getType()->isAggregateType())
311 Type *ArgTy = Arg.getType();
312 Align ABITypeAlign =
DL.getABITypeAlign(ArgTy);
313 uint64_t AllocSize =
DL.getTypeAllocSize(ArgTy);
314 ExplicitArgOffset =
alignTo(ExplicitArgOffset, ABITypeAlign) + AllocSize;
316 if (!PreloadInfo.canPreloadKernArgAtOffset(ExplicitArgOffset))
319 Arg.addAttr(Attribute::InReg);
320 NumPreloadedExplicitArgs++;
321 if (NumPreloadsRequested > 0)
322 NumPreloadsRequested--;
327 if (NumPreloadedExplicitArgs ==
F.arg_size()) {
329 alignTo(ExplicitArgOffset, ST.getAlignmentForImplicitArgPtr()) +
331 PreloadInfo.tryAllocHiddenArgPreloadSGPRs(ImplicitArgsBaseOffset,
335 Changed |= NumPreloadedExplicitArgs > 0;
341 for (
auto *
F : FunctionsToErase)
342 F->eraseFromParent();
347bool AMDGPUPreloadKernelArgumentsLegacy::runOnModule(
Module &M) {
348 if (skipModule(M) || !TM)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool markKernelArgsAsInreg(Module &M, const TargetMachine &TM)
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents an incoming formal argument to a Function.
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
A parsed version of the target data layout string in and methods for querying it.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
AttributeList getAttributes() const
Return the attribute list for this Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Argument * getArg(unsigned i) const
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
unsigned getNumFreeUserSGPRs()
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Primary interface to the complete machine description for the target machine.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ Load
The value being inserted comes from a load (InsertElement only).
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
ModulePass * createAMDGPUPreloadKernelArgumentsLegacyPass(const TargetMachine *)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Function object to check whether the second component of a container supported by std::get (like std:...