xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp (revision 2224bbcd7409c54770d1eaaed527e8dd344acfef)
1 //===-- AMDGPULowerModuleLDSPass.cpp ------------------------------*- C++ -*-=//
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 // This pass eliminates LDS uses from non-kernel functions.
10 //
11 // The strategy is to create a new struct with a field for each LDS variable
12 // and allocate that struct at the same address for every kernel. Uses of the
13 // original LDS variables are then replaced with compile time offsets from that
14 // known address. AMDGPUMachineFunction allocates the LDS global.
15 //
16 // Local variables with constant annotation or non-undef initializer are passed
17 // through unchanged for simplification or error diagnostics in later passes.
18 //
19 // To reduce the memory overhead variables that are only used by kernels are
20 // excluded from this transform. The analysis to determine whether a variable
21 // is only used by a kernel is cheap and conservative so this may allocate
22 // a variable in every kernel when it was not strictly necessary to do so.
23 //
24 // A possible future refinement is to specialise the structure per-kernel, so
25 // that fields can be elided based on more expensive analysis.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "AMDGPU.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "Utils/AMDGPUMemoryUtils.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Analysis/CallGraph.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/OptimizedStructLayout.h"
45 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include <vector>
47 
48 #define DEBUG_TYPE "amdgpu-lower-module-lds"
49 
50 using namespace llvm;
51 
52 static cl::opt<bool> SuperAlignLDSGlobals(
53     "amdgpu-super-align-lds-globals",
54     cl::desc("Increase alignment of LDS if it is not on align boundary"),
55     cl::init(true), cl::Hidden);
56 
57 namespace {
58 class AMDGPULowerModuleLDS : public ModulePass {
59 
60   static void removeFromUsedList(Module &M, StringRef Name,
61                                  SmallPtrSetImpl<Constant *> &ToRemove) {
62     GlobalVariable *GV = M.getNamedGlobal(Name);
63     if (!GV || ToRemove.empty()) {
64       return;
65     }
66 
67     SmallVector<Constant *, 16> Init;
68     auto *CA = cast<ConstantArray>(GV->getInitializer());
69     for (auto &Op : CA->operands()) {
70       // ModuleUtils::appendToUsed only inserts Constants
71       Constant *C = cast<Constant>(Op);
72       if (!ToRemove.contains(C->stripPointerCasts())) {
73         Init.push_back(C);
74       }
75     }
76 
77     if (Init.size() == CA->getNumOperands()) {
78       return; // none to remove
79     }
80 
81     GV->eraseFromParent();
82 
83     for (Constant *C : ToRemove) {
84       C->removeDeadConstantUsers();
85     }
86 
87     if (!Init.empty()) {
88       ArrayType *ATy =
89           ArrayType::get(Type::getInt8PtrTy(M.getContext()), Init.size());
90       GV =
91           new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
92                                    ConstantArray::get(ATy, Init), Name);
93       GV->setSection("llvm.metadata");
94     }
95   }
96 
97   static void
98   removeFromUsedLists(Module &M,
99                       const std::vector<GlobalVariable *> &LocalVars) {
100     SmallPtrSet<Constant *, 32> LocalVarsSet;
101     for (GlobalVariable *LocalVar : LocalVars)
102       if (Constant *C = dyn_cast<Constant>(LocalVar->stripPointerCasts()))
103         LocalVarsSet.insert(C);
104     removeFromUsedList(M, "llvm.used", LocalVarsSet);
105     removeFromUsedList(M, "llvm.compiler.used", LocalVarsSet);
106   }
107 
108   static void markUsedByKernel(IRBuilder<> &Builder, Function *Func,
109                                GlobalVariable *SGV) {
110     // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
111     // that might call a function which accesses a field within it. This is
112     // presently approximated to 'all kernels' if there are any such functions
113     // in the module. This implicit use is redefined as an explicit use here so
114     // that later passes, specifically PromoteAlloca, account for the required
115     // memory without any knowledge of this transform.
116 
117     // An operand bundle on llvm.donothing works because the call instruction
118     // survives until after the last pass that needs to account for LDS. It is
119     // better than inline asm as the latter survives until the end of codegen. A
120     // totally robust solution would be a function with the same semantics as
121     // llvm.donothing that takes a pointer to the instance and is lowered to a
122     // no-op after LDS is allocated, but that is not presently necessary.
123 
124     LLVMContext &Ctx = Func->getContext();
125 
126     Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI());
127 
128     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {});
129 
130     Function *Decl =
131         Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {});
132 
133     Value *UseInstance[1] = {Builder.CreateInBoundsGEP(
134         SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))};
135 
136     Builder.CreateCall(FTy, Decl, {},
137                        {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)},
138                        "");
139   }
140 
141 public:
142   static char ID;
143 
144   AMDGPULowerModuleLDS() : ModulePass(ID) {
145     initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry());
146   }
147 
148   bool runOnModule(Module &M) override {
149     CallGraph CG = CallGraph(M);
150     bool Changed = superAlignLDSGlobals(M);
151     std::vector<GlobalVariable *> ModuleScopeVariables =
152         AMDGPU::findVariablesToLower(M, nullptr);
153     Changed |= processUsedLDS(CG, M, ModuleScopeVariables);
154 
155     for (Function &F : M.functions()) {
156       if (F.isDeclaration())
157         continue;
158 
159       // Only lower compute kernels' LDS.
160       if (!AMDGPU::isKernel(F.getCallingConv()))
161         continue;
162       std::vector<GlobalVariable *> KernelUsedVariables =
163           AMDGPU::findVariablesToLower(M, &F);
164       Changed |= processUsedLDS(CG, M, KernelUsedVariables, &F);
165     }
166 
167     return Changed;
168   }
169 
170 private:
171   // Increase the alignment of LDS globals if necessary to maximise the chance
172   // that we can use aligned LDS instructions to access them.
173   static bool superAlignLDSGlobals(Module &M) {
174     const DataLayout &DL = M.getDataLayout();
175     bool Changed = false;
176     if (!SuperAlignLDSGlobals) {
177       return Changed;
178     }
179 
180     for (auto &GV : M.globals()) {
181       if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) {
182         // Only changing alignment of LDS variables
183         continue;
184       }
185       if (!GV.hasInitializer()) {
186         // cuda/hip extern __shared__ variable, leave alignment alone
187         continue;
188       }
189 
190       Align Alignment = AMDGPU::getAlign(DL, &GV);
191       TypeSize GVSize = DL.getTypeAllocSize(GV.getValueType());
192 
193       if (GVSize > 8) {
194         // We might want to use a b96 or b128 load/store
195         Alignment = std::max(Alignment, Align(16));
196       } else if (GVSize > 4) {
197         // We might want to use a b64 load/store
198         Alignment = std::max(Alignment, Align(8));
199       } else if (GVSize > 2) {
200         // We might want to use a b32 load/store
201         Alignment = std::max(Alignment, Align(4));
202       } else if (GVSize > 1) {
203         // We might want to use a b16 load/store
204         Alignment = std::max(Alignment, Align(2));
205       }
206 
207       if (Alignment != AMDGPU::getAlign(DL, &GV)) {
208         Changed = true;
209         GV.setAlignment(Alignment);
210       }
211     }
212     return Changed;
213   }
214 
215   bool processUsedLDS(CallGraph const &CG, Module &M,
216                       std::vector<GlobalVariable *> const &LDSVarsToTransform,
217                       Function *F = nullptr) {
218     LLVMContext &Ctx = M.getContext();
219     const DataLayout &DL = M.getDataLayout();
220 
221     if (LDSVarsToTransform.empty()) {
222       // No variables to rewrite, no changes made.
223       return false;
224     }
225 
226     SmallVector<OptimizedStructLayoutField, 8> LayoutFields;
227     LayoutFields.reserve(LDSVarsToTransform.size());
228     for (GlobalVariable *GV : LDSVarsToTransform) {
229       OptimizedStructLayoutField F(GV, DL.getTypeAllocSize(GV->getValueType()),
230                                    AMDGPU::getAlign(DL, GV));
231       LayoutFields.emplace_back(F);
232     }
233 
234     performOptimizedStructLayout(LayoutFields);
235 
236     std::vector<GlobalVariable *> LocalVars;
237     LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
238     {
239       // This usually won't need to insert any padding, perhaps avoid the alloc
240       uint64_t CurrentOffset = 0;
241       for (size_t I = 0; I < LayoutFields.size(); I++) {
242         GlobalVariable *FGV = static_cast<GlobalVariable *>(
243             const_cast<void *>(LayoutFields[I].Id));
244         Align DataAlign = LayoutFields[I].Alignment;
245 
246         uint64_t DataAlignV = DataAlign.value();
247         if (uint64_t Rem = CurrentOffset % DataAlignV) {
248           uint64_t Padding = DataAlignV - Rem;
249 
250           // Append an array of padding bytes to meet alignment requested
251           // Note (o +      (a - (o % a)) ) % a == 0
252           //      (offset + Padding       ) % align == 0
253 
254           Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
255           LocalVars.push_back(new GlobalVariable(
256               M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy),
257               "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
258               false));
259           CurrentOffset += Padding;
260         }
261 
262         LocalVars.push_back(FGV);
263         CurrentOffset += LayoutFields[I].Size;
264       }
265     }
266 
267     std::vector<Type *> LocalVarTypes;
268     LocalVarTypes.reserve(LocalVars.size());
269     std::transform(
270         LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
271         [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
272 
273     std::string VarName(
274         F ? (Twine("llvm.amdgcn.kernel.") + F->getName() + ".lds").str()
275           : "llvm.amdgcn.module.lds");
276     StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
277 
278     Align StructAlign =
279         AMDGPU::getAlign(DL, LocalVars[0]);
280 
281     GlobalVariable *SGV = new GlobalVariable(
282         M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy),
283         VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
284         false);
285     SGV->setAlignment(StructAlign);
286     if (!F) {
287       appendToCompilerUsed(
288           M, {static_cast<GlobalValue *>(
289                  ConstantExpr::getPointerBitCastOrAddrSpaceCast(
290                      cast<Constant>(SGV), Type::getInt8PtrTy(Ctx)))});
291     }
292 
293     // The verifier rejects used lists containing an inttoptr of a constant
294     // so remove the variables from these lists before replaceAllUsesWith
295     removeFromUsedLists(M, LocalVars);
296 
297     // Create alias.scope and their lists. Each field in the new structure
298     // does not alias with all other fields.
299     SmallVector<MDNode *> AliasScopes;
300     SmallVector<Metadata *> NoAliasList;
301     if (LocalVars.size() > 1) {
302       MDBuilder MDB(Ctx);
303       AliasScopes.reserve(LocalVars.size());
304       MDNode *Domain = MDB.createAnonymousAliasScopeDomain();
305       for (size_t I = 0; I < LocalVars.size(); I++) {
306         MDNode *Scope = MDB.createAnonymousAliasScope(Domain);
307         AliasScopes.push_back(Scope);
308       }
309       NoAliasList.append(&AliasScopes[1], AliasScopes.end());
310     }
311 
312     // Replace uses of ith variable with a constantexpr to the ith field of the
313     // instance that will be allocated by AMDGPUMachineFunction
314     Type *I32 = Type::getInt32Ty(Ctx);
315     for (size_t I = 0; I < LocalVars.size(); I++) {
316       GlobalVariable *GV = LocalVars[I];
317       Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
318       Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx);
319       if (F) {
320         // Replace all constant uses with instructions if they belong to the
321         // current kernel.
322         for (User *U : make_early_inc_range(GV->users())) {
323           if (ConstantExpr *C = dyn_cast<ConstantExpr>(U))
324             AMDGPU::replaceConstantUsesInFunction(C, F);
325         }
326 
327         GV->removeDeadConstantUsers();
328 
329         GV->replaceUsesWithIf(GEP, [F](Use &U) {
330           Instruction *I = dyn_cast<Instruction>(U.getUser());
331           return I && I->getFunction() == F;
332         });
333       } else {
334         GV->replaceAllUsesWith(GEP);
335       }
336       if (GV->use_empty()) {
337         GV->eraseFromParent();
338       }
339 
340       uint64_t Off = DL.getStructLayout(LDSTy)->getElementOffset(I);
341       Align A = commonAlignment(StructAlign, Off);
342 
343       if (I)
344         NoAliasList[I - 1] = AliasScopes[I - 1];
345       MDNode *NoAlias =
346           NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
347       MDNode *AliasScope =
348           AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
349 
350       refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
351     }
352 
353     // This ensures the variable is allocated when called functions access it.
354     // It also lets other passes, specifically PromoteAlloca, accurately
355     // calculate how much LDS will be used by the kernel after lowering.
356     if (!F) {
357       IRBuilder<> Builder(Ctx);
358       for (Function &Func : M.functions()) {
359         if (!Func.isDeclaration() && AMDGPU::isKernelCC(&Func)) {
360           const CallGraphNode *N = CG[&Func];
361           const bool CalleesRequireModuleLDS = N->size() > 0;
362 
363           if (CalleesRequireModuleLDS) {
364             // If a function this kernel might call requires module LDS,
365             // annotate the kernel to let later passes know it will allocate
366             // this structure, even if not apparent from the IR.
367             markUsedByKernel(Builder, &Func, SGV);
368           } else {
369             // However if we are certain this kernel cannot call a function that
370             // requires module LDS, annotate the kernel so the backend can elide
371             // the allocation without repeating callgraph walks.
372             Func.addFnAttr("amdgpu-elide-module-lds");
373           }
374         }
375       }
376     }
377     return true;
378   }
379 
380   void refineUsesAlignmentAndAA(Value *Ptr, Align A, const DataLayout &DL,
381                                 MDNode *AliasScope, MDNode *NoAlias,
382                                 unsigned MaxDepth = 5) {
383     if (!MaxDepth || (A == 1 && !AliasScope))
384       return;
385 
386     for (User *U : Ptr->users()) {
387       if (auto *I = dyn_cast<Instruction>(U)) {
388         if (AliasScope && I->mayReadOrWriteMemory()) {
389           MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
390           AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
391                    : AliasScope);
392           I->setMetadata(LLVMContext::MD_alias_scope, AS);
393 
394           MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
395           NA = (NA ? MDNode::intersect(NA, NoAlias) : NoAlias);
396           I->setMetadata(LLVMContext::MD_noalias, NA);
397         }
398       }
399 
400       if (auto *LI = dyn_cast<LoadInst>(U)) {
401         LI->setAlignment(std::max(A, LI->getAlign()));
402         continue;
403       }
404       if (auto *SI = dyn_cast<StoreInst>(U)) {
405         if (SI->getPointerOperand() == Ptr)
406           SI->setAlignment(std::max(A, SI->getAlign()));
407         continue;
408       }
409       if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
410         // None of atomicrmw operations can work on pointers, but let's
411         // check it anyway in case it will or we will process ConstantExpr.
412         if (AI->getPointerOperand() == Ptr)
413           AI->setAlignment(std::max(A, AI->getAlign()));
414         continue;
415       }
416       if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
417         if (AI->getPointerOperand() == Ptr)
418           AI->setAlignment(std::max(A, AI->getAlign()));
419         continue;
420       }
421       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
422         unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
423         APInt Off(BitWidth, 0);
424         if (GEP->getPointerOperand() == Ptr) {
425           Align GA;
426           if (GEP->accumulateConstantOffset(DL, Off))
427             GA = commonAlignment(A, Off.getLimitedValue());
428           refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
429                                    MaxDepth - 1);
430         }
431         continue;
432       }
433       if (auto *I = dyn_cast<Instruction>(U)) {
434         if (I->getOpcode() == Instruction::BitCast ||
435             I->getOpcode() == Instruction::AddrSpaceCast)
436           refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
437       }
438     }
439   }
440 };
441 
442 } // namespace
443 char AMDGPULowerModuleLDS::ID = 0;
444 
445 char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID;
446 
447 INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE,
448                 "Lower uses of LDS variables from non-kernel functions", false,
449                 false)
450 
451 ModulePass *llvm::createAMDGPULowerModuleLDSPass() {
452   return new AMDGPULowerModuleLDS();
453 }
454 
455 PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M,
456                                                 ModuleAnalysisManager &) {
457   return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none()
458                                                : PreservedAnalyses::all();
459 }
460