LLVM 22.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 LDS 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 LDS variable and encodes
12// this identifier within the !absolute_symbol metadata of that global.
13// This encoding ensures that subsequent LDS lowering passes can process these
14// barriers correctly without conflicts.
15//
16//===----------------------------------------------------------------------===//
17
18#include "AMDGPU.h"
19#include "AMDGPUMemoryUtils.h"
20#include "AMDGPUTargetMachine.h"
21#include "llvm/ADT/DenseMap.h"
24#include "llvm/IR/Constants.h"
28#include "llvm/Pass.h"
29
30#include <algorithm>
31
32#define DEBUG_TYPE "amdgpu-lower-exec-sync"
33
34using namespace llvm;
35using namespace AMDGPU;
36
37namespace {
38
39// If GV is also used directly by other kernels, create a new GV
40// used only by this kernel and its function.
41static GlobalVariable *uniquifyGVPerKernel(Module &M, GlobalVariable *GV,
42 Function *KF) {
43 bool NeedsReplacement = false;
44 for (Use &U : GV->uses()) {
45 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
46 Function *F = I->getFunction();
47 if (isKernelLDS(F) && F != KF) {
48 NeedsReplacement = true;
49 break;
50 }
51 }
52 }
53 if (!NeedsReplacement)
54 return GV;
55 // Create a new GV used only by this kernel and its function
56 GlobalVariable *NewGV = new GlobalVariable(
57 M, GV->getValueType(), GV->isConstant(), GV->getLinkage(),
58 GV->getInitializer(), GV->getName() + "." + KF->getName(), nullptr,
60 NewGV->copyAttributesFrom(GV);
61 for (Use &U : make_early_inc_range(GV->uses())) {
62 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
63 Function *F = I->getFunction();
64 if (!isKernelLDS(F) || F == KF) {
65 U.getUser()->replaceUsesOfWith(GV, NewGV);
66 }
67 }
68 }
69 return NewGV;
70}
71
72// Write the specified address into metadata where it can be retrieved by
73// the assembler. Format is a half open range, [Address Address+1)
74static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
75 uint32_t Address) {
76 LLVMContext &Ctx = M->getContext();
77 auto *IntTy = M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
78 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
79 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
80 GV->setMetadata(LLVMContext::MD_absolute_symbol,
81 MDNode::get(Ctx, {MinC, MaxC}));
82}
83
84template <typename T> SmallVector<T> sortByName(SmallVector<T> &&V) {
85 sort(V, [](const auto *L, const auto *R) {
86 return L->getName() < R->getName();
87 });
88 return {std::move(V)};
89}
90
91// Main utility function for special LDS variables lowering.
92static bool lowerExecSyncGlobalVariables(
93 Module &M, LDSUsesInfoTy &LDSUsesInfo,
94 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly) {
95 bool Changed = false;
96 const DataLayout &DL = M.getDataLayout();
97 // The 1st round: give module-absolute assignments
98 int NumAbsolutes = 0;
100 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
101 GlobalVariable *GV = K.first;
102 if (!isNamedBarrier(*GV))
103 continue;
104 // give a module-absolute assignment if it is indirectly accessed by
105 // multiple kernels. This is not precise, but we don't want to duplicate
106 // a function when it is called by multiple kernels.
107 if (LDSToKernelsThatNeedToAccessItIndirectly[GV].size() > 1) {
108 OrderedGVs.push_back(GV);
109 } else {
110 // leave it to the 2nd round, which will give a kernel-relative
111 // assignment if it is only indirectly accessed by one kernel
112 LDSUsesInfo.direct_access[*K.second.begin()].insert(GV);
113 }
114 LDSToKernelsThatNeedToAccessItIndirectly.erase(GV);
115 }
116 OrderedGVs = sortByName(std::move(OrderedGVs));
117 for (GlobalVariable *GV : OrderedGVs) {
118 unsigned BarrierScope = AMDGPU::Barrier::BARRIER_SCOPE_WORKGROUP;
119 unsigned BarId = NumAbsolutes + 1;
120 unsigned BarCnt = DL.getTypeAllocSize(GV->getValueType()) / 16;
121 NumAbsolutes += BarCnt;
122
123 // 4 bits for alignment, 5 bits for the barrier num,
124 // 3 bits for the barrier scope
125 unsigned Offset = 0x802000u | BarrierScope << 9 | BarId << 4;
126 recordLDSAbsoluteAddress(&M, GV, Offset);
127 }
128 OrderedGVs.clear();
129
130 // The 2nd round: give a kernel-relative assignment for GV that
131 // either only indirectly accessed by single kernel or only directly
132 // accessed by multiple kernels.
133 SmallVector<Function *> OrderedKernels;
134 for (auto &K : LDSUsesInfo.direct_access) {
135 Function *F = K.first;
137 OrderedKernels.push_back(F);
138 }
139 OrderedKernels = sortByName(std::move(OrderedKernels));
140
142 for (Function *F : OrderedKernels) {
143 for (GlobalVariable *GV : LDSUsesInfo.direct_access[F]) {
144 if (!isNamedBarrier(*GV))
145 continue;
146
147 LDSUsesInfo.direct_access[F].erase(GV);
148 if (GV->isAbsoluteSymbolRef()) {
149 // already assigned
150 continue;
151 }
152 OrderedGVs.push_back(GV);
153 }
154 OrderedGVs = sortByName(std::move(OrderedGVs));
155 for (GlobalVariable *GV : OrderedGVs) {
156 // GV could also be used directly by other kernels. If so, we need to
157 // create a new GV used only by this kernel and its function.
158 auto NewGV = uniquifyGVPerKernel(M, GV, F);
159 Changed |= (NewGV != GV);
160 unsigned BarrierScope = AMDGPU::Barrier::BARRIER_SCOPE_WORKGROUP;
161 unsigned BarId = Kernel2BarId[F];
162 BarId += NumAbsolutes + 1;
163 unsigned BarCnt = DL.getTypeAllocSize(GV->getValueType()) / 16;
164 Kernel2BarId[F] += BarCnt;
165 unsigned Offset = 0x802000u | BarrierScope << 9 | BarId << 4;
166 recordLDSAbsoluteAddress(&M, NewGV, Offset);
167 }
168 OrderedGVs.clear();
169 }
170 // Also erase those special LDS variables from indirect_access.
171 for (auto &K : LDSUsesInfo.indirect_access) {
172 assert(isKernelLDS(K.first));
173 for (GlobalVariable *GV : K.second) {
174 if (isNamedBarrier(*GV))
175 K.second.erase(GV);
176 }
177 }
178 return Changed;
179}
180
181static bool runLowerExecSyncGlobals(Module &M) {
182 CallGraph CG = CallGraph(M);
183 bool Changed = false;
185
186 // For each kernel, what variables does it access directly or through
187 // callees
188 LDSUsesInfoTy LDSUsesInfo = getTransitiveUsesOfLDS(CG, M);
189
190 // For each variable accessed through callees, which kernels access it
191 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
192 for (auto &K : LDSUsesInfo.indirect_access) {
193 Function *F = K.first;
195 for (GlobalVariable *GV : K.second) {
196 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
197 }
198 }
199
200 if (LDSUsesInfo.HasSpecialGVs) {
201 // Special LDS variables need special address assignment
202 Changed |= lowerExecSyncGlobalVariables(
203 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly);
204 }
205 return Changed;
206}
207
208class AMDGPULowerExecSyncLegacy : public ModulePass {
209public:
210 static char ID;
211 AMDGPULowerExecSyncLegacy() : ModulePass(ID) {}
212 bool runOnModule(Module &M) override;
213};
214
215} // namespace
216
217char AMDGPULowerExecSyncLegacy::ID = 0;
218char &llvm::AMDGPULowerExecSyncLegacyPassID = AMDGPULowerExecSyncLegacy::ID;
219
220INITIALIZE_PASS_BEGIN(AMDGPULowerExecSyncLegacy, DEBUG_TYPE,
221 "AMDGPU lowering of execution synchronization", false,
222 false)
224INITIALIZE_PASS_END(AMDGPULowerExecSyncLegacy, DEBUG_TYPE,
225 "AMDGPU lowering of execution synchronization", false,
226 false)
227
228bool AMDGPULowerExecSyncLegacy::runOnModule(Module &M) {
229 return runLowerExecSyncGlobals(M);
230}
231
233 return new AMDGPULowerExecSyncLegacy();
234}
235
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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...
This file defines the DenseMap class.
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#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
Target-Independent Code Generator Pass Configuration Options pass.
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:536
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LinkageTypes getLinkage() const
LLVM_ABI bool isAbsoluteSymbolRef() const
Returns whether this is a reference to an absolute symbol.
Definition Globals.cpp:437
ThreadLocalMode getThreadLocalMode() const
PointerType * getType() const
Global values are always pointers.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition Globals.cpp:553
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
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:1569
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:67
unsigned getAddressSpace() const
Return the address space of the Pointer type.
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
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Target-Independent Code Generator Pass Configuration Options.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Changed
@ LOCAL_ADDRESS
Address space for local memory.
LDSUsesInfoTy getTransitiveUsesOfLDS(const CallGraph &CG, Module &M)
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
bool eliminateConstantExprUsesOfLDSFromAllInstructions(Module &M)
DenseMap< GlobalVariable *, DenseSet< Function * > > VariableFunctionMap
bool isKernelLDS(const Function *F)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1655
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
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
ModulePass * createAMDGPULowerExecSyncLegacyPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
FunctionVariableMap direct_access
FunctionVariableMap indirect_access