LLVM 22.0.0git
AMDGPULowerKernelArguments.cpp
Go to the documentation of this file.
1//===-- AMDGPULowerKernelArguments.cpp ------------------------------------------===//
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 This pass replaces accesses to kernel arguments with loads from
10/// offsets from the kernarg base pointer.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPU.h"
15#include "GCNSubtarget.h"
18#include "llvm/IR/Attributes.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/IntrinsicsAMDGPU.h"
21#include "llvm/IR/MDBuilder.h"
23
24#define DEBUG_TYPE "amdgpu-lower-kernel-arguments"
25
26using namespace llvm;
27
28namespace {
29
30class AMDGPULowerKernelArguments : public FunctionPass {
31public:
32 static char ID;
33
34 AMDGPULowerKernelArguments() : FunctionPass(ID) {}
35
36 bool runOnFunction(Function &F) override;
37
38 void getAnalysisUsage(AnalysisUsage &AU) const override {
40 AU.setPreservesAll();
41 }
42};
43
44} // end anonymous namespace
45
46// skip allocas
49 for (BasicBlock::iterator E = BB.end(); InsPt != E; ++InsPt) {
50 AllocaInst *AI = dyn_cast<AllocaInst>(&*InsPt);
51
52 // If this is a dynamic alloca, the value may depend on the loaded kernargs,
53 // so loads will need to be inserted before it.
54 if (!AI || !AI->isStaticAlloca())
55 break;
56 }
57
58 return InsPt;
59}
60
61static bool lowerKernelArguments(Function &F, const TargetMachine &TM) {
62 CallingConv::ID CC = F.getCallingConv();
63 if (CC != CallingConv::AMDGPU_KERNEL || F.arg_empty())
64 return false;
65
66 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
67 LLVMContext &Ctx = F.getParent()->getContext();
68 const DataLayout &DL = F.getDataLayout();
69 BasicBlock &EntryBlock = *F.begin();
70 IRBuilder<> Builder(&EntryBlock, getInsertPt(EntryBlock));
71
72 const Align KernArgBaseAlign(16); // FIXME: Increase if necessary
73 const uint64_t BaseOffset = ST.getExplicitKernelArgOffset();
74
75 Align MaxAlign;
76 // FIXME: Alignment is broken with explicit arg offset.;
77 const uint64_t TotalKernArgSize = ST.getKernArgSegmentSize(F, MaxAlign);
78 if (TotalKernArgSize == 0)
79 return false;
80
81 CallInst *KernArgSegment =
82 Builder.CreateIntrinsic(Intrinsic::amdgcn_kernarg_segment_ptr, {},
83 nullptr, F.getName() + ".kernarg.segment");
84 KernArgSegment->addRetAttr(Attribute::NonNull);
85 KernArgSegment->addRetAttr(
86 Attribute::getWithDereferenceableBytes(Ctx, TotalKernArgSize));
87
88 uint64_t ExplicitArgOffset = 0;
89 for (Argument &Arg : F.args()) {
90 const bool IsByRef = Arg.hasByRefAttr();
91 Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
92 MaybeAlign ParamAlign = IsByRef ? Arg.getParamAlign() : std::nullopt;
93 Align ABITypeAlign = DL.getValueOrABITypeAlignment(ParamAlign, ArgTy);
94
95 uint64_t Size = DL.getTypeSizeInBits(ArgTy);
96 uint64_t AllocSize = DL.getTypeAllocSize(ArgTy);
97
98 uint64_t EltOffset = alignTo(ExplicitArgOffset, ABITypeAlign) + BaseOffset;
99 ExplicitArgOffset = alignTo(ExplicitArgOffset, ABITypeAlign) + AllocSize;
100
101 // Skip inreg arguments which should be preloaded.
102 if (Arg.use_empty() || Arg.hasInRegAttr())
103 continue;
104
105 // If this is byval, the loads are already explicit in the function. We just
106 // need to rewrite the pointer values.
107 if (IsByRef) {
108 Value *ArgOffsetPtr = Builder.CreateConstInBoundsGEP1_64(
109 Builder.getInt8Ty(), KernArgSegment, EltOffset,
110 Arg.getName() + ".byval.kernarg.offset");
111
112 Value *CastOffsetPtr =
113 Builder.CreateAddrSpaceCast(ArgOffsetPtr, Arg.getType());
114 Arg.replaceAllUsesWith(CastOffsetPtr);
115 continue;
116 }
117
118 if (PointerType *PT = dyn_cast<PointerType>(ArgTy)) {
119 // FIXME: Hack. We rely on AssertZext to be able to fold DS addressing
120 // modes on SI to know the high bits are 0 so pointer adds don't wrap. We
121 // can't represent this with range metadata because it's only allowed for
122 // integer types.
123 if ((PT->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
124 PT->getAddressSpace() == AMDGPUAS::REGION_ADDRESS) &&
125 !ST.hasUsableDSOffset())
126 continue;
127
128 // FIXME: We can replace this with equivalent alias.scope/noalias
129 // metadata, but this appears to be a lot of work.
130 if (Arg.hasNoAliasAttr())
131 continue;
132 }
133
134 auto *VT = dyn_cast<FixedVectorType>(ArgTy);
135 bool IsV3 = VT && VT->getNumElements() == 3;
136 bool DoShiftOpt = Size < 32 && !ArgTy->isAggregateType();
137
138 VectorType *V4Ty = nullptr;
139
140 int64_t AlignDownOffset = alignDown(EltOffset, 4);
141 int64_t OffsetDiff = EltOffset - AlignDownOffset;
142 Align AdjustedAlign = commonAlignment(
143 KernArgBaseAlign, DoShiftOpt ? AlignDownOffset : EltOffset);
144
145 Value *ArgPtr;
146 Type *AdjustedArgTy;
147 if (DoShiftOpt) { // FIXME: Handle aggregate types
148 // Since we don't have sub-dword scalar loads, avoid doing an extload by
149 // loading earlier than the argument address, and extracting the relevant
150 // bits.
151 // TODO: Update this for GFX12 which does have scalar sub-dword loads.
152 //
153 // Additionally widen any sub-dword load to i32 even if suitably aligned,
154 // so that CSE between different argument loads works easily.
155 ArgPtr = Builder.CreateConstInBoundsGEP1_64(
156 Builder.getInt8Ty(), KernArgSegment, AlignDownOffset,
157 Arg.getName() + ".kernarg.offset.align.down");
158 AdjustedArgTy = Builder.getInt32Ty();
159 } else {
160 ArgPtr = Builder.CreateConstInBoundsGEP1_64(
161 Builder.getInt8Ty(), KernArgSegment, EltOffset,
162 Arg.getName() + ".kernarg.offset");
163 AdjustedArgTy = ArgTy;
164 }
165
166 if (IsV3 && Size >= 32) {
167 V4Ty = FixedVectorType::get(VT->getElementType(), 4);
168 // Use the hack that clang uses to avoid SelectionDAG ruining v3 loads
169 AdjustedArgTy = V4Ty;
170 }
171
172 LoadInst *Load =
173 Builder.CreateAlignedLoad(AdjustedArgTy, ArgPtr, AdjustedAlign);
174 Load->setMetadata(LLVMContext::MD_invariant_load, MDNode::get(Ctx, {}));
175
176 MDBuilder MDB(Ctx);
177
178 if (Arg.hasAttribute(Attribute::NoUndef))
179 Load->setMetadata(LLVMContext::MD_noundef, MDNode::get(Ctx, {}));
180
181 if (Arg.hasAttribute(Attribute::Range)) {
182 const ConstantRange &Range =
183 Arg.getAttribute(Attribute::Range).getValueAsConstantRange();
184 Load->setMetadata(LLVMContext::MD_range,
186 }
187
188 if (isa<PointerType>(ArgTy)) {
189 if (Arg.hasNonNullAttr())
190 Load->setMetadata(LLVMContext::MD_nonnull, MDNode::get(Ctx, {}));
191
192 uint64_t DerefBytes = Arg.getDereferenceableBytes();
193 if (DerefBytes != 0) {
194 Load->setMetadata(
195 LLVMContext::MD_dereferenceable,
196 MDNode::get(Ctx,
197 MDB.createConstant(
198 ConstantInt::get(Builder.getInt64Ty(), DerefBytes))));
199 }
200
201 uint64_t DerefOrNullBytes = Arg.getDereferenceableOrNullBytes();
202 if (DerefOrNullBytes != 0) {
203 Load->setMetadata(
204 LLVMContext::MD_dereferenceable_or_null,
205 MDNode::get(Ctx,
206 MDB.createConstant(ConstantInt::get(Builder.getInt64Ty(),
207 DerefOrNullBytes))));
208 }
209
210 if (MaybeAlign ParamAlign = Arg.getParamAlign()) {
211 Load->setMetadata(
212 LLVMContext::MD_align,
213 MDNode::get(Ctx, MDB.createConstant(ConstantInt::get(
214 Builder.getInt64Ty(), ParamAlign->value()))));
215 }
216 }
217
218 // TODO: Convert noalias arg to !noalias
219
220 if (DoShiftOpt) {
221 Value *ExtractBits = OffsetDiff == 0 ?
222 Load : Builder.CreateLShr(Load, OffsetDiff * 8);
223
224 IntegerType *ArgIntTy = Builder.getIntNTy(Size);
225 Value *Trunc = Builder.CreateTrunc(ExtractBits, ArgIntTy);
226 Value *NewVal = Builder.CreateBitCast(Trunc, ArgTy,
227 Arg.getName() + ".load");
228 Arg.replaceAllUsesWith(NewVal);
229 } else if (IsV3) {
230 Value *Shuf = Builder.CreateShuffleVector(Load, ArrayRef<int>{0, 1, 2},
231 Arg.getName() + ".load");
232 Arg.replaceAllUsesWith(Shuf);
233 } else {
234 Load->setName(Arg.getName() + ".load");
235 Arg.replaceAllUsesWith(Load);
236 }
237 }
238
239 KernArgSegment->addRetAttr(
240 Attribute::getWithAlignment(Ctx, std::max(KernArgBaseAlign, MaxAlign)));
241
242 return true;
243}
244
245bool AMDGPULowerKernelArguments::runOnFunction(Function &F) {
246 auto &TPC = getAnalysis<TargetPassConfig>();
247 const TargetMachine &TM = TPC.getTM<TargetMachine>();
248 return lowerKernelArguments(F, TM);
249}
250
251INITIALIZE_PASS_BEGIN(AMDGPULowerKernelArguments, DEBUG_TYPE,
252 "AMDGPU Lower Kernel Arguments", false, false)
253INITIALIZE_PASS_END(AMDGPULowerKernelArguments, DEBUG_TYPE, "AMDGPU Lower Kernel Arguments",
255
256char AMDGPULowerKernelArguments::ID = 0;
257
259 return new AMDGPULowerKernelArguments();
260}
261
264 bool Changed = lowerKernelArguments(F, TM);
265 if (Changed) {
266 // TODO: Preserves a lot more.
269 return PA;
270 }
271
272 return PreservedAnalyses::all();
273}
AMDGPU Lower Kernel Arguments
static BasicBlock::iterator getInsertPt(BasicBlock &BB)
static bool lowerKernelArguments(Function &F, const TargetMachine &TM)
#define DEBUG_TYPE
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
uint64_t Size
AMD GCN specific subclass of TargetSubtarget.
#define F(x, y, z)
Definition: MD5.cpp:55
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#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
Target-Independent Code Generator Pass Configuration Options pass.
PreservedAnalyses run(Function &, FunctionAnalysisManager &)
an instruction to allocate memory on the stack
Definition: Instructions.h:64
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:244
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:234
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator end()
Definition: BasicBlock.h:472
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:393
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Definition: InstrTypes.h:1491
This class represents a function call, abstracting a target machine's calling convention.
This class represents a range of values.
Definition: ConstantRange.h:47
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:803
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition: IRBuilder.h:575
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1864
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1513
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:562
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:567
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:834
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2204
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2593
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2068
Value * CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition: IRBuilder.h:1993
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:552
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2209
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
Class to represent integer types.
Definition: DerivedTypes.h:42
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
An instruction for reading from memory.
Definition: Instructions.h:180
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:25
LLVM_ABI MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
Definition: MDBuilder.cpp:96
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:112
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:151
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:83
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:304
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:551
FunctionPass * createAMDGPULowerKernelArgumentsPass()
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117