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 "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/IR/BasicBlock.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/Support/Format.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 namespace {
30 constexpr unsigned CudaFatMagic = 0x466243b1;
31 constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
32 
33 class CGNVCUDARuntime : public CGCUDARuntime {
34 
35 private:
36   llvm::IntegerType *IntTy, *SizeTy;
37   llvm::Type *VoidTy;
38   llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
39 
40   /// Convenience reference to LLVM Context
41   llvm::LLVMContext &Context;
42   /// Convenience reference to the current module
43   llvm::Module &TheModule;
44   /// Keeps track of kernel launch stubs emitted in this module
45   struct KernelInfo {
46     llvm::Function *Kernel;
47     const Decl *D;
48   };
49   llvm::SmallVector<KernelInfo, 16> EmittedKernels;
50   struct VarInfo {
51     llvm::GlobalVariable *Var;
52     const VarDecl *D;
53     DeviceVarFlags Flags;
54   };
55   llvm::SmallVector<VarInfo, 16> DeviceVars;
56   /// Keeps track of variable containing handle of GPU binary. Populated by
57   /// ModuleCtorFunction() and used to create corresponding cleanup calls in
58   /// ModuleDtorFunction()
59   llvm::GlobalVariable *GpuBinaryHandle = nullptr;
60   /// Whether we generate relocatable device code.
61   bool RelocatableDeviceCode;
62   /// Mangle context for device.
63   std::unique_ptr<MangleContext> DeviceMC;
64 
65   llvm::FunctionCallee getSetupArgumentFn() const;
66   llvm::FunctionCallee getLaunchFn() const;
67 
68   llvm::FunctionType *getRegisterGlobalsFnTy() const;
69   llvm::FunctionType *getCallbackFnTy() const;
70   llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
71   std::string addPrefixToName(StringRef FuncName) const;
72   std::string addUnderscoredPrefixToName(StringRef FuncName) const;
73 
74   /// Creates a function to register all kernel stubs generated in this module.
75   llvm::Function *makeRegisterGlobalsFn();
76 
77   /// Helper function that generates a constant string and returns a pointer to
78   /// the start of the string.  The result of this function can be used anywhere
79   /// where the C code specifies const char*.
makeConstantString(const std::string & Str,const std::string & Name="",const std::string & SectionName="",unsigned Alignment=0)80   llvm::Constant *makeConstantString(const std::string &Str,
81                                      const std::string &Name = "",
82                                      const std::string &SectionName = "",
83                                      unsigned Alignment = 0) {
84     llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
85                                llvm::ConstantInt::get(SizeTy, 0)};
86     auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
87     llvm::GlobalVariable *GV =
88         cast<llvm::GlobalVariable>(ConstStr.getPointer());
89     if (!SectionName.empty()) {
90       GV->setSection(SectionName);
91       // Mark the address as used which make sure that this section isn't
92       // merged and we will really have it in the object file.
93       GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
94     }
95     if (Alignment)
96       GV->setAlignment(llvm::Align(Alignment));
97 
98     return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
99                                                 ConstStr.getPointer(), Zeros);
100   }
101 
102   /// Helper function that generates an empty dummy function returning void.
makeDummyFunction(llvm::FunctionType * FnTy)103   llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
104     assert(FnTy->getReturnType()->isVoidTy() &&
105            "Can only generate dummy functions returning void!");
106     llvm::Function *DummyFunc = llvm::Function::Create(
107         FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
108 
109     llvm::BasicBlock *DummyBlock =
110         llvm::BasicBlock::Create(Context, "", DummyFunc);
111     CGBuilderTy FuncBuilder(CGM, Context);
112     FuncBuilder.SetInsertPoint(DummyBlock);
113     FuncBuilder.CreateRetVoid();
114 
115     return DummyFunc;
116   }
117 
118   void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
119   void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
120   std::string getDeviceSideName(const NamedDecl *ND) override;
121 
122 public:
123   CGNVCUDARuntime(CodeGenModule &CGM);
124 
125   void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
registerDeviceVar(const VarDecl * VD,llvm::GlobalVariable & Var,bool Extern,bool Constant)126   void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
127                          bool Extern, bool Constant) override {
128     DeviceVars.push_back({&Var,
129                           VD,
130                           {DeviceVarFlags::Variable, Extern, Constant,
131                            /*Normalized*/ false, /*Type*/ 0}});
132   }
registerDeviceSurf(const VarDecl * VD,llvm::GlobalVariable & Var,bool Extern,int Type)133   void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,
134                           bool Extern, int Type) override {
135     DeviceVars.push_back({&Var,
136                           VD,
137                           {DeviceVarFlags::Surface, Extern, /*Constant*/ false,
138                            /*Normalized*/ false, Type}});
139   }
registerDeviceTex(const VarDecl * VD,llvm::GlobalVariable & Var,bool Extern,int Type,bool Normalized)140   void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,
141                          bool Extern, int Type, bool Normalized) override {
142     DeviceVars.push_back({&Var,
143                           VD,
144                           {DeviceVarFlags::Texture, Extern, /*Constant*/ false,
145                            Normalized, Type}});
146   }
147 
148   /// Creates module constructor function
149   llvm::Function *makeModuleCtorFunction() override;
150   /// Creates module destructor function
151   llvm::Function *makeModuleDtorFunction() override;
152 };
153 
154 }
155 
addPrefixToName(StringRef FuncName) const156 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
157   if (CGM.getLangOpts().HIP)
158     return ((Twine("hip") + Twine(FuncName)).str());
159   return ((Twine("cuda") + Twine(FuncName)).str());
160 }
161 std::string
addUnderscoredPrefixToName(StringRef FuncName) const162 CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
163   if (CGM.getLangOpts().HIP)
164     return ((Twine("__hip") + Twine(FuncName)).str());
165   return ((Twine("__cuda") + Twine(FuncName)).str());
166 }
167 
CGNVCUDARuntime(CodeGenModule & CGM)168 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
169     : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
170       TheModule(CGM.getModule()),
171       RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
172       DeviceMC(CGM.getContext().createMangleContext(
173           CGM.getContext().getAuxTargetInfo())) {
174   CodeGen::CodeGenTypes &Types = CGM.getTypes();
175   ASTContext &Ctx = CGM.getContext();
176 
177   IntTy = CGM.IntTy;
178   SizeTy = CGM.SizeTy;
179   VoidTy = CGM.VoidTy;
180 
181   unsigned DefaultAS = CGM.getTargetCodeGenInfo().getDefaultAS();
182   CharPtrTy = llvm::PointerType::get(Types.ConvertType(Ctx.CharTy), DefaultAS);
183   VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
184   VoidPtrPtrTy = VoidPtrTy->getPointerTo(DefaultAS);
185 }
186 
getSetupArgumentFn() const187 llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
188   // cudaError_t cudaSetupArgument(void *, size_t, size_t)
189   llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
190   return CGM.CreateRuntimeFunction(
191       llvm::FunctionType::get(IntTy, Params, false),
192       addPrefixToName("SetupArgument"));
193 }
194 
getLaunchFn() const195 llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
196   if (CGM.getLangOpts().HIP) {
197     // hipError_t hipLaunchByPtr(char *);
198     return CGM.CreateRuntimeFunction(
199         llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
200   } else {
201     // cudaError_t cudaLaunch(char *);
202     return CGM.CreateRuntimeFunction(
203         llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
204   }
205 }
206 
getRegisterGlobalsFnTy() const207 llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
208   return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
209 }
210 
getCallbackFnTy() const211 llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
212   return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
213 }
214 
getRegisterLinkedBinaryFnTy() const215 llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
216   auto CallbackFnTy = getCallbackFnTy();
217   auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
218   llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
219                           VoidPtrTy, CallbackFnTy->getPointerTo()};
220   return llvm::FunctionType::get(VoidTy, Params, false);
221 }
222 
getDeviceSideName(const NamedDecl * ND)223 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
224   GlobalDecl GD;
225   // D could be either a kernel or a variable.
226   if (auto *FD = dyn_cast<FunctionDecl>(ND))
227     GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
228   else
229     GD = GlobalDecl(ND);
230   std::string DeviceSideName;
231   if (DeviceMC->shouldMangleDeclName(ND)) {
232     SmallString<256> Buffer;
233     llvm::raw_svector_ostream Out(Buffer);
234     DeviceMC->mangleName(GD, Out);
235     DeviceSideName = std::string(Out.str());
236   } else
237     DeviceSideName = std::string(ND->getIdentifier()->getName());
238   return DeviceSideName;
239 }
240 
emitDeviceStub(CodeGenFunction & CGF,FunctionArgList & Args)241 void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
242                                      FunctionArgList &Args) {
243   EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
244   if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
245                          CudaFeature::CUDA_USES_NEW_LAUNCH) ||
246       (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI))
247     emitDeviceStubBodyNew(CGF, Args);
248   else
249     emitDeviceStubBodyLegacy(CGF, Args);
250 }
251 
252 // CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
253 // array and kernels are launched using cudaLaunchKernel().
emitDeviceStubBodyNew(CodeGenFunction & CGF,FunctionArgList & Args)254 void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
255                                             FunctionArgList &Args) {
256   // Build the shadow stack entry at the very start of the function.
257 
258   // Calculate amount of space we will need for all arguments.  If we have no
259   // args, allocate a single pointer so we still have a valid pointer to the
260   // argument array that we can pass to runtime, even if it will be unused.
261   Address KernelArgs = CGF.CreateTempAlloca(
262       VoidPtrTy, CharUnits::fromQuantity(16), "kernel_args",
263       llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
264   // Store pointers to the arguments in a locally allocated launch_args.
265   for (unsigned i = 0; i < Args.size(); ++i) {
266     llvm::Value* VarPtr = CGF.GetAddrOfLocalVar(Args[i]).getPointer();
267     llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, VoidPtrTy);
268     CGF.Builder.CreateDefaultAlignedStore(
269         VoidVarPtr, CGF.Builder.CreateConstGEP1_32(KernelArgs.getPointer(), i));
270   }
271 
272   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
273 
274   // Lookup cudaLaunchKernel/hipLaunchKernel function.
275   // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
276   //                              void **args, size_t sharedMem,
277   //                              cudaStream_t stream);
278   // hipError_t hipLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
279   //                            void **args, size_t sharedMem,
280   //                            hipStream_t stream);
281   TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
282   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
283   auto LaunchKernelName = addPrefixToName("LaunchKernel");
284   IdentifierInfo &cudaLaunchKernelII =
285       CGM.getContext().Idents.get(LaunchKernelName);
286   FunctionDecl *cudaLaunchKernelFD = nullptr;
287   for (const auto &Result : DC->lookup(&cudaLaunchKernelII)) {
288     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
289       cudaLaunchKernelFD = FD;
290   }
291 
292   if (cudaLaunchKernelFD == nullptr) {
293     CGM.Error(CGF.CurFuncDecl->getLocation(),
294               "Can't find declaration for " + LaunchKernelName);
295     return;
296   }
297   // Create temporary dim3 grid_dim, block_dim.
298   ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
299   QualType Dim3Ty = GridDimParam->getType();
300   Address GridDim =
301       CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
302   Address BlockDim =
303       CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
304   Address ShmemSize =
305       CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size");
306   Address Stream =
307       CGF.CreateTempAlloca(VoidPtrTy, CGM.getPointerAlign(), "stream");
308   llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
309       llvm::FunctionType::get(IntTy,
310                               {/*gridDim=*/GridDim.getType(),
311                                /*blockDim=*/BlockDim.getType(),
312                                /*ShmemSize=*/ShmemSize.getType(),
313                                /*Stream=*/Stream.getType()},
314                               /*isVarArg=*/false),
315       addUnderscoredPrefixToName("PopCallConfiguration"));
316 
317   CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn,
318                               {GridDim.getPointer(), BlockDim.getPointer(),
319                                ShmemSize.getPointer(), Stream.getPointer()});
320 
321   // Emit the call to cudaLaunch
322   llvm::Value *Kernel = CGF.Builder.CreatePointerCast(CGF.CurFn, VoidPtrTy);
323   CallArgList LaunchKernelArgs;
324   LaunchKernelArgs.add(RValue::get(Kernel),
325                        cudaLaunchKernelFD->getParamDecl(0)->getType());
326   LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
327   LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
328   LaunchKernelArgs.add(RValue::get(KernelArgs.getPointer()),
329                        cudaLaunchKernelFD->getParamDecl(3)->getType());
330   LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
331                        cudaLaunchKernelFD->getParamDecl(4)->getType());
332   LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
333                        cudaLaunchKernelFD->getParamDecl(5)->getType());
334 
335   QualType QT = cudaLaunchKernelFD->getType();
336   QualType CQT = QT.getCanonicalType();
337   llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
338   llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(Ty);
339 
340   const CGFunctionInfo &FI =
341       CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
342   llvm::FunctionCallee cudaLaunchKernelFn =
343       CGM.CreateRuntimeFunction(FTy, LaunchKernelName);
344   CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
345                LaunchKernelArgs);
346   CGF.EmitBranch(EndBlock);
347 
348   CGF.EmitBlock(EndBlock);
349 }
350 
emitDeviceStubBodyLegacy(CodeGenFunction & CGF,FunctionArgList & Args)351 void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
352                                                FunctionArgList &Args) {
353   // Emit a call to cudaSetupArgument for each arg in Args.
354   llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
355   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
356   CharUnits Offset = CharUnits::Zero();
357   for (const VarDecl *A : Args) {
358     CharUnits TyWidth, TyAlign;
359     std::tie(TyWidth, TyAlign) =
360         CGM.getContext().getTypeInfoInChars(A->getType());
361     Offset = Offset.alignTo(TyAlign);
362     llvm::Value *Args[] = {
363         CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
364                                       VoidPtrTy),
365         llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
366         llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
367     };
368     llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
369     llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
370     llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
371     llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
372     CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
373     CGF.EmitBlock(NextBlock);
374     Offset += TyWidth;
375   }
376 
377   // Emit the call to cudaLaunch
378   llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
379   llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
380   CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
381   CGF.EmitBranch(EndBlock);
382 
383   CGF.EmitBlock(EndBlock);
384 }
385 
386 /// Creates a function that sets up state on the host side for CUDA objects that
387 /// have a presence on both the host and device sides. Specifically, registers
388 /// the host side of kernel functions and device global variables with the CUDA
389 /// runtime.
390 /// \code
391 /// void __cuda_register_globals(void** GpuBinaryHandle) {
392 ///    __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
393 ///    ...
394 ///    __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
395 ///    __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
396 ///    ...
397 ///    __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
398 /// }
399 /// \endcode
makeRegisterGlobalsFn()400 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
401   // No need to register anything
402   if (EmittedKernels.empty() && DeviceVars.empty())
403     return nullptr;
404 
405   llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
406       getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
407       addUnderscoredPrefixToName("_register_globals"), &TheModule);
408   llvm::BasicBlock *EntryBB =
409       llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
410   CGBuilderTy Builder(CGM, Context);
411   Builder.SetInsertPoint(EntryBB);
412 
413   unsigned DefaultAS = CGM.getTargetCodeGenInfo().getDefaultAS();
414   // void __cudaRegisterFunction(void **, const char *, char *, const char *,
415   //                             int, uint3*, uint3*, dim3*, dim3*, int*)
416   llvm::Type *RegisterFuncParams[] = {
417       VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
418       VoidPtrTy,    VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo(DefaultAS)};
419   llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
420       llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
421       addUnderscoredPrefixToName("RegisterFunction"));
422 
423   // Extract GpuBinaryHandle passed as the first argument passed to
424   // __cuda_register_globals() and generate __cudaRegisterFunction() call for
425   // each emitted kernel.
426   llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
427   for (auto &&I : EmittedKernels) {
428     llvm::Constant *KernelName =
429         makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));
430     llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
431     llvm::Value *Args[] = {
432         &GpuBinaryHandlePtr,
433         Builder.CreateBitCast(I.Kernel, VoidPtrTy),
434         KernelName,
435         KernelName,
436         llvm::ConstantInt::get(IntTy, -1),
437         NullPtr,
438         NullPtr,
439         NullPtr,
440         NullPtr,
441         llvm::ConstantPointerNull::get(IntTy->getPointerTo(DefaultAS))};
442     Builder.CreateCall(RegisterFunc, Args);
443   }
444 
445   llvm::Type *VarSizeTy = IntTy;
446   // For HIP or CUDA 9.0+, device variable size is type of `size_t`.
447   if (CGM.getLangOpts().HIP ||
448       ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)
449     VarSizeTy = SizeTy;
450 
451   // void __cudaRegisterVar(void **, char *, char *, const char *,
452   //                        int, int, int, int)
453   llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
454                                      CharPtrTy,    IntTy,     VarSizeTy,
455                                      IntTy,        IntTy};
456   llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
457       llvm::FunctionType::get(VoidTy, RegisterVarParams, false),
458       addUnderscoredPrefixToName("RegisterVar"));
459   // void __cudaRegisterSurface(void **, const struct surfaceReference *,
460   //                            const void **, const char *, int, int);
461   llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(
462       llvm::FunctionType::get(
463           VoidTy, {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy},
464           false),
465       addUnderscoredPrefixToName("RegisterSurface"));
466   // void __cudaRegisterTexture(void **, const struct textureReference *,
467   //                            const void **, const char *, int, int, int)
468   llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(
469       llvm::FunctionType::get(
470           VoidTy,
471           {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy, IntTy},
472           false),
473       addUnderscoredPrefixToName("RegisterTexture"));
474   for (auto &&Info : DeviceVars) {
475     llvm::GlobalVariable *Var = Info.Var;
476     llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
477     switch (Info.Flags.getKind()) {
478     case DeviceVarFlags::Variable: {
479       uint64_t VarSize =
480           CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
481       llvm::Value *Args[] = {
482           &GpuBinaryHandlePtr,
483           Builder.CreateBitCast(Var, VoidPtrTy),
484           VarName,
485           VarName,
486           llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),
487           llvm::ConstantInt::get(VarSizeTy, VarSize),
488           llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),
489           llvm::ConstantInt::get(IntTy, 0)};
490       Builder.CreateCall(RegisterVar, Args);
491       break;
492     }
493     case DeviceVarFlags::Surface:
494       Builder.CreateCall(
495           RegisterSurf,
496           {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
497            VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
498            llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
499       break;
500     case DeviceVarFlags::Texture:
501       Builder.CreateCall(
502           RegisterTex,
503           {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
504            VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
505            llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),
506            llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
507       break;
508     }
509   }
510 
511   Builder.CreateRetVoid();
512   return RegisterKernelsFunc;
513 }
514 
515 /// Creates a global constructor function for the module:
516 ///
517 /// For CUDA:
518 /// \code
519 /// void __cuda_module_ctor(void*) {
520 ///     Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
521 ///     __cuda_register_globals(Handle);
522 /// }
523 /// \endcode
524 ///
525 /// For HIP:
526 /// \code
527 /// void __hip_module_ctor(void*) {
528 ///     if (__hip_gpubin_handle == 0) {
529 ///         __hip_gpubin_handle  = __hipRegisterFatBinary(GpuBinaryBlob);
530 ///         __hip_register_globals(__hip_gpubin_handle);
531 ///     }
532 /// }
533 /// \endcode
makeModuleCtorFunction()534 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
535   bool IsHIP = CGM.getLangOpts().HIP;
536   bool IsCUDA = CGM.getLangOpts().CUDA;
537   // No need to generate ctors/dtors if there is no GPU binary.
538   StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
539   if (CudaGpuBinaryFileName.empty() && !IsHIP)
540     return nullptr;
541   if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&
542       DeviceVars.empty())
543     return nullptr;
544 
545   // void __{cuda|hip}_register_globals(void* handle);
546   llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
547   // We always need a function to pass in as callback. Create a dummy
548   // implementation if we don't need to register anything.
549   if (RelocatableDeviceCode && !RegisterGlobalsFunc)
550     RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
551 
552   // void ** __{cuda|hip}RegisterFatBinary(void *);
553   llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
554       llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
555       addUnderscoredPrefixToName("RegisterFatBinary"));
556   // struct { int magic, int version, void * gpu_binary, void * dont_care };
557   llvm::StructType *FatbinWrapperTy =
558       llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
559 
560   // Register GPU binary with the CUDA runtime, store returned handle in a
561   // global variable and save a reference in GpuBinaryHandle to be cleaned up
562   // in destructor on exit. Then associate all known kernels with the GPU binary
563   // handle so CUDA runtime can figure out what to call on the GPU side.
564   std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
565   if (!CudaGpuBinaryFileName.empty()) {
566     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
567         llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
568     if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
569       CGM.getDiags().Report(diag::err_cannot_open_file)
570           << CudaGpuBinaryFileName << EC.message();
571       return nullptr;
572     }
573     CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
574   }
575 
576   llvm::Function *ModuleCtorFunc = llvm::Function::Create(
577       llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
578       llvm::GlobalValue::InternalLinkage,
579       addUnderscoredPrefixToName("_module_ctor"), &TheModule);
580   llvm::BasicBlock *CtorEntryBB =
581       llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
582   CGBuilderTy CtorBuilder(CGM, Context);
583 
584   CtorBuilder.SetInsertPoint(CtorEntryBB);
585 
586   const char *FatbinConstantName;
587   const char *FatbinSectionName;
588   const char *ModuleIDSectionName;
589   StringRef ModuleIDPrefix;
590   llvm::Constant *FatBinStr;
591   unsigned FatMagic;
592   if (IsHIP) {
593     FatbinConstantName = ".hip_fatbin";
594     FatbinSectionName = ".hipFatBinSegment";
595 
596     ModuleIDSectionName = "__hip_module_id";
597     ModuleIDPrefix = "__hip_";
598 
599     if (CudaGpuBinary) {
600       // If fatbin is available from early finalization, create a string
601       // literal containing the fat binary loaded from the given file.
602       FatBinStr = makeConstantString(std::string(CudaGpuBinary->getBuffer()),
603                                      "", FatbinConstantName, 8);
604     } else {
605       // If fatbin is not available, create an external symbol
606       // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
607       // to contain the fat binary but will be populated somewhere else,
608       // e.g. by lld through link script.
609       FatBinStr = new llvm::GlobalVariable(
610         CGM.getModule(), CGM.Int8Ty,
611         /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
612         "__hip_fatbin", nullptr,
613         llvm::GlobalVariable::NotThreadLocal);
614       cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
615     }
616 
617     FatMagic = HIPFatMagic;
618   } else {
619     if (RelocatableDeviceCode)
620       FatbinConstantName = CGM.getTriple().isMacOSX()
621                                ? "__NV_CUDA,__nv_relfatbin"
622                                : "__nv_relfatbin";
623     else
624       FatbinConstantName =
625           CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
626     // NVIDIA's cuobjdump looks for fatbins in this section.
627     FatbinSectionName =
628         CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
629 
630     ModuleIDSectionName = CGM.getTriple().isMacOSX()
631                               ? "__NV_CUDA,__nv_module_id"
632                               : "__nv_module_id";
633     ModuleIDPrefix = "__nv_";
634 
635     // For CUDA, create a string literal containing the fat binary loaded from
636     // the given file.
637     FatBinStr = makeConstantString(std::string(CudaGpuBinary->getBuffer()), "",
638                                    FatbinConstantName, 8);
639     FatMagic = CudaFatMagic;
640   }
641 
642   // Create initialized wrapper structure that points to the loaded GPU binary
643   ConstantInitBuilder Builder(CGM);
644   auto Values = Builder.beginStruct(FatbinWrapperTy);
645   // Fatbin wrapper magic.
646   Values.addInt(IntTy, FatMagic);
647   // Fatbin version.
648   Values.addInt(IntTy, 1);
649   // Data.
650   Values.add(FatBinStr);
651   // Unused in fatbin v1.
652   Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
653   llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
654       addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
655       /*constant*/ true);
656   FatbinWrapper->setSection(FatbinSectionName);
657 
658   // There is only one HIP fat binary per linked module, however there are
659   // multiple constructor functions. Make sure the fat binary is registered
660   // only once. The constructor functions are executed by the dynamic loader
661   // before the program gains control. The dynamic loader cannot execute the
662   // constructor functions concurrently since doing that would not guarantee
663   // thread safety of the loaded program. Therefore we can assume sequential
664   // execution of constructor functions here.
665   if (IsHIP) {
666     auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage :
667         llvm::GlobalValue::LinkOnceAnyLinkage;
668     llvm::BasicBlock *IfBlock =
669         llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
670     llvm::BasicBlock *ExitBlock =
671         llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
672     // The name, size, and initialization pattern of this variable is part
673     // of HIP ABI.
674     GpuBinaryHandle = new llvm::GlobalVariable(
675         TheModule, VoidPtrPtrTy, /*isConstant=*/false,
676         Linkage,
677         /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
678         "__hip_gpubin_handle");
679     GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
680     // Prevent the weak symbol in different shared libraries being merged.
681     if (Linkage != llvm::GlobalValue::InternalLinkage)
682       GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
683     Address GpuBinaryAddr(
684         GpuBinaryHandle,
685         CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
686     {
687       auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
688       llvm::Constant *Zero =
689           llvm::Constant::getNullValue(HandleValue->getType());
690       llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
691       CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
692     }
693     {
694       CtorBuilder.SetInsertPoint(IfBlock);
695       // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
696       llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
697           RegisterFatbinFunc,
698           CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
699       CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
700       CtorBuilder.CreateBr(ExitBlock);
701     }
702     {
703       CtorBuilder.SetInsertPoint(ExitBlock);
704       // Call __hip_register_globals(GpuBinaryHandle);
705       if (RegisterGlobalsFunc) {
706         auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
707         CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
708       }
709     }
710   } else if (!RelocatableDeviceCode) {
711     // Register binary with CUDA runtime. This is substantially different in
712     // default mode vs. separate compilation!
713     // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
714     llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
715         RegisterFatbinFunc,
716         CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
717     GpuBinaryHandle = new llvm::GlobalVariable(
718         TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
719         llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
720     GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
721     CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
722                                    CGM.getPointerAlign());
723 
724     // Call __cuda_register_globals(GpuBinaryHandle);
725     if (RegisterGlobalsFunc)
726       CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
727 
728     // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
729     if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
730                            CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
731       // void __cudaRegisterFatBinaryEnd(void **);
732       llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
733           llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
734           "__cudaRegisterFatBinaryEnd");
735       CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
736     }
737   } else {
738     // Generate a unique module ID.
739     SmallString<64> ModuleID;
740     llvm::raw_svector_ostream OS(ModuleID);
741     OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
742     llvm::Constant *ModuleIDConstant = makeConstantString(
743         std::string(ModuleID.str()), "", ModuleIDSectionName, 32);
744 
745     // Create an alias for the FatbinWrapper that nvcc will look for.
746     llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
747                               Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
748 
749     // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
750     // void *, void (*)(void **))
751     SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
752     RegisterLinkedBinaryName += ModuleID;
753     llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
754         getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
755 
756     assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
757     llvm::Value *Args[] = {RegisterGlobalsFunc,
758                            CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
759                            ModuleIDConstant,
760                            makeDummyFunction(getCallbackFnTy())};
761     CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
762   }
763 
764   // Create destructor and register it with atexit() the way NVCC does it. Doing
765   // it during regular destructor phase worked in CUDA before 9.2 but results in
766   // double-free in 9.2.
767   if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
768     // extern "C" int atexit(void (*f)(void));
769     llvm::FunctionType *AtExitTy =
770         llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
771     llvm::FunctionCallee AtExitFunc =
772         CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
773                                   /*Local=*/true);
774     CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
775   }
776 
777   CtorBuilder.CreateRetVoid();
778   return ModuleCtorFunc;
779 }
780 
781 /// Creates a global destructor function that unregisters the GPU code blob
782 /// registered by constructor.
783 ///
784 /// For CUDA:
785 /// \code
786 /// void __cuda_module_dtor(void*) {
787 ///     __cudaUnregisterFatBinary(Handle);
788 /// }
789 /// \endcode
790 ///
791 /// For HIP:
792 /// \code
793 /// void __hip_module_dtor(void*) {
794 ///     if (__hip_gpubin_handle) {
795 ///         __hipUnregisterFatBinary(__hip_gpubin_handle);
796 ///         __hip_gpubin_handle = 0;
797 ///     }
798 /// }
799 /// \endcode
makeModuleDtorFunction()800 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
801   // No need for destructor if we don't have a handle to unregister.
802   if (!GpuBinaryHandle)
803     return nullptr;
804 
805   // void __cudaUnregisterFatBinary(void ** handle);
806   llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
807       llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
808       addUnderscoredPrefixToName("UnregisterFatBinary"));
809 
810   llvm::Function *ModuleDtorFunc = llvm::Function::Create(
811       llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
812       llvm::GlobalValue::InternalLinkage,
813       addUnderscoredPrefixToName("_module_dtor"), &TheModule);
814 
815   llvm::BasicBlock *DtorEntryBB =
816       llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
817   CGBuilderTy DtorBuilder(CGM, Context);
818   DtorBuilder.SetInsertPoint(DtorEntryBB);
819 
820   Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
821                                              GpuBinaryHandle->getAlignment()));
822   auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
823   // There is only one HIP fat binary per linked module, however there are
824   // multiple destructor functions. Make sure the fat binary is unregistered
825   // only once.
826   if (CGM.getLangOpts().HIP) {
827     llvm::BasicBlock *IfBlock =
828         llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
829     llvm::BasicBlock *ExitBlock =
830         llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
831     llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
832     llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
833     DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
834 
835     DtorBuilder.SetInsertPoint(IfBlock);
836     DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
837     DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
838     DtorBuilder.CreateBr(ExitBlock);
839 
840     DtorBuilder.SetInsertPoint(ExitBlock);
841   } else {
842     DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
843   }
844   DtorBuilder.CreateRetVoid();
845   return ModuleDtorFunc;
846 }
847 
CreateNVCUDARuntime(CodeGenModule & CGM)848 CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
849   return new CGNVCUDARuntime(CGM);
850 }
851