clang 23.0.0git
CGCUDANV.cpp
Go to the documentation of this file.
1//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for CUDA code generation targeting the NVIDIA CUDA
10// runtime library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/Basic/Cuda.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Frontend/Offloading/Utility.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/ReplaceConstant.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/VirtualFileSystem.h"
31#include "llvm/Transforms/Utils/ModuleUtils.h"
32
33using namespace clang;
34using namespace CodeGen;
35
36namespace {
37constexpr unsigned CudaFatMagic = 0x466243b1;
38constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
39
40class CGNVCUDARuntime : public CGCUDARuntime {
41
42 /// The prefix used for function calls and section names (CUDA, HIP, LLVM)
43 StringRef Prefix;
44
45private:
46 llvm::IntegerType *IntTy, *SizeTy;
47 llvm::Type *VoidTy;
48 llvm::PointerType *PtrTy;
49
50 /// Convenience reference to LLVM Context
51 llvm::LLVMContext &Context;
52 /// Convenience reference to the current module
53 llvm::Module &TheModule;
54 /// Keeps track of kernel launch stubs and handles emitted in this module
55 struct KernelInfo {
56 llvm::Function *Kernel; // stub function to help launch kernel
57 const Decl *D;
58 };
59 llvm::SmallVector<KernelInfo, 16> EmittedKernels;
60 // Map a kernel mangled name to a symbol for identifying kernel in host code
61 // For CUDA, the symbol for identifying the kernel is the same as the device
62 // stub function. For HIP, they are different.
63 llvm::DenseMap<StringRef, llvm::GlobalValue *> KernelHandles;
64 // Map a kernel handle to the kernel stub.
65 llvm::DenseMap<llvm::GlobalValue *, llvm::Function *> KernelStubs;
66 struct VarInfo {
67 llvm::GlobalVariable *Var;
68 const VarDecl *D;
69 DeviceVarFlags Flags;
70 };
71 llvm::SmallVector<VarInfo, 16> DeviceVars;
72 /// Keeps track of variable containing handle of GPU binary. Populated by
73 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
74 /// ModuleDtorFunction()
75 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
76 /// Host-side shadow for the per-TU __llvm_profile_sections_<CUID> global,
77 /// emitted only for HIP host compiles when PGO is on. Registered via
78 /// __hipRegisterVar (non-RDC) or an offloading entry (RDC) so the runtime
79 /// can locate the device-side table by name.
80 llvm::GlobalVariable *OffloadProfShadow = nullptr;
81 /// Whether we generate relocatable device code.
82 bool RelocatableDeviceCode;
83 /// Mangle context for device.
84 std::unique_ptr<MangleContext> DeviceMC;
85
86 llvm::FunctionCallee getSetupArgumentFn() const;
87 llvm::FunctionCallee getLaunchFn() const;
88
89 llvm::FunctionType *getRegisterGlobalsFnTy() const;
90 llvm::FunctionType *getCallbackFnTy() const;
91 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
92 std::string addPrefixToName(StringRef FuncName) const;
93 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
94
95 /// Creates a function to register all kernel stubs generated in this module.
96 llvm::Function *makeRegisterGlobalsFn();
97
98 /// Helper function that generates a constant string and returns a pointer to
99 /// the start of the string. The result of this function can be used anywhere
100 /// where the C code specifies const char*.
101 llvm::Constant *makeConstantString(const std::string &Str,
102 const std::string &Name = "") {
103 return CGM.GetAddrOfConstantCString(Str, Name).getPointer();
104 }
105
106 /// Helper function which generates an initialized constant array from Str,
107 /// and optionally sets section name and alignment. AddNull specifies whether
108 /// the array should nave NUL termination.
109 llvm::Constant *makeConstantArray(StringRef Str,
110 StringRef Name = "",
111 StringRef SectionName = "",
112 unsigned Alignment = 0,
113 bool AddNull = false) {
114 llvm::Constant *Value =
115 llvm::ConstantDataArray::getString(Context, Str, AddNull);
116 auto *GV = new llvm::GlobalVariable(
117 TheModule, Value->getType(), /*isConstant=*/true,
118 llvm::GlobalValue::PrivateLinkage, Value, Name);
119 if (!SectionName.empty()) {
120 GV->setSection(SectionName);
121 // Mark the address as used which make sure that this section isn't
122 // merged and we will really have it in the object file.
123 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
124 }
125 if (Alignment)
126 GV->setAlignment(llvm::Align(Alignment));
127 return GV;
128 }
129
130 /// Helper function that generates an empty dummy function returning void.
131 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
132 assert(FnTy->getReturnType()->isVoidTy() &&
133 "Can only generate dummy functions returning void!");
134 llvm::Function *DummyFunc = llvm::Function::Create(
135 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
136
137 llvm::BasicBlock *DummyBlock =
138 llvm::BasicBlock::Create(Context, "", DummyFunc);
139 CGBuilderTy FuncBuilder(CGM, Context);
140 FuncBuilder.SetInsertPoint(DummyBlock);
141 FuncBuilder.CreateRetVoid();
142
143 return DummyFunc;
144 }
145
146 Address prepareKernelArgs(CodeGenFunction &CGF, FunctionArgList &Args);
147 Address prepareKernelArgsLLVMOffload(CodeGenFunction &CGF,
148 FunctionArgList &Args);
149 void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
150 void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
151 std::string getDeviceSideName(const NamedDecl *ND) override;
152
153 void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
154 bool Extern, bool Constant) {
155 DeviceVars.push_back({&Var,
156 VD,
157 {DeviceVarFlags::Variable, Extern, Constant,
158 VD->hasAttr<HIPManagedAttr>(),
159 /*Normalized*/ false, 0}});
160 }
161 void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,
162 bool Extern, int Type) {
163 DeviceVars.push_back({&Var,
164 VD,
165 {DeviceVarFlags::Surface, Extern, /*Constant*/ false,
166 /*Managed*/ false,
167 /*Normalized*/ false, Type}});
168 }
169 void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,
170 bool Extern, int Type, bool Normalized) {
171 DeviceVars.push_back({&Var,
172 VD,
173 {DeviceVarFlags::Texture, Extern, /*Constant*/ false,
174 /*Managed*/ false, Normalized, Type}});
175 }
176
177 /// Creates module constructor function
178 llvm::Function *makeModuleCtorFunction();
179 /// Creates module destructor function
180 llvm::Function *makeModuleDtorFunction();
181 /// Transform managed variables for device compilation.
182 void transformManagedVars();
183 /// Create offloading entries to register globals in RDC mode.
184 void createOffloadingEntries();
185 /// For HIP+PGO, emit the per-TU __llvm_profile_sections_<CUID> global.
186 /// On the device side it is the populated 7-pointer section-bounds table.
187 /// On the host side it is a placeholder void* shadow stored in
188 /// OffloadProfShadow, registered later by makeRegisterGlobalsFn (non-RDC)
189 /// or createOffloadingEntries (RDC) so the runtime can locate the
190 /// device-side table by name.
191 void emitOffloadProfilingSections();
192
193public:
194 CGNVCUDARuntime(CodeGenModule &CGM);
195
196 llvm::GlobalValue *getKernelHandle(llvm::Function *F, GlobalDecl GD) override;
197 llvm::Function *getKernelStub(llvm::GlobalValue *Handle) override {
198 auto Loc = KernelStubs.find(Handle);
199 assert(Loc != KernelStubs.end());
200 return Loc->second;
201 }
202 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
203 void handleVarRegistration(const VarDecl *VD,
204 llvm::GlobalVariable &Var) override;
205 void
206 internalizeDeviceSideVar(const VarDecl *D,
207 llvm::GlobalValue::LinkageTypes &Linkage) override;
208
209 llvm::Function *finalizeModule() override;
210};
211
212} // end anonymous namespace
213
214std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
215 return (Prefix + FuncName).str();
216}
217std::string
218CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
219 return ("__" + Prefix + FuncName).str();
220}
221
222static std::unique_ptr<MangleContext> InitDeviceMC(CodeGenModule &CGM) {
223 // If the host and device have different C++ ABIs, mark it as the device
224 // mangle context so that the mangling needs to retrieve the additional
225 // device lambda mangling number instead of the regular host one.
226 if (CGM.getContext().getAuxTargetInfo() &&
229 return std::unique_ptr<MangleContext>(
231 *CGM.getContext().getAuxTargetInfo()));
232 }
233
234 return std::unique_ptr<MangleContext>(CGM.getContext().createMangleContext(
236}
237
238CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
239 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
240 TheModule(CGM.getModule()),
241 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
242 DeviceMC(InitDeviceMC(CGM)) {
243 IntTy = CGM.IntTy;
244 SizeTy = CGM.SizeTy;
245 VoidTy = CGM.VoidTy;
246 PtrTy = CGM.DefaultPtrTy;
247
248 if (CGM.getLangOpts().OffloadViaLLVM)
249 Prefix = "llvm";
250 else if (CGM.getLangOpts().HIP)
251 Prefix = "hip";
252 else
253 Prefix = "cuda";
254}
255
256llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
257 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
258 llvm::Type *Params[] = {PtrTy, SizeTy, SizeTy};
259 return CGM.CreateRuntimeFunction(
260 llvm::FunctionType::get(IntTy, Params, false),
261 addPrefixToName("SetupArgument"));
262}
263
264llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
265 if (CGM.getLangOpts().HIP) {
266 // hipError_t hipLaunchByPtr(char *);
267 return CGM.CreateRuntimeFunction(
268 llvm::FunctionType::get(IntTy, PtrTy, false), "hipLaunchByPtr");
269 }
270 // cudaError_t cudaLaunch(char *);
271 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(IntTy, PtrTy, false),
272 "cudaLaunch");
273}
274
275llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
276 return llvm::FunctionType::get(VoidTy, PtrTy, false);
277}
278
279llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
280 return llvm::FunctionType::get(VoidTy, PtrTy, false);
281}
282
283llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
284 llvm::Type *Params[] = {llvm::PointerType::getUnqual(Context), PtrTy, PtrTy,
285 llvm::PointerType::getUnqual(Context)};
286 return llvm::FunctionType::get(VoidTy, Params, false);
287}
288
289std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
290 GlobalDecl GD;
291 // D could be either a kernel or a variable.
292 if (auto *FD = dyn_cast<FunctionDecl>(ND))
293 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
294 else
295 GD = GlobalDecl(ND);
296 std::string DeviceSideName;
297 MangleContext *MC;
298 if (CGM.getLangOpts().CUDAIsDevice)
299 MC = &CGM.getCXXABI().getMangleContext();
300 else
301 MC = DeviceMC.get();
302 if (MC->shouldMangleDeclName(ND)) {
303 SmallString<256> Buffer;
304 llvm::raw_svector_ostream Out(Buffer);
305 MC->mangleName(GD, Out);
306 DeviceSideName = std::string(Out.str());
307 } else
308 DeviceSideName = std::string(ND->getIdentifier()->getName());
309
310 // Make unique name for device side static file-scope variable for HIP.
311 if (CGM.getContext().shouldExternalize(ND) &&
312 CGM.getLangOpts().GPURelocatableDeviceCode) {
313 SmallString<256> Buffer;
314 llvm::raw_svector_ostream Out(Buffer);
315 Out << DeviceSideName;
317 DeviceSideName = std::string(Out.str());
318 }
319 return DeviceSideName;
320}
321
322void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
323 FunctionArgList &Args) {
324 EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
325 if (auto *GV =
326 dyn_cast<llvm::GlobalVariable>(KernelHandles[CGF.CurFn->getName()])) {
327 GV->setLinkage(CGF.CurFn->getLinkage());
328 GV->setInitializer(CGF.CurFn);
329 }
331 CudaFeature::CUDA_USES_NEW_LAUNCH) ||
332 (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI) ||
333 (CGF.getLangOpts().OffloadViaLLVM))
334 emitDeviceStubBodyNew(CGF, Args);
335 else
336 emitDeviceStubBodyLegacy(CGF, Args);
337}
338
339/// CUDA passes the arguments with a level of indirection. For example, a
340/// (void*, short, void*) is passed as {void **, short *, void **} to the launch
341/// function. For the LLVM/offload launch we flatten the arguments into the
342/// struct directly. In addition, we include the size of the arguments, thus
343/// pass {sizeof({void *, short, void *}), ptr to {void *, short, void *},
344/// nullptr}. The last nullptr needs to be initialized to an array of pointers
345/// pointing to the arguments if we want to offload to the host.
346Address CGNVCUDARuntime::prepareKernelArgsLLVMOffload(CodeGenFunction &CGF,
347 FunctionArgList &Args) {
348 SmallVector<llvm::Type *> ArgTypes, KernelLaunchParamsTypes;
349 for (auto &Arg : Args)
350 ArgTypes.push_back(CGF.ConvertTypeForMem(Arg->getType()));
351 llvm::StructType *KernelArgsTy = llvm::StructType::create(ArgTypes);
352
353 auto *Int64Ty = CGF.Builder.getInt64Ty();
354 KernelLaunchParamsTypes.push_back(Int64Ty);
355 KernelLaunchParamsTypes.push_back(PtrTy);
356 KernelLaunchParamsTypes.push_back(PtrTy);
357
358 llvm::StructType *KernelLaunchParamsTy =
359 llvm::StructType::create(KernelLaunchParamsTypes);
360 Address KernelArgs = CGF.CreateTempAllocaWithoutCast(
361 KernelArgsTy, CharUnits::fromQuantity(16), "kernel_args");
362 Address KernelLaunchParams = CGF.CreateTempAllocaWithoutCast(
363 KernelLaunchParamsTy, CharUnits::fromQuantity(16),
364 "kernel_launch_params");
365
366 auto KernelArgsSize = CGM.getDataLayout().getTypeAllocSize(KernelArgsTy);
367 CGF.Builder.CreateStore(llvm::ConstantInt::get(Int64Ty, KernelArgsSize),
368 CGF.Builder.CreateStructGEP(KernelLaunchParams, 0));
369 CGF.Builder.CreateStore(KernelArgs.emitRawPointer(CGF),
370 CGF.Builder.CreateStructGEP(KernelLaunchParams, 1));
371 CGF.Builder.CreateStore(llvm::Constant::getNullValue(PtrTy),
372 CGF.Builder.CreateStructGEP(KernelLaunchParams, 2));
373
374 for (unsigned i = 0; i < Args.size(); ++i) {
375 auto *ArgVal = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[i]));
376 CGF.Builder.CreateStore(ArgVal, CGF.Builder.CreateStructGEP(KernelArgs, i));
377 }
378
379 return KernelLaunchParams;
380}
381
382Address CGNVCUDARuntime::prepareKernelArgs(CodeGenFunction &CGF,
383 FunctionArgList &Args) {
384 // Calculate amount of space we will need for all arguments. If we have no
385 // args, allocate a single pointer so we still have a valid pointer to the
386 // argument array that we can pass to runtime, even if it will be unused.
387 Address KernelArgs = CGF.CreateTempAlloca(
388 PtrTy, LangAS::Default, CharUnits::fromQuantity(16), "kernel_args",
389 llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
390 // Store pointers to the arguments in a locally allocated launch_args.
391 for (unsigned i = 0; i < Args.size(); ++i) {
392 llvm::Value *VarPtr = CGF.GetAddrOfLocalVar(Args[i]).emitRawPointer(CGF);
393 llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, PtrTy);
395 VoidVarPtr, CGF.Builder.CreateConstGEP1_32(
396 PtrTy, KernelArgs.emitRawPointer(CGF), i));
397 }
398 return KernelArgs;
399}
400
401// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
402// array and kernels are launched using cudaLaunchKernel().
403void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
404 FunctionArgList &Args) {
405 // Build the shadow stack entry at the very start of the function.
406 Address KernelArgs = CGF.getLangOpts().OffloadViaLLVM
407 ? prepareKernelArgsLLVMOffload(CGF, Args)
408 : prepareKernelArgs(CGF, Args);
409
410 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
411
412 // Lookup cudaLaunchKernel/hipLaunchKernel function.
413 // HIP kernel launching API name depends on -fgpu-default-stream option. For
414 // the default value 'legacy', it is hipLaunchKernel. For 'per-thread',
415 // it is hipLaunchKernel_spt.
416 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
417 // void **args, size_t sharedMem,
418 // cudaStream_t stream);
419 // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,
420 // dim3 blockDim, void **args,
421 // size_t sharedMem, hipStream_t stream);
422 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
423 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
424 std::string KernelLaunchAPI = "LaunchKernel";
425 if (CGF.getLangOpts().GPUDefaultStream ==
426 LangOptions::GPUDefaultStreamKind::PerThread) {
427 if (CGF.getLangOpts().HIP)
428 KernelLaunchAPI = KernelLaunchAPI + "_spt";
429 else if (CGF.getLangOpts().CUDA)
430 KernelLaunchAPI = KernelLaunchAPI + "_ptsz";
431 }
432 auto LaunchKernelName = addPrefixToName(KernelLaunchAPI);
433 const IdentifierInfo &cudaLaunchKernelII =
434 CGM.getContext().Idents.get(LaunchKernelName);
435 FunctionDecl *cudaLaunchKernelFD = nullptr;
436 for (auto *Result : DC->lookup(&cudaLaunchKernelII)) {
437 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
438 cudaLaunchKernelFD = FD;
439 }
440
441 if (cudaLaunchKernelFD == nullptr) {
442 CGM.Error(CGF.CurFuncDecl->getLocation(),
443 "Can't find declaration for " + LaunchKernelName);
444 return;
445 }
446 // Create temporary dim3 grid_dim, block_dim.
447 ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
448 QualType Dim3Ty = GridDimParam->getType();
449 Address GridDim = CGF.CreateMemTempWithoutCast(
450 Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
451 Address BlockDim = CGF.CreateMemTempWithoutCast(
452 Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
453 Address ShmemSize = CGF.CreateTempAlloca(SizeTy, LangAS::Default,
454 CGM.getSizeAlign(), "shmem_size");
455 Address Stream = CGF.CreateTempAlloca(PtrTy, LangAS::Default,
456 CGM.getPointerAlign(), "stream");
457 llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
458 llvm::FunctionType::get(IntTy,
459 {/*gridDim=*/GridDim.getType(),
460 /*blockDim=*/BlockDim.getType(),
461 /*ShmemSize=*/ShmemSize.getType(),
462 /*Stream=*/Stream.getType()},
463 /*isVarArg=*/false),
464 addUnderscoredPrefixToName("PopCallConfiguration"));
465
466 CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn, {GridDim.emitRawPointer(CGF),
467 BlockDim.emitRawPointer(CGF),
468 ShmemSize.emitRawPointer(CGF),
469 Stream.emitRawPointer(CGF)});
470
471 // Emit the call to cudaLaunch
472 llvm::Value *Kernel =
473 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);
474 CallArgList LaunchKernelArgs;
475 LaunchKernelArgs.add(RValue::get(Kernel),
476 cudaLaunchKernelFD->getParamDecl(0)->getType());
477 LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
478 LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
479 LaunchKernelArgs.add(RValue::get(KernelArgs, CGF),
480 cudaLaunchKernelFD->getParamDecl(3)->getType());
481 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
482 cudaLaunchKernelFD->getParamDecl(4)->getType());
483 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
484 cudaLaunchKernelFD->getParamDecl(5)->getType());
485
486 QualType QT = cudaLaunchKernelFD->getType();
487 QualType CQT = QT.getCanonicalType();
488 llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
489 llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
490
491 const CGFunctionInfo &FI =
492 CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
493 llvm::FunctionCallee cudaLaunchKernelFn =
494 CGM.CreateRuntimeFunction(FTy, LaunchKernelName);
495 CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
496 LaunchKernelArgs);
497
498 // To prevent CUDA device stub functions from being merged by ICF in MSVC
499 // environment, create an unique global variable for each kernel and write to
500 // the variable in the device stub.
502 !CGF.getLangOpts().HIP) {
503 llvm::Function *KernelFunction = llvm::cast<llvm::Function>(Kernel);
504 std::string GlobalVarName = (KernelFunction->getName() + ".id").str();
505
506 llvm::GlobalVariable *HandleVar =
507 CGM.getModule().getNamedGlobal(GlobalVarName);
508 if (!HandleVar) {
509 HandleVar = new llvm::GlobalVariable(
510 CGM.getModule(), CGM.Int8Ty,
511 /*Constant=*/false, KernelFunction->getLinkage(),
512 llvm::ConstantInt::get(CGM.Int8Ty, 0), GlobalVarName);
513 HandleVar->setDSOLocal(KernelFunction->isDSOLocal());
514 HandleVar->setVisibility(KernelFunction->getVisibility());
515 if (KernelFunction->hasComdat())
516 HandleVar->setComdat(CGM.getModule().getOrInsertComdat(GlobalVarName));
517 }
518
519 CGF.Builder.CreateAlignedStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
520 HandleVar, CharUnits::One(),
521 /*IsVolatile=*/true);
522 }
523
524 CGF.EmitBranch(EndBlock);
525
526 CGF.EmitBlock(EndBlock);
527}
528
529void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
530 FunctionArgList &Args) {
531 // Emit a call to cudaSetupArgument for each arg in Args.
532 llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
533 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
534 CharUnits Offset = CharUnits::Zero();
535 for (const VarDecl *A : Args) {
536 auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType());
537 Offset = Offset.alignTo(TInfo.Align);
538 llvm::Value *Args[] = {
539 CGF.Builder.CreatePointerCast(
540 CGF.GetAddrOfLocalVar(A).emitRawPointer(CGF), PtrTy),
541 llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()),
542 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
543 };
544 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
545 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
546 llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
547 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
548 CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
549 CGF.EmitBlock(NextBlock);
550 Offset += TInfo.Width;
551 }
552
553 // Emit the call to cudaLaunch
554 llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
555 llvm::Value *Arg =
556 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);
557 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
558 CGF.EmitBranch(EndBlock);
559
560 CGF.EmitBlock(EndBlock);
561}
562
563// Replace the original variable Var with the address loaded from variable
564// ManagedVar populated by HIP runtime.
565static void replaceManagedVar(llvm::GlobalVariable *Var,
566 llvm::GlobalVariable *ManagedVar) {
568 for (auto &&VarUse : Var->uses()) {
569 WorkList.push_back({VarUse.getUser()});
570 }
571 while (!WorkList.empty()) {
572 auto &&WorkItem = WorkList.pop_back_val();
573 auto *U = WorkItem.back();
575 for (auto &&UU : U->uses()) {
576 WorkItem.push_back(UU.getUser());
577 WorkList.push_back(WorkItem);
578 WorkItem.pop_back();
579 }
580 continue;
581 }
582 if (auto *I = dyn_cast<llvm::Instruction>(U)) {
583 llvm::Value *OldV = Var;
584 llvm::Instruction *NewV = new llvm::LoadInst(
585 Var->getType(), ManagedVar, "ld.managed", false,
586 llvm::Align(Var->getAlignment()), I->getIterator());
587 WorkItem.pop_back();
588 // Replace constant expressions directly or indirectly using the managed
589 // variable with instructions.
590 for (auto &&Op : WorkItem) {
591 auto *CE = cast<llvm::ConstantExpr>(Op);
592 auto *NewInst = CE->getAsInstruction();
593 NewInst->insertBefore(*I->getParent(), I->getIterator());
594 NewInst->replaceUsesOfWith(OldV, NewV);
595 OldV = CE;
596 NewV = NewInst;
597 }
598 I->replaceUsesOfWith(OldV, NewV);
599 } else {
600 llvm_unreachable("Invalid use of managed variable");
601 }
602 }
603}
604
605/// Creates a function that sets up state on the host side for CUDA objects that
606/// have a presence on both the host and device sides. Specifically, registers
607/// the host side of kernel functions and device global variables with the CUDA
608/// runtime.
609/// \code
610/// void __cuda_register_globals(void** GpuBinaryHandle) {
611/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
612/// ...
613/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
614/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
615/// ...
616/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
617/// }
618/// \endcode
619llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
620 // No need to register anything
621 if (EmittedKernels.empty() && DeviceVars.empty())
622 return nullptr;
623
624 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
625 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
626 addUnderscoredPrefixToName("_register_globals"), &TheModule);
627 llvm::BasicBlock *EntryBB =
628 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
629 CGBuilderTy Builder(CGM, Context);
630 Builder.SetInsertPoint(EntryBB);
631
632 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
633 // int, uint3*, uint3*, dim3*, dim3*, int*)
634 llvm::Type *RegisterFuncParams[] = {
635 PtrTy, PtrTy, PtrTy, PtrTy, IntTy,
636 PtrTy, PtrTy, PtrTy, PtrTy, llvm::PointerType::getUnqual(Context)};
637 llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
638 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
639 addUnderscoredPrefixToName("RegisterFunction"));
640
641 // Extract GpuBinaryHandle passed as the first argument passed to
642 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
643 // each emitted kernel.
644 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
645 for (auto &&I : EmittedKernels) {
646 llvm::Constant *KernelName =
647 makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));
648 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(PtrTy);
649 llvm::Value *Args[] = {
650 &GpuBinaryHandlePtr,
651 KernelHandles[I.Kernel->getName()],
652 KernelName,
653 KernelName,
654 llvm::ConstantInt::getAllOnesValue(IntTy),
655 NullPtr,
656 NullPtr,
657 NullPtr,
658 NullPtr,
659 llvm::ConstantPointerNull::get(llvm::PointerType::getUnqual(Context))};
660 Builder.CreateCall(RegisterFunc, Args);
661 }
662
663 llvm::Type *VarSizeTy = IntTy;
664 // For HIP or CUDA 9.0+, device variable size is type of `size_t`.
665 if (CGM.getLangOpts().HIP ||
666 ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)
667 VarSizeTy = SizeTy;
668
669 // void __cudaRegisterVar(void **, char *, char *, const char *,
670 // int, int, int, int)
671 llvm::Type *RegisterVarParams[] = {PtrTy, PtrTy, PtrTy, PtrTy,
672 IntTy, VarSizeTy, IntTy, IntTy};
673 llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
674 llvm::FunctionType::get(VoidTy, RegisterVarParams, false),
675 addUnderscoredPrefixToName("RegisterVar"));
676 // void __hipRegisterManagedVar(void **, char *, char *, const char *,
677 // size_t, unsigned)
678 llvm::Type *RegisterManagedVarParams[] = {PtrTy, PtrTy, PtrTy,
679 PtrTy, VarSizeTy, IntTy};
680 llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction(
681 llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false),
682 addUnderscoredPrefixToName("RegisterManagedVar"));
683 // void __cudaRegisterSurface(void **, const struct surfaceReference *,
684 // const void **, const char *, int, int);
685 llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(
686 llvm::FunctionType::get(
687 VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy}, false),
688 addUnderscoredPrefixToName("RegisterSurface"));
689 // void __cudaRegisterTexture(void **, const struct textureReference *,
690 // const void **, const char *, int, int, int)
691 llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(
692 llvm::FunctionType::get(
693 VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy, IntTy}, false),
694 addUnderscoredPrefixToName("RegisterTexture"));
695 for (auto &&Info : DeviceVars) {
696 llvm::GlobalVariable *Var = Info.Var;
697 assert((!Var->isDeclaration() || Info.Flags.isManaged()) &&
698 "External variables should not show up here, except HIP managed "
699 "variables");
700 llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
701 switch (Info.Flags.getKind()) {
702 case DeviceVarFlags::Variable: {
703 uint64_t VarSize =
704 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
705 if (Info.Flags.isManaged()) {
706 assert(Var->getName().ends_with(".managed") &&
707 "HIP managed variables not transformed");
708 auto *ManagedVar = CGM.getModule().getNamedGlobal(
709 Var->getName().drop_back(StringRef(".managed").size()));
710 llvm::Value *Args[] = {
711 &GpuBinaryHandlePtr,
712 ManagedVar,
713 Var,
714 VarName,
715 llvm::ConstantInt::get(VarSizeTy, VarSize),
716 llvm::ConstantInt::get(IntTy, Var->getAlignment())};
717 if (!Var->isDeclaration())
718 Builder.CreateCall(RegisterManagedVar, Args);
719 } else {
720 llvm::Value *Args[] = {
721 &GpuBinaryHandlePtr,
722 Var,
723 VarName,
724 VarName,
725 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),
726 llvm::ConstantInt::get(VarSizeTy, VarSize),
727 llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),
728 llvm::ConstantInt::get(IntTy, 0)};
729 Builder.CreateCall(RegisterVar, Args);
730 }
731 break;
732 }
733 case DeviceVarFlags::Surface:
734 Builder.CreateCall(
735 RegisterSurf,
736 {&GpuBinaryHandlePtr, Var, VarName, VarName,
737 llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
738 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
739 break;
740 case DeviceVarFlags::Texture:
741 Builder.CreateCall(
742 RegisterTex,
743 {&GpuBinaryHandlePtr, Var, VarName, VarName,
744 llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
745 llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),
746 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
747 break;
748 }
749 }
750
751 // Register the per-TU offload-profiling shadow so the host runtime can
752 // locate the matching device-side __llvm_profile_sections_<CUID>. We
753 // emit both __hipRegisterVar (so the HIP runtime can map the host
754 // shadow to the device symbol) and
755 // __llvm_profile_offload_register_shadow_variable (so the profile
756 // runtime adds the shadow to its drain list).
757 if (OffloadProfShadow) {
758 llvm::Constant *Name =
759 makeConstantString(std::string(OffloadProfShadow->getName()));
760 llvm::Value *RegisterVarArgs[] = {
761 &GpuBinaryHandlePtr,
762 OffloadProfShadow,
763 Name,
764 Name,
765 llvm::ConstantInt::get(IntTy, /*Extern=*/0),
766 llvm::ConstantInt::get(VarSizeTy, CGM.getDataLayout().getPointerSize()),
767 llvm::ConstantInt::get(IntTy, /*Constant=*/0),
768 llvm::ConstantInt::get(IntTy, 0)};
769 Builder.CreateCall(RegisterVar, RegisterVarArgs);
770
771 llvm::FunctionCallee RegisterShadow = CGM.CreateRuntimeFunction(
772 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
773 "__llvm_profile_offload_register_shadow_variable");
774 Builder.CreateCall(RegisterShadow, {OffloadProfShadow});
775 }
776
777 Builder.CreateRetVoid();
778 return RegisterKernelsFunc;
779}
780
781/// Creates a global constructor function for the module:
782///
783/// For CUDA:
784/// \code
785/// void __cuda_module_ctor() {
786/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
787/// __cuda_register_globals(Handle);
788/// }
789/// \endcode
790///
791/// For HIP:
792/// \code
793/// void __hip_module_ctor() {
794/// if (__hip_gpubin_handle == 0) {
795/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);
796/// __hip_register_globals(__hip_gpubin_handle);
797/// }
798/// }
799/// \endcode
800llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
801 bool IsHIP = CGM.getLangOpts().HIP;
802 bool IsCUDA = CGM.getLangOpts().CUDA;
803 // No need to generate ctors/dtors if there is no GPU binary.
804 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
805 if (CudaGpuBinaryFileName.empty() && !IsHIP)
806 return nullptr;
807 if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&
808 DeviceVars.empty())
809 return nullptr;
810
811 // void __{cuda|hip}_register_globals(void* handle);
812 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
813 // We always need a function to pass in as callback. Create a dummy
814 // implementation if we don't need to register anything.
815 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
816 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
817
818 // void ** __{cuda|hip}RegisterFatBinary(void *);
819 llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
820 llvm::FunctionType::get(PtrTy, PtrTy, false),
821 addUnderscoredPrefixToName("RegisterFatBinary"));
822 // struct { int magic, int version, void * gpu_binary, void * dont_care };
823 llvm::StructType *FatbinWrapperTy =
824 llvm::StructType::get(IntTy, IntTy, PtrTy, PtrTy);
825
826 // Register GPU binary with the CUDA runtime, store returned handle in a
827 // global variable and save a reference in GpuBinaryHandle to be cleaned up
828 // in destructor on exit. Then associate all known kernels with the GPU binary
829 // handle so CUDA runtime can figure out what to call on the GPU side.
830 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
831 if (!CudaGpuBinaryFileName.empty()) {
832 auto VFS = CGM.getFileSystem();
833 auto CudaGpuBinaryOrErr =
834 VFS->getBufferForFile(CudaGpuBinaryFileName, -1, false);
835 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
836 CGM.getDiags().Report(diag::err_cannot_open_file)
837 << CudaGpuBinaryFileName << EC.message();
838 return nullptr;
839 }
840 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
841 }
842
843 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
844 llvm::FunctionType::get(VoidTy, false),
845 llvm::GlobalValue::InternalLinkage,
846 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
847 llvm::BasicBlock *CtorEntryBB =
848 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
849 CGBuilderTy CtorBuilder(CGM, Context);
850
851 CtorBuilder.SetInsertPoint(CtorEntryBB);
852
853 const char *FatbinConstantName;
854 const char *FatbinSectionName;
855 const char *ModuleIDSectionName;
856 StringRef ModuleIDPrefix;
857 llvm::Constant *FatBinStr;
858 unsigned FatMagic;
859 if (IsHIP) {
860 // On macOS (Mach-O), section names must be in "segment,section" format.
861 FatbinConstantName =
862 CGM.getTriple().isMacOSX() ? "__HIP,__hip_fatbin" : ".hip_fatbin";
863 FatbinSectionName =
864 CGM.getTriple().isMacOSX() ? "__HIP,__fatbin" : ".hipFatBinSegment";
865
866 ModuleIDSectionName =
867 CGM.getTriple().isMacOSX() ? "__HIP,__module_id" : "__hip_module_id";
868 ModuleIDPrefix = "__hip_";
869
870 if (CudaGpuBinary) {
871 // If fatbin is available from early finalization, create a string
872 // literal containing the fat binary loaded from the given file.
873 const unsigned HIPCodeObjectAlign = 4096;
874 FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",
875 FatbinConstantName, HIPCodeObjectAlign);
876 } else {
877 // If fatbin is not available, create an external symbol
878 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
879 // to contain the fat binary but will be populated somewhere else,
880 // e.g. by lld through link script.
881 FatBinStr = new llvm::GlobalVariable(
882 CGM.getModule(), CGM.Int8Ty,
883 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
884 "__hip_fatbin" + (CGM.getLangOpts().CUID.empty()
885 ? ""
886 : "_" + CGM.getContext().getCUIDHash()),
887 nullptr, llvm::GlobalVariable::NotThreadLocal);
888 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
889 }
890
891 FatMagic = HIPFatMagic;
892 } else {
893 if (RelocatableDeviceCode)
894 FatbinConstantName = CGM.getTriple().isMacOSX()
895 ? "__NV_CUDA,__nv_relfatbin"
896 : "__nv_relfatbin";
897 else
898 FatbinConstantName =
899 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
900 // NVIDIA's cuobjdump looks for fatbins in this section.
901 FatbinSectionName =
902 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
903
904 ModuleIDSectionName = CGM.getTriple().isMacOSX()
905 ? "__NV_CUDA,__nv_module_id"
906 : "__nv_module_id";
907 ModuleIDPrefix = "__nv_";
908
909 // For CUDA, create a string literal containing the fat binary loaded from
910 // the given file.
911 FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",
912 FatbinConstantName, 8);
913 FatMagic = CudaFatMagic;
914 }
915
916 // Create initialized wrapper structure that points to the loaded GPU binary
917 ConstantInitBuilder Builder(CGM);
918 auto Values = Builder.beginStruct(FatbinWrapperTy);
919 // Fatbin wrapper magic.
920 Values.addInt(IntTy, FatMagic);
921 // Fatbin version.
922 Values.addInt(IntTy, 1);
923 // Data.
924 Values.add(FatBinStr);
925 // Unused in fatbin v1.
926 Values.add(llvm::ConstantPointerNull::get(PtrTy));
927 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
928 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
929 /*constant*/ true);
930 FatbinWrapper->setSection(FatbinSectionName);
932
933 // There is only one HIP fat binary per linked module, however there are
934 // multiple constructor functions. Make sure the fat binary is registered
935 // only once. The constructor functions are executed by the dynamic loader
936 // before the program gains control. The dynamic loader cannot execute the
937 // constructor functions concurrently since doing that would not guarantee
938 // thread safety of the loaded program. Therefore we can assume sequential
939 // execution of constructor functions here.
940 if (IsHIP) {
941 auto Linkage = RelocatableDeviceCode ? llvm::GlobalValue::ExternalLinkage
942 : llvm::GlobalValue::InternalLinkage;
943 llvm::BasicBlock *IfBlock =
944 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
945 llvm::BasicBlock *ExitBlock =
946 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
947 // The name, size, and initialization pattern of this variable is part
948 // of HIP ABI.
949 GpuBinaryHandle = new llvm::GlobalVariable(
950 TheModule, PtrTy, /*isConstant=*/false, Linkage,
951 /*Initializer=*/
952 !RelocatableDeviceCode ? llvm::ConstantPointerNull::get(PtrTy)
953 : nullptr,
954 "__hip_gpubin_handle" + (CGM.getLangOpts().CUID.empty()
955 ? ""
956 : "_" + CGM.getContext().getCUIDHash()));
957 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
958 // Prevent the weak symbol in different shared libraries being merged.
959 if (Linkage != llvm::GlobalValue::InternalLinkage)
960 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
961 Address GpuBinaryAddr(
962 GpuBinaryHandle, PtrTy,
963 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
964 {
965 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
966 llvm::Constant *Zero =
967 llvm::Constant::getNullValue(HandleValue->getType());
968 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
969 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
970 }
971 {
972 CtorBuilder.SetInsertPoint(IfBlock);
973 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
974 llvm::CallInst *RegisterFatbinCall =
975 CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);
976 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
977 CtorBuilder.CreateBr(ExitBlock);
978 }
979 {
980 CtorBuilder.SetInsertPoint(ExitBlock);
981 // Call __hip_register_globals(GpuBinaryHandle);
982 if (RegisterGlobalsFunc) {
983 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
984 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
985 }
986 }
987 } else if (!RelocatableDeviceCode) {
988 // Register binary with CUDA runtime. This is substantially different in
989 // default mode vs. separate compilation!
990 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
991 llvm::CallInst *RegisterFatbinCall =
992 CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);
993 GpuBinaryHandle = new llvm::GlobalVariable(
994 TheModule, PtrTy, false, llvm::GlobalValue::InternalLinkage,
995 llvm::ConstantPointerNull::get(PtrTy), "__cuda_gpubin_handle");
996 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
997 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
998 CGM.getPointerAlign());
999
1000 // Call __cuda_register_globals(GpuBinaryHandle);
1001 if (RegisterGlobalsFunc)
1002 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
1003
1004 // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
1006 CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
1007 // void __cudaRegisterFatBinaryEnd(void **);
1008 llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
1009 llvm::FunctionType::get(VoidTy, PtrTy, false),
1010 "__cudaRegisterFatBinaryEnd");
1011 CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
1012 }
1013 } else {
1014 // Generate a unique module ID.
1015 SmallString<64> ModuleID;
1016 llvm::raw_svector_ostream OS(ModuleID);
1017 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
1018 llvm::Constant *ModuleIDConstant = makeConstantArray(
1019 std::string(ModuleID), "", ModuleIDSectionName, 32, /*AddNull=*/true);
1020
1021 // Create an alias for the FatbinWrapper that nvcc will look for.
1022 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
1023 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
1024
1025 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
1026 // void *, void (*)(void **))
1027 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
1028 RegisterLinkedBinaryName += ModuleID;
1029 llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
1030 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
1031
1032 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
1033 llvm::Value *Args[] = {RegisterGlobalsFunc, FatbinWrapper, ModuleIDConstant,
1034 makeDummyFunction(getCallbackFnTy())};
1035 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
1036 }
1037
1038 // Create destructor and register it with atexit() the way NVCC does it. Doing
1039 // it during regular destructor phase worked in CUDA before 9.2 but results in
1040 // double-free in 9.2.
1041 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
1042 // extern "C" int atexit(void (*f)(void));
1043 llvm::FunctionType *AtExitTy =
1044 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
1045 llvm::FunctionCallee AtExitFunc =
1046 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
1047 /*Local=*/true);
1048 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
1049 }
1050
1051 CtorBuilder.CreateRetVoid();
1052 return ModuleCtorFunc;
1053}
1054
1055/// Creates a global destructor function that unregisters the GPU code blob
1056/// registered by constructor.
1057///
1058/// For CUDA:
1059/// \code
1060/// void __cuda_module_dtor() {
1061/// __cudaUnregisterFatBinary(Handle);
1062/// }
1063/// \endcode
1064///
1065/// For HIP:
1066/// \code
1067/// void __hip_module_dtor() {
1068/// if (__hip_gpubin_handle) {
1069/// __hipUnregisterFatBinary(__hip_gpubin_handle);
1070/// __hip_gpubin_handle = 0;
1071/// }
1072/// }
1073/// \endcode
1074llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
1075 // No need for destructor if we don't have a handle to unregister.
1076 if (!GpuBinaryHandle)
1077 return nullptr;
1078
1079 // void __cudaUnregisterFatBinary(void ** handle);
1080 llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
1081 llvm::FunctionType::get(VoidTy, PtrTy, false),
1082 addUnderscoredPrefixToName("UnregisterFatBinary"));
1083
1084 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
1085 llvm::FunctionType::get(VoidTy, false),
1086 llvm::GlobalValue::InternalLinkage,
1087 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
1088
1089 llvm::BasicBlock *DtorEntryBB =
1090 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
1091 CGBuilderTy DtorBuilder(CGM, Context);
1092 DtorBuilder.SetInsertPoint(DtorEntryBB);
1093
1094 Address GpuBinaryAddr(
1095 GpuBinaryHandle, GpuBinaryHandle->getValueType(),
1096 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
1097 auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
1098 // There is only one HIP fat binary per linked module, however there are
1099 // multiple destructor functions. Make sure the fat binary is unregistered
1100 // only once.
1101 if (CGM.getLangOpts().HIP) {
1102 llvm::BasicBlock *IfBlock =
1103 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
1104 llvm::BasicBlock *ExitBlock =
1105 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
1106 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
1107 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
1108 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
1109
1110 DtorBuilder.SetInsertPoint(IfBlock);
1111 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
1112 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
1113 DtorBuilder.CreateBr(ExitBlock);
1114
1115 DtorBuilder.SetInsertPoint(ExitBlock);
1116 } else {
1117 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
1118 }
1119 DtorBuilder.CreateRetVoid();
1120 return ModuleDtorFunc;
1121}
1122
1124 return new CGNVCUDARuntime(CGM);
1125}
1126
1127void CGNVCUDARuntime::internalizeDeviceSideVar(
1128 const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) {
1129 // For -fno-gpu-rdc, host-side shadows of external declarations of device-side
1130 // global variables become internal definitions. These have to be internal in
1131 // order to prevent name conflicts with global host variables with the same
1132 // name in a different TUs.
1133 //
1134 // For -fgpu-rdc, the shadow variables should not be internalized because
1135 // they may be accessed by different TU.
1136 if (CGM.getLangOpts().GPURelocatableDeviceCode)
1137 return;
1138
1139 // __shared__ variables are odd. Shadows do get created, but
1140 // they are not registered with the CUDA runtime, so they
1141 // can't really be used to access their device-side
1142 // counterparts. It's not clear yet whether it's nvcc's bug or
1143 // a feature, but we've got to do the same for compatibility.
1144 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
1145 D->hasAttr<CUDASharedAttr>() ||
1148 Linkage = llvm::GlobalValue::InternalLinkage;
1149 }
1150}
1151
1152void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D,
1153 llvm::GlobalVariable &GV) {
1154 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
1155 // Shadow variables and their properties must be registered with CUDA
1156 // runtime. Skip Extern global variables, which will be registered in
1157 // the TU where they are defined.
1158 //
1159 // Don't register a C++17 inline variable. The local symbol can be
1160 // discarded and referencing a discarded local symbol from outside the
1161 // comdat (__cuda_register_globals) is disallowed by the ELF spec.
1162 //
1163 // HIP managed variables need to be always recorded in device and host
1164 // compilations for transformation.
1165 //
1166 // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are
1167 // added to llvm.compiler-used, therefore they are safe to be registered.
1168 if ((!D->hasExternalStorage() && !D->isInline()) ||
1169 CGM.getContext().CUDADeviceVarODRUsedByHost.contains(D) ||
1170 D->hasAttr<HIPManagedAttr>()) {
1171 registerDeviceVar(D, GV, !D->hasDefinition(),
1172 D->hasAttr<CUDAConstantAttr>());
1173 }
1174 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
1176 // Builtin surfaces and textures and their template arguments are
1177 // also registered with CUDA runtime.
1180 const TemplateArgumentList &Args = TD->getTemplateArgs();
1181 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
1182 assert(Args.size() == 2 &&
1183 "Unexpected number of template arguments of CUDA device "
1184 "builtin surface type.");
1185 auto SurfType = Args[1].getAsIntegral();
1186 if (!D->hasExternalStorage())
1187 registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue());
1188 } else {
1189 assert(Args.size() == 3 &&
1190 "Unexpected number of template arguments of CUDA device "
1191 "builtin texture type.");
1192 auto TexType = Args[1].getAsIntegral();
1193 auto Normalized = Args[2].getAsIntegral();
1194 if (!D->hasExternalStorage())
1195 registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(),
1196 Normalized.getZExtValue());
1197 }
1198 }
1199}
1200
1201// Transform managed variables to pointers to managed variables in device code.
1202// Each use of the original managed variable is replaced by a load from the
1203// transformed managed variable. The transformed managed variable contains
1204// the address of managed memory which will be allocated by the runtime.
1205void CGNVCUDARuntime::transformManagedVars() {
1206 for (auto &&Info : DeviceVars) {
1207 llvm::GlobalVariable *Var = Info.Var;
1208 if (Info.Flags.getKind() == DeviceVarFlags::Variable &&
1209 Info.Flags.isManaged()) {
1210 auto *ManagedVar = new llvm::GlobalVariable(
1211 CGM.getModule(), Var->getType(),
1212 /*isConstant=*/false, Var->getLinkage(),
1213 /*Init=*/Var->isDeclaration()
1214 ? nullptr
1215 : llvm::ConstantPointerNull::get(Var->getType()),
1216 /*Name=*/"", /*InsertBefore=*/nullptr,
1217 llvm::GlobalVariable::NotThreadLocal,
1218 CGM.getContext().getTargetAddressSpace(CGM.getLangOpts().CUDAIsDevice
1219 ? LangAS::cuda_device
1220 : LangAS::Default));
1221 ManagedVar->setDSOLocal(Var->isDSOLocal());
1222 ManagedVar->setVisibility(Var->getVisibility());
1223 ManagedVar->setExternallyInitialized(true);
1224 replaceManagedVar(Var, ManagedVar);
1225 ManagedVar->takeName(Var);
1226 Var->setName(Twine(ManagedVar->getName()) + ".managed");
1227 // Keep managed variables even if they are not used in device code since
1228 // they need to be allocated by the runtime.
1229 if (CGM.getLangOpts().CUDAIsDevice && !Var->isDeclaration()) {
1230 assert(!ManagedVar->isDeclaration());
1231 CGM.addCompilerUsedGlobal(Var);
1232 CGM.addCompilerUsedGlobal(ManagedVar);
1233 }
1234 }
1235 }
1236}
1237
1238// Creates offloading entries for all the kernels and globals that must be
1239// registered. The linker will provide a pointer to this section so we can
1240// register the symbols with the linked device image.
1241void CGNVCUDARuntime::createOffloadingEntries() {
1242 llvm::object::OffloadKind Kind = CGM.getLangOpts().HIP
1243 ? llvm::object::OffloadKind::OFK_HIP
1244 : llvm::object::OffloadKind::OFK_Cuda;
1245 // For now, just spoof this as OpenMP because that's the runtime it uses.
1246 if (CGM.getLangOpts().OffloadViaLLVM)
1247 Kind = llvm::object::OffloadKind::OFK_OpenMP;
1248
1249 llvm::Module &M = CGM.getModule();
1250 for (KernelInfo &I : EmittedKernels)
1251 llvm::offloading::emitOffloadingEntry(
1252 M, Kind, KernelHandles[I.Kernel->getName()],
1253 getDeviceSideName(cast<NamedDecl>(I.D)), /*Flags=*/0, /*Data=*/0,
1254 llvm::offloading::OffloadGlobalEntry);
1255
1256 for (VarInfo &I : DeviceVars) {
1257 uint64_t VarSize =
1258 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
1259 int32_t Flags =
1260 (I.Flags.isExtern()
1261 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalExtern)
1262 : 0) |
1263 (I.Flags.isConstant()
1264 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalConstant)
1265 : 0) |
1266 (I.Flags.isNormalized()
1267 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalNormalized)
1268 : 0);
1269 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
1270 if (I.Flags.isManaged()) {
1271 assert(I.Var->getName().ends_with(".managed") &&
1272 "HIP managed variables not transformed");
1273
1274 auto *ManagedVar = M.getNamedGlobal(
1275 I.Var->getName().drop_back(StringRef(".managed").size()));
1276 llvm::offloading::emitOffloadingEntry(
1277 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1278 llvm::offloading::OffloadGlobalManagedEntry | Flags,
1279 /*Data=*/I.Var->getAlignment(), ManagedVar);
1280 } else {
1281 llvm::offloading::emitOffloadingEntry(
1282 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1283 llvm::offloading::OffloadGlobalEntry | Flags,
1284 /*Data=*/0);
1285 }
1286 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
1287 llvm::offloading::emitOffloadingEntry(
1288 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1289 llvm::offloading::OffloadGlobalSurfaceEntry | Flags,
1290 I.Flags.getSurfTexType());
1291 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
1292 llvm::offloading::emitOffloadingEntry(
1293 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1294 llvm::offloading::OffloadGlobalTextureEntry | Flags,
1295 I.Flags.getSurfTexType());
1296 }
1297 }
1298
1299 // Register the per-TU offload-profiling shadow. The offloading entry
1300 // makes the linker-wrapper emit the host __hipRegisterVar call in the
1301 // combined ctor. Separately emit a per-TU ctor that registers the
1302 // shadow with the profile runtime's drain list.
1303 if (OffloadProfShadow) {
1304 llvm::offloading::emitOffloadingEntry(
1305 M, Kind, OffloadProfShadow, OffloadProfShadow->getName(),
1306 CGM.getDataLayout().getPointerSize(),
1307 llvm::offloading::OffloadGlobalEntry, /*Data=*/0);
1308
1309 llvm::LLVMContext &Ctx = M.getContext();
1310 auto *PtrTy = llvm::PointerType::getUnqual(Ctx);
1311 llvm::FunctionCallee RegisterShadow = CGM.CreateRuntimeFunction(
1312 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
1313 "__llvm_profile_offload_register_shadow_variable");
1314 auto *CtorFn = llvm::Function::Create(
1315 llvm::FunctionType::get(VoidTy, false),
1316 llvm::GlobalValue::InternalLinkage,
1317 "__llvm_profile_register_shadow." + CGM.getContext().getCUIDHash(), &M);
1318 auto *Entry = llvm::BasicBlock::Create(Ctx, "entry", CtorFn);
1319 llvm::IRBuilder<> B(Entry);
1320 B.CreateCall(RegisterShadow, {OffloadProfShadow});
1321 B.CreateRetVoid();
1322 llvm::appendToGlobalCtors(M, CtorFn, /*Priority=*/65535);
1323 }
1324}
1325
1326// For HIP host+device compiles with PGO enabled, emit the per-TU global
1327// __llvm_profile_sections_<CUID>. Device side: a 7-pointer struct holding
1328// section start/stop bounds for the names/counters/data sections plus the
1329// raw-version variable. Host side: an opaque void* shadow whose only
1330// purpose is to give the host-runtime a registered symbol name to look up
1331// via hipGetSymbolAddress; the actual device-side data lives in the
1332// matching device-side global.
1333void CGNVCUDARuntime::emitOffloadProfilingSections() {
1334 if (!CGM.getLangOpts().HIP)
1335 return;
1336 if (!CGM.getCodeGenOpts().hasProfileInstr())
1337 return;
1338
1339 StringRef CUIDHash = CGM.getContext().getCUIDHash();
1340 if (CUIDHash.empty())
1341 return;
1342
1343 llvm::Module &M = CGM.getModule();
1344 llvm::LLVMContext &Ctx = M.getContext();
1345 std::string Name = ("__llvm_profile_sections_" + CUIDHash).str();
1346
1347 // If the global already exists (e.g. another TU was merged in), don't
1348 // duplicate it.
1349 if (M.getNamedValue(Name))
1350 return;
1351
1352 if (CGM.getLangOpts().CUDAIsDevice) {
1353 // Device side: emit the populated struct. Section start/stop symbols
1354 // are linker-defined (ELF auto-generates __start_/__stop_ for any
1355 // section whose name is a valid C identifier; AMDGPU is ELF).
1356 unsigned GlobalAS = M.getDataLayout().getDefaultGlobalsAddressSpace();
1357 auto *PtrTy = llvm::PointerType::get(Ctx, GlobalAS);
1358 auto getOrDeclare = [&](StringRef SymName) {
1359 if (auto *GV = M.getNamedGlobal(SymName))
1360 return GV;
1361 auto *GV = new llvm::GlobalVariable(
1362 M, llvm::Type::getInt8Ty(Ctx), /*isConstant=*/false,
1363 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr, SymName,
1364 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1365 GlobalAS);
1366 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1367 return GV;
1368 };
1369 auto *VersionGV = M.getNamedGlobal("__llvm_profile_raw_version");
1370 if (!VersionGV) {
1371 VersionGV = new llvm::GlobalVariable(
1372 M, llvm::Type::getInt64Ty(Ctx), /*isConstant=*/true,
1373 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
1374 "__llvm_profile_raw_version",
1375 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1376 GlobalAS);
1377 }
1378
1379 auto *StructTy = llvm::StructType::get(
1380 Ctx, {PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy});
1381 llvm::Constant *Fields[] = {
1382 getOrDeclare("__start___llvm_prf_names"),
1383 getOrDeclare("__stop___llvm_prf_names"),
1384 getOrDeclare("__start___llvm_prf_cnts"),
1385 getOrDeclare("__stop___llvm_prf_cnts"),
1386 getOrDeclare("__start___llvm_prf_data"),
1387 getOrDeclare("__stop___llvm_prf_data"),
1388 VersionGV,
1389 };
1390 auto *Init = llvm::ConstantStruct::get(StructTy, Fields);
1391 auto *GV = new llvm::GlobalVariable(
1392 M, StructTy, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
1393 Init, Name, /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1394 GlobalAS);
1395 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1396 CGM.addCompilerUsedGlobal(GV);
1397 return;
1398 }
1399
1400 // Host side: emit an opaque void* shadow. Layout doesn't matter — the
1401 // runtime locates it by name via hipGetSymbolAddress and treats it as
1402 // the address of the device-side struct. Registration with the HIP
1403 // runtime is added by makeRegisterGlobalsFn (non-RDC) or
1404 // createOffloadingEntries (RDC).
1405 auto *PtrTy = llvm::PointerType::getUnqual(Ctx);
1406 OffloadProfShadow = new llvm::GlobalVariable(
1407 M, PtrTy, /*isConstant=*/false, llvm::GlobalValue::ExternalLinkage,
1408 llvm::ConstantPointerNull::get(PtrTy), Name);
1409 CGM.addCompilerUsedGlobal(OffloadProfShadow);
1410}
1411
1412// Returns module constructor to be added.
1413llvm::Function *CGNVCUDARuntime::finalizeModule() {
1414 transformManagedVars();
1415 emitOffloadProfilingSections();
1416 if (CGM.getLangOpts().CUDAIsDevice) {
1417 // Mark ODR-used device variables as compiler used to prevent it from being
1418 // eliminated by optimization. This is necessary for device variables
1419 // ODR-used by host functions. Sema correctly marks them as ODR-used no
1420 // matter whether they are ODR-used by device or host functions.
1421 //
1422 // We do not need to do this if the variable has used attribute since it
1423 // has already been added.
1424 //
1425 // Static device variables have been externalized at this point, therefore
1426 // variables with LLVM private or internal linkage need not be added.
1427 for (auto &&Info : DeviceVars) {
1428 auto Kind = Info.Flags.getKind();
1429 if (!Info.Var->isDeclaration() &&
1430 !llvm::GlobalValue::isLocalLinkage(Info.Var->getLinkage()) &&
1431 (Kind == DeviceVarFlags::Variable ||
1432 Kind == DeviceVarFlags::Surface ||
1433 Kind == DeviceVarFlags::Texture) &&
1434 Info.D->isUsed() && !Info.D->hasAttr<UsedAttr>()) {
1435 CGM.addCompilerUsedGlobal(Info.Var);
1436 }
1437 }
1438 return nullptr;
1439 }
1440 if (CGM.getLangOpts().OffloadViaLLVM ||
1441 (CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode))
1442 createOffloadingEntries();
1443 else
1444 return makeModuleCtorFunction();
1445
1446 return nullptr;
1447}
1448
1449llvm::GlobalValue *CGNVCUDARuntime::getKernelHandle(llvm::Function *F,
1450 GlobalDecl GD) {
1451 auto Loc = KernelHandles.find(F->getName());
1452 if (Loc != KernelHandles.end()) {
1453 auto OldHandle = Loc->second;
1454 if (KernelStubs[OldHandle] == F)
1455 return OldHandle;
1456
1457 // We've found the function name, but F itself has changed, so we need to
1458 // update the references.
1459 if (CGM.getLangOpts().HIP) {
1460 // For HIP compilation the handle itself does not change, so we only need
1461 // to update the Stub value.
1462 KernelStubs[OldHandle] = F;
1463 return OldHandle;
1464 }
1465 // For non-HIP compilation, erase the old Stub and fall-through to creating
1466 // new entries.
1467 KernelStubs.erase(OldHandle);
1468 }
1469
1470 if (!CGM.getLangOpts().HIP) {
1471 KernelHandles[F->getName()] = F;
1472 KernelStubs[F] = F;
1473 return F;
1474 }
1475
1476 auto *Var = new llvm::GlobalVariable(
1477 TheModule, F->getType(), /*isConstant=*/true, F->getLinkage(),
1478 /*Initializer=*/nullptr,
1479 CGM.getMangledName(
1480 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel)));
1481 Var->setAlignment(CGM.getPointerAlign().getAsAlign());
1482 Var->setDSOLocal(F->isDSOLocal());
1483 Var->setVisibility(F->getVisibility());
1484 auto *FD = cast<FunctionDecl>(GD.getDecl());
1485 auto *FT = FD->getPrimaryTemplate();
1486 if (!FT || FT->isThisDeclarationADefinition())
1487 CGM.maybeSetTrivialComdat(*FD, *Var);
1488 KernelHandles[F->getName()] = Var;
1489 KernelStubs[Var] = F;
1490 return Var;
1491}
static std::unique_ptr< MangleContext > InitDeviceMC(CodeGenModule &CGM)
Definition CGCUDANV.cpp:222
static void replaceManagedVar(llvm::GlobalVariable *Var, llvm::GlobalVariable *ManagedVar)
Definition CGCUDANV.cpp:565
Result
Implement __builtin_bit_cast and related operations.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
StringRef getCUIDHash() const
IdentifierTable & Idents
Definition ASTContext.h:804
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:924
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
TypeInfoChars getTypeInfoInChars(const Type *T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:923
unsigned getTargetAddressSpace(LangAS AS) const
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
bool hasProfileInstr() const
Check if any form of instrumentation is on.
std::string CudaGpuBinaryFileName
Name of file passed with -fcuda-include-gpubinary option to forward to CUDA runtime back-end for inco...
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition CGBuilder.h:153
llvm::StoreInst * CreateDefaultAlignedStore(llvm::Value *Val, llvm::Value *Addr, bool IsVolatile=false)
Definition CGBuilder.h:161
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:138
void add(RValue rvalue, QualType type)
Definition CGCall.h:303
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5295
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:159
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5451
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:231
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:108
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:663
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:643
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
SanitizerMetadata * getSanitizerMetadata()
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeFunctionDeclaration(const GlobalDecl GD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition CGCall.cpp:531
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
Definition GlobalDecl.h:203
const Decl * getDecl() const
Definition GlobalDecl.h:106
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
std::string CUID
The user provided compilation unit ID, if non-empty.
GPUDefaultStreamKind GPUDefaultStream
The default stream kind used for HIP kernel launching.
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:127
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:190
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
QualType getCanonicalType() const
Definition TypeBase.h:8497
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
const llvm::VersionTuple & getSDKVersion() const
unsigned size() const
Retrieve the number of template arguments in this template argument list.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition Decl.h:151
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5460
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5469
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1230
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
@ VFS
Remove unused -ivfsoverlay arguments.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
CudaVersion ToCudaVersion(llvm::VersionTuple)
Definition Cuda.cpp:72
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:172
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Type
The name was classified as a type.
Definition Sema.h:564
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64