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 simplication 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 "llvm/ADT/STLExtras.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/IRBuilder.h" 35 #include "llvm/IR/InlineAsm.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/InitializePasses.h" 38 #include "llvm/Pass.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Transforms/Utils/ModuleUtils.h" 41 #include <algorithm> 42 #include <vector> 43 44 #define DEBUG_TYPE "amdgpu-lower-module-lds" 45 46 using namespace llvm; 47 48 namespace { 49 50 class AMDGPULowerModuleLDS : public ModulePass { 51 52 static bool isKernelCC(Function *Func) { 53 return AMDGPU::isModuleEntryFunctionCC(Func->getCallingConv()); 54 } 55 56 static Align getAlign(DataLayout const &DL, const GlobalVariable *GV) { 57 return DL.getValueOrABITypeAlignment(GV->getPointerAlignment(DL), 58 GV->getValueType()); 59 } 60 61 static bool 62 userRequiresLowering(const SmallPtrSetImpl<GlobalValue *> &UsedList, 63 User *InitialUser) { 64 // Any LDS variable can be lowered by moving into the created struct 65 // Each variable so lowered is allocated in every kernel, so variables 66 // whose users are all known to be safe to lower without the transform 67 // are left unchanged. 68 SmallPtrSet<User *, 8> Visited; 69 SmallVector<User *, 16> Stack; 70 Stack.push_back(InitialUser); 71 72 while (!Stack.empty()) { 73 User *V = Stack.pop_back_val(); 74 Visited.insert(V); 75 76 if (auto *G = dyn_cast<GlobalValue>(V->stripPointerCasts())) { 77 if (UsedList.contains(G)) { 78 continue; 79 } 80 } 81 82 if (auto *I = dyn_cast<Instruction>(V)) { 83 if (isKernelCC(I->getFunction())) { 84 continue; 85 } 86 } 87 88 if (auto *E = dyn_cast<ConstantExpr>(V)) { 89 for (Value::user_iterator EU = E->user_begin(); EU != E->user_end(); 90 ++EU) { 91 if (Visited.insert(*EU).second) { 92 Stack.push_back(*EU); 93 } 94 } 95 continue; 96 } 97 98 // Unknown user, conservatively lower the variable 99 return true; 100 } 101 102 return false; 103 } 104 105 static std::vector<GlobalVariable *> 106 findVariablesToLower(Module &M, 107 const SmallPtrSetImpl<GlobalValue *> &UsedList) { 108 std::vector<llvm::GlobalVariable *> LocalVars; 109 for (auto &GV : M.globals()) { 110 if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) { 111 continue; 112 } 113 if (!GV.hasInitializer()) { 114 // addrspace(3) without initializer implies cuda/hip extern __shared__ 115 // the semantics for such a variable appears to be that all extern 116 // __shared__ variables alias one another, in which case this transform 117 // is not required 118 continue; 119 } 120 if (!isa<UndefValue>(GV.getInitializer())) { 121 // Initializers are unimplemented for local address space. 122 // Leave such variables in place for consistent error reporting. 123 continue; 124 } 125 if (GV.isConstant()) { 126 // A constant undef variable can't be written to, and any load is 127 // undef, so it should be eliminated by the optimizer. It could be 128 // dropped by the back end if not. This pass skips over it. 129 continue; 130 } 131 if (std::none_of(GV.user_begin(), GV.user_end(), [&](User *U) { 132 return userRequiresLowering(UsedList, U); 133 })) { 134 continue; 135 } 136 LocalVars.push_back(&GV); 137 } 138 return LocalVars; 139 } 140 141 static void removeFromUsedList(Module &M, StringRef Name, 142 SmallPtrSetImpl<Constant *> &ToRemove) { 143 GlobalVariable *GV = M.getGlobalVariable(Name); 144 if (!GV || ToRemove.empty()) { 145 return; 146 } 147 148 SmallVector<Constant *, 16> Init; 149 auto *CA = cast<ConstantArray>(GV->getInitializer()); 150 for (auto &Op : CA->operands()) { 151 // ModuleUtils::appendToUsed only inserts Constants 152 Constant *C = cast<Constant>(Op); 153 if (!ToRemove.contains(C->stripPointerCasts())) { 154 Init.push_back(C); 155 } 156 } 157 158 if (Init.size() == CA->getNumOperands()) { 159 return; // none to remove 160 } 161 162 GV->eraseFromParent(); 163 164 if (!Init.empty()) { 165 ArrayType *ATy = 166 ArrayType::get(Type::getInt8PtrTy(M.getContext()), Init.size()); 167 GV = 168 new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage, 169 ConstantArray::get(ATy, Init), Name); 170 GV->setSection("llvm.metadata"); 171 } 172 } 173 174 static void 175 removeFromUsedLists(Module &M, 176 const std::vector<GlobalVariable *> &LocalVars) { 177 SmallPtrSet<Constant *, 32> LocalVarsSet; 178 for (size_t I = 0; I < LocalVars.size(); I++) { 179 if (Constant *C = dyn_cast<Constant>(LocalVars[I]->stripPointerCasts())) { 180 LocalVarsSet.insert(C); 181 } 182 } 183 removeFromUsedList(M, "llvm.used", LocalVarsSet); 184 removeFromUsedList(M, "llvm.compiler.used", LocalVarsSet); 185 } 186 187 static void markUsedByKernel(IRBuilder<> &Builder, Function *Func, 188 GlobalVariable *SGV) { 189 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels 190 // that might call a function which accesses a field within it. This is 191 // presently approximated to 'all kernels' if there are any such functions 192 // in the module. This implicit use is reified as an explicit use here so 193 // that later passes, specifically PromoteAlloca, account for the required 194 // memory without any knowledge of this transform. 195 196 // An operand bundle on llvm.donothing works because the call instruction 197 // survives until after the last pass that needs to account for LDS. It is 198 // better than inline asm as the latter survives until the end of codegen. A 199 // totally robust solution would be a function with the same semantics as 200 // llvm.donothing that takes a pointer to the instance and is lowered to a 201 // no-op after LDS is allocated, but that is not presently necessary. 202 203 LLVMContext &Ctx = Func->getContext(); 204 205 Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI()); 206 207 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {}); 208 209 Function *Decl = 210 Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {}); 211 212 Value *UseInstance[1] = {Builder.CreateInBoundsGEP( 213 SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))}; 214 215 Builder.CreateCall(FTy, Decl, {}, 216 {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)}, 217 ""); 218 } 219 220 static SmallPtrSet<GlobalValue *, 32> getUsedList(Module &M) { 221 SmallPtrSet<GlobalValue *, 32> UsedList; 222 223 SmallVector<GlobalValue *, 32> TmpVec; 224 collectUsedGlobalVariables(M, TmpVec, true); 225 UsedList.insert(TmpVec.begin(), TmpVec.end()); 226 227 TmpVec.clear(); 228 collectUsedGlobalVariables(M, TmpVec, false); 229 UsedList.insert(TmpVec.begin(), TmpVec.end()); 230 231 return UsedList; 232 } 233 234 public: 235 static char ID; 236 237 AMDGPULowerModuleLDS() : ModulePass(ID) { 238 initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry()); 239 } 240 241 bool runOnModule(Module &M) override { 242 LLVMContext &Ctx = M.getContext(); 243 const DataLayout &DL = M.getDataLayout(); 244 SmallPtrSet<GlobalValue *, 32> UsedList = getUsedList(M); 245 246 // Find variables to move into new struct instance 247 std::vector<GlobalVariable *> FoundLocalVars = 248 findVariablesToLower(M, UsedList); 249 250 if (FoundLocalVars.empty()) { 251 // No variables to rewrite, no changes made. 252 return false; 253 } 254 255 // Sort by alignment, descending, to minimise padding. 256 // On ties, sort by size, descending, then by name, lexicographical. 257 llvm::stable_sort( 258 FoundLocalVars, 259 [&](const GlobalVariable *LHS, const GlobalVariable *RHS) -> bool { 260 Align ALHS = getAlign(DL, LHS); 261 Align ARHS = getAlign(DL, RHS); 262 if (ALHS != ARHS) { 263 return ALHS > ARHS; 264 } 265 266 TypeSize SLHS = DL.getTypeAllocSize(LHS->getValueType()); 267 TypeSize SRHS = DL.getTypeAllocSize(RHS->getValueType()); 268 if (SLHS != SRHS) { 269 return SLHS > SRHS; 270 } 271 272 // By variable name on tie for predictable order in test cases. 273 return LHS->getName() < RHS->getName(); 274 }); 275 276 std::vector<GlobalVariable *> LocalVars; 277 LocalVars.reserve(FoundLocalVars.size()); // will be at least this large 278 { 279 // This usually won't need to insert any padding, perhaps avoid the alloc 280 uint64_t CurrentOffset = 0; 281 for (size_t I = 0; I < FoundLocalVars.size(); I++) { 282 GlobalVariable *FGV = FoundLocalVars[I]; 283 Align DataAlign = getAlign(DL, FGV); 284 285 uint64_t DataAlignV = DataAlign.value(); 286 if (uint64_t Rem = CurrentOffset % DataAlignV) { 287 uint64_t Padding = DataAlignV - Rem; 288 289 // Append an array of padding bytes to meet alignment requested 290 // Note (o + (a - (o % a)) ) % a == 0 291 // (offset + Padding ) % align == 0 292 293 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding); 294 LocalVars.push_back(new GlobalVariable( 295 M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy), 296 "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 297 false)); 298 CurrentOffset += Padding; 299 } 300 301 LocalVars.push_back(FGV); 302 CurrentOffset += DL.getTypeAllocSize(FGV->getValueType()); 303 } 304 } 305 306 std::vector<Type *> LocalVarTypes; 307 LocalVarTypes.reserve(LocalVars.size()); 308 std::transform( 309 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes), 310 [](const GlobalVariable *V) -> Type * { return V->getValueType(); }); 311 312 StructType *LDSTy = StructType::create( 313 Ctx, LocalVarTypes, llvm::StringRef("llvm.amdgcn.module.lds.t")); 314 315 Align MaxAlign = getAlign(DL, LocalVars[0]); // was sorted on alignment 316 Constant *InstanceAddress = Constant::getIntegerValue( 317 PointerType::get(LDSTy, AMDGPUAS::LOCAL_ADDRESS), APInt(32, 0)); 318 319 GlobalVariable *SGV = new GlobalVariable( 320 M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy), 321 "llvm.amdgcn.module.lds", nullptr, GlobalValue::NotThreadLocal, 322 AMDGPUAS::LOCAL_ADDRESS, false); 323 SGV->setAlignment(MaxAlign); 324 appendToCompilerUsed( 325 M, {static_cast<GlobalValue *>( 326 ConstantExpr::getPointerBitCastOrAddrSpaceCast( 327 cast<Constant>(SGV), Type::getInt8PtrTy(Ctx)))}); 328 329 // The verifier rejects used lists containing an inttoptr of a constant 330 // so remove the variables from these lists before replaceAllUsesWith 331 removeFromUsedLists(M, LocalVars); 332 333 // Replace uses of ith variable with a constantexpr to the ith field of the 334 // instance that will be allocated by AMDGPUMachineFunction 335 Type *I32 = Type::getInt32Ty(Ctx); 336 for (size_t I = 0; I < LocalVars.size(); I++) { 337 GlobalVariable *GV = LocalVars[I]; 338 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)}; 339 GV->replaceAllUsesWith( 340 ConstantExpr::getGetElementPtr(LDSTy, InstanceAddress, GEPIdx)); 341 GV->eraseFromParent(); 342 } 343 344 // Mark kernels with asm that reads the address of the allocated structure 345 // This is not necessary for lowering. This lets other passes, specifically 346 // PromoteAlloca, accurately calculate how much LDS will be used by the 347 // kernel after lowering. 348 { 349 IRBuilder<> Builder(Ctx); 350 SmallPtrSet<Function *, 32> Kernels; 351 for (auto &I : M.functions()) { 352 Function *Func = &I; 353 if (isKernelCC(Func) && !Kernels.contains(Func)) { 354 markUsedByKernel(Builder, Func, SGV); 355 Kernels.insert(Func); 356 } 357 } 358 } 359 return true; 360 } 361 }; 362 363 } // namespace 364 char AMDGPULowerModuleLDS::ID = 0; 365 366 char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID; 367 368 INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE, 369 "Lower uses of LDS variables from non-kernel functions", false, 370 false) 371 372 ModulePass *llvm::createAMDGPULowerModuleLDSPass() { 373 return new AMDGPULowerModuleLDS(); 374 } 375 376 PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M, 377 ModuleAnalysisManager &) { 378 return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none() 379 : PreservedAnalyses::all(); 380 } 381