Coverage Report

Created: 2020-09-19 12:23

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