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