Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp
35233 views
//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This provides a class for CUDA code generation targeting the NVIDIA CUDA9// runtime library.10//11//===----------------------------------------------------------------------===//1213#include "CGCUDARuntime.h"14#include "CGCXXABI.h"15#include "CodeGenFunction.h"16#include "CodeGenModule.h"17#include "clang/AST/Decl.h"18#include "clang/Basic/Cuda.h"19#include "clang/CodeGen/CodeGenABITypes.h"20#include "clang/CodeGen/ConstantInitBuilder.h"21#include "llvm/Frontend/Offloading/Utility.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#include "llvm/Support/VirtualFileSystem.h"2829using namespace clang;30using namespace CodeGen;3132namespace {33constexpr unsigned CudaFatMagic = 0x466243b1;34constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"3536class CGNVCUDARuntime : public CGCUDARuntime {3738private:39llvm::IntegerType *IntTy, *SizeTy;40llvm::Type *VoidTy;41llvm::PointerType *PtrTy;4243/// Convenience reference to LLVM Context44llvm::LLVMContext &Context;45/// Convenience reference to the current module46llvm::Module &TheModule;47/// Keeps track of kernel launch stubs and handles emitted in this module48struct KernelInfo {49llvm::Function *Kernel; // stub function to help launch kernel50const Decl *D;51};52llvm::SmallVector<KernelInfo, 16> EmittedKernels;53// Map a kernel mangled name to a symbol for identifying kernel in host code54// For CUDA, the symbol for identifying the kernel is the same as the device55// stub function. For HIP, they are different.56llvm::DenseMap<StringRef, llvm::GlobalValue *> KernelHandles;57// Map a kernel handle to the kernel stub.58llvm::DenseMap<llvm::GlobalValue *, llvm::Function *> KernelStubs;59struct VarInfo {60llvm::GlobalVariable *Var;61const VarDecl *D;62DeviceVarFlags Flags;63};64llvm::SmallVector<VarInfo, 16> DeviceVars;65/// Keeps track of variable containing handle of GPU binary. Populated by66/// ModuleCtorFunction() and used to create corresponding cleanup calls in67/// ModuleDtorFunction()68llvm::GlobalVariable *GpuBinaryHandle = nullptr;69/// Whether we generate relocatable device code.70bool RelocatableDeviceCode;71/// Mangle context for device.72std::unique_ptr<MangleContext> DeviceMC;7374llvm::FunctionCallee getSetupArgumentFn() const;75llvm::FunctionCallee getLaunchFn() const;7677llvm::FunctionType *getRegisterGlobalsFnTy() const;78llvm::FunctionType *getCallbackFnTy() const;79llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;80std::string addPrefixToName(StringRef FuncName) const;81std::string addUnderscoredPrefixToName(StringRef FuncName) const;8283/// Creates a function to register all kernel stubs generated in this module.84llvm::Function *makeRegisterGlobalsFn();8586/// Helper function that generates a constant string and returns a pointer to87/// the start of the string. The result of this function can be used anywhere88/// where the C code specifies const char*.89llvm::Constant *makeConstantString(const std::string &Str,90const std::string &Name = "") {91return CGM.GetAddrOfConstantCString(Str, Name.c_str()).getPointer();92}9394/// Helper function which generates an initialized constant array from Str,95/// and optionally sets section name and alignment. AddNull specifies whether96/// the array should nave NUL termination.97llvm::Constant *makeConstantArray(StringRef Str,98StringRef Name = "",99StringRef SectionName = "",100unsigned Alignment = 0,101bool AddNull = false) {102llvm::Constant *Value =103llvm::ConstantDataArray::getString(Context, Str, AddNull);104auto *GV = new llvm::GlobalVariable(105TheModule, Value->getType(), /*isConstant=*/true,106llvm::GlobalValue::PrivateLinkage, Value, Name);107if (!SectionName.empty()) {108GV->setSection(SectionName);109// Mark the address as used which make sure that this section isn't110// merged and we will really have it in the object file.111GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);112}113if (Alignment)114GV->setAlignment(llvm::Align(Alignment));115return GV;116}117118/// Helper function that generates an empty dummy function returning void.119llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {120assert(FnTy->getReturnType()->isVoidTy() &&121"Can only generate dummy functions returning void!");122llvm::Function *DummyFunc = llvm::Function::Create(123FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);124125llvm::BasicBlock *DummyBlock =126llvm::BasicBlock::Create(Context, "", DummyFunc);127CGBuilderTy FuncBuilder(CGM, Context);128FuncBuilder.SetInsertPoint(DummyBlock);129FuncBuilder.CreateRetVoid();130131return DummyFunc;132}133134void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);135void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);136std::string getDeviceSideName(const NamedDecl *ND) override;137138void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,139bool Extern, bool Constant) {140DeviceVars.push_back({&Var,141VD,142{DeviceVarFlags::Variable, Extern, Constant,143VD->hasAttr<HIPManagedAttr>(),144/*Normalized*/ false, 0}});145}146void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,147bool Extern, int Type) {148DeviceVars.push_back({&Var,149VD,150{DeviceVarFlags::Surface, Extern, /*Constant*/ false,151/*Managed*/ false,152/*Normalized*/ false, Type}});153}154void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,155bool Extern, int Type, bool Normalized) {156DeviceVars.push_back({&Var,157VD,158{DeviceVarFlags::Texture, Extern, /*Constant*/ false,159/*Managed*/ false, Normalized, Type}});160}161162/// Creates module constructor function163llvm::Function *makeModuleCtorFunction();164/// Creates module destructor function165llvm::Function *makeModuleDtorFunction();166/// Transform managed variables for device compilation.167void transformManagedVars();168/// Create offloading entries to register globals in RDC mode.169void createOffloadingEntries();170171public:172CGNVCUDARuntime(CodeGenModule &CGM);173174llvm::GlobalValue *getKernelHandle(llvm::Function *F, GlobalDecl GD) override;175llvm::Function *getKernelStub(llvm::GlobalValue *Handle) override {176auto Loc = KernelStubs.find(Handle);177assert(Loc != KernelStubs.end());178return Loc->second;179}180void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;181void handleVarRegistration(const VarDecl *VD,182llvm::GlobalVariable &Var) override;183void184internalizeDeviceSideVar(const VarDecl *D,185llvm::GlobalValue::LinkageTypes &Linkage) override;186187llvm::Function *finalizeModule() override;188};189190} // end anonymous namespace191192std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {193if (CGM.getLangOpts().HIP)194return ((Twine("hip") + Twine(FuncName)).str());195return ((Twine("cuda") + Twine(FuncName)).str());196}197std::string198CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {199if (CGM.getLangOpts().HIP)200return ((Twine("__hip") + Twine(FuncName)).str());201return ((Twine("__cuda") + Twine(FuncName)).str());202}203204static std::unique_ptr<MangleContext> InitDeviceMC(CodeGenModule &CGM) {205// If the host and device have different C++ ABIs, mark it as the device206// mangle context so that the mangling needs to retrieve the additional207// device lambda mangling number instead of the regular host one.208if (CGM.getContext().getAuxTargetInfo() &&209CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() &&210CGM.getContext().getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {211return std::unique_ptr<MangleContext>(212CGM.getContext().createDeviceMangleContext(213*CGM.getContext().getAuxTargetInfo()));214}215216return std::unique_ptr<MangleContext>(CGM.getContext().createMangleContext(217CGM.getContext().getAuxTargetInfo()));218}219220CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)221: CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),222TheModule(CGM.getModule()),223RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),224DeviceMC(InitDeviceMC(CGM)) {225IntTy = CGM.IntTy;226SizeTy = CGM.SizeTy;227VoidTy = CGM.VoidTy;228PtrTy = CGM.UnqualPtrTy;229}230231llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {232// cudaError_t cudaSetupArgument(void *, size_t, size_t)233llvm::Type *Params[] = {PtrTy, SizeTy, SizeTy};234return CGM.CreateRuntimeFunction(235llvm::FunctionType::get(IntTy, Params, false),236addPrefixToName("SetupArgument"));237}238239llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {240if (CGM.getLangOpts().HIP) {241// hipError_t hipLaunchByPtr(char *);242return CGM.CreateRuntimeFunction(243llvm::FunctionType::get(IntTy, PtrTy, false), "hipLaunchByPtr");244}245// cudaError_t cudaLaunch(char *);246return CGM.CreateRuntimeFunction(llvm::FunctionType::get(IntTy, PtrTy, false),247"cudaLaunch");248}249250llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {251return llvm::FunctionType::get(VoidTy, PtrTy, false);252}253254llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {255return llvm::FunctionType::get(VoidTy, PtrTy, false);256}257258llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {259llvm::Type *Params[] = {llvm::PointerType::getUnqual(Context), PtrTy, PtrTy,260llvm::PointerType::getUnqual(Context)};261return llvm::FunctionType::get(VoidTy, Params, false);262}263264std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {265GlobalDecl GD;266// D could be either a kernel or a variable.267if (auto *FD = dyn_cast<FunctionDecl>(ND))268GD = GlobalDecl(FD, KernelReferenceKind::Kernel);269else270GD = GlobalDecl(ND);271std::string DeviceSideName;272MangleContext *MC;273if (CGM.getLangOpts().CUDAIsDevice)274MC = &CGM.getCXXABI().getMangleContext();275else276MC = DeviceMC.get();277if (MC->shouldMangleDeclName(ND)) {278SmallString<256> Buffer;279llvm::raw_svector_ostream Out(Buffer);280MC->mangleName(GD, Out);281DeviceSideName = std::string(Out.str());282} else283DeviceSideName = std::string(ND->getIdentifier()->getName());284285// Make unique name for device side static file-scope variable for HIP.286if (CGM.getContext().shouldExternalize(ND) &&287CGM.getLangOpts().GPURelocatableDeviceCode) {288SmallString<256> Buffer;289llvm::raw_svector_ostream Out(Buffer);290Out << DeviceSideName;291CGM.printPostfixForExternalizedDecl(Out, ND);292DeviceSideName = std::string(Out.str());293}294return DeviceSideName;295}296297void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,298FunctionArgList &Args) {299EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});300if (auto *GV =301dyn_cast<llvm::GlobalVariable>(KernelHandles[CGF.CurFn->getName()])) {302GV->setLinkage(CGF.CurFn->getLinkage());303GV->setInitializer(CGF.CurFn);304}305if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),306CudaFeature::CUDA_USES_NEW_LAUNCH) ||307(CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI))308emitDeviceStubBodyNew(CGF, Args);309else310emitDeviceStubBodyLegacy(CGF, Args);311}312313// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local314// array and kernels are launched using cudaLaunchKernel().315void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,316FunctionArgList &Args) {317// Build the shadow stack entry at the very start of the function.318319// Calculate amount of space we will need for all arguments. If we have no320// args, allocate a single pointer so we still have a valid pointer to the321// argument array that we can pass to runtime, even if it will be unused.322Address KernelArgs = CGF.CreateTempAlloca(323PtrTy, CharUnits::fromQuantity(16), "kernel_args",324llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));325// Store pointers to the arguments in a locally allocated launch_args.326for (unsigned i = 0; i < Args.size(); ++i) {327llvm::Value *VarPtr = CGF.GetAddrOfLocalVar(Args[i]).emitRawPointer(CGF);328llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, PtrTy);329CGF.Builder.CreateDefaultAlignedStore(330VoidVarPtr, CGF.Builder.CreateConstGEP1_32(331PtrTy, KernelArgs.emitRawPointer(CGF), i));332}333334llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");335336// Lookup cudaLaunchKernel/hipLaunchKernel function.337// HIP kernel launching API name depends on -fgpu-default-stream option. For338// the default value 'legacy', it is hipLaunchKernel. For 'per-thread',339// it is hipLaunchKernel_spt.340// cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,341// void **args, size_t sharedMem,342// cudaStream_t stream);343// hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,344// dim3 blockDim, void **args,345// size_t sharedMem, hipStream_t stream);346TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();347DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);348std::string KernelLaunchAPI = "LaunchKernel";349if (CGF.getLangOpts().GPUDefaultStream ==350LangOptions::GPUDefaultStreamKind::PerThread) {351if (CGF.getLangOpts().HIP)352KernelLaunchAPI = KernelLaunchAPI + "_spt";353else if (CGF.getLangOpts().CUDA)354KernelLaunchAPI = KernelLaunchAPI + "_ptsz";355}356auto LaunchKernelName = addPrefixToName(KernelLaunchAPI);357const IdentifierInfo &cudaLaunchKernelII =358CGM.getContext().Idents.get(LaunchKernelName);359FunctionDecl *cudaLaunchKernelFD = nullptr;360for (auto *Result : DC->lookup(&cudaLaunchKernelII)) {361if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))362cudaLaunchKernelFD = FD;363}364365if (cudaLaunchKernelFD == nullptr) {366CGM.Error(CGF.CurFuncDecl->getLocation(),367"Can't find declaration for " + LaunchKernelName);368return;369}370// Create temporary dim3 grid_dim, block_dim.371ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);372QualType Dim3Ty = GridDimParam->getType();373Address GridDim =374CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");375Address BlockDim =376CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim");377Address ShmemSize =378CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size");379Address Stream = CGF.CreateTempAlloca(PtrTy, CGM.getPointerAlign(), "stream");380llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(381llvm::FunctionType::get(IntTy,382{/*gridDim=*/GridDim.getType(),383/*blockDim=*/BlockDim.getType(),384/*ShmemSize=*/ShmemSize.getType(),385/*Stream=*/Stream.getType()},386/*isVarArg=*/false),387addUnderscoredPrefixToName("PopCallConfiguration"));388389CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn, {GridDim.emitRawPointer(CGF),390BlockDim.emitRawPointer(CGF),391ShmemSize.emitRawPointer(CGF),392Stream.emitRawPointer(CGF)});393394// Emit the call to cudaLaunch395llvm::Value *Kernel =396CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);397CallArgList LaunchKernelArgs;398LaunchKernelArgs.add(RValue::get(Kernel),399cudaLaunchKernelFD->getParamDecl(0)->getType());400LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);401LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);402LaunchKernelArgs.add(RValue::get(KernelArgs, CGF),403cudaLaunchKernelFD->getParamDecl(3)->getType());404LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),405cudaLaunchKernelFD->getParamDecl(4)->getType());406LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),407cudaLaunchKernelFD->getParamDecl(5)->getType());408409QualType QT = cudaLaunchKernelFD->getType();410QualType CQT = QT.getCanonicalType();411llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);412llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);413414const CGFunctionInfo &FI =415CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);416llvm::FunctionCallee cudaLaunchKernelFn =417CGM.CreateRuntimeFunction(FTy, LaunchKernelName);418CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),419LaunchKernelArgs);420421// To prevent CUDA device stub functions from being merged by ICF in MSVC422// environment, create an unique global variable for each kernel and write to423// the variable in the device stub.424if (CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() &&425!CGF.getLangOpts().HIP) {426llvm::Function *KernelFunction = llvm::cast<llvm::Function>(Kernel);427std::string GlobalVarName = (KernelFunction->getName() + ".id").str();428429llvm::GlobalVariable *HandleVar =430CGM.getModule().getNamedGlobal(GlobalVarName);431if (!HandleVar) {432HandleVar = new llvm::GlobalVariable(433CGM.getModule(), CGM.Int8Ty,434/*Constant=*/false, KernelFunction->getLinkage(),435llvm::ConstantInt::get(CGM.Int8Ty, 0), GlobalVarName);436HandleVar->setDSOLocal(KernelFunction->isDSOLocal());437HandleVar->setVisibility(KernelFunction->getVisibility());438if (KernelFunction->hasComdat())439HandleVar->setComdat(CGM.getModule().getOrInsertComdat(GlobalVarName));440}441442CGF.Builder.CreateAlignedStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),443HandleVar, CharUnits::One(),444/*IsVolatile=*/true);445}446447CGF.EmitBranch(EndBlock);448449CGF.EmitBlock(EndBlock);450}451452void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,453FunctionArgList &Args) {454// Emit a call to cudaSetupArgument for each arg in Args.455llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();456llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");457CharUnits Offset = CharUnits::Zero();458for (const VarDecl *A : Args) {459auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType());460Offset = Offset.alignTo(TInfo.Align);461llvm::Value *Args[] = {462CGF.Builder.CreatePointerCast(463CGF.GetAddrOfLocalVar(A).emitRawPointer(CGF), PtrTy),464llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()),465llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),466};467llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);468llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);469llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);470llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");471CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);472CGF.EmitBlock(NextBlock);473Offset += TInfo.Width;474}475476// Emit the call to cudaLaunch477llvm::FunctionCallee cudaLaunchFn = getLaunchFn();478llvm::Value *Arg =479CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);480CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);481CGF.EmitBranch(EndBlock);482483CGF.EmitBlock(EndBlock);484}485486// Replace the original variable Var with the address loaded from variable487// ManagedVar populated by HIP runtime.488static void replaceManagedVar(llvm::GlobalVariable *Var,489llvm::GlobalVariable *ManagedVar) {490SmallVector<SmallVector<llvm::User *, 8>, 8> WorkList;491for (auto &&VarUse : Var->uses()) {492WorkList.push_back({VarUse.getUser()});493}494while (!WorkList.empty()) {495auto &&WorkItem = WorkList.pop_back_val();496auto *U = WorkItem.back();497if (isa<llvm::ConstantExpr>(U)) {498for (auto &&UU : U->uses()) {499WorkItem.push_back(UU.getUser());500WorkList.push_back(WorkItem);501WorkItem.pop_back();502}503continue;504}505if (auto *I = dyn_cast<llvm::Instruction>(U)) {506llvm::Value *OldV = Var;507llvm::Instruction *NewV =508new llvm::LoadInst(Var->getType(), ManagedVar, "ld.managed", false,509llvm::Align(Var->getAlignment()), I);510WorkItem.pop_back();511// Replace constant expressions directly or indirectly using the managed512// variable with instructions.513for (auto &&Op : WorkItem) {514auto *CE = cast<llvm::ConstantExpr>(Op);515auto *NewInst = CE->getAsInstruction();516NewInst->insertBefore(*I->getParent(), I->getIterator());517NewInst->replaceUsesOfWith(OldV, NewV);518OldV = CE;519NewV = NewInst;520}521I->replaceUsesOfWith(OldV, NewV);522} else {523llvm_unreachable("Invalid use of managed variable");524}525}526}527528/// Creates a function that sets up state on the host side for CUDA objects that529/// have a presence on both the host and device sides. Specifically, registers530/// the host side of kernel functions and device global variables with the CUDA531/// runtime.532/// \code533/// void __cuda_register_globals(void** GpuBinaryHandle) {534/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);535/// ...536/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);537/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);538/// ...539/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);540/// }541/// \endcode542llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {543// No need to register anything544if (EmittedKernels.empty() && DeviceVars.empty())545return nullptr;546547llvm::Function *RegisterKernelsFunc = llvm::Function::Create(548getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,549addUnderscoredPrefixToName("_register_globals"), &TheModule);550llvm::BasicBlock *EntryBB =551llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);552CGBuilderTy Builder(CGM, Context);553Builder.SetInsertPoint(EntryBB);554555// void __cudaRegisterFunction(void **, const char *, char *, const char *,556// int, uint3*, uint3*, dim3*, dim3*, int*)557llvm::Type *RegisterFuncParams[] = {558PtrTy, PtrTy, PtrTy, PtrTy, IntTy,559PtrTy, PtrTy, PtrTy, PtrTy, llvm::PointerType::getUnqual(Context)};560llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(561llvm::FunctionType::get(IntTy, RegisterFuncParams, false),562addUnderscoredPrefixToName("RegisterFunction"));563564// Extract GpuBinaryHandle passed as the first argument passed to565// __cuda_register_globals() and generate __cudaRegisterFunction() call for566// each emitted kernel.567llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();568for (auto &&I : EmittedKernels) {569llvm::Constant *KernelName =570makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));571llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(PtrTy);572llvm::Value *Args[] = {573&GpuBinaryHandlePtr,574KernelHandles[I.Kernel->getName()],575KernelName,576KernelName,577llvm::ConstantInt::get(IntTy, -1),578NullPtr,579NullPtr,580NullPtr,581NullPtr,582llvm::ConstantPointerNull::get(llvm::PointerType::getUnqual(Context))};583Builder.CreateCall(RegisterFunc, Args);584}585586llvm::Type *VarSizeTy = IntTy;587// For HIP or CUDA 9.0+, device variable size is type of `size_t`.588if (CGM.getLangOpts().HIP ||589ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)590VarSizeTy = SizeTy;591592// void __cudaRegisterVar(void **, char *, char *, const char *,593// int, int, int, int)594llvm::Type *RegisterVarParams[] = {PtrTy, PtrTy, PtrTy, PtrTy,595IntTy, VarSizeTy, IntTy, IntTy};596llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(597llvm::FunctionType::get(VoidTy, RegisterVarParams, false),598addUnderscoredPrefixToName("RegisterVar"));599// void __hipRegisterManagedVar(void **, char *, char *, const char *,600// size_t, unsigned)601llvm::Type *RegisterManagedVarParams[] = {PtrTy, PtrTy, PtrTy,602PtrTy, VarSizeTy, IntTy};603llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction(604llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false),605addUnderscoredPrefixToName("RegisterManagedVar"));606// void __cudaRegisterSurface(void **, const struct surfaceReference *,607// const void **, const char *, int, int);608llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(609llvm::FunctionType::get(610VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy}, false),611addUnderscoredPrefixToName("RegisterSurface"));612// void __cudaRegisterTexture(void **, const struct textureReference *,613// const void **, const char *, int, int, int)614llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(615llvm::FunctionType::get(616VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy, IntTy}, false),617addUnderscoredPrefixToName("RegisterTexture"));618for (auto &&Info : DeviceVars) {619llvm::GlobalVariable *Var = Info.Var;620assert((!Var->isDeclaration() || Info.Flags.isManaged()) &&621"External variables should not show up here, except HIP managed "622"variables");623llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));624switch (Info.Flags.getKind()) {625case DeviceVarFlags::Variable: {626uint64_t VarSize =627CGM.getDataLayout().getTypeAllocSize(Var->getValueType());628if (Info.Flags.isManaged()) {629assert(Var->getName().ends_with(".managed") &&630"HIP managed variables not transformed");631auto *ManagedVar = CGM.getModule().getNamedGlobal(632Var->getName().drop_back(StringRef(".managed").size()));633llvm::Value *Args[] = {634&GpuBinaryHandlePtr,635ManagedVar,636Var,637VarName,638llvm::ConstantInt::get(VarSizeTy, VarSize),639llvm::ConstantInt::get(IntTy, Var->getAlignment())};640if (!Var->isDeclaration())641Builder.CreateCall(RegisterManagedVar, Args);642} else {643llvm::Value *Args[] = {644&GpuBinaryHandlePtr,645Var,646VarName,647VarName,648llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),649llvm::ConstantInt::get(VarSizeTy, VarSize),650llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),651llvm::ConstantInt::get(IntTy, 0)};652Builder.CreateCall(RegisterVar, Args);653}654break;655}656case DeviceVarFlags::Surface:657Builder.CreateCall(658RegisterSurf,659{&GpuBinaryHandlePtr, Var, VarName, VarName,660llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),661llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});662break;663case DeviceVarFlags::Texture:664Builder.CreateCall(665RegisterTex,666{&GpuBinaryHandlePtr, Var, VarName, VarName,667llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),668llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),669llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});670break;671}672}673674Builder.CreateRetVoid();675return RegisterKernelsFunc;676}677678/// Creates a global constructor function for the module:679///680/// For CUDA:681/// \code682/// void __cuda_module_ctor() {683/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);684/// __cuda_register_globals(Handle);685/// }686/// \endcode687///688/// For HIP:689/// \code690/// void __hip_module_ctor() {691/// if (__hip_gpubin_handle == 0) {692/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);693/// __hip_register_globals(__hip_gpubin_handle);694/// }695/// }696/// \endcode697llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {698bool IsHIP = CGM.getLangOpts().HIP;699bool IsCUDA = CGM.getLangOpts().CUDA;700// No need to generate ctors/dtors if there is no GPU binary.701StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;702if (CudaGpuBinaryFileName.empty() && !IsHIP)703return nullptr;704if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&705DeviceVars.empty())706return nullptr;707708// void __{cuda|hip}_register_globals(void* handle);709llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();710// We always need a function to pass in as callback. Create a dummy711// implementation if we don't need to register anything.712if (RelocatableDeviceCode && !RegisterGlobalsFunc)713RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());714715// void ** __{cuda|hip}RegisterFatBinary(void *);716llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(717llvm::FunctionType::get(PtrTy, PtrTy, false),718addUnderscoredPrefixToName("RegisterFatBinary"));719// struct { int magic, int version, void * gpu_binary, void * dont_care };720llvm::StructType *FatbinWrapperTy =721llvm::StructType::get(IntTy, IntTy, PtrTy, PtrTy);722723// Register GPU binary with the CUDA runtime, store returned handle in a724// global variable and save a reference in GpuBinaryHandle to be cleaned up725// in destructor on exit. Then associate all known kernels with the GPU binary726// handle so CUDA runtime can figure out what to call on the GPU side.727std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;728if (!CudaGpuBinaryFileName.empty()) {729auto VFS = CGM.getFileSystem();730auto CudaGpuBinaryOrErr =731VFS->getBufferForFile(CudaGpuBinaryFileName, -1, false);732if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {733CGM.getDiags().Report(diag::err_cannot_open_file)734<< CudaGpuBinaryFileName << EC.message();735return nullptr;736}737CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());738}739740llvm::Function *ModuleCtorFunc = llvm::Function::Create(741llvm::FunctionType::get(VoidTy, false),742llvm::GlobalValue::InternalLinkage,743addUnderscoredPrefixToName("_module_ctor"), &TheModule);744llvm::BasicBlock *CtorEntryBB =745llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);746CGBuilderTy CtorBuilder(CGM, Context);747748CtorBuilder.SetInsertPoint(CtorEntryBB);749750const char *FatbinConstantName;751const char *FatbinSectionName;752const char *ModuleIDSectionName;753StringRef ModuleIDPrefix;754llvm::Constant *FatBinStr;755unsigned FatMagic;756if (IsHIP) {757FatbinConstantName = ".hip_fatbin";758FatbinSectionName = ".hipFatBinSegment";759760ModuleIDSectionName = "__hip_module_id";761ModuleIDPrefix = "__hip_";762763if (CudaGpuBinary) {764// If fatbin is available from early finalization, create a string765// literal containing the fat binary loaded from the given file.766const unsigned HIPCodeObjectAlign = 4096;767FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",768FatbinConstantName, HIPCodeObjectAlign);769} else {770// If fatbin is not available, create an external symbol771// __hip_fatbin in section .hip_fatbin. The external symbol is supposed772// to contain the fat binary but will be populated somewhere else,773// e.g. by lld through link script.774FatBinStr = new llvm::GlobalVariable(775CGM.getModule(), CGM.Int8Ty,776/*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,777"__hip_fatbin_" + CGM.getContext().getCUIDHash(), nullptr,778llvm::GlobalVariable::NotThreadLocal);779cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);780}781782FatMagic = HIPFatMagic;783} else {784if (RelocatableDeviceCode)785FatbinConstantName = CGM.getTriple().isMacOSX()786? "__NV_CUDA,__nv_relfatbin"787: "__nv_relfatbin";788else789FatbinConstantName =790CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";791// NVIDIA's cuobjdump looks for fatbins in this section.792FatbinSectionName =793CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";794795ModuleIDSectionName = CGM.getTriple().isMacOSX()796? "__NV_CUDA,__nv_module_id"797: "__nv_module_id";798ModuleIDPrefix = "__nv_";799800// For CUDA, create a string literal containing the fat binary loaded from801// the given file.802FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",803FatbinConstantName, 8);804FatMagic = CudaFatMagic;805}806807// Create initialized wrapper structure that points to the loaded GPU binary808ConstantInitBuilder Builder(CGM);809auto Values = Builder.beginStruct(FatbinWrapperTy);810// Fatbin wrapper magic.811Values.addInt(IntTy, FatMagic);812// Fatbin version.813Values.addInt(IntTy, 1);814// Data.815Values.add(FatBinStr);816// Unused in fatbin v1.817Values.add(llvm::ConstantPointerNull::get(PtrTy));818llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(819addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),820/*constant*/ true);821FatbinWrapper->setSection(FatbinSectionName);822823// There is only one HIP fat binary per linked module, however there are824// multiple constructor functions. Make sure the fat binary is registered825// only once. The constructor functions are executed by the dynamic loader826// before the program gains control. The dynamic loader cannot execute the827// constructor functions concurrently since doing that would not guarantee828// thread safety of the loaded program. Therefore we can assume sequential829// execution of constructor functions here.830if (IsHIP) {831auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage832: llvm::GlobalValue::ExternalLinkage;833llvm::BasicBlock *IfBlock =834llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);835llvm::BasicBlock *ExitBlock =836llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);837// The name, size, and initialization pattern of this variable is part838// of HIP ABI.839GpuBinaryHandle = new llvm::GlobalVariable(840TheModule, PtrTy, /*isConstant=*/false, Linkage,841/*Initializer=*/842CudaGpuBinary ? llvm::ConstantPointerNull::get(PtrTy) : nullptr,843CudaGpuBinary844? "__hip_gpubin_handle"845: "__hip_gpubin_handle_" + CGM.getContext().getCUIDHash());846GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());847// Prevent the weak symbol in different shared libraries being merged.848if (Linkage != llvm::GlobalValue::InternalLinkage)849GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);850Address GpuBinaryAddr(851GpuBinaryHandle, PtrTy,852CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));853{854auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);855llvm::Constant *Zero =856llvm::Constant::getNullValue(HandleValue->getType());857llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);858CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);859}860{861CtorBuilder.SetInsertPoint(IfBlock);862// GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);863llvm::CallInst *RegisterFatbinCall =864CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);865CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);866CtorBuilder.CreateBr(ExitBlock);867}868{869CtorBuilder.SetInsertPoint(ExitBlock);870// Call __hip_register_globals(GpuBinaryHandle);871if (RegisterGlobalsFunc) {872auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);873CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);874}875}876} else if (!RelocatableDeviceCode) {877// Register binary with CUDA runtime. This is substantially different in878// default mode vs. separate compilation!879// GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);880llvm::CallInst *RegisterFatbinCall =881CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);882GpuBinaryHandle = new llvm::GlobalVariable(883TheModule, PtrTy, false, llvm::GlobalValue::InternalLinkage,884llvm::ConstantPointerNull::get(PtrTy), "__cuda_gpubin_handle");885GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());886CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,887CGM.getPointerAlign());888889// Call __cuda_register_globals(GpuBinaryHandle);890if (RegisterGlobalsFunc)891CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);892893// Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.894if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),895CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {896// void __cudaRegisterFatBinaryEnd(void **);897llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(898llvm::FunctionType::get(VoidTy, PtrTy, false),899"__cudaRegisterFatBinaryEnd");900CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);901}902} else {903// Generate a unique module ID.904SmallString<64> ModuleID;905llvm::raw_svector_ostream OS(ModuleID);906OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());907llvm::Constant *ModuleIDConstant = makeConstantArray(908std::string(ModuleID), "", ModuleIDSectionName, 32, /*AddNull=*/true);909910// Create an alias for the FatbinWrapper that nvcc will look for.911llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,912Twine("__fatbinwrap") + ModuleID, FatbinWrapper);913914// void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,915// void *, void (*)(void **))916SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");917RegisterLinkedBinaryName += ModuleID;918llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(919getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);920921assert(RegisterGlobalsFunc && "Expecting at least dummy function!");922llvm::Value *Args[] = {RegisterGlobalsFunc, FatbinWrapper, ModuleIDConstant,923makeDummyFunction(getCallbackFnTy())};924CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);925}926927// Create destructor and register it with atexit() the way NVCC does it. Doing928// it during regular destructor phase worked in CUDA before 9.2 but results in929// double-free in 9.2.930if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {931// extern "C" int atexit(void (*f)(void));932llvm::FunctionType *AtExitTy =933llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);934llvm::FunctionCallee AtExitFunc =935CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),936/*Local=*/true);937CtorBuilder.CreateCall(AtExitFunc, CleanupFn);938}939940CtorBuilder.CreateRetVoid();941return ModuleCtorFunc;942}943944/// Creates a global destructor function that unregisters the GPU code blob945/// registered by constructor.946///947/// For CUDA:948/// \code949/// void __cuda_module_dtor() {950/// __cudaUnregisterFatBinary(Handle);951/// }952/// \endcode953///954/// For HIP:955/// \code956/// void __hip_module_dtor() {957/// if (__hip_gpubin_handle) {958/// __hipUnregisterFatBinary(__hip_gpubin_handle);959/// __hip_gpubin_handle = 0;960/// }961/// }962/// \endcode963llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {964// No need for destructor if we don't have a handle to unregister.965if (!GpuBinaryHandle)966return nullptr;967968// void __cudaUnregisterFatBinary(void ** handle);969llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(970llvm::FunctionType::get(VoidTy, PtrTy, false),971addUnderscoredPrefixToName("UnregisterFatBinary"));972973llvm::Function *ModuleDtorFunc = llvm::Function::Create(974llvm::FunctionType::get(VoidTy, false),975llvm::GlobalValue::InternalLinkage,976addUnderscoredPrefixToName("_module_dtor"), &TheModule);977978llvm::BasicBlock *DtorEntryBB =979llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);980CGBuilderTy DtorBuilder(CGM, Context);981DtorBuilder.SetInsertPoint(DtorEntryBB);982983Address GpuBinaryAddr(984GpuBinaryHandle, GpuBinaryHandle->getValueType(),985CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));986auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);987// There is only one HIP fat binary per linked module, however there are988// multiple destructor functions. Make sure the fat binary is unregistered989// only once.990if (CGM.getLangOpts().HIP) {991llvm::BasicBlock *IfBlock =992llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);993llvm::BasicBlock *ExitBlock =994llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);995llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());996llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);997DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);998999DtorBuilder.SetInsertPoint(IfBlock);1000DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);1001DtorBuilder.CreateStore(Zero, GpuBinaryAddr);1002DtorBuilder.CreateBr(ExitBlock);10031004DtorBuilder.SetInsertPoint(ExitBlock);1005} else {1006DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);1007}1008DtorBuilder.CreateRetVoid();1009return ModuleDtorFunc;1010}10111012CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {1013return new CGNVCUDARuntime(CGM);1014}10151016void CGNVCUDARuntime::internalizeDeviceSideVar(1017const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) {1018// For -fno-gpu-rdc, host-side shadows of external declarations of device-side1019// global variables become internal definitions. These have to be internal in1020// order to prevent name conflicts with global host variables with the same1021// name in a different TUs.1022//1023// For -fgpu-rdc, the shadow variables should not be internalized because1024// they may be accessed by different TU.1025if (CGM.getLangOpts().GPURelocatableDeviceCode)1026return;10271028// __shared__ variables are odd. Shadows do get created, but1029// they are not registered with the CUDA runtime, so they1030// can't really be used to access their device-side1031// counterparts. It's not clear yet whether it's nvcc's bug or1032// a feature, but we've got to do the same for compatibility.1033if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||1034D->hasAttr<CUDASharedAttr>() ||1035D->getType()->isCUDADeviceBuiltinSurfaceType() ||1036D->getType()->isCUDADeviceBuiltinTextureType()) {1037Linkage = llvm::GlobalValue::InternalLinkage;1038}1039}10401041void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D,1042llvm::GlobalVariable &GV) {1043if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {1044// Shadow variables and their properties must be registered with CUDA1045// runtime. Skip Extern global variables, which will be registered in1046// the TU where they are defined.1047//1048// Don't register a C++17 inline variable. The local symbol can be1049// discarded and referencing a discarded local symbol from outside the1050// comdat (__cuda_register_globals) is disallowed by the ELF spec.1051//1052// HIP managed variables need to be always recorded in device and host1053// compilations for transformation.1054//1055// HIP managed variables and variables in CUDADeviceVarODRUsedByHost are1056// added to llvm.compiler-used, therefore they are safe to be registered.1057if ((!D->hasExternalStorage() && !D->isInline()) ||1058CGM.getContext().CUDADeviceVarODRUsedByHost.contains(D) ||1059D->hasAttr<HIPManagedAttr>()) {1060registerDeviceVar(D, GV, !D->hasDefinition(),1061D->hasAttr<CUDAConstantAttr>());1062}1063} else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||1064D->getType()->isCUDADeviceBuiltinTextureType()) {1065// Builtin surfaces and textures and their template arguments are1066// also registered with CUDA runtime.1067const auto *TD = cast<ClassTemplateSpecializationDecl>(1068D->getType()->castAs<RecordType>()->getDecl());1069const TemplateArgumentList &Args = TD->getTemplateArgs();1070if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {1071assert(Args.size() == 2 &&1072"Unexpected number of template arguments of CUDA device "1073"builtin surface type.");1074auto SurfType = Args[1].getAsIntegral();1075if (!D->hasExternalStorage())1076registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue());1077} else {1078assert(Args.size() == 3 &&1079"Unexpected number of template arguments of CUDA device "1080"builtin texture type.");1081auto TexType = Args[1].getAsIntegral();1082auto Normalized = Args[2].getAsIntegral();1083if (!D->hasExternalStorage())1084registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(),1085Normalized.getZExtValue());1086}1087}1088}10891090// Transform managed variables to pointers to managed variables in device code.1091// Each use of the original managed variable is replaced by a load from the1092// transformed managed variable. The transformed managed variable contains1093// the address of managed memory which will be allocated by the runtime.1094void CGNVCUDARuntime::transformManagedVars() {1095for (auto &&Info : DeviceVars) {1096llvm::GlobalVariable *Var = Info.Var;1097if (Info.Flags.getKind() == DeviceVarFlags::Variable &&1098Info.Flags.isManaged()) {1099auto *ManagedVar = new llvm::GlobalVariable(1100CGM.getModule(), Var->getType(),1101/*isConstant=*/false, Var->getLinkage(),1102/*Init=*/Var->isDeclaration()1103? nullptr1104: llvm::ConstantPointerNull::get(Var->getType()),1105/*Name=*/"", /*InsertBefore=*/nullptr,1106llvm::GlobalVariable::NotThreadLocal,1107CGM.getContext().getTargetAddressSpace(CGM.getLangOpts().CUDAIsDevice1108? LangAS::cuda_device1109: LangAS::Default));1110ManagedVar->setDSOLocal(Var->isDSOLocal());1111ManagedVar->setVisibility(Var->getVisibility());1112ManagedVar->setExternallyInitialized(true);1113replaceManagedVar(Var, ManagedVar);1114ManagedVar->takeName(Var);1115Var->setName(Twine(ManagedVar->getName()) + ".managed");1116// Keep managed variables even if they are not used in device code since1117// they need to be allocated by the runtime.1118if (CGM.getLangOpts().CUDAIsDevice && !Var->isDeclaration()) {1119assert(!ManagedVar->isDeclaration());1120CGM.addCompilerUsedGlobal(Var);1121CGM.addCompilerUsedGlobal(ManagedVar);1122}1123}1124}1125}11261127// Creates offloading entries for all the kernels and globals that must be1128// registered. The linker will provide a pointer to this section so we can1129// register the symbols with the linked device image.1130void CGNVCUDARuntime::createOffloadingEntries() {1131StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"1132: "cuda_offloading_entries";1133llvm::Module &M = CGM.getModule();1134for (KernelInfo &I : EmittedKernels)1135llvm::offloading::emitOffloadingEntry(1136M, KernelHandles[I.Kernel->getName()],1137getDeviceSideName(cast<NamedDecl>(I.D)), /*Flags=*/0, /*Data=*/0,1138llvm::offloading::OffloadGlobalEntry, Section);11391140for (VarInfo &I : DeviceVars) {1141uint64_t VarSize =1142CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());1143int32_t Flags =1144(I.Flags.isExtern()1145? static_cast<int32_t>(llvm::offloading::OffloadGlobalExtern)1146: 0) |1147(I.Flags.isConstant()1148? static_cast<int32_t>(llvm::offloading::OffloadGlobalConstant)1149: 0) |1150(I.Flags.isNormalized()1151? static_cast<int32_t>(llvm::offloading::OffloadGlobalNormalized)1152: 0);1153if (I.Flags.getKind() == DeviceVarFlags::Variable) {1154llvm::offloading::emitOffloadingEntry(1155M, I.Var, getDeviceSideName(I.D), VarSize,1156(I.Flags.isManaged() ? llvm::offloading::OffloadGlobalManagedEntry1157: llvm::offloading::OffloadGlobalEntry) |1158Flags,1159/*Data=*/0, Section);1160} else if (I.Flags.getKind() == DeviceVarFlags::Surface) {1161llvm::offloading::emitOffloadingEntry(1162M, I.Var, getDeviceSideName(I.D), VarSize,1163llvm::offloading::OffloadGlobalSurfaceEntry | Flags,1164I.Flags.getSurfTexType(), Section);1165} else if (I.Flags.getKind() == DeviceVarFlags::Texture) {1166llvm::offloading::emitOffloadingEntry(1167M, I.Var, getDeviceSideName(I.D), VarSize,1168llvm::offloading::OffloadGlobalTextureEntry | Flags,1169I.Flags.getSurfTexType(), Section);1170}1171}1172}11731174// Returns module constructor to be added.1175llvm::Function *CGNVCUDARuntime::finalizeModule() {1176transformManagedVars();1177if (CGM.getLangOpts().CUDAIsDevice) {1178// Mark ODR-used device variables as compiler used to prevent it from being1179// eliminated by optimization. This is necessary for device variables1180// ODR-used by host functions. Sema correctly marks them as ODR-used no1181// matter whether they are ODR-used by device or host functions.1182//1183// We do not need to do this if the variable has used attribute since it1184// has already been added.1185//1186// Static device variables have been externalized at this point, therefore1187// variables with LLVM private or internal linkage need not be added.1188for (auto &&Info : DeviceVars) {1189auto Kind = Info.Flags.getKind();1190if (!Info.Var->isDeclaration() &&1191!llvm::GlobalValue::isLocalLinkage(Info.Var->getLinkage()) &&1192(Kind == DeviceVarFlags::Variable ||1193Kind == DeviceVarFlags::Surface ||1194Kind == DeviceVarFlags::Texture) &&1195Info.D->isUsed() && !Info.D->hasAttr<UsedAttr>()) {1196CGM.addCompilerUsedGlobal(Info.Var);1197}1198}1199return nullptr;1200}1201if (CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode)1202createOffloadingEntries();1203else1204return makeModuleCtorFunction();12051206return nullptr;1207}12081209llvm::GlobalValue *CGNVCUDARuntime::getKernelHandle(llvm::Function *F,1210GlobalDecl GD) {1211auto Loc = KernelHandles.find(F->getName());1212if (Loc != KernelHandles.end()) {1213auto OldHandle = Loc->second;1214if (KernelStubs[OldHandle] == F)1215return OldHandle;12161217// We've found the function name, but F itself has changed, so we need to1218// update the references.1219if (CGM.getLangOpts().HIP) {1220// For HIP compilation the handle itself does not change, so we only need1221// to update the Stub value.1222KernelStubs[OldHandle] = F;1223return OldHandle;1224}1225// For non-HIP compilation, erase the old Stub and fall-through to creating1226// new entries.1227KernelStubs.erase(OldHandle);1228}12291230if (!CGM.getLangOpts().HIP) {1231KernelHandles[F->getName()] = F;1232KernelStubs[F] = F;1233return F;1234}12351236auto *Var = new llvm::GlobalVariable(1237TheModule, F->getType(), /*isConstant=*/true, F->getLinkage(),1238/*Initializer=*/nullptr,1239CGM.getMangledName(1240GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel)));1241Var->setAlignment(CGM.getPointerAlign().getAsAlign());1242Var->setDSOLocal(F->isDSOLocal());1243Var->setVisibility(F->getVisibility());1244auto *FD = cast<FunctionDecl>(GD.getDecl());1245auto *FT = FD->getPrimaryTemplate();1246if (!FT || FT->isThisDeclarationADefinition())1247CGM.maybeSetTrivialComdat(*FD, *Var);1248KernelHandles[F->getName()] = Var;1249KernelStubs[Var] = F;1250return Var;1251}125212531254