LLVM 24.0.0git
AMDGPUMemoryUtils.cpp
Go to the documentation of this file.
1//===-- AMDGPUMemoryUtils.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#include "AMDGPUMemoryUtils.h"
15#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/IntrinsicsAMDGPU.h"
19#include "llvm/IR/LLVMContext.h"
21
22#define DEBUG_TYPE "amdgpu-memory-utils"
23
24using namespace llvm;
25
26namespace llvm::AMDGPU {
27
29 return DL.getValueOrABITypeAlignment(GV->getPointerAlignment(DL),
30 GV->getValueType());
31}
32
33void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source) {
35 Source.getAllMetadata(MD);
36 for (const auto &[ID, N] : MD) {
37 switch (ID) {
38 case LLVMContext::MD_dbg:
39 case LLVMContext::MD_invariant_load:
40 case LLVMContext::MD_nontemporal:
41 Dest.setMetadata(ID, N);
42 break;
43 default:
44 break;
45 }
46 }
47}
48
49// Returns the target extension type of a global variable,
50// which can only be a TargetExtType, an array or single-element struct of it,
51// or their nesting combination.
52// TODO: allow struct of multiple TargetExtType elements of the same type.
53// TODO: Disallow other uses of target("amdgcn.named.barrier") including:
54// - Structs containing barriers in different scope/rank
55// - Structs containing a mixture of barriers and other data.
56// - Globals in other address spaces.
57// - Allocas.
59 Type *Ty = GV.getValueType();
60 while (true) {
61 if (auto *TTy = dyn_cast<TargetExtType>(Ty))
62 return TTy;
63 if (auto *STy = dyn_cast<StructType>(Ty)) {
64 if (STy->getNumElements() != 1)
65 return nullptr;
66 Ty = STy->getElementType(0);
67 continue;
68 }
69 if (auto *ATy = dyn_cast<ArrayType>(Ty)) {
70 Ty = ATy->getElementType();
71 continue;
72 }
73 return nullptr;
74 }
75}
76
78 if (TargetExtType *Ty = getTargetExtType(GV))
79 return Ty->getName() == "amdgcn.named.barrier" ? Ty : nullptr;
80 return nullptr;
81}
82
84 // external zero size addrspace(3) without initializer is dynlds.
85 const Module *M = GV.getParent();
86 const DataLayout &DL = M->getDataLayout();
88 return false;
89 return GV.getGlobalSize(DL) == 0;
90}
91
94 return false;
95 }
96 if (isDynamicLDS(GV)) {
97 return true;
98 }
99 if (GV.isConstant()) {
100 // A constant undef variable can't be written to, and any load is
101 // undef, so it should be eliminated by the optimizer. It could be
102 // dropped by the back end if not. This pass skips over it.
103 return false;
104 }
105 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
106 // Initializers are unimplemented for LDS address space.
107 // Leave such variables in place for consistent error reporting.
108 return false;
109 }
110 return true;
111}
112
114 Module &M, function_ref<bool(const GlobalVariable &)> Filter) {
116 for (auto &GV : M.globals())
117 if (Filter(GV))
118 Worklist.push_back(&GV);
120}
121
123 function_ref<bool(const GlobalVariable &)> Filter,
124 FunctionVariableMap &Kernels,
125 FunctionVariableMap &Functions) {
126 // Get uses from the current function, excluding uses by called Functions
127 // Two output variables to avoid walking the globals list twice
128 for (auto &GV : M.globals()) {
129 if (!Filter(GV))
130 continue;
131 for (User *V : GV.users()) {
132 if (auto *I = dyn_cast<Instruction>(V)) {
133 Function *F = I->getFunction();
134 if (isKernel(*F))
135 Kernels[F].insert(&GV);
136 else
137 Functions[F].insert(&GV);
138 }
139 }
140 }
141}
142
143GVUsesInfoTy
145 function_ref<bool(const GlobalVariable &)> Filter) {
146
147 FunctionVariableMap DirectMapKernel;
148 FunctionVariableMap DirectMapFunction;
149 getUsesOfGVByFunction(CG, M, Filter, DirectMapKernel, DirectMapFunction);
150
151 // Collect functions whose address has escaped
152 DenseSet<Function *> AddressTakenFuncs;
153 for (Function &F : M.functions()) {
154 if (!isKernel(F))
155 if (F.hasAddressTaken(nullptr,
156 /* IgnoreCallbackUses */ false,
157 /* IgnoreAssumeLikeCalls */ false,
158 /* IgnoreLLVMUsed */ true,
159 /* IgnoreArcAttachedCall */ false)) {
160 AddressTakenFuncs.insert(&F);
161 }
162 }
163
164 // Collect variables that are used by functions whose address has escaped
165 DenseSet<GlobalVariable *> VariablesReachableThroughFunctionPointer;
166 for (Function *F : AddressTakenFuncs) {
167 set_union(VariablesReachableThroughFunctionPointer, DirectMapFunction[F]);
168 }
169
170 auto FunctionMakesUnknownCall = [&](const Function *F) -> bool {
171 assert(!F->isDeclaration());
172 for (const CallGraphNode::CallRecord &R : *CG[F]) {
173 if (!R.second->getFunction())
174 return true;
175 }
176 return false;
177 };
178
179 // Work out which variables are reachable through function calls
180 FunctionVariableMap TransitiveMapFunction = DirectMapFunction;
181
182 // If the function makes any unknown call, assume the worst case that it can
183 // access all variables accessed by functions whose address escaped
184 for (Function &F : M.functions()) {
185 if (!F.isDeclaration() && FunctionMakesUnknownCall(&F)) {
186 if (!isKernel(F)) {
187 set_union(TransitiveMapFunction[&F],
188 VariablesReachableThroughFunctionPointer);
189 }
190 }
191 }
192
193 // Direct implementation of collecting all variables reachable from each
194 // function
195 for (Function &Func : M.functions()) {
196 if (Func.isDeclaration() || isKernel(Func))
197 continue;
198
199 DenseSet<Function *> seen; // catches cycles
200 SmallVector<Function *, 4> wip = {&Func};
201
202 while (!wip.empty()) {
203 Function *F = wip.pop_back_val();
204
205 // Can accelerate this by referring to transitive map for functions that
206 // have already been computed, with more care than this
207 set_union(TransitiveMapFunction[&Func], DirectMapFunction[F]);
208
209 for (const CallGraphNode::CallRecord &R : *CG[F]) {
210 Function *Ith = R.second->getFunction();
211 if (Ith) {
212 if (!seen.contains(Ith)) {
213 seen.insert(Ith);
214 wip.push_back(Ith);
215 }
216 }
217 }
218 }
219 }
220
221 // Collect variables that are transitively used by functions whose address has
222 // escaped
223 for (Function *F : AddressTakenFuncs) {
224 set_union(VariablesReachableThroughFunctionPointer,
225 TransitiveMapFunction[F]);
226 }
227
228 // DirectMapKernel lists which variables are used by the kernel
229 // find the variables which are used through a function call
230 FunctionVariableMap IndirectMapKernel;
231
232 for (Function &Func : M.functions()) {
233 if (Func.isDeclaration() || !isKernel(Func))
234 continue;
235
236 for (const CallGraphNode::CallRecord &R : *CG[&Func]) {
237 Function *Ith = R.second->getFunction();
238 if (Ith) {
239 set_union(IndirectMapKernel[&Func], TransitiveMapFunction[Ith]);
240 }
241 }
242
243 // Check if the kernel encounters unknows calls, wheher directly or
244 // indirectly.
245 bool SeesUnknownCalls = [&]() {
246 SmallVector<Function *> WorkList = {CG[&Func]->getFunction()};
248
249 while (!WorkList.empty()) {
250 Function *F = WorkList.pop_back_val();
251
252 for (const CallGraphNode::CallRecord &CallRecord : *CG[F]) {
253 if (!CallRecord.second)
254 continue;
255
256 Function *Callee = CallRecord.second->getFunction();
257 if (!Callee)
258 return true;
259
260 if (Visited.insert(Callee).second)
261 WorkList.push_back(Callee);
262 }
263 }
264 return false;
265 }();
266
267 if (SeesUnknownCalls) {
268 set_union(IndirectMapKernel[&Func],
269 VariablesReachableThroughFunctionPointer);
270 }
271 }
272
273 return {std::move(DirectMapKernel), std::move(IndirectMapKernel)};
274}
275
278 // Verify that we fall into one of 2 cases:
279 // - All variables are either absolute
280 // or direct mapped dynamic LDS that is not lowered.
281 // - No variables are absolute.
282 // Named-barriers which are absolute symbols are removed
283 // from the maps.
284 std::optional<bool> HasAbsoluteGVs;
285 for (auto &Map : {UsesInfo.DirectAccess, UsesInfo.IndirectAccess}) {
286 for (auto &[Fn, GVs] : Map) {
287 for (auto *GV : GVs) {
288 bool IsAbsolute = GV->isAbsoluteSymbolRef();
289 bool IsDirectMapDynLDSGV =
290 AMDGPU::isDynamicLDS(*GV) && UsesInfo.DirectAccess.contains(Fn);
291 if (IsDirectMapDynLDSGV)
292 continue;
293
294 // TODO: Remove once barriers are no longer in the LDS AS.
295 if (isNamedBarrier(*GV)) {
296 if (IsAbsolute) {
297 UsesInfo.DirectAccess[Fn].erase(GV);
298 UsesInfo.IndirectAccess[Fn].erase(GV);
299 }
300 continue;
301 }
302
303 if (HasAbsoluteGVs.has_value()) {
304 if (*HasAbsoluteGVs != IsAbsolute) {
306 "module cannot mix absolute and non-absolute LDS GVs");
307 }
308 } else
309 HasAbsoluteGVs = IsAbsolute;
310 }
311 }
312 }
313
314 // If we only had absolute GVs, we have nothing to do, return an empty
315 // result.
316 if (HasAbsoluteGVs && *HasAbsoluteGVs)
317 return GVUsesInfoTy();
318
319 return UsesInfo;
320}
321
323 ArrayRef<StringRef> FnAttrs) {
324 for (StringRef Attr : FnAttrs)
325 KernelRoot->removeFnAttr(Attr);
326
327 SmallVector<Function *> WorkList = {CG[KernelRoot]->getFunction()};
329 bool SeenUnknownCall = false;
330
331 while (!WorkList.empty()) {
332 Function *F = WorkList.pop_back_val();
333
334 for (auto &CallRecord : *CG[F]) {
335 if (!CallRecord.second)
336 continue;
337
338 Function *Callee = CallRecord.second->getFunction();
339 if (!Callee) {
340 if (!SeenUnknownCall) {
341 SeenUnknownCall = true;
342
343 // If we see any indirect calls, assume nothing about potential
344 // targets.
345 // TODO: This could be refined to possible LDS global users.
346 for (auto &ExternalCallRecord : *CG.getExternalCallingNode()) {
347 Function *PotentialCallee =
348 ExternalCallRecord.second->getFunction();
349 assert(PotentialCallee);
350 if (!isKernel(*PotentialCallee)) {
351 for (StringRef Attr : FnAttrs)
352 PotentialCallee->removeFnAttr(Attr);
353 }
354 }
355 }
356 } else {
357 for (StringRef Attr : FnAttrs)
358 Callee->removeFnAttr(Attr);
359 if (Visited.insert(Callee).second)
360 WorkList.push_back(Callee);
361 }
362 }
363 }
364}
365
366bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, AAResults *AA) {
367 Instruction *DefInst = Def->getMemoryInst();
368
369 if (isa<FenceInst>(DefInst))
370 return false;
371
372 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
373 switch (II->getIntrinsicID()) {
374 case Intrinsic::amdgcn_s_barrier:
375 case Intrinsic::amdgcn_s_cluster_barrier:
376 case Intrinsic::amdgcn_s_barrier_signal:
377 case Intrinsic::amdgcn_s_barrier_signal_var:
378 case Intrinsic::amdgcn_s_barrier_signal_isfirst:
379 case Intrinsic::amdgcn_s_barrier_init:
380 case Intrinsic::amdgcn_s_barrier_join:
381 case Intrinsic::amdgcn_s_barrier_wait:
382 case Intrinsic::amdgcn_s_barrier_leave:
383 case Intrinsic::amdgcn_s_get_barrier_state:
384 case Intrinsic::amdgcn_s_wakeup_barrier:
385 case Intrinsic::amdgcn_wave_barrier:
386 case Intrinsic::amdgcn_sched_barrier:
387 case Intrinsic::amdgcn_sched_group_barrier:
388 case Intrinsic::amdgcn_iglp_opt:
389 return false;
390 default:
391 break;
392 }
393 }
394
395 // Ignore atomics not aliasing with the original load, any atomic is a
396 // universal MemoryDef from MSSA's point of view too, just like a fence.
397 const auto checkNoAlias = [AA, Ptr](auto I) -> bool {
398 return I && AA->isNoAlias(I->getPointerOperand(), Ptr);
399 };
400
401 if (checkNoAlias(dyn_cast<AtomicCmpXchgInst>(DefInst)) ||
402 checkNoAlias(dyn_cast<AtomicRMWInst>(DefInst)))
403 return false;
404
405 return true;
406}
407
409 AAResults *AA) {
410 MemorySSAWalker *Walker = MSSA->getWalker();
414 Walker->getClobberingMemoryAccess(Use->getDefiningAccess(), Loc)};
416
417 LLVM_DEBUG(dbgs() << "Checking clobbering of: " << *Load << '\n');
418
419 // Start with a nearest dominating clobbering access, it will be either
420 // live on entry (nothing to do, load is not clobbered), MemoryDef, or
421 // MemoryPhi if several MemoryDefs can define this memory state. In that
422 // case add all Defs to WorkList and continue going up and checking all
423 // the definitions of this memory location until the root. When all the
424 // defs are exhausted and came to the entry state we have no clobber.
425 // Along the scan ignore barriers and fences which are considered clobbers
426 // by the MemorySSA, but not really writing anything into the memory.
427 while (!WorkList.empty()) {
428 MemoryAccess *MA = WorkList.pop_back_val();
429 if (!Visited.insert(MA).second)
430 continue;
431
432 if (MSSA->isLiveOnEntryDef(MA))
433 continue;
434
435 if (MemoryDef *Def = dyn_cast<MemoryDef>(MA)) {
436 LLVM_DEBUG(dbgs() << " Def: " << *Def->getMemoryInst() << '\n');
437
438 if (isReallyAClobber(Load->getPointerOperand(), Def, AA)) {
439 LLVM_DEBUG(dbgs() << " -> load is clobbered\n");
440 return true;
441 }
442
443 WorkList.push_back(
444 Walker->getClobberingMemoryAccess(Def->getDefiningAccess(), Loc));
445 continue;
446 }
447
448 const MemoryPhi *Phi = cast<MemoryPhi>(MA);
449 for (const auto &Use : Phi->incoming_values())
450 WorkList.push_back(
452 }
453
454 LLVM_DEBUG(dbgs() << " -> no clobber\n");
455 return false;
456}
457
458} // end namespace llvm::AMDGPU
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define F(x, y, z)
Definition MD5.cpp:54
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
This file defines generic set operations that may be used on set's of different types,...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
std::pair< std::optional< WeakTrackingVH >, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called.
Definition CallGraph.h:174
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
CallGraphNode * getExternalCallingNode() const
Returns the CallGraphNode which is used to represent undetermined calls into the callgraph.
Definition CallGraph.h:127
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
const Function & getFunction() const
Definition Function.h:166
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition Function.cpp:685
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:371
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Represents phi nodes for memory accesses.
Definition MemorySSA.h:479
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1006
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1035
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:250
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
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.
Definition StringRef.h:56
Class to represent target extensions types, which are generally unintrospectable from target-independ...
StringRef getName() const
Return the name for this target extension type.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
An efficient, type-erasing, non-owning reference to a callable.
Abstract Attribute helper functions.
Definition Attributor.h:165
@ LOCAL_ADDRESS
Address space for local memory.
GVUsesInfoTy getTransitiveUsesOfLDSForLowering(const CallGraph &CG, Module &M)
Collects all uses of LDS Global Variables in M using getUsesOfGVByFunction, with isLDSVariableToLower...
bool isDynamicLDS(const GlobalVariable &GV)
void removeFnAttrFromReachable(CallGraph &CG, Function *KernelRoot, ArrayRef< StringRef > FnAttrs)
Strip FnAttr attribute from any functions where we may have introduced its use.
bool eliminateGVConstantExprUsesFromAllInstructions(Module &M, function_ref< bool(const GlobalVariable &)> Filter)
Iterates over all GlobalVariables in M, and whenever Filter returns true, replace all constant users ...
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
void getUsesOfGVByFunction(const CallGraph &CG, Module &M, function_ref< bool(const GlobalVariable &)> Filter, FunctionVariableMap &Kernels, FunctionVariableMap &Functions)
Finds uses of Global Variables on a per-function basis.
bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, AAResults *AA)
Given a Def clobbering a load from Ptr according to the MSSA check if this is actually a memory updat...
static TargetExtType * getTargetExtType(const GlobalVariable &GV)
DenseMap< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
bool isLDSVariableToLower(const GlobalVariable &GV)
Align getAlign(const DataLayout &DL, const GlobalVariable *GV)
void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source)
bool isClobberedInFunction(const LoadInst *Load, MemorySSA *MSSA, AAResults *AA)
Check is a Load is clobbered in its function.
GVUsesInfoTy getTransitiveUsesOfGV(const CallGraph &CG, Module &M, function_ref< bool(const GlobalVariable &)> Filter)
Collects all uses of Global Variables in M using getUsesOfGVByFunction.
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.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
FunctionVariableMap DirectAccess
FunctionVariableMap IndirectAccess
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39