1 //===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===// 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 provides a class for CUDA code generation targeting the NVIDIA CUDA 10 // runtime library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGCUDARuntime.h" 15 #include "CGCXXABI.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenModule.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/Basic/Cuda.h" 20 #include "clang/CodeGen/CodeGenABITypes.h" 21 #include "clang/CodeGen/ConstantInitBuilder.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/ReplaceConstant.h" 26 #include "llvm/Support/Format.h" 27 28 using namespace clang; 29 using namespace CodeGen; 30 31 namespace { 32 constexpr unsigned CudaFatMagic = 0x466243b1; 33 constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF" 34 35 class CGNVCUDARuntime : public CGCUDARuntime { 36 37 private: 38 llvm::IntegerType *IntTy, *SizeTy; 39 llvm::Type *VoidTy; 40 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy; 41 42 /// Convenience reference to LLVM Context 43 llvm::LLVMContext &Context; 44 /// Convenience reference to the current module 45 llvm::Module &TheModule; 46 /// Keeps track of kernel launch stubs and handles emitted in this module 47 struct KernelInfo { 48 llvm::Function *Kernel; // stub function to help launch kernel 49 const Decl *D; 50 }; 51 llvm::SmallVector<KernelInfo, 16> EmittedKernels; 52 // Map a device stub function to a symbol for identifying kernel in host code. 53 // For CUDA, the symbol for identifying the kernel is the same as the device 54 // stub function. For HIP, they are different. 55 llvm::DenseMap<llvm::Function *, llvm::GlobalValue *> KernelHandles; 56 // Map a kernel handle to the kernel stub. 57 llvm::DenseMap<llvm::GlobalValue *, llvm::Function *> KernelStubs; 58 struct VarInfo { 59 llvm::GlobalVariable *Var; 60 const VarDecl *D; 61 DeviceVarFlags Flags; 62 }; 63 llvm::SmallVector<VarInfo, 16> DeviceVars; 64 /// Keeps track of variable containing handle of GPU binary. Populated by 65 /// ModuleCtorFunction() and used to create corresponding cleanup calls in 66 /// ModuleDtorFunction() 67 llvm::GlobalVariable *GpuBinaryHandle = nullptr; 68 /// Whether we generate relocatable device code. 69 bool RelocatableDeviceCode; 70 /// Mangle context for device. 71 std::unique_ptr<MangleContext> DeviceMC; 72 73 llvm::FunctionCallee getSetupArgumentFn() const; 74 llvm::FunctionCallee getLaunchFn() const; 75 76 llvm::FunctionType *getRegisterGlobalsFnTy() const; 77 llvm::FunctionType *getCallbackFnTy() const; 78 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const; 79 std::string addPrefixToName(StringRef FuncName) const; 80 std::string addUnderscoredPrefixToName(StringRef FuncName) const; 81 82 /// Creates a function to register all kernel stubs generated in this module. 83 llvm::Function *makeRegisterGlobalsFn(); 84 85 /// Helper function that generates a constant string and returns a pointer to 86 /// the start of the string. The result of this function can be used anywhere 87 /// where the C code specifies const char*. 88 llvm::Constant *makeConstantString(const std::string &Str, 89 const std::string &Name = "", 90 const std::string &SectionName = "", 91 unsigned Alignment = 0) { 92 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0), 93 llvm::ConstantInt::get(SizeTy, 0)}; 94 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str()); 95 llvm::GlobalVariable *GV = 96 cast<llvm::GlobalVariable>(ConstStr.getPointer()); 97 if (!SectionName.empty()) { 98 GV->setSection(SectionName); 99 // Mark the address as used which make sure that this section isn't 100 // merged and we will really have it in the object file. 101 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None); 102 } 103 if (Alignment) 104 GV->setAlignment(llvm::Align(Alignment)); 105 106 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(), 107 ConstStr.getPointer(), Zeros); 108 } 109 110 /// Helper function that generates an empty dummy function returning void. 111 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) { 112 assert(FnTy->getReturnType()->isVoidTy() && 113 "Can only generate dummy functions returning void!"); 114 llvm::Function *DummyFunc = llvm::Function::Create( 115 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule); 116 117 llvm::BasicBlock *DummyBlock = 118 llvm::BasicBlock::Create(Context, "", DummyFunc); 119 CGBuilderTy FuncBuilder(CGM, Context); 120 FuncBuilder.SetInsertPoint(DummyBlock); 121 FuncBuilder.CreateRetVoid(); 122 123 return DummyFunc; 124 } 125 126 void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args); 127 void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args); 128 std::string getDeviceSideName(const NamedDecl *ND) override; 129 130 void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var, 131 bool Extern, bool Constant) { 132 DeviceVars.push_back({&Var, 133 VD, 134 {DeviceVarFlags::Variable, Extern, Constant, 135 VD->hasAttr<HIPManagedAttr>(), 136 /*Normalized*/ false, 0}}); 137 } 138 void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var, 139 bool Extern, int Type) { 140 DeviceVars.push_back({&Var, 141 VD, 142 {DeviceVarFlags::Surface, Extern, /*Constant*/ false, 143 /*Managed*/ false, 144 /*Normalized*/ false, Type}}); 145 } 146 void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var, 147 bool Extern, int Type, bool Normalized) { 148 DeviceVars.push_back({&Var, 149 VD, 150 {DeviceVarFlags::Texture, Extern, /*Constant*/ false, 151 /*Managed*/ false, Normalized, Type}}); 152 } 153 154 /// Creates module constructor function 155 llvm::Function *makeModuleCtorFunction(); 156 /// Creates module destructor function 157 llvm::Function *makeModuleDtorFunction(); 158 /// Transform managed variables for device compilation. 159 void transformManagedVars(); 160 161 public: 162 CGNVCUDARuntime(CodeGenModule &CGM); 163 164 llvm::GlobalValue *getKernelHandle(llvm::Function *F, GlobalDecl GD) override; 165 llvm::Function *getKernelStub(llvm::GlobalValue *Handle) override { 166 auto Loc = KernelStubs.find(Handle); 167 assert(Loc != KernelStubs.end()); 168 return Loc->second; 169 } 170 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override; 171 void handleVarRegistration(const VarDecl *VD, 172 llvm::GlobalVariable &Var) override; 173 void 174 internalizeDeviceSideVar(const VarDecl *D, 175 llvm::GlobalValue::LinkageTypes &Linkage) override; 176 177 llvm::Function *finalizeModule() override; 178 }; 179 180 } // end anonymous namespace 181 182 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const { 183 if (CGM.getLangOpts().HIP) 184 return ((Twine("hip") + Twine(FuncName)).str()); 185 return ((Twine("cuda") + Twine(FuncName)).str()); 186 } 187 std::string 188 CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const { 189 if (CGM.getLangOpts().HIP) 190 return ((Twine("__hip") + Twine(FuncName)).str()); 191 return ((Twine("__cuda") + Twine(FuncName)).str()); 192 } 193 194 static std::unique_ptr<MangleContext> InitDeviceMC(CodeGenModule &CGM) { 195 // If the host and device have different C++ ABIs, mark it as the device 196 // mangle context so that the mangling needs to retrieve the additional 197 // device lambda mangling number instead of the regular host one. 198 if (CGM.getContext().getAuxTargetInfo() && 199 CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() && 200 CGM.getContext().getAuxTargetInfo()->getCXXABI().isItaniumFamily()) { 201 return std::unique_ptr<MangleContext>( 202 CGM.getContext().createDeviceMangleContext( 203 *CGM.getContext().getAuxTargetInfo())); 204 } 205 206 return std::unique_ptr<MangleContext>(CGM.getContext().createMangleContext( 207 CGM.getContext().getAuxTargetInfo())); 208 } 209 210 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM) 211 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()), 212 TheModule(CGM.getModule()), 213 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode), 214 DeviceMC(InitDeviceMC(CGM)) { 215 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 216 ASTContext &Ctx = CGM.getContext(); 217 218 IntTy = CGM.IntTy; 219 SizeTy = CGM.SizeTy; 220 VoidTy = CGM.VoidTy; 221 222 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy)); 223 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy)); 224 VoidPtrPtrTy = VoidPtrTy->getPointerTo(); 225 } 226 227 llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const { 228 // cudaError_t cudaSetupArgument(void *, size_t, size_t) 229 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy}; 230 return CGM.CreateRuntimeFunction( 231 llvm::FunctionType::get(IntTy, Params, false), 232 addPrefixToName("SetupArgument")); 233 } 234 235 llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const { 236 if (CGM.getLangOpts().HIP) { 237 // hipError_t hipLaunchByPtr(char *); 238 return CGM.CreateRuntimeFunction( 239 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr"); 240 } 241 // cudaError_t cudaLaunch(char *); 242 return CGM.CreateRuntimeFunction( 243 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch"); 244 } 245 246 llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const { 247 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false); 248 } 249 250 llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const { 251 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false); 252 } 253 254 llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const { 255 auto *CallbackFnTy = getCallbackFnTy(); 256 auto *RegisterGlobalsFnTy = getRegisterGlobalsFnTy(); 257 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy, 258 VoidPtrTy, CallbackFnTy->getPointerTo()}; 259 return llvm::FunctionType::get(VoidTy, Params, false); 260 } 261 262 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) { 263 GlobalDecl GD; 264 // D could be either a kernel or a variable. 265 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 266 GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 267 else 268 GD = GlobalDecl(ND); 269 std::string DeviceSideName; 270 MangleContext *MC; 271 if (CGM.getLangOpts().CUDAIsDevice) 272 MC = &CGM.getCXXABI().getMangleContext(); 273 else 274 MC = DeviceMC.get(); 275 if (MC->shouldMangleDeclName(ND)) { 276 SmallString<256> Buffer; 277 llvm::raw_svector_ostream Out(Buffer); 278 MC->mangleName(GD, Out); 279 DeviceSideName = std::string(Out.str()); 280 } else 281 DeviceSideName = std::string(ND->getIdentifier()->getName()); 282 283 // Make unique name for device side static file-scope variable for HIP. 284 if (CGM.getContext().shouldExternalize(ND) && 285 CGM.getLangOpts().GPURelocatableDeviceCode && 286 !CGM.getLangOpts().CUID.empty()) { 287 SmallString<256> Buffer; 288 llvm::raw_svector_ostream Out(Buffer); 289 Out << DeviceSideName; 290 CGM.printPostfixForExternalizedDecl(Out, ND); 291 DeviceSideName = std::string(Out.str()); 292 } 293 return DeviceSideName; 294 } 295 296 void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF, 297 FunctionArgList &Args) { 298 EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl}); 299 if (auto *GV = dyn_cast<llvm::GlobalVariable>(KernelHandles[CGF.CurFn])) { 300 GV->setLinkage(CGF.CurFn->getLinkage()); 301 GV->setInitializer(CGF.CurFn); 302 } 303 if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(), 304 CudaFeature::CUDA_USES_NEW_LAUNCH) || 305 (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI)) 306 emitDeviceStubBodyNew(CGF, Args); 307 else 308 emitDeviceStubBodyLegacy(CGF, Args); 309 } 310 311 // CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local 312 // array and kernels are launched using cudaLaunchKernel(). 313 void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF, 314 FunctionArgList &Args) { 315 // Build the shadow stack entry at the very start of the function. 316 317 // Calculate amount of space we will need for all arguments. If we have no 318 // args, allocate a single pointer so we still have a valid pointer to the 319 // argument array that we can pass to runtime, even if it will be unused. 320 Address KernelArgs = CGF.CreateTempAlloca( 321 VoidPtrTy, CharUnits::fromQuantity(16), "kernel_args", 322 llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size()))); 323 // Store pointers to the arguments in a locally allocated launch_args. 324 for (unsigned i = 0; i < Args.size(); ++i) { 325 llvm::Value* VarPtr = CGF.GetAddrOfLocalVar(Args[i]).getPointer(); 326 llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, VoidPtrTy); 327 CGF.Builder.CreateDefaultAlignedStore( 328 VoidVarPtr, 329 CGF.Builder.CreateConstGEP1_32(VoidPtrTy, KernelArgs.getPointer(), i)); 330 } 331 332 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end"); 333 334 // Lookup cudaLaunchKernel/hipLaunchKernel function. 335 // HIP kernel launching API name depends on -fgpu-default-stream option. For 336 // the default value 'legacy', it is hipLaunchKernel. For 'per-thread', 337 // it is hipLaunchKernel_spt. 338 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim, 339 // void **args, size_t sharedMem, 340 // cudaStream_t stream); 341 // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim, 342 // dim3 blockDim, void **args, 343 // size_t sharedMem, hipStream_t stream); 344 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 345 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 346 std::string KernelLaunchAPI = "LaunchKernel"; 347 if (CGF.getLangOpts().HIP && CGF.getLangOpts().GPUDefaultStream == 348 LangOptions::GPUDefaultStreamKind::PerThread) 349 KernelLaunchAPI = KernelLaunchAPI + "_spt"; 350 auto LaunchKernelName = addPrefixToName(KernelLaunchAPI); 351 IdentifierInfo &cudaLaunchKernelII = 352 CGM.getContext().Idents.get(LaunchKernelName); 353 FunctionDecl *cudaLaunchKernelFD = nullptr; 354 for (auto *Result : DC->lookup(&cudaLaunchKernelII)) { 355 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result)) 356 cudaLaunchKernelFD = FD; 357 } 358 359 if (cudaLaunchKernelFD == nullptr) { 360 CGM.Error(CGF.CurFuncDecl->getLocation(), 361 "Can't find declaration for " + LaunchKernelName); 362 return; 363 } 364 // Create temporary dim3 grid_dim, block_dim. 365 ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1); 366 QualType Dim3Ty = GridDimParam->getType(); 367 Address GridDim = 368 CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim"); 369 Address BlockDim = 370 CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim"); 371 Address ShmemSize = 372 CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size"); 373 Address Stream = 374 CGF.CreateTempAlloca(VoidPtrTy, CGM.getPointerAlign(), "stream"); 375 llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction( 376 llvm::FunctionType::get(IntTy, 377 {/*gridDim=*/GridDim.getType(), 378 /*blockDim=*/BlockDim.getType(), 379 /*ShmemSize=*/ShmemSize.getType(), 380 /*Stream=*/Stream.getType()}, 381 /*isVarArg=*/false), 382 addUnderscoredPrefixToName("PopCallConfiguration")); 383 384 CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn, 385 {GridDim.getPointer(), BlockDim.getPointer(), 386 ShmemSize.getPointer(), Stream.getPointer()}); 387 388 // Emit the call to cudaLaunch 389 llvm::Value *Kernel = 390 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn], VoidPtrTy); 391 CallArgList LaunchKernelArgs; 392 LaunchKernelArgs.add(RValue::get(Kernel), 393 cudaLaunchKernelFD->getParamDecl(0)->getType()); 394 LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty); 395 LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty); 396 LaunchKernelArgs.add(RValue::get(KernelArgs.getPointer()), 397 cudaLaunchKernelFD->getParamDecl(3)->getType()); 398 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)), 399 cudaLaunchKernelFD->getParamDecl(4)->getType()); 400 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)), 401 cudaLaunchKernelFD->getParamDecl(5)->getType()); 402 403 QualType QT = cudaLaunchKernelFD->getType(); 404 QualType CQT = QT.getCanonicalType(); 405 llvm::Type *Ty = CGM.getTypes().ConvertType(CQT); 406 llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 407 408 const CGFunctionInfo &FI = 409 CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD); 410 llvm::FunctionCallee cudaLaunchKernelFn = 411 CGM.CreateRuntimeFunction(FTy, LaunchKernelName); 412 CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(), 413 LaunchKernelArgs); 414 CGF.EmitBranch(EndBlock); 415 416 CGF.EmitBlock(EndBlock); 417 } 418 419 void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF, 420 FunctionArgList &Args) { 421 // Emit a call to cudaSetupArgument for each arg in Args. 422 llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn(); 423 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end"); 424 CharUnits Offset = CharUnits::Zero(); 425 for (const VarDecl *A : Args) { 426 auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType()); 427 Offset = Offset.alignTo(TInfo.Align); 428 llvm::Value *Args[] = { 429 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(), 430 VoidPtrTy), 431 llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()), 432 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()), 433 }; 434 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args); 435 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0); 436 llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero); 437 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next"); 438 CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock); 439 CGF.EmitBlock(NextBlock); 440 Offset += TInfo.Width; 441 } 442 443 // Emit the call to cudaLaunch 444 llvm::FunctionCallee cudaLaunchFn = getLaunchFn(); 445 llvm::Value *Arg = 446 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn], CharPtrTy); 447 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg); 448 CGF.EmitBranch(EndBlock); 449 450 CGF.EmitBlock(EndBlock); 451 } 452 453 // Replace the original variable Var with the address loaded from variable 454 // ManagedVar populated by HIP runtime. 455 static void replaceManagedVar(llvm::GlobalVariable *Var, 456 llvm::GlobalVariable *ManagedVar) { 457 SmallVector<SmallVector<llvm::User *, 8>, 8> WorkList; 458 for (auto &&VarUse : Var->uses()) { 459 WorkList.push_back({VarUse.getUser()}); 460 } 461 while (!WorkList.empty()) { 462 auto &&WorkItem = WorkList.pop_back_val(); 463 auto *U = WorkItem.back(); 464 if (isa<llvm::ConstantExpr>(U)) { 465 for (auto &&UU : U->uses()) { 466 WorkItem.push_back(UU.getUser()); 467 WorkList.push_back(WorkItem); 468 WorkItem.pop_back(); 469 } 470 continue; 471 } 472 if (auto *I = dyn_cast<llvm::Instruction>(U)) { 473 llvm::Value *OldV = Var; 474 llvm::Instruction *NewV = 475 new llvm::LoadInst(Var->getType(), ManagedVar, "ld.managed", false, 476 llvm::Align(Var->getAlignment()), I); 477 WorkItem.pop_back(); 478 // Replace constant expressions directly or indirectly using the managed 479 // variable with instructions. 480 for (auto &&Op : WorkItem) { 481 auto *CE = cast<llvm::ConstantExpr>(Op); 482 auto *NewInst = CE->getAsInstruction(I); 483 NewInst->replaceUsesOfWith(OldV, NewV); 484 OldV = CE; 485 NewV = NewInst; 486 } 487 I->replaceUsesOfWith(OldV, NewV); 488 } else { 489 llvm_unreachable("Invalid use of managed variable"); 490 } 491 } 492 } 493 494 /// Creates a function that sets up state on the host side for CUDA objects that 495 /// have a presence on both the host and device sides. Specifically, registers 496 /// the host side of kernel functions and device global variables with the CUDA 497 /// runtime. 498 /// \code 499 /// void __cuda_register_globals(void** GpuBinaryHandle) { 500 /// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...); 501 /// ... 502 /// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...); 503 /// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...); 504 /// ... 505 /// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...); 506 /// } 507 /// \endcode 508 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() { 509 // No need to register anything 510 if (EmittedKernels.empty() && DeviceVars.empty()) 511 return nullptr; 512 513 llvm::Function *RegisterKernelsFunc = llvm::Function::Create( 514 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage, 515 addUnderscoredPrefixToName("_register_globals"), &TheModule); 516 llvm::BasicBlock *EntryBB = 517 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc); 518 CGBuilderTy Builder(CGM, Context); 519 Builder.SetInsertPoint(EntryBB); 520 521 // void __cudaRegisterFunction(void **, const char *, char *, const char *, 522 // int, uint3*, uint3*, dim3*, dim3*, int*) 523 llvm::Type *RegisterFuncParams[] = { 524 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy, 525 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()}; 526 llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction( 527 llvm::FunctionType::get(IntTy, RegisterFuncParams, false), 528 addUnderscoredPrefixToName("RegisterFunction")); 529 530 // Extract GpuBinaryHandle passed as the first argument passed to 531 // __cuda_register_globals() and generate __cudaRegisterFunction() call for 532 // each emitted kernel. 533 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin(); 534 for (auto &&I : EmittedKernels) { 535 llvm::Constant *KernelName = 536 makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D))); 537 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy); 538 llvm::Value *Args[] = { 539 &GpuBinaryHandlePtr, 540 Builder.CreateBitCast(KernelHandles[I.Kernel], VoidPtrTy), 541 KernelName, 542 KernelName, 543 llvm::ConstantInt::get(IntTy, -1), 544 NullPtr, 545 NullPtr, 546 NullPtr, 547 NullPtr, 548 llvm::ConstantPointerNull::get(IntTy->getPointerTo())}; 549 Builder.CreateCall(RegisterFunc, Args); 550 } 551 552 llvm::Type *VarSizeTy = IntTy; 553 // For HIP or CUDA 9.0+, device variable size is type of `size_t`. 554 if (CGM.getLangOpts().HIP || 555 ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90) 556 VarSizeTy = SizeTy; 557 558 // void __cudaRegisterVar(void **, char *, char *, const char *, 559 // int, int, int, int) 560 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy, 561 CharPtrTy, IntTy, VarSizeTy, 562 IntTy, IntTy}; 563 llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction( 564 llvm::FunctionType::get(VoidTy, RegisterVarParams, false), 565 addUnderscoredPrefixToName("RegisterVar")); 566 // void __hipRegisterManagedVar(void **, char *, char *, const char *, 567 // size_t, unsigned) 568 llvm::Type *RegisterManagedVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy, 569 CharPtrTy, VarSizeTy, IntTy}; 570 llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction( 571 llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false), 572 addUnderscoredPrefixToName("RegisterManagedVar")); 573 // void __cudaRegisterSurface(void **, const struct surfaceReference *, 574 // const void **, const char *, int, int); 575 llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction( 576 llvm::FunctionType::get( 577 VoidTy, {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy}, 578 false), 579 addUnderscoredPrefixToName("RegisterSurface")); 580 // void __cudaRegisterTexture(void **, const struct textureReference *, 581 // const void **, const char *, int, int, int) 582 llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction( 583 llvm::FunctionType::get( 584 VoidTy, 585 {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy, IntTy}, 586 false), 587 addUnderscoredPrefixToName("RegisterTexture")); 588 for (auto &&Info : DeviceVars) { 589 llvm::GlobalVariable *Var = Info.Var; 590 assert((!Var->isDeclaration() || Info.Flags.isManaged()) && 591 "External variables should not show up here, except HIP managed " 592 "variables"); 593 llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D)); 594 switch (Info.Flags.getKind()) { 595 case DeviceVarFlags::Variable: { 596 uint64_t VarSize = 597 CGM.getDataLayout().getTypeAllocSize(Var->getValueType()); 598 if (Info.Flags.isManaged()) { 599 auto *ManagedVar = new llvm::GlobalVariable( 600 CGM.getModule(), Var->getType(), 601 /*isConstant=*/false, Var->getLinkage(), 602 /*Init=*/Var->isDeclaration() 603 ? nullptr 604 : llvm::ConstantPointerNull::get(Var->getType()), 605 /*Name=*/"", /*InsertBefore=*/nullptr, 606 llvm::GlobalVariable::NotThreadLocal); 607 ManagedVar->setDSOLocal(Var->isDSOLocal()); 608 ManagedVar->setVisibility(Var->getVisibility()); 609 ManagedVar->setExternallyInitialized(true); 610 ManagedVar->takeName(Var); 611 Var->setName(Twine(ManagedVar->getName() + ".managed")); 612 replaceManagedVar(Var, ManagedVar); 613 llvm::Value *Args[] = { 614 &GpuBinaryHandlePtr, 615 Builder.CreateBitCast(ManagedVar, VoidPtrTy), 616 Builder.CreateBitCast(Var, VoidPtrTy), 617 VarName, 618 llvm::ConstantInt::get(VarSizeTy, VarSize), 619 llvm::ConstantInt::get(IntTy, Var->getAlignment())}; 620 if (!Var->isDeclaration()) 621 Builder.CreateCall(RegisterManagedVar, Args); 622 } else { 623 llvm::Value *Args[] = { 624 &GpuBinaryHandlePtr, 625 Builder.CreateBitCast(Var, VoidPtrTy), 626 VarName, 627 VarName, 628 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()), 629 llvm::ConstantInt::get(VarSizeTy, VarSize), 630 llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()), 631 llvm::ConstantInt::get(IntTy, 0)}; 632 Builder.CreateCall(RegisterVar, Args); 633 } 634 break; 635 } 636 case DeviceVarFlags::Surface: 637 Builder.CreateCall( 638 RegisterSurf, 639 {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName, 640 VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()), 641 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())}); 642 break; 643 case DeviceVarFlags::Texture: 644 Builder.CreateCall( 645 RegisterTex, 646 {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName, 647 VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()), 648 llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()), 649 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())}); 650 break; 651 } 652 } 653 654 Builder.CreateRetVoid(); 655 return RegisterKernelsFunc; 656 } 657 658 /// Creates a global constructor function for the module: 659 /// 660 /// For CUDA: 661 /// \code 662 /// void __cuda_module_ctor() { 663 /// Handle = __cudaRegisterFatBinary(GpuBinaryBlob); 664 /// __cuda_register_globals(Handle); 665 /// } 666 /// \endcode 667 /// 668 /// For HIP: 669 /// \code 670 /// void __hip_module_ctor() { 671 /// if (__hip_gpubin_handle == 0) { 672 /// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob); 673 /// __hip_register_globals(__hip_gpubin_handle); 674 /// } 675 /// } 676 /// \endcode 677 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { 678 bool IsHIP = CGM.getLangOpts().HIP; 679 bool IsCUDA = CGM.getLangOpts().CUDA; 680 // No need to generate ctors/dtors if there is no GPU binary. 681 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName; 682 if (CudaGpuBinaryFileName.empty() && !IsHIP) 683 return nullptr; 684 if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() && 685 DeviceVars.empty()) 686 return nullptr; 687 688 // void __{cuda|hip}_register_globals(void* handle); 689 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn(); 690 // We always need a function to pass in as callback. Create a dummy 691 // implementation if we don't need to register anything. 692 if (RelocatableDeviceCode && !RegisterGlobalsFunc) 693 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy()); 694 695 // void ** __{cuda|hip}RegisterFatBinary(void *); 696 llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction( 697 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false), 698 addUnderscoredPrefixToName("RegisterFatBinary")); 699 // struct { int magic, int version, void * gpu_binary, void * dont_care }; 700 llvm::StructType *FatbinWrapperTy = 701 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy); 702 703 // Register GPU binary with the CUDA runtime, store returned handle in a 704 // global variable and save a reference in GpuBinaryHandle to be cleaned up 705 // in destructor on exit. Then associate all known kernels with the GPU binary 706 // handle so CUDA runtime can figure out what to call on the GPU side. 707 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr; 708 if (!CudaGpuBinaryFileName.empty()) { 709 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr = 710 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName); 711 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) { 712 CGM.getDiags().Report(diag::err_cannot_open_file) 713 << CudaGpuBinaryFileName << EC.message(); 714 return nullptr; 715 } 716 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get()); 717 } 718 719 llvm::Function *ModuleCtorFunc = llvm::Function::Create( 720 llvm::FunctionType::get(VoidTy, false), 721 llvm::GlobalValue::InternalLinkage, 722 addUnderscoredPrefixToName("_module_ctor"), &TheModule); 723 llvm::BasicBlock *CtorEntryBB = 724 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc); 725 CGBuilderTy CtorBuilder(CGM, Context); 726 727 CtorBuilder.SetInsertPoint(CtorEntryBB); 728 729 const char *FatbinConstantName; 730 const char *FatbinSectionName; 731 const char *ModuleIDSectionName; 732 StringRef ModuleIDPrefix; 733 llvm::Constant *FatBinStr; 734 unsigned FatMagic; 735 if (IsHIP) { 736 FatbinConstantName = ".hip_fatbin"; 737 FatbinSectionName = ".hipFatBinSegment"; 738 739 ModuleIDSectionName = "__hip_module_id"; 740 ModuleIDPrefix = "__hip_"; 741 742 if (CudaGpuBinary) { 743 // If fatbin is available from early finalization, create a string 744 // literal containing the fat binary loaded from the given file. 745 const unsigned HIPCodeObjectAlign = 4096; 746 FatBinStr = 747 makeConstantString(std::string(CudaGpuBinary->getBuffer()), "", 748 FatbinConstantName, HIPCodeObjectAlign); 749 } else { 750 // If fatbin is not available, create an external symbol 751 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed 752 // to contain the fat binary but will be populated somewhere else, 753 // e.g. by lld through link script. 754 FatBinStr = new llvm::GlobalVariable( 755 CGM.getModule(), CGM.Int8Ty, 756 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, 757 "__hip_fatbin", nullptr, 758 llvm::GlobalVariable::NotThreadLocal); 759 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName); 760 } 761 762 FatMagic = HIPFatMagic; 763 } else { 764 if (RelocatableDeviceCode) 765 FatbinConstantName = CGM.getTriple().isMacOSX() 766 ? "__NV_CUDA,__nv_relfatbin" 767 : "__nv_relfatbin"; 768 else 769 FatbinConstantName = 770 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin"; 771 // NVIDIA's cuobjdump looks for fatbins in this section. 772 FatbinSectionName = 773 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment"; 774 775 ModuleIDSectionName = CGM.getTriple().isMacOSX() 776 ? "__NV_CUDA,__nv_module_id" 777 : "__nv_module_id"; 778 ModuleIDPrefix = "__nv_"; 779 780 // For CUDA, create a string literal containing the fat binary loaded from 781 // the given file. 782 FatBinStr = makeConstantString(std::string(CudaGpuBinary->getBuffer()), "", 783 FatbinConstantName, 8); 784 FatMagic = CudaFatMagic; 785 } 786 787 // Create initialized wrapper structure that points to the loaded GPU binary 788 ConstantInitBuilder Builder(CGM); 789 auto Values = Builder.beginStruct(FatbinWrapperTy); 790 // Fatbin wrapper magic. 791 Values.addInt(IntTy, FatMagic); 792 // Fatbin version. 793 Values.addInt(IntTy, 1); 794 // Data. 795 Values.add(FatBinStr); 796 // Unused in fatbin v1. 797 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy)); 798 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal( 799 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(), 800 /*constant*/ true); 801 FatbinWrapper->setSection(FatbinSectionName); 802 803 // There is only one HIP fat binary per linked module, however there are 804 // multiple constructor functions. Make sure the fat binary is registered 805 // only once. The constructor functions are executed by the dynamic loader 806 // before the program gains control. The dynamic loader cannot execute the 807 // constructor functions concurrently since doing that would not guarantee 808 // thread safety of the loaded program. Therefore we can assume sequential 809 // execution of constructor functions here. 810 if (IsHIP) { 811 auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage : 812 llvm::GlobalValue::LinkOnceAnyLinkage; 813 llvm::BasicBlock *IfBlock = 814 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc); 815 llvm::BasicBlock *ExitBlock = 816 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc); 817 // The name, size, and initialization pattern of this variable is part 818 // of HIP ABI. 819 GpuBinaryHandle = new llvm::GlobalVariable( 820 TheModule, VoidPtrPtrTy, /*isConstant=*/false, 821 Linkage, 822 /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy), 823 "__hip_gpubin_handle"); 824 if (Linkage == llvm::GlobalValue::LinkOnceAnyLinkage) 825 GpuBinaryHandle->setComdat( 826 CGM.getModule().getOrInsertComdat(GpuBinaryHandle->getName())); 827 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign()); 828 // Prevent the weak symbol in different shared libraries being merged. 829 if (Linkage != llvm::GlobalValue::InternalLinkage) 830 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility); 831 Address GpuBinaryAddr( 832 GpuBinaryHandle, VoidPtrPtrTy, 833 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment())); 834 { 835 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr); 836 llvm::Constant *Zero = 837 llvm::Constant::getNullValue(HandleValue->getType()); 838 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero); 839 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock); 840 } 841 { 842 CtorBuilder.SetInsertPoint(IfBlock); 843 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper); 844 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall( 845 RegisterFatbinFunc, 846 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy)); 847 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr); 848 CtorBuilder.CreateBr(ExitBlock); 849 } 850 { 851 CtorBuilder.SetInsertPoint(ExitBlock); 852 // Call __hip_register_globals(GpuBinaryHandle); 853 if (RegisterGlobalsFunc) { 854 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr); 855 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue); 856 } 857 } 858 } else if (!RelocatableDeviceCode) { 859 // Register binary with CUDA runtime. This is substantially different in 860 // default mode vs. separate compilation! 861 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper); 862 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall( 863 RegisterFatbinFunc, 864 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy)); 865 GpuBinaryHandle = new llvm::GlobalVariable( 866 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage, 867 llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle"); 868 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign()); 869 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle, 870 CGM.getPointerAlign()); 871 872 // Call __cuda_register_globals(GpuBinaryHandle); 873 if (RegisterGlobalsFunc) 874 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall); 875 876 // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it. 877 if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(), 878 CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) { 879 // void __cudaRegisterFatBinaryEnd(void **); 880 llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction( 881 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false), 882 "__cudaRegisterFatBinaryEnd"); 883 CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall); 884 } 885 } else { 886 // Generate a unique module ID. 887 SmallString<64> ModuleID; 888 llvm::raw_svector_ostream OS(ModuleID); 889 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID()); 890 llvm::Constant *ModuleIDConstant = makeConstantString( 891 std::string(ModuleID.str()), "", ModuleIDSectionName, 32); 892 893 // Create an alias for the FatbinWrapper that nvcc will look for. 894 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage, 895 Twine("__fatbinwrap") + ModuleID, FatbinWrapper); 896 897 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *, 898 // void *, void (*)(void **)) 899 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary"); 900 RegisterLinkedBinaryName += ModuleID; 901 llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction( 902 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName); 903 904 assert(RegisterGlobalsFunc && "Expecting at least dummy function!"); 905 llvm::Value *Args[] = {RegisterGlobalsFunc, 906 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy), 907 ModuleIDConstant, 908 makeDummyFunction(getCallbackFnTy())}; 909 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args); 910 } 911 912 // Create destructor and register it with atexit() the way NVCC does it. Doing 913 // it during regular destructor phase worked in CUDA before 9.2 but results in 914 // double-free in 9.2. 915 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) { 916 // extern "C" int atexit(void (*f)(void)); 917 llvm::FunctionType *AtExitTy = 918 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false); 919 llvm::FunctionCallee AtExitFunc = 920 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(), 921 /*Local=*/true); 922 CtorBuilder.CreateCall(AtExitFunc, CleanupFn); 923 } 924 925 CtorBuilder.CreateRetVoid(); 926 return ModuleCtorFunc; 927 } 928 929 /// Creates a global destructor function that unregisters the GPU code blob 930 /// registered by constructor. 931 /// 932 /// For CUDA: 933 /// \code 934 /// void __cuda_module_dtor() { 935 /// __cudaUnregisterFatBinary(Handle); 936 /// } 937 /// \endcode 938 /// 939 /// For HIP: 940 /// \code 941 /// void __hip_module_dtor() { 942 /// if (__hip_gpubin_handle) { 943 /// __hipUnregisterFatBinary(__hip_gpubin_handle); 944 /// __hip_gpubin_handle = 0; 945 /// } 946 /// } 947 /// \endcode 948 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() { 949 // No need for destructor if we don't have a handle to unregister. 950 if (!GpuBinaryHandle) 951 return nullptr; 952 953 // void __cudaUnregisterFatBinary(void ** handle); 954 llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction( 955 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false), 956 addUnderscoredPrefixToName("UnregisterFatBinary")); 957 958 llvm::Function *ModuleDtorFunc = llvm::Function::Create( 959 llvm::FunctionType::get(VoidTy, false), 960 llvm::GlobalValue::InternalLinkage, 961 addUnderscoredPrefixToName("_module_dtor"), &TheModule); 962 963 llvm::BasicBlock *DtorEntryBB = 964 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc); 965 CGBuilderTy DtorBuilder(CGM, Context); 966 DtorBuilder.SetInsertPoint(DtorEntryBB); 967 968 Address GpuBinaryAddr( 969 GpuBinaryHandle, GpuBinaryHandle->getValueType(), 970 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment())); 971 auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr); 972 // There is only one HIP fat binary per linked module, however there are 973 // multiple destructor functions. Make sure the fat binary is unregistered 974 // only once. 975 if (CGM.getLangOpts().HIP) { 976 llvm::BasicBlock *IfBlock = 977 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc); 978 llvm::BasicBlock *ExitBlock = 979 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc); 980 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType()); 981 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero); 982 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock); 983 984 DtorBuilder.SetInsertPoint(IfBlock); 985 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue); 986 DtorBuilder.CreateStore(Zero, GpuBinaryAddr); 987 DtorBuilder.CreateBr(ExitBlock); 988 989 DtorBuilder.SetInsertPoint(ExitBlock); 990 } else { 991 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue); 992 } 993 DtorBuilder.CreateRetVoid(); 994 return ModuleDtorFunc; 995 } 996 997 CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) { 998 return new CGNVCUDARuntime(CGM); 999 } 1000 1001 void CGNVCUDARuntime::internalizeDeviceSideVar( 1002 const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) { 1003 // For -fno-gpu-rdc, host-side shadows of external declarations of device-side 1004 // global variables become internal definitions. These have to be internal in 1005 // order to prevent name conflicts with global host variables with the same 1006 // name in a different TUs. 1007 // 1008 // For -fgpu-rdc, the shadow variables should not be internalized because 1009 // they may be accessed by different TU. 1010 if (CGM.getLangOpts().GPURelocatableDeviceCode) 1011 return; 1012 1013 // __shared__ variables are odd. Shadows do get created, but 1014 // they are not registered with the CUDA runtime, so they 1015 // can't really be used to access their device-side 1016 // counterparts. It's not clear yet whether it's nvcc's bug or 1017 // a feature, but we've got to do the same for compatibility. 1018 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 1019 D->hasAttr<CUDASharedAttr>() || 1020 D->getType()->isCUDADeviceBuiltinSurfaceType() || 1021 D->getType()->isCUDADeviceBuiltinTextureType()) { 1022 Linkage = llvm::GlobalValue::InternalLinkage; 1023 } 1024 } 1025 1026 void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D, 1027 llvm::GlobalVariable &GV) { 1028 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 1029 // Shadow variables and their properties must be registered with CUDA 1030 // runtime. Skip Extern global variables, which will be registered in 1031 // the TU where they are defined. 1032 // 1033 // Don't register a C++17 inline variable. The local symbol can be 1034 // discarded and referencing a discarded local symbol from outside the 1035 // comdat (__cuda_register_globals) is disallowed by the ELF spec. 1036 // 1037 // HIP managed variables need to be always recorded in device and host 1038 // compilations for transformation. 1039 // 1040 // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are 1041 // added to llvm.compiler-used, therefore they are safe to be registered. 1042 if ((!D->hasExternalStorage() && !D->isInline()) || 1043 CGM.getContext().CUDADeviceVarODRUsedByHost.contains(D) || 1044 D->hasAttr<HIPManagedAttr>()) { 1045 registerDeviceVar(D, GV, !D->hasDefinition(), 1046 D->hasAttr<CUDAConstantAttr>()); 1047 } 1048 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() || 1049 D->getType()->isCUDADeviceBuiltinTextureType()) { 1050 // Builtin surfaces and textures and their template arguments are 1051 // also registered with CUDA runtime. 1052 const auto *TD = cast<ClassTemplateSpecializationDecl>( 1053 D->getType()->castAs<RecordType>()->getDecl()); 1054 const TemplateArgumentList &Args = TD->getTemplateArgs(); 1055 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) { 1056 assert(Args.size() == 2 && 1057 "Unexpected number of template arguments of CUDA device " 1058 "builtin surface type."); 1059 auto SurfType = Args[1].getAsIntegral(); 1060 if (!D->hasExternalStorage()) 1061 registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue()); 1062 } else { 1063 assert(Args.size() == 3 && 1064 "Unexpected number of template arguments of CUDA device " 1065 "builtin texture type."); 1066 auto TexType = Args[1].getAsIntegral(); 1067 auto Normalized = Args[2].getAsIntegral(); 1068 if (!D->hasExternalStorage()) 1069 registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(), 1070 Normalized.getZExtValue()); 1071 } 1072 } 1073 } 1074 1075 // Transform managed variables to pointers to managed variables in device code. 1076 // Each use of the original managed variable is replaced by a load from the 1077 // transformed managed variable. The transformed managed variable contains 1078 // the address of managed memory which will be allocated by the runtime. 1079 void CGNVCUDARuntime::transformManagedVars() { 1080 for (auto &&Info : DeviceVars) { 1081 llvm::GlobalVariable *Var = Info.Var; 1082 if (Info.Flags.getKind() == DeviceVarFlags::Variable && 1083 Info.Flags.isManaged()) { 1084 auto *ManagedVar = new llvm::GlobalVariable( 1085 CGM.getModule(), Var->getType(), 1086 /*isConstant=*/false, Var->getLinkage(), 1087 /*Init=*/Var->isDeclaration() 1088 ? nullptr 1089 : llvm::ConstantPointerNull::get(Var->getType()), 1090 /*Name=*/"", /*InsertBefore=*/nullptr, 1091 llvm::GlobalVariable::NotThreadLocal, 1092 CGM.getContext().getTargetAddressSpace(LangAS::cuda_device)); 1093 ManagedVar->setDSOLocal(Var->isDSOLocal()); 1094 ManagedVar->setVisibility(Var->getVisibility()); 1095 ManagedVar->setExternallyInitialized(true); 1096 replaceManagedVar(Var, ManagedVar); 1097 ManagedVar->takeName(Var); 1098 Var->setName(Twine(ManagedVar->getName()) + ".managed"); 1099 // Keep managed variables even if they are not used in device code since 1100 // they need to be allocated by the runtime. 1101 if (!Var->isDeclaration()) { 1102 assert(!ManagedVar->isDeclaration()); 1103 CGM.addCompilerUsedGlobal(Var); 1104 CGM.addCompilerUsedGlobal(ManagedVar); 1105 } 1106 } 1107 } 1108 } 1109 1110 // Returns module constructor to be added. 1111 llvm::Function *CGNVCUDARuntime::finalizeModule() { 1112 if (CGM.getLangOpts().CUDAIsDevice) { 1113 transformManagedVars(); 1114 1115 // Mark ODR-used device variables as compiler used to prevent it from being 1116 // eliminated by optimization. This is necessary for device variables 1117 // ODR-used by host functions. Sema correctly marks them as ODR-used no 1118 // matter whether they are ODR-used by device or host functions. 1119 // 1120 // We do not need to do this if the variable has used attribute since it 1121 // has already been added. 1122 // 1123 // Static device variables have been externalized at this point, therefore 1124 // variables with LLVM private or internal linkage need not be added. 1125 for (auto &&Info : DeviceVars) { 1126 auto Kind = Info.Flags.getKind(); 1127 if (!Info.Var->isDeclaration() && 1128 !llvm::GlobalValue::isLocalLinkage(Info.Var->getLinkage()) && 1129 (Kind == DeviceVarFlags::Variable || 1130 Kind == DeviceVarFlags::Surface || 1131 Kind == DeviceVarFlags::Texture) && 1132 Info.D->isUsed() && !Info.D->hasAttr<UsedAttr>()) { 1133 CGM.addCompilerUsedGlobal(Info.Var); 1134 } 1135 } 1136 return nullptr; 1137 } 1138 return makeModuleCtorFunction(); 1139 } 1140 1141 llvm::GlobalValue *CGNVCUDARuntime::getKernelHandle(llvm::Function *F, 1142 GlobalDecl GD) { 1143 auto Loc = KernelHandles.find(F); 1144 if (Loc != KernelHandles.end()) 1145 return Loc->second; 1146 1147 if (!CGM.getLangOpts().HIP) { 1148 KernelHandles[F] = F; 1149 KernelStubs[F] = F; 1150 return F; 1151 } 1152 1153 auto *Var = new llvm::GlobalVariable( 1154 TheModule, F->getType(), /*isConstant=*/true, F->getLinkage(), 1155 /*Initializer=*/nullptr, 1156 CGM.getMangledName( 1157 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel))); 1158 Var->setAlignment(CGM.getPointerAlign().getAsAlign()); 1159 Var->setDSOLocal(F->isDSOLocal()); 1160 Var->setVisibility(F->getVisibility()); 1161 CGM.maybeSetTrivialComdat(*GD.getDecl(), *Var); 1162 KernelHandles[F] = Var; 1163 KernelStubs[Var] = F; 1164 return Var; 1165 } 1166