clang 24.0.0git
CIRGenCUDANV.cpp
Go to the documentation of this file.
1//========- CIRGenCUDANV.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 "CIRGenCUDARuntime.h"
15#include "CIRGenCXXABI.h"
16#include "CIRGenFunction.h"
17#include "CIRGenModule.h"
18#include "mlir/IR/Operation.h"
20#include "clang/AST/Attrs.inc"
21#include "clang/AST/Decl.h"
24#include "clang/Basic/Cuda.h"
30#include "llvm/Support/Casting.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/VirtualFileSystem.h"
33
34using namespace clang;
35using namespace clang::CIRGen;
36
37namespace {
38
39class CIRGenNVCUDARuntime : public CIRGenCUDARuntime {
40protected:
41 StringRef prefix;
42
43 // Map a device stub function to a symbol for identifying kernel in host
44 // code. For CUDA, the symbol for identifying the kernel is the same as the
45 // device stub function. For HIP, they are different.
46 llvm::StringMap<mlir::Operation *> kernelHandles;
47
48 // Map a kernel handle to the kernel stub.
49 llvm::DenseMap<mlir::Operation *, mlir::Operation *> kernelStubs;
50
51 struct VarInfo {
52 cir::GlobalOp var;
53 const VarDecl *d;
54 cir::CUDADeviceVarKind flags;
55 };
56 llvm::SmallVector<VarInfo, 16> deviceVars;
57
58 // Mangle context for device.
59 std::unique_ptr<MangleContext> deviceMC;
60
61private:
62 void emitDeviceStubBodyNew(CIRGenFunction &cgf, cir::FuncOp fn,
63 FunctionArgList &args);
64 void recordDeviceBinary();
65 void transformManagedVars();
66 mlir::Value prepareKernelArgs(CIRGenFunction &cgf, mlir::Location loc,
67 FunctionArgList &args);
68 mlir::Operation *getKernelHandle(cir::FuncOp fn, GlobalDecl gd) override;
69
70 mlir::Operation *getKernelStub(mlir::Operation *handle) override {
71 auto it = kernelStubs.find(handle);
72 assert(it != kernelStubs.end());
73 return it->second;
74 }
75 std::string addPrefixToName(StringRef funcName) const;
76 std::string addUnderscoredPrefixToName(StringRef funcName) const;
77
78public:
79 CIRGenNVCUDARuntime(CIRGenModule &cgm);
80 ~CIRGenNVCUDARuntime();
81
82 void emitDeviceStub(CIRGenFunction &cgf, cir::FuncOp fn,
83 FunctionArgList &args) override;
84
85 void handleVarRegistration(const VarDecl *vd, cir::GlobalOp var) override;
86 void finalizeModule() override;
87 void handleGlobalReplace(cir::GlobalOp oldGV, cir::GlobalOp newGV) override;
88
89 void internalizeDeviceSideVar(const VarDecl *d,
90 cir::GlobalLinkageKind &linkage) override;
91
92 std::string getDeviceSideName(const NamedDecl *nd) override;
93
94 void registerDeviceVar(const VarDecl *vd, cir::GlobalOp &var, bool isExtern,
95 bool isConstant) {
96 // Attach the device var attribute to the GlobalOp
97 auto &builder = cgm.getBuilder();
98 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
99 cir::CUDAVarRegistrationInfoAttr::get(
100 builder.getContext(),
101 getDeviceSideName(cast<NamedDecl>(vd)),
102 cir::CUDADeviceVarKind::Variable, isExtern, isConstant,
103 vd->hasAttr<HIPManagedAttr>(),
104 /*surfTexType=*/0,
105 /*normalized=*/false));
106 deviceVars.push_back({
107 var,
108 vd,
109 cir::CUDADeviceVarKind::Variable,
110 });
111 }
112
113 void registerDeviceSurf(const VarDecl *vd, cir::GlobalOp &var, bool isExtern,
114 int32_t surfaceType) {
115 auto &builder = cgm.getBuilder();
116
117 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
118 cir::CUDAVarRegistrationInfoAttr::get(
119 builder.getContext(),
120 getDeviceSideName(cast<NamedDecl>(vd)),
121 cir::CUDADeviceVarKind::Surface, isExtern,
122 /*isConstant=*/false,
123 /*isManaged=*/false, surfaceType,
124 /*normalized=*/false));
125
126 deviceVars.push_back({
127 var,
128 vd,
129 cir::CUDADeviceVarKind::Surface,
130 });
131 }
132
133 void registerDeviceTex(const VarDecl *vd, cir::GlobalOp &var, bool isExtern,
134 int32_t textureType, bool normalized) {
135 auto &builder = cgm.getBuilder();
136
137 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
138 cir::CUDAVarRegistrationInfoAttr::get(
139 builder.getContext(),
140 getDeviceSideName(cast<NamedDecl>(vd)),
141 cir::CUDADeviceVarKind::Texture, isExtern,
142 /*isConstant=*/false,
143 /*isManaged=*/false, textureType, normalized));
144
145 deviceVars.push_back({
146 var,
147 vd,
148 cir::CUDADeviceVarKind::Texture,
149 });
150 }
151};
152
153} // namespace
154
155std::string CIRGenNVCUDARuntime::addPrefixToName(StringRef funcName) const {
156 return (prefix + funcName).str();
157}
158
159std::string
160CIRGenNVCUDARuntime::addUnderscoredPrefixToName(StringRef funcName) const {
161 return ("__" + prefix + funcName).str();
162}
163
164CIRGenNVCUDARuntime::CIRGenNVCUDARuntime(CIRGenModule &cgm)
165 : CIRGenCUDARuntime(cgm),
166 deviceMC(cgm.getASTContext().cudaNVInitDeviceMC()) {
167 if (cgm.getLangOpts().OffloadViaLLVM)
168 cgm.errorNYI("CIRGenNVCUDARuntime: Offload via LLVM");
169 else if (cgm.getLangOpts().HIP)
170 prefix = "hip";
171 else
172 prefix = "cuda";
173}
174
175mlir::Value CIRGenNVCUDARuntime::prepareKernelArgs(CIRGenFunction &cgf,
176 mlir::Location loc,
177 FunctionArgList &args) {
178 CIRGenBuilderTy &builder = cgm.getBuilder();
179
180 // Build void *args[] and populate with the addresses of kernel arguments.
181 auto voidPtrArrayTy = cir::ArrayType::get(cgm.voidPtrTy, args.size());
182 mlir::Value kernelArgs =
183 builder.createAlloca(loc, cir::PointerType::get(voidPtrArrayTy),
184 "kernel_args", CharUnits::fromQuantity(16));
185
186 mlir::Value kernelArgsDecayed =
187 builder.createCast(cir::CastKind::array_to_ptrdecay, kernelArgs,
188 cir::PointerType::get(cgm.voidPtrTy));
189
190 for (const auto &[i, arg] : llvm::enumerate(args)) {
191 mlir::Value index =
192 builder.getConstInt(loc, llvm::APInt(/*numBits=*/32, i));
193 mlir::Value storePos =
194 builder.createPtrStride(loc, kernelArgsDecayed, index);
195 mlir::Value argAddr = cgf.getAddrOfLocalVar(arg).getPointer();
196 mlir::Value argAsVoid = builder.createBitcast(argAddr, cgm.voidPtrTy);
197
198 builder.CIRBaseBuilderTy::createStore(loc, argAsVoid, storePos);
199 }
200
201 return kernelArgsDecayed;
202}
203
204// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
205// array and kernels are launched using cudaLaunchKernel().
206void CIRGenNVCUDARuntime::emitDeviceStubBodyNew(CIRGenFunction &cgf,
207 cir::FuncOp fn,
208 FunctionArgList &args) {
209
210 // This requires arguments to be sent to kernels in a different way.
211 if (cgm.getLangOpts().OffloadViaLLVM)
212 cgm.errorNYI("CIRGenNVCUDARuntime: Offload via LLVM");
213
214 CIRGenBuilderTy &builder = cgm.getBuilder();
215 mlir::Location loc = fn.getLoc();
216
217 // For [cuda|hip]LaunchKernel, we must add another layer of indirection
218 // to arguments. For example, for function `add(int a, float b)`,
219 // we need to pass it as `void *args[2] = { &a, &b }`.
220 mlir::Value kernelArgs = prepareKernelArgs(cgf, loc, args);
221
222 // Lookup cudaLaunchKernel/hipLaunchKernel function.
223 // HIP kernel launching API name depends on -fgpu-default-stream option. For
224 // the default value 'legacy', it is hipLaunchKernel. For 'per-thread',
225 // it is hipLaunchKernel_spt.
226 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
227 // void **args, size_t sharedMem,
228 // cudaStream_t stream);
229 // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,
230 // dim3 blockDim, void **args,
231 // size_t sharedMem, hipStream_t stream);
232 TranslationUnitDecl *tuDecl = cgm.getASTContext().getTranslationUnitDecl();
233 DeclContext *dc = TranslationUnitDecl::castToDeclContext(tuDecl);
234
235 // The default stream is usually stream 0 (the legacy default stream).
236 // For per-thread default stream, we need a different LaunchKernel function.
237 std::string kernelLaunchAPI = "LaunchKernel";
238 if (cgm.getLangOpts().GPUDefaultStream ==
239 LangOptions::GPUDefaultStreamKind::PerThread) {
240 if (cgm.getLangOpts().HIP)
241 kernelLaunchAPI += "_spt";
242 else if (cgm.getLangOpts().CUDA)
243 kernelLaunchAPI += "_ptsz";
244 }
245
246 std::string launchKernelName = addPrefixToName(kernelLaunchAPI);
247 const IdentifierInfo &launchII =
248 cgm.getASTContext().Idents.get(launchKernelName);
249 FunctionDecl *cudaLaunchKernelFD = nullptr;
250 for (NamedDecl *result : dc->lookup(&launchII)) {
251 if (FunctionDecl *fd = dyn_cast<FunctionDecl>(result))
252 cudaLaunchKernelFD = fd;
253 }
254
255 if (cudaLaunchKernelFD == nullptr) {
256 cgm.error(cgf.curFuncDecl->getLocation(),
257 "Can't find declaration for " + launchKernelName);
258 return;
259 }
260
261 // Use this function to retrieve arguments for cudaLaunchKernel:
262 // int __[cuda|hip]PopCallConfiguration(dim3 *gridDim, dim3 *blockDim, size_t
263 // *sharedMem, cudaStream_t *stream)
264 //
265 // Here [cuda|hip]Stream_t, while also being the 6th argument of
266 // [cuda|hip]LaunchKernel, is a pointer to some opaque struct.
267
268 mlir::Type dim3Ty = cgf.getTypes().convertType(
269 cudaLaunchKernelFD->getParamDecl(1)->getType());
270 mlir::Type streamTy = cgf.getTypes().convertType(
271 cudaLaunchKernelFD->getParamDecl(5)->getType());
272
273 mlir::Value gridDim =
274 builder.createAlloca(loc, cir::PointerType::get(dim3Ty), "grid_dim",
276 mlir::Value blockDim =
277 builder.createAlloca(loc, cir::PointerType::get(dim3Ty), "block_dim",
279 mlir::Value sharedMem = builder.createAlloca(
280 loc, cir::PointerType::get(cgm.sizeTy), "shared_mem", cgm.getSizeAlign());
281 mlir::Value stream = builder.createAlloca(
282 loc, cir::PointerType::get(streamTy), "stream", cgm.getPointerAlign());
283
284 cir::FuncOp popConfig = cgm.createRuntimeFunction(
285 cir::FuncType::get({gridDim.getType(), blockDim.getType(),
286 sharedMem.getType(), stream.getType()},
287 cgm.sInt32Ty),
288 addUnderscoredPrefixToName("PopCallConfiguration"));
289 cgf.emitRuntimeCall(loc, popConfig, {gridDim, blockDim, sharedMem, stream});
290
291 // Now emit the call to cudaLaunchKernel
292 // [cuda|hip]Error_t [cuda|hip]LaunchKernel(const void *func, dim3 gridDim,
293 // dim3 blockDim,
294 // void **args, size_t sharedMem,
295 // [cuda|hip]Stream_t stream);
296
297 // We now either pick the function or the stub global for cuda, hip
298 // respectively.
299 mlir::Value kernel = [&]() -> mlir::Value {
300 if (cir::GlobalOp globalOp = llvm::dyn_cast_or_null<cir::GlobalOp>(
301 kernelHandles[fn.getSymName()])) {
302 cir::PointerType kernelTy = cir::PointerType::get(globalOp.getSymType());
303 mlir::Value kernelVal = cir::GetGlobalOp::create(builder, loc, kernelTy,
304 globalOp.getSymName());
305 mlir::Value func = builder.createBitcast(kernelVal, cgm.voidPtrTy);
306 return func;
307 }
308 if (cir::FuncOp funcOp = llvm::dyn_cast_or_null<cir::FuncOp>(
309 kernelHandles[fn.getSymName()])) {
310 cir::PointerType kernelTy =
311 cir::PointerType::get(funcOp.getFunctionType());
312 mlir::Value kernelVal =
313 cir::GetGlobalOp::create(builder, loc, kernelTy, funcOp.getSymName());
314 mlir::Value func = builder.createBitcast(kernelVal, cgm.voidPtrTy);
315 return func;
316 }
317 llvm_unreachable("Expected stub handle to be cir::GlobalOp or FuncOp");
318 }();
319
320 CallArgList launchArgs;
321 launchArgs.add(RValue::get(kernel),
322 cudaLaunchKernelFD->getParamDecl(0)->getType());
323 launchArgs.add(
325 cudaLaunchKernelFD->getParamDecl(1)->getType());
326 launchArgs.add(
328 cudaLaunchKernelFD->getParamDecl(2)->getType());
329 launchArgs.add(RValue::get(kernelArgs),
330 cudaLaunchKernelFD->getParamDecl(3)->getType());
331 launchArgs.add(
332 RValue::get(builder.CIRBaseBuilderTy::createLoad(loc, sharedMem)),
333 cudaLaunchKernelFD->getParamDecl(4)->getType());
334 launchArgs.add(RValue::get(builder.CIRBaseBuilderTy::createLoad(loc, stream)),
335 cudaLaunchKernelFD->getParamDecl(5)->getType());
336
337 mlir::Type launchTy =
338 cgm.getTypes().convertType(cudaLaunchKernelFD->getType());
339 mlir::Operation *cudaKernelLauncherFn = cgm.createRuntimeFunction(
340 cast<cir::FuncType>(launchTy), launchKernelName);
341 const CIRGenFunctionInfo &callInfo =
342 cgm.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
343 cgf.emitCall(callInfo, CIRGenCallee::forDirect(cudaKernelLauncherFn),
344 ReturnValueSlot(), launchArgs, /*isMustTail=*/false);
345
347 !cgf.getLangOpts().HIP)
348 cgm.errorNYI("MSVC CUDA stub handling");
349}
350
351void CIRGenNVCUDARuntime::emitDeviceStub(CIRGenFunction &cgf, cir::FuncOp fn,
352 FunctionArgList &args) {
353 CIRGenBuilderTy &builder = cgm.getBuilder();
354 StringRef kernelName = cgm.getMangledName(
355 cgf.curGD.getWithKernelReferenceKind(KernelReferenceKind::Kernel));
356 auto kernelNameAttr = cir::CUDAKernelNameAttr::get(
357 builder.getContext(), builder.getStringAttr(kernelName));
358 fn->setDiscardableAttr(cir::CUDAKernelNameAttr::getMnemonic(),
359 kernelNameAttr);
360
361 if (auto globalOp =
362 llvm::dyn_cast<cir::GlobalOp>(kernelHandles[fn.getSymName()])) {
363 mlir::Type fnPtrTy = globalOp.getSymType();
364 auto sym = mlir::FlatSymbolRefAttr::get(fn.getSymNameAttr());
365 auto gv = cir::GlobalViewAttr::get(fnPtrTy, sym);
366
367 globalOp->setAttr("initial_value", gv);
368 globalOp->setAttr("alignment", builder.getI64IntegerAttr(
370
371 // The stub's linkage is only final once it is defined, so the handle
372 // takes it over here.
373 globalOp.setLinkage(fn.getLinkage());
374 mlir::SymbolTable::setSymbolVisibility(
375 globalOp, cgm.getMLIRVisibilityFromCIRLinkage(fn.getLinkage()));
376 cgm.setDSOLocal(static_cast<mlir::Operation *>(globalOp));
377 }
378
379 // CUDA 9.0 changed the way to launch kernels.
381 CudaFeature::CUDA_USES_NEW_LAUNCH) ||
382 (cgm.getLangOpts().HIP && cgm.getLangOpts().HIPUseNewLaunchAPI) ||
383 cgm.getLangOpts().OffloadViaLLVM)
384 emitDeviceStubBodyNew(cgf, fn, args);
385 else
386 cgm.errorNYI("Emit Stub Body Legacy");
387}
388
390 return new CIRGenNVCUDARuntime(cgm);
391}
392
393CIRGenNVCUDARuntime::~CIRGenNVCUDARuntime() {}
394
395mlir::Operation *CIRGenNVCUDARuntime::getKernelHandle(cir::FuncOp fn,
396 GlobalDecl gd) {
397
398 // Check if we already have a kernel handle for this function
399 auto it = kernelHandles.find(fn.getSymName());
400 if (it != kernelHandles.end()) {
401 mlir::Operation *oldHandle = it->second;
402 // Here we know that the fn did not change. Return it
403 if (kernelStubs[oldHandle] == fn)
404 return oldHandle;
405
406 // We've found the function name, but F itself has changed, so we need to
407 // update the references.
408 if (cgm.getLangOpts().HIP) {
409 // For HIP compilation the handle itself does not change, so we only need
410 // to update the Stub value.
411 kernelStubs[oldHandle] = fn;
412 return oldHandle;
413 }
414 // For non-HIP compilation, erase the old Stub and fall-through to creating
415 // new entries.
416 kernelStubs.erase(oldHandle);
417 }
418
419 // If not targeting HIP, store the function itself
420 if (!cgm.getLangOpts().HIP) {
421 kernelHandles[fn.getSymName()] = fn;
422 kernelStubs[fn] = fn;
423 return fn;
424 }
425
426 // Create a new CIR global variable to represent the kernel handle
427 CIRGenBuilderTy &builder = cgm.getBuilder();
428 StringRef globalName = cgm.getMangledName(
429 gd.getWithKernelReferenceKind(KernelReferenceKind::Kernel));
430 cir::PointerType fnPtrTy = builder.getPointerTo(fn.getFunctionType());
431 cir::GlobalOp globalOp =
432 cgm.createGlobalOp(fn.getLoc(), globalName, fnPtrTy, /*isConstant=*/true);
433
434 globalOp->setAttr("alignment", builder.getI64IntegerAttr(
436
437 // Inherit visibility and comdat from the kernel's declaration.
438 auto *fd = cast<FunctionDecl>(gd.getDecl());
439 cgm.setGVProperties(globalOp, fd);
440 FunctionTemplateDecl *ft = fd->getPrimaryTemplate();
441 if (!ft || ft->isThisDeclarationADefinition())
442 cgm.maybeSetTrivialComdat(*fd, globalOp);
443
444 // Store references
445 kernelHandles[fn.getSymName()] = globalOp;
446 kernelStubs[globalOp] = fn;
447
448 return globalOp;
449}
450
451void CIRGenNVCUDARuntime::internalizeDeviceSideVar(
452 const VarDecl *d, cir::GlobalLinkageKind &linkage) {
453 if (cgm.getLangOpts().GPURelocatableDeviceCode)
454 cgm.errorNYI(d->getSourceRange(),
455 "internalizeDeviceSideVar: GPU Relocatable Device Code (RDC)");
456
457 // __shared__ variables are odd. Shadows do get created, but
458 // they are not registered with the CUDA runtime, so they
459 // can't really be used to access their device-side
460 // counterparts. It's not clear yet whether it's nvcc's bug or
461 // a feature, but we've got to do the same for compatibility.
462 if (d->hasAttr<CUDADeviceAttr>() || d->hasAttr<CUDAConstantAttr>() ||
463 d->hasAttr<CUDASharedAttr>() ||
466 linkage = cir::GlobalLinkageKind::InternalLinkage;
467 }
468}
469
470std::string CIRGenNVCUDARuntime::getDeviceSideName(const NamedDecl *nd) {
471 GlobalDecl gd;
472 // nd could be either a kernel or a variable.
473 if (auto *fd = dyn_cast<FunctionDecl>(nd))
474 gd = GlobalDecl(fd, KernelReferenceKind::Kernel);
475 else
476 gd = GlobalDecl(nd);
477 std::string deviceSideName;
478 MangleContext *mc;
479 if (cgm.getLangOpts().CUDAIsDevice)
480 mc = &cgm.getCXXABI().getMangleContext();
481 else
482 mc = deviceMC.get();
483 if (mc->shouldMangleDeclName(nd)) {
484 SmallString<256> buffer;
485 llvm::raw_svector_ostream out(buffer);
486 mc->mangleName(gd, out);
487 deviceSideName = std::string(out.str());
488 } else
489 deviceSideName = std::string(nd->getIdentifier()->getName());
490
491 // Make unique name for device side static file-scope variable for HIP.
492 if (cgm.getASTContext().shouldExternalize(nd) &&
493 cgm.getLangOpts().GPURelocatableDeviceCode) {
494 SmallString<256> buffer;
495 llvm::raw_svector_ostream out(buffer);
496 out << deviceSideName;
498 deviceSideName = std::string(out.str());
499 }
500 return deviceSideName;
501}
502
503void CIRGenNVCUDARuntime::handleVarRegistration(const VarDecl *vd,
504 cir::GlobalOp var) {
505 if (vd->hasAttr<CUDADeviceAttr>() || vd->hasAttr<CUDAConstantAttr>()) {
506 // Shadow variables and their properties must be registered with CUDA
507 // runtime. Skip Extern global variables, which will be registered in
508 // the TU where they are defined.
509 //
510 // Don't register a C++17 inline variable. The local symbol can be
511 // discarded and referencing a discarded local symbol from outside the
512 // comdat (__cuda_register_globals) is disallowed by the ELF spec.
513 //
514 // HIP managed variables need to be always recorded in device and host
515 // compilations for transformation.
516 //
517 // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are
518 // added to llvm.compiler-used, therefore they are safe to be registered.
519 if ((!vd->hasExternalStorage() && !vd->isInline()) ||
520 cgm.getASTContext().CUDADeviceVarODRUsedByHost.contains(vd) ||
521 vd->hasAttr<HIPManagedAttr>()) {
522 registerDeviceVar(vd, var, !vd->hasDefinition(),
523 vd->hasAttr<CUDAConstantAttr>());
524 }
525 } else if (vd->getType()->isCUDADeviceBuiltinSurfaceType()) {
526 // Builtin surfaces and their template arguments are also registered
527 // with CUDA runtime.
530 const TemplateArgumentList &args = td->getTemplateArgs();
531
532 assert(args.size() == 2 &&
533 "Unexpected number of template arguments of CUDA device "
534 "builtin surface type.");
535
536 llvm::APSInt surfaceType = args[1].getAsIntegral();
537
538 if (!vd->hasExternalStorage())
539 registerDeviceSurf(vd, var, !vd->hasDefinition(),
540 surfaceType.getSExtValue());
541
542 } else if (vd->getType()->isCUDADeviceBuiltinTextureType()) {
543 // Builtin textures and their template arguments are also registered
544 // with CUDA runtime.
547 const TemplateArgumentList &args = td->getTemplateArgs();
548
549 assert(args.size() == 3 &&
550 "Unexpected number of template arguments of CUDA device "
551 "builtin texture type.");
552
553 llvm::APSInt textureType = args[1].getAsIntegral();
554 llvm::APSInt normalized = args[2].getAsIntegral();
555
556 if (!vd->hasExternalStorage())
557 registerDeviceTex(vd, var, !vd->hasDefinition(),
558 textureType.getSExtValue(), normalized.getZExtValue());
559 }
560}
561
562void CIRGenNVCUDARuntime::handleGlobalReplace(cir::GlobalOp oldGV,
563 cir::GlobalOp newGV) {
564 for (auto &info : deviceVars) {
565 if (info.var == oldGV)
566 info.var = newGV;
567 }
568}
569
570/// Whether this translation unit has anything for the CUDA runtime to register.
571/// Like LoweringPrepare, count only kernel stub definitions and device
572/// variables carrying registration metadata, not kernel declarations or
573/// launch-site calls.
574static bool hasEntitiesToRegister(mlir::ModuleOp module) {
575 // A walk, not a scan of the module body, so this stays in agreement with the
576 // recursive walk LoweringPrepare collects them with.
577 return module
578 ->walk([](mlir::Operation *op) {
579 if (auto fn = mlir::dyn_cast<cir::FuncOp>(op);
580 fn && !fn.isDeclaration() &&
581 fn->hasAttr(cir::CUDAKernelNameAttr::getMnemonic()))
582 return mlir::WalkResult::interrupt();
583 if (op->hasAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic()))
584 return mlir::WalkResult::interrupt();
585 return mlir::WalkResult::advance();
586 })
587 .wasInterrupted();
588}
589
590/// Read the device-side fat binary and record its contents on the module as
591/// `cir.cu.device_binary`, for LoweringPrepare to build the fatbin global from.
592///
593/// This mirrors the read in CGNVCUDARuntime::makeModuleCtorFunction, guards
594/// included: nothing is read in a compilation that would build no module
595/// constructor.
596void CIRGenNVCUDARuntime::recordDeviceBinary() {
597 StringRef binaryName = cgm.getCodeGenOpts().OffloadBinaryToEmbedFile;
598 if (binaryName.empty())
599 return;
600
601 const LangOptions &langOpts = cgm.getLangOpts();
602 if ((langOpts.HIP || !langOpts.GPURelocatableDeviceCode) &&
604 return;
605
606 llvm::vfs::FileSystem &fs = cgm.getASTContext()
610 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> binaryOrErr =
611 fs.getBufferForFile(binaryName, /*FileSize=*/-1,
612 /*RequiresNullTerminator=*/false);
613 if (std::error_code ec = binaryOrErr.getError()) {
614 cgm.getDiags().Report(diag::err_cannot_open_file)
615 << binaryName << ec.message();
616 return;
617 }
618
619 // Typed as the fatbin global's array type so LoweringPrepare can use this
620 // attribute as the initializer as-is: attributes are uniqued on {value, type}
621 // and never freed, so building a second, typed copy there would keep the fat
622 // binary in memory twice.
623 StringRef bytes = binaryOrErr.get()->getBuffer();
624 mlir::MLIRContext &ctx = cgm.getMLIRContext();
625 auto charTy = cir::IntType::get(&ctx, cgm.getTarget().getCharWidth(),
626 /*isSigned=*/false);
627 auto fatbinTy = cir::ArrayType::get(charTy, bytes.size());
628 cgm.getModule()->setAttr(cir::CIRDialect::getCUDADeviceBinaryAttrName(),
629 mlir::StringAttr::get(bytes, fatbinTy));
630}
631
632// Uses of a managed variable load its address from a pointer the runtime fills.
633void CIRGenNVCUDARuntime::transformManagedVars() {
634 CIRGenBuilderTy &builder = cgm.getBuilder();
635 mlir::ModuleOp module = cgm.getModule();
636 for (auto &&info : deviceVars) {
637 cir::GlobalOp var = info.var;
638 if (info.flags != cir::CUDADeviceVarKind::Variable ||
639 !info.d->hasAttr<HIPManagedAttr>())
640 continue;
641
642 cir::PointerType varPtrTy =
643 builder.getPointerTo(var.getSymType(), var.getAddrSpaceAttr());
644 mlir::ptr::MemorySpaceAttrInterface managedAS = cir::toCIRAddressSpaceAttr(
645 cgm.getMLIRContext(),
646 cgm.getLangOpts().CUDAIsDevice ? LangAS::cuda_device : LangAS::Default);
647 std::optional<mlir::SymbolTable::UseRange> uses = var.getSymbolUses(module);
648
649 std::string name = var.getSymName().str();
650 // An empty comdat would follow the rename.
651 std::optional<llvm::StringRef> comdat = var.getComdat();
652 if (comdat && comdat->empty())
653 var.setComdat(llvm::StringRef(name));
654 cgm.eraseGlobalSymbol(var);
655 var.setSymName(name + ".managed");
656 cgm.insertGlobalSymbol(var);
657
658 cir::GlobalOp managedVar =
659 cgm.createGlobalOp(var.getLoc(), name, varPtrTy,
660 /*isConstant=*/false, managedAS);
661 managedVar.setLinkage(var.getLinkage());
662 if (!var.isDeclaration())
663 managedVar.setInitialValueAttr(builder.getConstNullPtrAttr(varPtrTy));
664 managedVar.setDsoLocal(var.getDsoLocal());
665 managedVar.setGlobalVisibility(var.getGlobalVisibility());
666 mlir::SymbolTable::setSymbolVisibility(
667 managedVar, mlir::SymbolTable::getSymbolVisibility(var));
668 managedVar->setAttr(
669 cir::CUDAExternallyInitializedAttr::getMnemonic(),
670 cir::CUDAExternallyInitializedAttr::get(&cgm.getMLIRContext()));
671
672 // The uses now name the pointer global.
673 cir::PointerType managedPtrTy =
674 builder.getPointerTo(varPtrTy, managedVar.getAddrSpaceAttr());
675 for (mlir::SymbolTable::SymbolUse use : *uses) {
676 auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(use.getUser());
677 if (!getGlobalOp) {
678 cgm.errorNYI(info.d->getSourceRange(),
679 "transformManagedVars: non-instruction use");
680 continue;
681 }
682 mlir::Value addr = getGlobalOp.getAddr();
683 addr.setType(managedPtrTy);
684 mlir::OpBuilder::InsertionGuard guard(builder);
685 builder.setInsertionPointAfter(getGlobalOp);
686 mlir::Value ld = builder.createAlignedLoad(
687 getGlobalOp.getLoc(), varPtrTy, addr,
688 CharUnits::fromQuantity(var.getAlignment().value_or(1)));
689 addr.replaceAllUsesExcept(ld, ld.getDefiningOp());
690 }
691
692 // The runtime allocates them even if device code never uses them.
693 if (cgm.getLangOpts().CUDAIsDevice && !var.isDeclaration()) {
694 cgm.addCompilerUsedGlobal(var);
695 cgm.addCompilerUsedGlobal(managedVar);
696 }
697 }
698}
699
700void CIRGenNVCUDARuntime::finalizeModule() {
701 transformManagedVars();
702 if (!cgm.getLangOpts().CUDAIsDevice) {
703 recordDeviceBinary();
704 return;
705 }
706
707 // Mark ODR-used device variables as compiler used to prevent them from being
708 // eliminated by optimization. This is necessary for device variables
709 // ODR-used by host functions. Sema correctly marks them as ODR-used no
710 // matter whether they are ODR-used by device or host functions.
711 //
712 // We do not need to do this if the variable has used attribute since it
713 // has already been added.
714 //
715 // Static device variables have been externalized at this point, therefore
716 // variables with private or internal linkage need not be added.
717 for (auto &&info : deviceVars) {
718 auto kind = info.flags;
719 bool isDecl = info.var.isDeclaration();
720 bool isLocalLinkage = cir::isLocalLinkage(info.var.getLinkage());
721 bool isVarOrSurfaceOrTexture = (kind == cir::CUDADeviceVarKind::Variable ||
722 kind == cir::CUDADeviceVarKind::Surface ||
723 kind == cir::CUDADeviceVarKind::Texture);
724 bool isUsed = info.d->isUsed();
725 bool hasUsedAttr = info.d->hasAttr<UsedAttr>();
726 if (!isDecl && !isLocalLinkage && isVarOrSurfaceOrTexture && isUsed &&
727 !hasUsedAttr) {
728 if (auto globalValue = mlir::dyn_cast<cir::CIRGlobalValueInterface>(
729 info.var.getOperation())) {
730 cgm.addCompilerUsedGlobal(globalValue);
731 }
732 }
733 }
734}
Defines the clang::ASTContext interface.
static StringRef bytes(const std::vector< T, Allocator > &v)
Provides definitions for the various language-specific address spaces.
static bool hasEntitiesToRegister(mlir::ModuleOp module)
Whether this translation unit has anything for the CUDA runtime to register.
Defines the clang::FileManager interface and associated types.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the SourceManager interface.
__CUDA_BUILTIN_VAR __cuda_builtin_blockDim_t blockDim
__CUDA_BUILTIN_VAR __cuda_builtin_gridDim_t gridDim
mlir::TypedAttr getConstNullPtrAttr(mlir::Type t)
mlir::Value createCast(mlir::Location loc, cir::CastKind kind, mlir::Value src, mlir::Type newTy)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
cir::PointerType getPointerTo(mlir::Type ty)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
SourceManager & getSourceManager()
Definition ASTContext.h:913
TranslationUnitDecl * getTranslationUnitDecl() const
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
IdentifierTable & Idents
Definition ASTContext.h:852
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
mlir::Value getPointer() const
Definition Address.h:98
cir::LoadOp createAlignedLoad(mlir::Location loc, mlir::Type ty, mlir::Value ptr, llvm::MaybeAlign align)
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
clang::MangleContext & getMangleContext()
Gets the mangle context.
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
clang::GlobalDecl curGD
The GlobalDecl for the current function being compiled or the global variable currently being initial...
CIRGenTypes & getTypes() const
const clang::LangOptions & getLangOpts() const
const clang::Decl * curFuncDecl
Address getAddrOfLocalVar(const clang::VarDecl *vd)
Return the address of a local variable.
mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee, llvm::ArrayRef< mlir::Value > args={}, mlir::NamedAttrList attrs={})
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
This class organizes the cross-function state that is used while generating CIR code.
llvm::StringRef getMangledName(clang::GlobalDecl gd)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
void insertGlobalSymbol(mlir::Operation *op)
CIRGenBuilderTy & getBuilder()
void setDSOLocal(mlir::Operation *op) const
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
clang::DiagnosticsEngine & getDiags() const
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
const clang::TargetInfo & getTarget() const
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
void eraseGlobalSymbol(mlir::Operation *op)
const clang::CodeGenOptions & getCodeGenOpts() const
const clang::LangOptions & getLangOpts() const
void printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d)
Print the postfix for externalized static variable or kernels for single source offloading languages ...
cir::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
mlir::ModuleOp getModule() const
void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmCompilerUsed list.
mlir::MLIRContext & getMLIRContext()
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
CIRGenCXXABI & getCXXABI() const
const CIRGenFunctionInfo & arrangeFunctionDeclaration(const clang::FunctionDecl *fd)
Free functions are functions that are compatible with an ordinary C function pointer type.
mlir::Type convertType(clang::QualType type)
Convert a Clang type into a mlir::Type.
void add(RValue rvalue, clang::QualType type)
Definition CIRGenCall.h:241
Type for representing both the decl and type of parameters to a function.
Definition CIRGenCall.h:195
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
std::string OffloadBinaryToEmbedFile
Name of file passed with -foffload-include-binary option to forward to offloading runtime back-end fo...
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:448
bool hasAttr() const
Definition DeclBase.h:586
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
llvm::vfs::FileSystem & getVirtualFileSystem() const
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
bool isThisDeclarationADefinition() const
Returns whether this template declaration defines the primary pattern.
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
Definition GlobalDecl.h:200
const Decl * getDecl() const
Definition GlobalDecl.h:115
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
GPUDefaultStreamKind GPUDefaultStream
The default stream kind used for HIP kernel launching.
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:129
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
FileManager & getFileManager() const
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getCharWidth() const
Definition TargetInfo.h:528
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:153
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5652
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5661
QualType getType() const
Definition Decl.h:725
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1588
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1240
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2377
static bool isLocalLinkage(GlobalLinkageKind linkage)
Definition CIROpsEnums.h:51
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
CIRGenCUDARuntime * createNVCUDARuntime(CIRGenModule &cgm)
constexpr Variable var(Literal L)
Returns the variable of L.
Definition CNFFormula.h:64
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Top level wrappers for InstallAPI frontend operations.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:119
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 int32_t
clang::CharUnits getPointerAlign() const
clang::CharUnits getSizeAlign() const
cir::PointerType voidPtrTy
void* in address space 0