blob: 1c578bd151bdad990aa71de1bac737e4a807f562 [file] [log] [blame]
Peter Collingbournefe883422011-10-06 18:29:37 +00001//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for CUDA code generation targeting the NVIDIA CUDA
11// runtime library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCUDARuntime.h"
Peter Collingbournefa4d6032011-10-06 18:51:56 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "clang/AST/Decl.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000020#include "llvm/IR/BasicBlock.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000024#include "llvm/Support/Format.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
Yaxun Liu29155b02018-05-18 15:07:56 +000030constexpr unsigned CudaFatMagic = 0x466243b1;
31constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
Peter Collingbournefe883422011-10-06 18:29:37 +000032
33class CGNVCUDARuntime : public CGCUDARuntime {
Peter Collingbournefa4d6032011-10-06 18:51:56 +000034
35private:
John McCall6c9f1fdb2016-11-19 08:17:24 +000036 llvm::IntegerType *IntTy, *SizeTy;
37 llvm::Type *VoidTy;
Artem Belevich52cc4872015-05-07 19:34:16 +000038 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 llvm::SmallVector<llvm::Function *, 16> EmittedKernels;
Artem Belevich42e19492016-03-02 18:28:50 +000046 llvm::SmallVector<std::pair<llvm::GlobalVariable *, unsigned>, 16> DeviceVars;
Jonas Hahnfelde7681322018-02-28 17:53:46 +000047 /// Keeps track of variable containing handle of GPU binary. Populated by
Artem Belevich52cc4872015-05-07 19:34:16 +000048 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
49 /// ModuleDtorFunction()
Jonas Hahnfelde7681322018-02-28 17:53:46 +000050 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000051 /// Whether we generate relocatable device code.
52 bool RelocatableDeviceCode;
Peter Collingbournefa4d6032011-10-06 18:51:56 +000053
54 llvm::Constant *getSetupArgumentFn() const;
55 llvm::Constant *getLaunchFn() const;
56
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000057 llvm::FunctionType *getRegisterGlobalsFnTy() const;
58 llvm::FunctionType *getCallbackFnTy() const;
59 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
Yaxun Liu887c5692018-04-25 01:10:37 +000060 std::string addPrefixToName(StringRef FuncName) const;
61 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000062
Artem Belevich52cc4872015-05-07 19:34:16 +000063 /// Creates a function to register all kernel stubs generated in this module.
Artem Belevich42e19492016-03-02 18:28:50 +000064 llvm::Function *makeRegisterGlobalsFn();
Artem Belevich52cc4872015-05-07 19:34:16 +000065
66 /// Helper function that generates a constant string and returns a pointer to
67 /// the start of the string. The result of this function can be used anywhere
68 /// where the C code specifies const char*.
69 llvm::Constant *makeConstantString(const std::string &Str,
70 const std::string &Name = "",
Artem Belevich4c093182016-08-12 18:44:01 +000071 const std::string &SectionName = "",
Artem Belevich52cc4872015-05-07 19:34:16 +000072 unsigned Alignment = 0) {
73 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
74 llvm::ConstantInt::get(SizeTy, 0)};
John McCall7f416cc2015-09-08 08:05:57 +000075 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Artem Belevich4c093182016-08-12 18:44:01 +000076 llvm::GlobalVariable *GV =
77 cast<llvm::GlobalVariable>(ConstStr.getPointer());
Jonas Hahnfeld3b9cbba92018-06-08 11:17:08 +000078 if (!SectionName.empty()) {
Artem Belevich4c093182016-08-12 18:44:01 +000079 GV->setSection(SectionName);
Jonas Hahnfeld3b9cbba92018-06-08 11:17:08 +000080 // Mark the address as used which make sure that this section isn't
81 // merged and we will really have it in the object file.
82 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
83 }
Artem Belevich4c093182016-08-12 18:44:01 +000084 if (Alignment)
85 GV->setAlignment(Alignment);
86
John McCall7f416cc2015-09-08 08:05:57 +000087 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
88 ConstStr.getPointer(), Zeros);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000089 }
90
91 /// Helper function that generates an empty dummy function returning void.
92 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
93 assert(FnTy->getReturnType()->isVoidTy() &&
94 "Can only generate dummy functions returning void!");
95 llvm::Function *DummyFunc = llvm::Function::Create(
96 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
97
98 llvm::BasicBlock *DummyBlock =
99 llvm::BasicBlock::Create(Context, "", DummyFunc);
100 CGBuilderTy FuncBuilder(CGM, Context);
101 FuncBuilder.SetInsertPoint(DummyBlock);
102 FuncBuilder.CreateRetVoid();
103
104 return DummyFunc;
105 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000106
107 void emitDeviceStubBody(CodeGenFunction &CGF, FunctionArgList &Args);
108
Peter Collingbournefe883422011-10-06 18:29:37 +0000109public:
110 CGNVCUDARuntime(CodeGenModule &CGM);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000111
Artem Belevich52cc4872015-05-07 19:34:16 +0000112 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
Artem Belevich42e19492016-03-02 18:28:50 +0000113 void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags) override {
114 DeviceVars.push_back(std::make_pair(&Var, Flags));
115 }
116
Artem Belevich52cc4872015-05-07 19:34:16 +0000117 /// Creates module constructor function
118 llvm::Function *makeModuleCtorFunction() override;
119 /// Creates module destructor function
120 llvm::Function *makeModuleDtorFunction() override;
Peter Collingbournefe883422011-10-06 18:29:37 +0000121};
122
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000123}
Peter Collingbournefe883422011-10-06 18:29:37 +0000124
Yaxun Liu887c5692018-04-25 01:10:37 +0000125std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
126 if (CGM.getLangOpts().HIP)
127 return ((Twine("hip") + Twine(FuncName)).str());
128 return ((Twine("cuda") + Twine(FuncName)).str());
129}
130std::string
131CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
132 if (CGM.getLangOpts().HIP)
133 return ((Twine("__hip") + Twine(FuncName)).str());
134 return ((Twine("__cuda") + Twine(FuncName)).str());
135}
136
Artem Belevich52cc4872015-05-07 19:34:16 +0000137CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
138 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000139 TheModule(CGM.getModule()),
Yaxun Liu97670892018-10-02 17:48:54 +0000140 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode) {
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000141 CodeGen::CodeGenTypes &Types = CGM.getTypes();
142 ASTContext &Ctx = CGM.getContext();
143
John McCall6c9f1fdb2016-11-19 08:17:24 +0000144 IntTy = CGM.IntTy;
145 SizeTy = CGM.SizeTy;
146 VoidTy = CGM.VoidTy;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000147
148 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
149 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
Artem Belevich52cc4872015-05-07 19:34:16 +0000150 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000151}
152
153llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn() const {
154 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
Benjamin Kramer30934732016-07-02 11:41:41 +0000155 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
Yaxun Liu887c5692018-04-25 01:10:37 +0000156 return CGM.CreateRuntimeFunction(
157 llvm::FunctionType::get(IntTy, Params, false),
158 addPrefixToName("SetupArgument"));
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000159}
160
161llvm::Constant *CGNVCUDARuntime::getLaunchFn() const {
Yaxun Liu887c5692018-04-25 01:10:37 +0000162 if (CGM.getLangOpts().HIP) {
163 // hipError_t hipLaunchByPtr(char *);
164 return CGM.CreateRuntimeFunction(
165 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
166 } else {
167 // cudaError_t cudaLaunch(char *);
168 return CGM.CreateRuntimeFunction(
169 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
170 }
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000171}
172
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000173llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
174 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
175}
176
177llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
178 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
179}
180
181llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
182 auto CallbackFnTy = getCallbackFnTy();
183 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
184 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
185 VoidPtrTy, CallbackFnTy->getPointerTo()};
186 return llvm::FunctionType::get(VoidTy, Params, false);
187}
188
Artem Belevich52cc4872015-05-07 19:34:16 +0000189void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
190 FunctionArgList &Args) {
191 EmittedKernels.push_back(CGF.CurFn);
192 emitDeviceStubBody(CGF, Args);
193}
194
195void CGNVCUDARuntime::emitDeviceStubBody(CodeGenFunction &CGF,
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000196 FunctionArgList &Args) {
Justin Lebare56360a2016-07-27 22:36:21 +0000197 // Emit a call to cudaSetupArgument for each arg in Args.
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000198 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
Justin Lebare56360a2016-07-27 22:36:21 +0000199 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
200 CharUnits Offset = CharUnits::Zero();
201 for (const VarDecl *A : Args) {
202 CharUnits TyWidth, TyAlign;
203 std::tie(TyWidth, TyAlign) =
204 CGM.getContext().getTypeInfoInChars(A->getType());
205 Offset = Offset.alignTo(TyAlign);
206 llvm::Value *Args[] = {
207 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
208 VoidPtrTy),
209 llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
210 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
211 };
John McCall882987f2013-02-28 19:01:20 +0000212 llvm::CallSite CS = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000213 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
214 llvm::Value *CSZero = CGF.Builder.CreateICmpEQ(CS.getInstruction(), Zero);
Justin Lebare56360a2016-07-27 22:36:21 +0000215 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000216 CGF.Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
217 CGF.EmitBlock(NextBlock);
Justin Lebare56360a2016-07-27 22:36:21 +0000218 Offset += TyWidth;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000219 }
220
221 // Emit the call to cudaLaunch
222 llvm::Constant *cudaLaunchFn = getLaunchFn();
223 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
John McCall882987f2013-02-28 19:01:20 +0000224 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000225 CGF.EmitBranch(EndBlock);
226
227 CGF.EmitBlock(EndBlock);
Peter Collingbournefe883422011-10-06 18:29:37 +0000228}
229
Artem Belevich42e19492016-03-02 18:28:50 +0000230/// Creates a function that sets up state on the host side for CUDA objects that
231/// have a presence on both the host and device sides. Specifically, registers
232/// the host side of kernel functions and device global variables with the CUDA
233/// runtime.
Artem Belevich52cc4872015-05-07 19:34:16 +0000234/// \code
Artem Belevich42e19492016-03-02 18:28:50 +0000235/// void __cuda_register_globals(void** GpuBinaryHandle) {
Artem Belevich52cc4872015-05-07 19:34:16 +0000236/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
237/// ...
238/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
Artem Belevich42e19492016-03-02 18:28:50 +0000239/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
240/// ...
241/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
Artem Belevich52cc4872015-05-07 19:34:16 +0000242/// }
243/// \endcode
Artem Belevich42e19492016-03-02 18:28:50 +0000244llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000245 // No need to register anything
246 if (EmittedKernels.empty() && DeviceVars.empty())
247 return nullptr;
248
Artem Belevich52cc4872015-05-07 19:34:16 +0000249 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000250 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000251 addUnderscoredPrefixToName("_register_globals"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000252 llvm::BasicBlock *EntryBB =
253 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000254 CGBuilderTy Builder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000255 Builder.SetInsertPoint(EntryBB);
256
257 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
258 // int, uint3*, uint3*, dim3*, dim3*, int*)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000259 llvm::Type *RegisterFuncParams[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000260 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
261 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
262 llvm::Constant *RegisterFunc = CGM.CreateRuntimeFunction(
263 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000264 addUnderscoredPrefixToName("RegisterFunction"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000265
266 // Extract GpuBinaryHandle passed as the first argument passed to
Artem Belevich42e19492016-03-02 18:28:50 +0000267 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
Artem Belevich52cc4872015-05-07 19:34:16 +0000268 // each emitted kernel.
269 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
270 for (llvm::Function *Kernel : EmittedKernels) {
271 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
272 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
Artem Belevich42e19492016-03-02 18:28:50 +0000273 llvm::Value *Args[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000274 &GpuBinaryHandlePtr, Builder.CreateBitCast(Kernel, VoidPtrTy),
275 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
276 NullPtr, NullPtr, NullPtr,
277 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
Artem Belevich42e19492016-03-02 18:28:50 +0000278 Builder.CreateCall(RegisterFunc, Args);
279 }
280
281 // void __cudaRegisterVar(void **, char *, char *, const char *,
282 // int, int, int, int)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000283 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
284 CharPtrTy, IntTy, IntTy,
285 IntTy, IntTy};
Artem Belevich42e19492016-03-02 18:28:50 +0000286 llvm::Constant *RegisterVar = CGM.CreateRuntimeFunction(
287 llvm::FunctionType::get(IntTy, RegisterVarParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000288 addUnderscoredPrefixToName("RegisterVar"));
Artem Belevich42e19492016-03-02 18:28:50 +0000289 for (auto &Pair : DeviceVars) {
290 llvm::GlobalVariable *Var = Pair.first;
291 unsigned Flags = Pair.second;
292 llvm::Constant *VarName = makeConstantString(Var->getName());
293 uint64_t VarSize =
294 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
295 llvm::Value *Args[] = {
296 &GpuBinaryHandlePtr,
297 Builder.CreateBitCast(Var, VoidPtrTy),
298 VarName,
299 VarName,
300 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
301 llvm::ConstantInt::get(IntTy, VarSize),
302 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
303 llvm::ConstantInt::get(IntTy, 0)};
304 Builder.CreateCall(RegisterVar, Args);
Artem Belevich52cc4872015-05-07 19:34:16 +0000305 }
306
307 Builder.CreateRetVoid();
308 return RegisterKernelsFunc;
309}
310
311/// Creates a global constructor function for the module:
Yaxun Liuf99752b2018-07-20 22:45:24 +0000312///
313/// For CUDA:
Artem Belevich52cc4872015-05-07 19:34:16 +0000314/// \code
315/// void __cuda_module_ctor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000316/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
317/// __cuda_register_globals(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000318/// }
319/// \endcode
Yaxun Liuf99752b2018-07-20 22:45:24 +0000320///
321/// For HIP:
322/// \code
323/// void __hip_module_ctor(void*) {
324/// if (__hip_gpubin_handle == 0) {
325/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);
326/// __hip_register_globals(__hip_gpubin_handle);
327/// }
328/// }
329/// \endcode
Artem Belevich52cc4872015-05-07 19:34:16 +0000330llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
Yaxun Liu29155b02018-05-18 15:07:56 +0000331 bool IsHIP = CGM.getLangOpts().HIP;
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000332 // No need to generate ctors/dtors if there is no GPU binary.
Yaxun Liu29155b02018-05-18 15:07:56 +0000333 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
334 if (CudaGpuBinaryFileName.empty() && !IsHIP)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000335 return nullptr;
336
Yaxun Liu29155b02018-05-18 15:07:56 +0000337 // void __{cuda|hip}_register_globals(void* handle);
Artem Belevich42e19492016-03-02 18:28:50 +0000338 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000339 // We always need a function to pass in as callback. Create a dummy
340 // implementation if we don't need to register anything.
341 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
342 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
343
Yaxun Liu29155b02018-05-18 15:07:56 +0000344 // void ** __{cuda|hip}RegisterFatBinary(void *);
Artem Belevich52cc4872015-05-07 19:34:16 +0000345 llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
346 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000347 addUnderscoredPrefixToName("RegisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000348 // struct { int magic, int version, void * gpu_binary, void * dont_care };
349 llvm::StructType *FatbinWrapperTy =
Serge Guelton1d993272017-05-09 19:31:30 +0000350 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
Artem Belevich52cc4872015-05-07 19:34:16 +0000351
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000352 // Register GPU binary with the CUDA runtime, store returned handle in a
353 // global variable and save a reference in GpuBinaryHandle to be cleaned up
354 // in destructor on exit. Then associate all known kernels with the GPU binary
355 // handle so CUDA runtime can figure out what to call on the GPU side.
Yaxun Liu97670892018-10-02 17:48:54 +0000356 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
357 if (!CudaGpuBinaryFileName.empty()) {
Yaxun Liu29155b02018-05-18 15:07:56 +0000358 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
359 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
360 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
361 CGM.getDiags().Report(diag::err_cannot_open_file)
362 << CudaGpuBinaryFileName << EC.message();
363 return nullptr;
364 }
365 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000366 }
367
Artem Belevich52cc4872015-05-07 19:34:16 +0000368 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
369 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000370 llvm::GlobalValue::InternalLinkage,
371 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000372 llvm::BasicBlock *CtorEntryBB =
373 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000374 CGBuilderTy CtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000375
376 CtorBuilder.SetInsertPoint(CtorEntryBB);
377
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000378 const char *FatbinConstantName;
Yaxun Liu29155b02018-05-18 15:07:56 +0000379 const char *FatbinSectionName;
380 const char *ModuleIDSectionName;
381 StringRef ModuleIDPrefix;
382 llvm::Constant *FatBinStr;
383 unsigned FatMagic;
384 if (IsHIP) {
385 FatbinConstantName = ".hip_fatbin";
386 FatbinSectionName = ".hipFatBinSegment";
387
388 ModuleIDSectionName = "__hip_module_id";
389 ModuleIDPrefix = "__hip_";
390
Yaxun Liu97670892018-10-02 17:48:54 +0000391 if (CudaGpuBinary) {
392 // If fatbin is available from early finalization, create a string
393 // literal containing the fat binary loaded from the given file.
394 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
395 FatbinConstantName, 8);
396 } else {
397 // If fatbin is not available, create an external symbol
398 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
399 // to contain the fat binary but will be populated somewhere else,
400 // e.g. by lld through link script.
401 FatBinStr = new llvm::GlobalVariable(
Yaxun Liu29155b02018-05-18 15:07:56 +0000402 CGM.getModule(), CGM.Int8Ty,
403 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
404 "__hip_fatbin", nullptr,
405 llvm::GlobalVariable::NotThreadLocal);
Yaxun Liu97670892018-10-02 17:48:54 +0000406 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
407 }
Yaxun Liu29155b02018-05-18 15:07:56 +0000408
409 FatMagic = HIPFatMagic;
410 } else {
411 if (RelocatableDeviceCode)
Artem Belevich5ce0a082018-06-28 17:15:52 +0000412 FatbinConstantName = CGM.getTriple().isMacOSX()
413 ? "__NV_CUDA,__nv_relfatbin"
414 : "__nv_relfatbin";
Yaxun Liu29155b02018-05-18 15:07:56 +0000415 else
416 FatbinConstantName =
417 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
418 // NVIDIA's cuobjdump looks for fatbins in this section.
419 FatbinSectionName =
420 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
421
Artem Belevich5ce0a082018-06-28 17:15:52 +0000422 ModuleIDSectionName = CGM.getTriple().isMacOSX()
423 ? "__NV_CUDA,__nv_module_id"
424 : "__nv_module_id";
Yaxun Liu29155b02018-05-18 15:07:56 +0000425 ModuleIDPrefix = "__nv_";
426
427 // For CUDA, create a string literal containing the fat binary loaded from
428 // the given file.
429 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
430 FatbinConstantName, 8);
431 FatMagic = CudaFatMagic;
432 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000433
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000434 // Create initialized wrapper structure that points to the loaded GPU binary
435 ConstantInitBuilder Builder(CGM);
436 auto Values = Builder.beginStruct(FatbinWrapperTy);
437 // Fatbin wrapper magic.
Yaxun Liu29155b02018-05-18 15:07:56 +0000438 Values.addInt(IntTy, FatMagic);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000439 // Fatbin version.
440 Values.addInt(IntTy, 1);
441 // Data.
Yaxun Liu29155b02018-05-18 15:07:56 +0000442 Values.add(FatBinStr);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000443 // Unused in fatbin v1.
444 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
445 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
Yaxun Liu887c5692018-04-25 01:10:37 +0000446 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000447 /*constant*/ true);
448 FatbinWrapper->setSection(FatbinSectionName);
Justin Lebard14fe882016-11-18 00:41:31 +0000449
Yaxun Liuf99752b2018-07-20 22:45:24 +0000450 // There is only one HIP fat binary per linked module, however there are
451 // multiple constructor functions. Make sure the fat binary is registered
452 // only once. The constructor functions are executed by the dynamic loader
453 // before the program gains control. The dynamic loader cannot execute the
454 // constructor functions concurrently since doing that would not guarantee
455 // thread safety of the loaded program. Therefore we can assume sequential
456 // execution of constructor functions here.
457 if (IsHIP) {
Yaxun Liu97670892018-10-02 17:48:54 +0000458 auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage :
459 llvm::GlobalValue::LinkOnceAnyLinkage;
Yaxun Liuf99752b2018-07-20 22:45:24 +0000460 llvm::BasicBlock *IfBlock =
461 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
462 llvm::BasicBlock *ExitBlock =
463 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
464 // The name, size, and initialization pattern of this variable is part
465 // of HIP ABI.
466 GpuBinaryHandle = new llvm::GlobalVariable(
467 TheModule, VoidPtrPtrTy, /*isConstant=*/false,
Yaxun Liu97670892018-10-02 17:48:54 +0000468 Linkage,
Yaxun Liuf99752b2018-07-20 22:45:24 +0000469 /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
470 "__hip_gpubin_handle");
471 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
Yaxun Liu94ff57f2018-08-17 17:47:31 +0000472 // Prevent the weak symbol in different shared libraries being merged.
Yaxun Liu97670892018-10-02 17:48:54 +0000473 if (Linkage != llvm::GlobalValue::InternalLinkage)
474 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
Yaxun Liuf99752b2018-07-20 22:45:24 +0000475 Address GpuBinaryAddr(
476 GpuBinaryHandle,
477 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
478 {
479 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
480 llvm::Constant *Zero =
481 llvm::Constant::getNullValue(HandleValue->getType());
482 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
483 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
484 }
485 {
486 CtorBuilder.SetInsertPoint(IfBlock);
487 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
488 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
489 RegisterFatbinFunc,
490 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
491 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
492 CtorBuilder.CreateBr(ExitBlock);
493 }
494 {
495 CtorBuilder.SetInsertPoint(ExitBlock);
496 // Call __hip_register_globals(GpuBinaryHandle);
497 if (RegisterGlobalsFunc) {
498 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
499 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
500 }
501 }
502 } else if (!RelocatableDeviceCode) {
503 // Register binary with CUDA runtime. This is substantially different in
504 // default mode vs. separate compilation!
505 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000506 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
507 RegisterFatbinFunc,
508 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
509 GpuBinaryHandle = new llvm::GlobalVariable(
510 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
Yaxun Liuf99752b2018-07-20 22:45:24 +0000511 llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
512 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000513 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
514 CGM.getPointerAlign());
Artem Belevich52cc4872015-05-07 19:34:16 +0000515
Yaxun Liuf99752b2018-07-20 22:45:24 +0000516 // Call __cuda_register_globals(GpuBinaryHandle);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000517 if (RegisterGlobalsFunc)
518 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
519 } else {
520 // Generate a unique module ID.
Yaxun Liu29155b02018-05-18 15:07:56 +0000521 SmallString<64> ModuleID;
522 llvm::raw_svector_ostream OS(ModuleID);
Artem Belevich93552b32018-10-05 18:39:58 +0000523 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
Yaxun Liu29155b02018-05-18 15:07:56 +0000524 llvm::Constant *ModuleIDConstant =
525 makeConstantString(ModuleID.str(), "", ModuleIDSectionName, 32);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000526
Yaxun Liuf99752b2018-07-20 22:45:24 +0000527 // Create an alias for the FatbinWrapper that nvcc will look for.
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000528 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
Yaxun Liu29155b02018-05-18 15:07:56 +0000529 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000530
Yaxun Liuf99752b2018-07-20 22:45:24 +0000531 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000532 // void *, void (*)(void **))
Yaxun Liuf99752b2018-07-20 22:45:24 +0000533 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
Yaxun Liu29155b02018-05-18 15:07:56 +0000534 RegisterLinkedBinaryName += ModuleID;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000535 llvm::Constant *RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
536 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
537
538 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
539 llvm::Value *Args[] = {RegisterGlobalsFunc,
540 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
Yaxun Liu29155b02018-05-18 15:07:56 +0000541 ModuleIDConstant,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000542 makeDummyFunction(getCallbackFnTy())};
543 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
544 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000545
Artem Belevichc66d2542018-06-27 18:32:51 +0000546 // Create destructor and register it with atexit() the way NVCC does it. Doing
547 // it during regular destructor phase worked in CUDA before 9.2 but results in
548 // double-free in 9.2.
549 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
550 // extern "C" int atexit(void (*f)(void));
551 llvm::FunctionType *AtExitTy =
552 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
553 llvm::Constant *AtExitFunc =
554 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
555 /*Local=*/true);
556 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
557 }
558
Artem Belevich52cc4872015-05-07 19:34:16 +0000559 CtorBuilder.CreateRetVoid();
560 return ModuleCtorFunc;
561}
562
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000563/// Creates a global destructor function that unregisters the GPU code blob
Artem Belevich52cc4872015-05-07 19:34:16 +0000564/// registered by constructor.
Yaxun Liuf99752b2018-07-20 22:45:24 +0000565///
566/// For CUDA:
Artem Belevich52cc4872015-05-07 19:34:16 +0000567/// \code
568/// void __cuda_module_dtor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000569/// __cudaUnregisterFatBinary(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000570/// }
571/// \endcode
Yaxun Liuf99752b2018-07-20 22:45:24 +0000572///
573/// For HIP:
574/// \code
575/// void __hip_module_dtor(void*) {
576/// if (__hip_gpubin_handle) {
577/// __hipUnregisterFatBinary(__hip_gpubin_handle);
578/// __hip_gpubin_handle = 0;
579/// }
580/// }
581/// \endcode
Artem Belevich52cc4872015-05-07 19:34:16 +0000582llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000583 // No need for destructor if we don't have a handle to unregister.
584 if (!GpuBinaryHandle)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000585 return nullptr;
586
Artem Belevich52cc4872015-05-07 19:34:16 +0000587 // void __cudaUnregisterFatBinary(void ** handle);
588 llvm::Constant *UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
589 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000590 addUnderscoredPrefixToName("UnregisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000591
592 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
593 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000594 llvm::GlobalValue::InternalLinkage,
595 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
596
Artem Belevich52cc4872015-05-07 19:34:16 +0000597 llvm::BasicBlock *DtorEntryBB =
598 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000599 CGBuilderTy DtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000600 DtorBuilder.SetInsertPoint(DtorEntryBB);
601
Yaxun Liuf99752b2018-07-20 22:45:24 +0000602 Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
603 GpuBinaryHandle->getAlignment()));
604 auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
605 // There is only one HIP fat binary per linked module, however there are
606 // multiple destructor functions. Make sure the fat binary is unregistered
607 // only once.
608 if (CGM.getLangOpts().HIP) {
609 llvm::BasicBlock *IfBlock =
610 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
611 llvm::BasicBlock *ExitBlock =
612 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
613 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
614 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
615 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
Artem Belevich52cc4872015-05-07 19:34:16 +0000616
Yaxun Liuf99752b2018-07-20 22:45:24 +0000617 DtorBuilder.SetInsertPoint(IfBlock);
618 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
619 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
620 DtorBuilder.CreateBr(ExitBlock);
621
622 DtorBuilder.SetInsertPoint(ExitBlock);
623 } else {
624 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
625 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000626 DtorBuilder.CreateRetVoid();
627 return ModuleDtorFunc;
628}
629
Peter Collingbournefe883422011-10-06 18:29:37 +0000630CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
631 return new CGNVCUDARuntime(CGM);
632}