LLVM 24.0.0git
AMDGPULowerExecSync.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Lower global variables with target extension type "amdgpu.named.barrier"
10// that require specialized address assignment. It assigns a unique
11// barrier identifier to each named-barrier variable and encodes
12// this identifier within the !absolute_symbol metadata of that global.
13//
14//===----------------------------------------------------------------------===//
15
16#include "AMDGPU.h"
17#include "AMDGPUMemoryUtils.h"
18#include "AMDGPUTargetMachine.h"
20#include "llvm/IR/Constants.h"
24#include "llvm/Pass.h"
26
27#define DEBUG_TYPE "amdgpu-lower-exec-sync"
28
29using namespace llvm;
30using namespace AMDGPU;
31
32namespace {
33
34static bool isNamedBarrierToLower(const GlobalVariable &GV) {
35 return isNamedBarrier(GV) && !GV.isAbsoluteSymbolRef();
36}
37
38// Write the specified address into metadata where it can be retrieved by
39// the assembler. Format is a half open range, [Address Address+1)
40static void recordAbsoluteAddress(Module *M, GlobalVariable *GV,
41 uint32_t Address) {
42 LLVMContext &Ctx = M->getContext();
43 auto *IntTy = M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
44 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
45 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
46 GV->setMetadata(LLVMContext::MD_absolute_symbol,
47 MDNode::get(Ctx, {MinC, MaxC}));
48}
49
50/// Get next available ID for sync object. The ID allocation is tracked in \p
51/// MaxNumGroup groups by \p NextAvailableIDTracker. Each call of the function
52/// will ask for \p IDCnt against all the \p Kernels, it will return the
53/// maximum of the available ones and update the ID tracker.
54template <typename T>
55unsigned allocateExecSyncID(T &NextAvailableIDTracker,
56 ArrayRef<Function *> Kernels, unsigned GroupID,
57 unsigned MaxNumGroup, unsigned IDCnt) {
58 constexpr unsigned InitialVal = 1;
59 unsigned NextID = InitialVal;
60 for (Function *F : Kernels) {
61 const SmallVectorImpl<unsigned> &NextAvailableID =
62 NextAvailableIDTracker.lookup(F);
63 unsigned ID = InitialVal;
64 if (!NextAvailableID.empty())
65 ID = NextAvailableID[GroupID];
66
67 if (ID > NextID)
68 NextID = ID;
69 }
70
71 // Bump the next available id for the kernels.
72 for (Function *F : Kernels) {
73 auto Inserted = NextAvailableIDTracker.try_emplace(F);
74 // Initialize on first insertion.
75 if (Inserted.second)
76 Inserted.first->second.assign(MaxNumGroup, InitialVal);
77 // Update the available ID.
78 Inserted.first->second[GroupID] = NextID + IDCnt;
79 }
80 return NextID;
81}
82
83// Main utility function for special LDS variables lowering.
84static bool lowerExecSyncGlobalVariables(Module &M, GVUsesInfoTy &GVUsesInfo) {
85 bool Changed = false;
86 const DataLayout &DL = M.getDataLayout();
87
88 constexpr unsigned NumBarScopes = 1;
91
92 for (auto &[F, GVs] : GVUsesInfo.IndirectAccess) {
93 for (auto *GV : GVs) {
94 if (!isNamedBarrier(*GV) || GV->isAbsoluteSymbolRef())
95 continue;
96 auto Iter = AllocationQ.find(GV);
97 if (Iter == AllocationQ.end())
98 AllocationQ.insert({GV, {F}});
99 else
100 Iter->second.push_back(F);
101 }
102 }
103
104 for (auto &[F, GVs] : GVUsesInfo.DirectAccess) {
105 for (auto *GV : GVs) {
106 if (!isNamedBarrier(*GV) || GV->isAbsoluteSymbolRef())
107 continue;
108 auto Iter = AllocationQ.find(GV);
109 if (Iter == AllocationQ.end())
110 AllocationQ.insert({GV, {F}});
111 else
112 Iter->second.push_back(F);
113 }
114 }
115
116 sort(AllocationQ, [](std::pair<GlobalVariable *, SmallVector<Function *>> A,
118 // First order by number of kernels that access the GlobalVariable.
119 if (A.second.size() != B.second.size())
120 return A.second.size() > B.second.size();
121
122 // Then order by their names so we always get a deterministic order.
123 return A.first->getName() < B.first->getName();
124 });
125
126 for (auto &[GV, Kernels] : AllocationQ) {
127 unsigned Offset;
128 if (TargetExtType *ExtTy = isNamedBarrier(*GV)) {
129 unsigned BarrierScope = ExtTy->getIntParameter(0);
130 unsigned BarCnt = GV->getGlobalSize(DL) / 16;
131
132 unsigned BarID = allocateExecSyncID(KernelBarrierIDs, Kernels,
133 BarrierScope, NumBarScopes, BarCnt);
134
135 LLVM_DEBUG(GV->printAsOperand(dbgs(), false);
136 dbgs() << " was assigned barrier id: " << BarID
137 << " id-count: " << BarCnt << "\n");
138 Offset = BarID;
139 } else {
140 llvm_unreachable("Unhandled special variable type.");
141 }
142
143 recordAbsoluteAddress(&M, GV, Offset);
144 }
145
146 // Also erase those special LDS variables from indirect_access.
147 for (auto &K : GVUsesInfo.IndirectAccess) {
148 assert(isKernel(*K.first));
149 K.second.remove_if([](GlobalVariable *GV) { return isNamedBarrier(*GV); });
150 }
151 return Changed;
152}
153
154static bool hasBarrierToLower(const GVUsesInfoTy &GVUsesInfo) {
155 for (auto &Map : {GVUsesInfo.DirectAccess, GVUsesInfo.IndirectAccess}) {
156 for (auto &[Fn, GVs] : Map) {
157 for (auto &GV : GVs) {
158 if (AMDGPU::isNamedBarrier(*GV))
159 return true;
160 }
161 }
162 }
163 return false;
164}
165
166// With object linking, barrier ID assignment is deferred to the linker.
167// Externalize named barrier globals and emit self-contained metadata so the
168// AsmPrinter can generate the callgraph entries the linker needs.
169static bool handleNamedBarriersForObjectLinking(Module &M) {
171 for (GlobalVariable &GV : M.globals()) {
172 if (!isNamedBarrier(GV) || GV.use_empty())
173 continue;
174 for (User *U : GV.users()) {
175 if (auto *I = dyn_cast<Instruction>(U))
176 BarrierToFuncs[&GV].insert(I->getFunction());
177 }
178 }
179 if (BarrierToFuncs.empty())
180 return false;
181
182 LLVMContext &Ctx = M.getContext();
183 NamedMDNode *BarMD = M.getOrInsertNamedMetadata("amdgpu.named_barrier.uses");
184
185 std::string ModuleId;
186 ModuleId = getUniqueModuleId(&M);
187 assert(!ModuleId.empty() &&
188 "modules with named barriers should have a unique ID");
189 for (auto &[V, Funcs] : BarrierToFuncs) {
190 if (V->hasLocalLinkage())
191 V->setName("__amdgpu_named_barrier." + V->getName() + ModuleId);
192 else if (!V->getName().starts_with("__amdgpu_named_barrier"))
193 V->setName("__amdgpu_named_barrier." + V->getName());
194 V->setInitializer(nullptr);
195 V->setLinkage(GlobalValue::ExternalLinkage);
196
198 Ops.push_back(ValueAsMetadata::get(V));
199 for (Function *F : Funcs)
200 Ops.push_back(ValueAsMetadata::get(F));
201 BarMD->addOperand(MDNode::get(Ctx, Ops));
202 }
203 return true;
204}
205
206static bool runLowerExecSyncGlobals(Module &M) {
208 return handleNamedBarriersForObjectLinking(M);
209
210 CallGraph CG = CallGraph(M);
211 bool Changed = false;
212 Changed |=
213 eliminateGVConstantExprUsesFromAllInstructions(M, isNamedBarrierToLower);
214
215 // For each kernel, what variables does it access directly or through
216 // callees
217 GVUsesInfoTy BarrierUsesInfo =
218 getTransitiveUsesOfGV(CG, M, isNamedBarrierToLower);
219
220 if (hasBarrierToLower(BarrierUsesInfo)) {
221 // Special LDS variables need special address assignment
222 Changed |= lowerExecSyncGlobalVariables(M, BarrierUsesInfo);
223 }
224
225 return Changed;
226}
227
228class AMDGPULowerExecSyncLegacy : public ModulePass {
229public:
230 static char ID;
231 AMDGPULowerExecSyncLegacy() : ModulePass(ID) {}
232 bool runOnModule(Module &M) override;
233};
234
235} // namespace
236
237char AMDGPULowerExecSyncLegacy::ID = 0;
238char &llvm::AMDGPULowerExecSyncLegacyPassID = AMDGPULowerExecSyncLegacy::ID;
239
240INITIALIZE_PASS_BEGIN(AMDGPULowerExecSyncLegacy, DEBUG_TYPE,
241 "AMDGPU lowering of execution synchronization", false,
242 false)
244INITIALIZE_PASS_END(AMDGPULowerExecSyncLegacy, DEBUG_TYPE,
245 "AMDGPU lowering of execution synchronization", false,
246 false)
247
248bool AMDGPULowerExecSyncLegacy::runOnModule(Module &M) {
249 return runLowerExecSyncGlobals(M);
250}
251
253 return new AMDGPULowerExecSyncLegacy();
254}
255
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#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
#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
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool empty() const
Definition DenseMap.h:199
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:312
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI bool isAbsoluteSymbolRef() const
Returns whether this is a reference to an absolute symbol.
Definition Globals.cpp:526
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1755
LLVM_ABI void addOperand(MDNode *M)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Target-Independent Code Generator Pass Configuration Options.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:506
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
bool use_empty() const
Definition Value.h:348
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
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)
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
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.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
char & AMDGPULowerExecSyncLegacyPassID
LLVM_ABI std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
ModulePass * createAMDGPULowerExecSyncLegacyPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
FunctionVariableMap DirectAccess
FunctionVariableMap IndirectAccess