1//===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
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/// \file
9/// This file implements semantic analysis for CUDA constructs.
10///
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/SemaCUDA.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/Basic/Cuda.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Overload.h"
22#include "clang/Sema/ScopeInfo.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
25#include "llvm/ADT/SmallVector.h"
26#include <optional>
27using namespace clang;
28
29SemaCUDA::SemaCUDA(Sema &S) : SemaBase(S) {}
30
31template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
32 if (!D)
33 return false;
34 if (auto *A = D->getAttr<AttrT>())
35 return !A->isImplicit();
36 return false;
37}
38
39void SemaCUDA::PushForceHostDevice() {
40 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
41 ForceHostDeviceDepth++;
42}
43
44bool SemaCUDA::PopForceHostDevice() {
45 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
46 if (ForceHostDeviceDepth == 0)
47 return false;
48 ForceHostDeviceDepth--;
49 return true;
50}
51
52ExprResult SemaCUDA::ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc,
53 MultiExprArg ExecConfig,
54 SourceLocation GGGLoc) {
55 bool IsDeviceKernelCall = false;
56 switch (CurrentTarget()) {
57 case CUDAFunctionTarget::Global:
58 case CUDAFunctionTarget::Device:
59 IsDeviceKernelCall = true;
60 break;
61 case CUDAFunctionTarget::HostDevice:
62 if (getLangOpts().CUDAIsDevice) {
63 IsDeviceKernelCall = true;
64 if (FunctionDecl *Caller =
65 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
66 Caller && isImplicitHostDeviceFunction(D: Caller)) {
67 // Under the device compilation, config call under an HD function should
68 // be treated as a device kernel call. But, for implicit HD ones (such
69 // as lambdas), need to check whether RDC is enabled or not.
70 if (!getLangOpts().GPURelocatableDeviceCode)
71 IsDeviceKernelCall = false;
72 // HIP doesn't support device-side kernel call yet. Still treat it as
73 // the host-side kernel call.
74 if (getLangOpts().HIP)
75 IsDeviceKernelCall = false;
76 }
77 }
78 break;
79 default:
80 break;
81 }
82
83 if (IsDeviceKernelCall && getLangOpts().HIP)
84 return ExprError(
85 Diag(Loc: LLLLoc, DiagID: diag::err_cuda_device_kernel_launch_not_supported));
86
87 if (IsDeviceKernelCall && !getLangOpts().GPURelocatableDeviceCode)
88 return ExprError(
89 Diag(Loc: LLLLoc, DiagID: diag::err_cuda_device_kernel_launch_require_rdc));
90
91 FunctionDecl *ConfigDecl = IsDeviceKernelCall
92 ? getASTContext().getcudaLaunchDeviceDecl()
93 : getASTContext().getcudaConfigureCallDecl();
94 if (!ConfigDecl)
95 return ExprError(Diag(Loc: LLLLoc, DiagID: diag::err_undeclared_var_use)
96 << (IsDeviceKernelCall ? getLaunchDeviceFuncName()
97 : getConfigureFuncName()));
98 // Additional check on the launch function if it's a device kernel call.
99 if (IsDeviceKernelCall) {
100 auto *GetParamBuf = getASTContext().getcudaGetParameterBufferDecl();
101 if (!GetParamBuf)
102 return ExprError(Diag(Loc: LLLLoc, DiagID: diag::err_undeclared_var_use)
103 << getGetParameterBufferFuncName());
104 }
105
106 QualType ConfigQTy = ConfigDecl->getType();
107
108 DeclRefExpr *ConfigDR = new (getASTContext()) DeclRefExpr(
109 getASTContext(), ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
110 SemaRef.MarkFunctionReferenced(Loc: LLLLoc, Func: ConfigDecl);
111
112 if (IsDeviceKernelCall) {
113 SmallVector<Expr *> Args;
114 // Use a null pointer as the kernel function, which may not be resolvable
115 // here. For example, resolving that kernel function may need additional
116 // kernel arguments.
117 llvm::APInt Zero(SemaRef.Context.getTypeSize(T: SemaRef.Context.IntTy), 0);
118 Args.push_back(Elt: IntegerLiteral::Create(C: SemaRef.Context, V: Zero,
119 type: SemaRef.Context.IntTy, l: LLLLoc));
120 // Use a null pointer as the placeholder of the parameter buffer, which
121 // should be replaced with the actual allocation later, in the codegen.
122 Args.push_back(Elt: IntegerLiteral::Create(C: SemaRef.Context, V: Zero,
123 type: SemaRef.Context.IntTy, l: LLLLoc));
124 // Add the original config arguments.
125 llvm::append_range(C&: Args, R&: ExecConfig);
126 // Add the default blockDim if it's missing.
127 if (Args.size() < 4) {
128 llvm::APInt One(SemaRef.Context.getTypeSize(T: SemaRef.Context.IntTy), 1);
129 Args.push_back(Elt: IntegerLiteral::Create(C: SemaRef.Context, V: One,
130 type: SemaRef.Context.IntTy, l: LLLLoc));
131 }
132 // Add the default sharedMemSize if it's missing.
133 if (Args.size() < 5)
134 Args.push_back(Elt: IntegerLiteral::Create(C: SemaRef.Context, V: Zero,
135 type: SemaRef.Context.IntTy, l: LLLLoc));
136 // Add the default stream if it's missing.
137 if (Args.size() < 6)
138 Args.push_back(Elt: new (SemaRef.Context) CXXNullPtrLiteralExpr(
139 SemaRef.Context.NullPtrTy, LLLLoc));
140 return SemaRef.BuildCallExpr(S, Fn: ConfigDR, LParenLoc: LLLLoc, ArgExprs: Args, RParenLoc: GGGLoc, ExecConfig: nullptr,
141 /*IsExecConfig=*/true);
142 }
143 return SemaRef.BuildCallExpr(S, Fn: ConfigDR, LParenLoc: LLLLoc, ArgExprs: ExecConfig, RParenLoc: GGGLoc, ExecConfig: nullptr,
144 /*IsExecConfig=*/true);
145}
146
147CUDAFunctionTarget SemaCUDA::IdentifyTarget(const ParsedAttributesView &Attrs) {
148 bool HasHostAttr = false;
149 bool HasDeviceAttr = false;
150 bool HasGlobalAttr = false;
151 bool HasInvalidTargetAttr = false;
152 for (const ParsedAttr &AL : Attrs) {
153 switch (AL.getKind()) {
154 case ParsedAttr::AT_CUDAGlobal:
155 HasGlobalAttr = true;
156 break;
157 case ParsedAttr::AT_CUDAHost:
158 HasHostAttr = true;
159 break;
160 case ParsedAttr::AT_CUDADevice:
161 HasDeviceAttr = true;
162 break;
163 case ParsedAttr::AT_CUDAInvalidTarget:
164 HasInvalidTargetAttr = true;
165 break;
166 default:
167 break;
168 }
169 }
170
171 if (HasInvalidTargetAttr)
172 return CUDAFunctionTarget::InvalidTarget;
173
174 if (HasGlobalAttr)
175 return CUDAFunctionTarget::Global;
176
177 if (HasHostAttr && HasDeviceAttr)
178 return CUDAFunctionTarget::HostDevice;
179
180 if (HasDeviceAttr)
181 return CUDAFunctionTarget::Device;
182
183 return CUDAFunctionTarget::Host;
184}
185
186template <typename A>
187static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr) {
188 return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
189 return isa<A>(Attribute) &&
190 !(IgnoreImplicitAttr && Attribute->isImplicit());
191 });
192}
193
194SemaCUDA::CUDATargetContextRAII::CUDATargetContextRAII(
195 SemaCUDA &S_, SemaCUDA::CUDATargetContextKind K, Decl *D)
196 : S(S_) {
197 SavedCtx = S.CurCUDATargetCtx;
198 assert(K == SemaCUDA::CTCK_InitGlobalVar);
199 auto *VD = dyn_cast_or_null<VarDecl>(Val: D);
200 if (VD && VD->hasGlobalStorage() && !VD->isStaticLocal()) {
201 auto Target = CUDAFunctionTarget::Host;
202 if ((hasAttr<CUDADeviceAttr>(D: VD, /*IgnoreImplicit=*/IgnoreImplicitAttr: true) &&
203 !hasAttr<CUDAHostAttr>(D: VD, /*IgnoreImplicit=*/IgnoreImplicitAttr: true)) ||
204 hasAttr<CUDASharedAttr>(D: VD, /*IgnoreImplicit=*/IgnoreImplicitAttr: true) ||
205 hasAttr<CUDAConstantAttr>(D: VD, /*IgnoreImplicit=*/IgnoreImplicitAttr: true))
206 Target = CUDAFunctionTarget::Device;
207 S.CurCUDATargetCtx = {.Target: Target, .Kind: K, .D: VD};
208 }
209}
210
211/// IdentifyTarget - Determine the CUDA compilation target for this function
212CUDAFunctionTarget SemaCUDA::IdentifyTarget(const FunctionDecl *D,
213 bool IgnoreImplicitHDAttr) {
214 // Code that lives outside a function gets the target from CurCUDATargetCtx.
215 if (D == nullptr)
216 return CurCUDATargetCtx.Target;
217
218 // C++ deduction guides are never codegen'ed and only participate in template
219 // argument deduction. Treat them as if they were always host+device so that
220 // CUDA/HIP target checking never rejects their use based solely on target.
221 if (isa<CXXDeductionGuideDecl>(Val: D))
222 return CUDAFunctionTarget::HostDevice;
223
224 if (D->hasAttr<CUDAInvalidTargetAttr>())
225 return CUDAFunctionTarget::InvalidTarget;
226
227 if (D->hasAttr<CUDAGlobalAttr>())
228 return CUDAFunctionTarget::Global;
229
230 if (D->isConsteval())
231 return CUDAFunctionTarget::HostDevice;
232
233 if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitAttr: IgnoreImplicitHDAttr)) {
234 if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitAttr: IgnoreImplicitHDAttr))
235 return CUDAFunctionTarget::HostDevice;
236 return CUDAFunctionTarget::Device;
237 } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitAttr: IgnoreImplicitHDAttr)) {
238 return CUDAFunctionTarget::Host;
239 } else if ((D->isImplicit() || !D->isUserProvided()) &&
240 !IgnoreImplicitHDAttr) {
241 // Some implicit declarations (like intrinsic functions) are not marked.
242 // Set the most lenient target on them for maximal flexibility.
243 return CUDAFunctionTarget::HostDevice;
244 }
245
246 return CUDAFunctionTarget::Host;
247}
248
249/// IdentifyTarget - Determine the CUDA compilation target for this variable.
250SemaCUDA::CUDAVariableTarget SemaCUDA::IdentifyTarget(const VarDecl *Var) {
251 if (Var->hasAttr<HIPManagedAttr>())
252 return CVT_Unified;
253 // Only constexpr and const variabless with implicit constant attribute
254 // are emitted on both sides. Such variables are promoted to device side
255 // only if they have static constant initializers on device side.
256 if ((Var->isConstexpr() || Var->getType().isConstQualified()) &&
257 Var->hasAttr<CUDAConstantAttr>() &&
258 !hasExplicitAttr<CUDAConstantAttr>(D: Var))
259 return CVT_Both;
260 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
261 Var->hasAttr<CUDASharedAttr>() ||
262 Var->getType()->isCUDADeviceBuiltinSurfaceType() ||
263 Var->getType()->isCUDADeviceBuiltinTextureType())
264 return CVT_Device;
265 // Function-scope static variable without explicit device or constant
266 // attribute are emitted
267 // - on both sides in host device functions
268 // - on device side in device or global functions
269 if (auto *FD = dyn_cast<FunctionDecl>(Val: Var->getDeclContext())) {
270 switch (IdentifyTarget(D: FD)) {
271 case CUDAFunctionTarget::HostDevice:
272 return CVT_Both;
273 case CUDAFunctionTarget::Device:
274 case CUDAFunctionTarget::Global:
275 return CVT_Device;
276 default:
277 return CVT_Host;
278 }
279 }
280 return CVT_Host;
281}
282
283// * CUDA Call preference table
284//
285// F - from,
286// T - to
287// Ph - preference in host mode
288// Pd - preference in device mode
289// H - handled in (x)
290// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
291//
292// | F | T | Ph | Pd | H |
293// |----+----+-----+-----+-----+
294// | d | d | N | N | (c) |
295// | d | g | -- | -- | (a) |
296// | d | h | -- | -- | (e) |
297// | d | hd | HD | HD | (b) |
298// | g | d | N | N | (c) |
299// | g | g | -- | -- | (a) |
300// | g | h | -- | -- | (e) |
301// | g | hd | HD | HD | (b) |
302// | h | d | -- | -- | (e) |
303// | h | g | N | N | (c) |
304// | h | h | N | N | (c) |
305// | h | hd | HD | HD | (b) |
306// | hd | d | WS | SS | (d) |
307// | hd | g | SS | -- |(d/a)|
308// | hd | h | SS | WS | (d) |
309// | hd | hd | HD | HD | (b) |
310
311SemaCUDA::CUDAFunctionPreference
312SemaCUDA::IdentifyPreference(const FunctionDecl *Caller,
313 const FunctionDecl *Callee) {
314 assert(Callee && "Callee must be valid.");
315
316 // Treat ctor/dtor as host device function in device var initializer to allow
317 // trivial ctor/dtor without device attr to be used. Non-trivial ctor/dtor
318 // will be diagnosed by checkAllowedInitializer.
319 if (Caller == nullptr && CurCUDATargetCtx.Kind == CTCK_InitGlobalVar &&
320 CurCUDATargetCtx.Target == CUDAFunctionTarget::Device &&
321 (isa<CXXConstructorDecl>(Val: Callee) || isa<CXXDestructorDecl>(Val: Callee)))
322 return CFP_HostDevice;
323
324 CUDAFunctionTarget CallerTarget = IdentifyTarget(D: Caller);
325 CUDAFunctionTarget CalleeTarget = IdentifyTarget(D: Callee);
326
327 // If one of the targets is invalid, the check always fails, no matter what
328 // the other target is.
329 if (CallerTarget == CUDAFunctionTarget::InvalidTarget ||
330 CalleeTarget == CUDAFunctionTarget::InvalidTarget)
331 return CFP_Never;
332
333 // (a) Call global from either global or device contexts is allowed as part
334 // of CUDA's dynamic parallelism support.
335 if (CalleeTarget == CUDAFunctionTarget::Global &&
336 (CallerTarget == CUDAFunctionTarget::Global ||
337 CallerTarget == CUDAFunctionTarget::Device))
338 return CFP_Native;
339
340 // (b) Calling HostDevice is OK for everyone.
341 if (CalleeTarget == CUDAFunctionTarget::HostDevice)
342 return CFP_HostDevice;
343
344 // (c) Best case scenarios
345 if (CalleeTarget == CallerTarget ||
346 (CallerTarget == CUDAFunctionTarget::Host &&
347 CalleeTarget == CUDAFunctionTarget::Global) ||
348 (CallerTarget == CUDAFunctionTarget::Global &&
349 CalleeTarget == CUDAFunctionTarget::Device))
350 return CFP_Native;
351
352 // HipStdPar mode is special, in that assessing whether a device side call to
353 // a host target is deferred to a subsequent pass, and cannot unambiguously be
354 // adjudicated in the AST, hence we optimistically allow them to pass here.
355 if (getLangOpts().HIPStdPar &&
356 (CallerTarget == CUDAFunctionTarget::Global ||
357 CallerTarget == CUDAFunctionTarget::Device ||
358 CallerTarget == CUDAFunctionTarget::HostDevice) &&
359 CalleeTarget == CUDAFunctionTarget::Host)
360 return CFP_HostDevice;
361
362 // (d) HostDevice behavior depends on compilation mode.
363 if (CallerTarget == CUDAFunctionTarget::HostDevice) {
364 // It's OK to call a compilation-mode matching function from an HD one.
365 if ((getLangOpts().CUDAIsDevice &&
366 (CalleeTarget == CUDAFunctionTarget::Device ||
367 CalleeTarget == CUDAFunctionTarget::Global)) ||
368 (!getLangOpts().CUDAIsDevice &&
369 (CalleeTarget == CUDAFunctionTarget::Host ||
370 CalleeTarget == CUDAFunctionTarget::Global)))
371 return CFP_SameSide;
372
373 // Calls from HD to non-mode-matching functions (i.e., to host functions
374 // when compiling in device mode or to device functions when compiling in
375 // host mode) are allowed at the sema level, but eventually rejected if
376 // they're ever codegened. TODO: Reject said calls earlier.
377 return CFP_WrongSide;
378 }
379
380 // (e) Calling across device/host boundary is not something you should do.
381 if ((CallerTarget == CUDAFunctionTarget::Host &&
382 CalleeTarget == CUDAFunctionTarget::Device) ||
383 (CallerTarget == CUDAFunctionTarget::Device &&
384 CalleeTarget == CUDAFunctionTarget::Host) ||
385 (CallerTarget == CUDAFunctionTarget::Global &&
386 CalleeTarget == CUDAFunctionTarget::Host))
387 return CFP_Never;
388
389 llvm_unreachable("All cases should've been handled by now.");
390}
391
392template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
393 if (!D)
394 return false;
395 if (auto *A = D->getAttr<AttrT>())
396 return A->isImplicit();
397 return D->isImplicit();
398}
399
400bool SemaCUDA::isImplicitHostDeviceFunction(const FunctionDecl *D) {
401 bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
402 bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
403 return IsImplicitDevAttr && IsImplicitHostAttr;
404}
405
406void SemaCUDA::EraseUnwantedMatches(
407 const FunctionDecl *Caller,
408 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
409 if (Matches.size() <= 1)
410 return;
411
412 using Pair = std::pair<DeclAccessPair, FunctionDecl *>;
413
414 // Gets the CUDA function preference for a call from Caller to Match.
415 auto GetCFP = [&](const Pair &Match) {
416 return IdentifyPreference(Caller, Callee: Match.second);
417 };
418
419 // Find the best call preference among the functions in Matches.
420 CUDAFunctionPreference BestCFP =
421 GetCFP(*llvm::max_element(Range&: Matches, C: [&](const Pair &M1, const Pair &M2) {
422 return GetCFP(M1) < GetCFP(M2);
423 }));
424
425 // Erase all functions with lower priority.
426 llvm::erase_if(C&: Matches,
427 P: [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
428}
429
430/// When an implicitly-declared special member has to invoke more than one
431/// base/field special member, conflicts may occur in the targets of these
432/// members. For example, if one base's member __host__ and another's is
433/// __device__, it's a conflict.
434/// This function figures out if the given targets \param Target1 and
435/// \param Target2 conflict, and if they do not it fills in
436/// \param ResolvedTarget with a target that resolves for both calls.
437/// \return true if there's a conflict, false otherwise.
438static bool
439resolveCalleeCUDATargetConflict(CUDAFunctionTarget Target1,
440 CUDAFunctionTarget Target2,
441 CUDAFunctionTarget *ResolvedTarget) {
442 // Only free functions and static member functions may be global.
443 assert(Target1 != CUDAFunctionTarget::Global);
444 assert(Target2 != CUDAFunctionTarget::Global);
445
446 if (Target1 == CUDAFunctionTarget::HostDevice) {
447 *ResolvedTarget = Target2;
448 } else if (Target2 == CUDAFunctionTarget::HostDevice) {
449 *ResolvedTarget = Target1;
450 } else if (Target1 != Target2) {
451 return true;
452 } else {
453 *ResolvedTarget = Target1;
454 }
455
456 return false;
457}
458
459bool SemaCUDA::inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
460 CXXSpecialMemberKind CSM,
461 CXXMethodDecl *MemberDecl,
462 bool ConstRHS,
463 bool Diagnose) {
464 // If MemberDecl is virtual destructor of an explicit template class
465 // instantiation, it must be emitted, therefore it needs to be inferred
466 // conservatively by ignoring implicit host/device attrs of member and parent
467 // dtors called by it. Also, it needs to be checed by deferred diag visitor.
468 bool IsExpVDtor = false;
469 if (isa<CXXDestructorDecl>(Val: MemberDecl) && MemberDecl->isVirtual()) {
470 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: ClassDecl)) {
471 TemplateSpecializationKind TSK = Spec->getTemplateSpecializationKind();
472 IsExpVDtor = TSK == TSK_ExplicitInstantiationDeclaration ||
473 TSK == TSK_ExplicitInstantiationDefinition;
474 }
475 }
476 if (IsExpVDtor)
477 SemaRef.DeclsToCheckForDeferredDiags.insert(X: MemberDecl);
478
479 // If the defaulted special member is defined lexically outside of its
480 // owning class, or the special member already has explicit device or host
481 // attributes, do not infer.
482 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
483 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
484 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
485 bool HasExplicitAttr =
486 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
487 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
488 if (!InClass || HasExplicitAttr)
489 return false;
490
491 std::optional<CUDAFunctionTarget> InferredTarget;
492
493 // We're going to invoke special member lookup; mark that these special
494 // members are called from this one, and not from its caller.
495 Sema::ContextRAII MethodContext(SemaRef, MemberDecl);
496
497 // Look for special members in base classes that should be invoked from here.
498 // Infer the target of this member base on the ones it should call.
499 // Skip direct and indirect virtual bases for abstract classes.
500 llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
501 for (const auto &B : ClassDecl->bases()) {
502 if (!B.isVirtual()) {
503 Bases.push_back(Elt: &B);
504 }
505 }
506
507 if (!ClassDecl->isAbstract()) {
508 llvm::append_range(C&: Bases, R: llvm::make_pointer_range(Range: ClassDecl->vbases()));
509 }
510
511 for (const auto *B : Bases) {
512 auto *BaseClassDecl = B->getType()->getAsCXXRecordDecl();
513 if (!BaseClassDecl)
514 continue;
515
516 Sema::SpecialMemberOverloadResult SMOR =
517 SemaRef.LookupSpecialMember(D: BaseClassDecl, SM: CSM,
518 /* ConstArg */ ConstRHS,
519 /* VolatileArg */ false,
520 /* RValueThis */ false,
521 /* ConstThis */ false,
522 /* VolatileThis */ false);
523
524 if (!SMOR.getMethod())
525 continue;
526
527 CUDAFunctionTarget BaseMethodTarget =
528 IdentifyTarget(D: SMOR.getMethod(), IgnoreImplicitHDAttr: IsExpVDtor);
529
530 if (!InferredTarget) {
531 InferredTarget = BaseMethodTarget;
532 } else {
533 bool ResolutionError = resolveCalleeCUDATargetConflict(
534 Target1: *InferredTarget, Target2: BaseMethodTarget, ResolvedTarget: &*InferredTarget);
535 if (ResolutionError) {
536 if (Diagnose) {
537 Diag(Loc: ClassDecl->getLocation(),
538 DiagID: diag::note_implicit_member_target_infer_collision)
539 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
540 }
541 MemberDecl->addAttr(
542 A: CUDAInvalidTargetAttr::CreateImplicit(Ctx&: getASTContext()));
543 return true;
544 }
545 }
546 }
547
548 // Same as for bases, but now for special members of fields.
549 for (const auto *F : ClassDecl->fields()) {
550 if (F->isInvalidDecl()) {
551 continue;
552 }
553
554 auto *FieldRecDecl =
555 getASTContext().getBaseElementType(QT: F->getType())->getAsCXXRecordDecl();
556 if (!FieldRecDecl)
557 continue;
558
559 Sema::SpecialMemberOverloadResult SMOR =
560 SemaRef.LookupSpecialMember(D: FieldRecDecl, SM: CSM,
561 /* ConstArg */ ConstRHS && !F->isMutable(),
562 /* VolatileArg */ false,
563 /* RValueThis */ false,
564 /* ConstThis */ false,
565 /* VolatileThis */ false);
566
567 if (!SMOR.getMethod())
568 continue;
569
570 CUDAFunctionTarget FieldMethodTarget =
571 IdentifyTarget(D: SMOR.getMethod(), IgnoreImplicitHDAttr: IsExpVDtor);
572
573 if (!InferredTarget) {
574 InferredTarget = FieldMethodTarget;
575 } else {
576 bool ResolutionError = resolveCalleeCUDATargetConflict(
577 Target1: *InferredTarget, Target2: FieldMethodTarget, ResolvedTarget: &*InferredTarget);
578 if (ResolutionError) {
579 if (Diagnose) {
580 Diag(Loc: ClassDecl->getLocation(),
581 DiagID: diag::note_implicit_member_target_infer_collision)
582 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
583 }
584 MemberDecl->addAttr(
585 A: CUDAInvalidTargetAttr::CreateImplicit(Ctx&: getASTContext()));
586 return true;
587 }
588 }
589 }
590
591 // If no target was inferred, mark this member as __host__ __device__;
592 // it's the least restrictive option that can be invoked from any target.
593 bool NeedsH = true, NeedsD = true;
594 if (InferredTarget) {
595 if (*InferredTarget == CUDAFunctionTarget::Device)
596 NeedsH = false;
597 else if (*InferredTarget == CUDAFunctionTarget::Host)
598 NeedsD = false;
599 }
600
601 // We either setting attributes first time, or the inferred ones must match
602 // previously set ones.
603 if (NeedsD && !HasD)
604 MemberDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
605 if (NeedsH && !HasH)
606 MemberDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
607
608 return false;
609}
610
611bool SemaCUDA::isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
612 if (!CD->isDefined() && CD->isTemplateInstantiation())
613 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CD->getFirstDecl());
614
615 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
616 // empty at a point in the translation unit, if it is either a
617 // trivial constructor
618 if (CD->isTrivial())
619 return true;
620
621 // ... or it satisfies all of the following conditions:
622 // The constructor function has been defined.
623 // The constructor function has no parameters,
624 // and the function body is an empty compound statement.
625 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
626 return false;
627
628 // Its class has no virtual functions and no virtual base classes.
629 if (CD->getParent()->isDynamicClass())
630 return false;
631
632 // Union ctor does not call ctors of its data members.
633 if (CD->getParent()->isUnion())
634 return true;
635
636 // The only form of initializer allowed is an empty constructor.
637 // This will recursively check all base classes and member initializers
638 if (!llvm::all_of(Range: CD->inits(), P: [&](const CXXCtorInitializer *CI) {
639 if (const CXXConstructExpr *CE =
640 dyn_cast<CXXConstructExpr>(Val: CI->getInit()))
641 return isEmptyConstructor(Loc, CD: CE->getConstructor());
642 return false;
643 }))
644 return false;
645
646 return true;
647}
648
649bool SemaCUDA::isEmptyDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
650 // No destructor -> no problem.
651 if (!DD)
652 return true;
653
654 if (!DD->isDefined() && DD->isTemplateInstantiation())
655 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: DD->getFirstDecl());
656
657 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
658 // empty at a point in the translation unit, if it is either a
659 // trivial constructor
660 if (DD->isTrivial())
661 return true;
662
663 // ... or it satisfies all of the following conditions:
664 // The destructor function has been defined.
665 // and the function body is an empty compound statement.
666 if (!DD->hasTrivialBody())
667 return false;
668
669 const CXXRecordDecl *ClassDecl = DD->getParent();
670
671 // Its class has no virtual functions and no virtual base classes.
672 if (ClassDecl->isDynamicClass())
673 return false;
674
675 // Union does not have base class and union dtor does not call dtors of its
676 // data members.
677 if (DD->getParent()->isUnion())
678 return true;
679
680 // Only empty destructors are allowed. This will recursively check
681 // destructors for all base classes...
682 if (!llvm::all_of(Range: ClassDecl->bases(), P: [&](const CXXBaseSpecifier &BS) {
683 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
684 return isEmptyDestructor(Loc, DD: RD->getDestructor());
685 return true;
686 }))
687 return false;
688
689 // ... and member fields.
690 if (!llvm::all_of(Range: ClassDecl->fields(), P: [&](const FieldDecl *Field) {
691 if (CXXRecordDecl *RD = Field->getType()
692 ->getBaseElementTypeUnsafe()
693 ->getAsCXXRecordDecl())
694 return isEmptyDestructor(Loc, DD: RD->getDestructor());
695 return true;
696 }))
697 return false;
698
699 return true;
700}
701
702namespace {
703enum CUDAInitializerCheckKind {
704 CICK_DeviceOrConstant, // Check initializer for device/constant variable
705 CICK_Shared, // Check initializer for shared variable
706};
707
708bool IsDependentVar(VarDecl *VD) {
709 if (VD->getType()->isDependentType())
710 return true;
711 if (const auto *Init = VD->getInit())
712 return Init->isValueDependent();
713 return false;
714}
715
716// Check whether a variable has an allowed initializer for a CUDA device side
717// variable with global storage. \p VD may be a host variable to be checked for
718// potential promotion to device side variable.
719//
720// CUDA/HIP allows only empty constructors as initializers for global
721// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
722// __shared__ variables whether they are local or not (they all are implicitly
723// static in CUDA). One exception is that CUDA allows constant initializers
724// for __constant__ and __device__ variables.
725bool HasAllowedCUDADeviceStaticInitializer(SemaCUDA &S, VarDecl *VD,
726 CUDAInitializerCheckKind CheckKind) {
727 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
728 assert(!IsDependentVar(VD) && "do not check dependent var");
729 const Expr *Init = VD->getInit();
730 auto IsEmptyInit = [&](const Expr *Init) {
731 if (!Init)
732 return true;
733 if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: Init)) {
734 return S.isEmptyConstructor(Loc: VD->getLocation(), CD: CE->getConstructor());
735 }
736 return false;
737 };
738 auto IsConstantInit = [&](const Expr *Init) {
739 assert(Init);
740 ASTContext::CUDAConstantEvalContextRAII EvalCtx(S.getASTContext(),
741 /*NoWronSidedVars=*/true);
742 return Init->isConstantInitializer(Ctx&: S.getASTContext(),
743 ForRef: VD->getType()->isReferenceType());
744 };
745 auto HasEmptyDtor = [&](VarDecl *VD) {
746 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
747 return S.isEmptyDestructor(Loc: VD->getLocation(), DD: RD->getDestructor());
748 return true;
749 };
750 if (CheckKind == CICK_Shared)
751 return IsEmptyInit(Init) && HasEmptyDtor(VD);
752 return S.getLangOpts().GPUAllowDeviceInit ||
753 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
754}
755} // namespace
756
757void SemaCUDA::checkAllowedInitializer(VarDecl *VD) {
758 // Return early if VD is inside a non-instantiated template function since
759 // the implicit constructor is not defined yet.
760 if (const FunctionDecl *FD =
761 dyn_cast_or_null<FunctionDecl>(Val: VD->getDeclContext());
762 FD && FD->isDependentContext())
763 return;
764
765 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
766 bool IsDeviceOrConstantVar =
767 !IsSharedVar &&
768 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
769 if ((IsSharedVar || IsDeviceOrConstantVar) &&
770 VD->getType().getQualifiers().getAddressSpace() != LangAS::Default) {
771 Diag(Loc: VD->getLocation(), DiagID: diag::err_cuda_address_space_gpuvar);
772 VD->setInvalidDecl();
773 return;
774 }
775 // Do not check dependent variables since the ctor/dtor/initializer are not
776 // determined. Do it after instantiation.
777 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
778 IsDependentVar(VD))
779 return;
780 const Expr *Init = VD->getInit();
781 if (IsDeviceOrConstantVar || IsSharedVar) {
782 if (HasAllowedCUDADeviceStaticInitializer(
783 S&: *this, VD, CheckKind: IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
784 return;
785 Diag(Loc: VD->getLocation(),
786 DiagID: IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
787 << Init->getSourceRange();
788 VD->setInvalidDecl();
789 } else {
790 // This is a host-side global variable. Check that the initializer is
791 // callable from the host side.
792 const FunctionDecl *InitFn = nullptr;
793 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: Init)) {
794 InitFn = CE->getConstructor();
795 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Val: Init)) {
796 InitFn = CE->getDirectCallee();
797 }
798 if (InitFn) {
799 CUDAFunctionTarget InitFnTarget = IdentifyTarget(D: InitFn);
800 if (InitFnTarget != CUDAFunctionTarget::Host &&
801 InitFnTarget != CUDAFunctionTarget::HostDevice) {
802 Diag(Loc: VD->getLocation(), DiagID: diag::err_ref_bad_target_global_initializer)
803 << InitFnTarget << InitFn;
804 Diag(Loc: InitFn->getLocation(), DiagID: diag::note_previous_decl) << InitFn;
805 VD->setInvalidDecl();
806 }
807 }
808 }
809}
810
811void SemaCUDA::RecordImplicitHostDeviceFuncUsedByDevice(
812 const FunctionDecl *Callee) {
813 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
814 if (!Caller)
815 return;
816
817 if (!isImplicitHostDeviceFunction(D: Callee))
818 return;
819
820 CUDAFunctionTarget CallerTarget = IdentifyTarget(D: Caller);
821
822 // Record whether an implicit host device function is used on device side.
823 if (CallerTarget != CUDAFunctionTarget::Device &&
824 CallerTarget != CUDAFunctionTarget::Global &&
825 (CallerTarget != CUDAFunctionTarget::HostDevice ||
826 (isImplicitHostDeviceFunction(D: Caller) &&
827 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Caller))))
828 return;
829
830 getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.insert(V: Callee);
831}
832
833// With -fcuda-host-device-constexpr, an unattributed constexpr function is
834// treated as implicitly __host__ __device__, unless:
835// * it is a variadic function (device-side variadic functions are not
836// allowed), or
837// * a __device__ function with this signature was already declared, in which
838// case in which case we output an error, unless the __device__ decl is in a
839// system header, in which case we leave the constexpr function unattributed.
840//
841// In addition, all function decls are treated as __host__ __device__ when
842// ForceHostDeviceDepth > 0 (corresponding to code within a
843// #pragma clang force_cuda_host_device_begin/end
844// pair).
845void SemaCUDA::maybeAddHostDeviceAttrs(FunctionDecl *NewD,
846 const LookupResult &Previous) {
847 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
848
849 if (ForceHostDeviceDepth > 0) {
850 if (!NewD->hasAttr<CUDAHostAttr>())
851 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
852 if (!NewD->hasAttr<CUDADeviceAttr>())
853 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
854 return;
855 }
856
857 // If a template function has no host/device/global attributes,
858 // make it implicitly host device function.
859 if (getLangOpts().OffloadImplicitHostDeviceTemplates &&
860 !NewD->hasAttr<CUDAHostAttr>() && !NewD->hasAttr<CUDADeviceAttr>() &&
861 !NewD->hasAttr<CUDAGlobalAttr>() &&
862 (NewD->getDescribedFunctionTemplate() ||
863 NewD->isFunctionTemplateSpecialization())) {
864 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
865 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
866 return;
867 }
868
869 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
870 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
871 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
872 return;
873
874 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
875 // attributes?
876 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
877 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(Val: D))
878 D = Using->getTargetDecl();
879 FunctionDecl *OldD = D->getAsFunction();
880 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
881 !OldD->hasAttr<CUDAHostAttr>() &&
882 !SemaRef.IsOverload(New: NewD, Old: OldD,
883 /* UseMemberUsingDeclRules = */ false,
884 /* ConsiderCudaAttrs = */ false);
885 };
886 auto It = llvm::find_if(Range: Previous, P: IsMatchingDeviceFn);
887 if (It != Previous.end()) {
888 // We found a __device__ function with the same name and signature as NewD
889 // (ignoring CUDA attrs). This is an error unless that function is defined
890 // in a system header, in which case we simply return without making NewD
891 // host+device.
892 NamedDecl *Match = *It;
893 if (!SemaRef.getSourceManager().isInSystemHeader(Loc: Match->getLocation())) {
894 Diag(Loc: NewD->getLocation(),
895 DiagID: diag::err_cuda_unattributed_constexpr_cannot_overload_device)
896 << NewD;
897 Diag(Loc: Match->getLocation(),
898 DiagID: diag::note_cuda_conflicting_device_function_declared_here);
899 }
900 return;
901 }
902
903 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
904 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
905}
906
907// TODO: `__constant__` memory may be a limited resource for certain targets.
908// A safeguard may be needed at the end of compilation pipeline if
909// `__constant__` memory usage goes beyond limit.
910void SemaCUDA::MaybeAddConstantAttr(VarDecl *VD) {
911 // Do not promote dependent variables since the cotr/dtor/initializer are
912 // not determined. Do it after instantiation.
913 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
914 !VD->hasAttr<CUDASharedAttr>() &&
915 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
916 !IsDependentVar(VD) &&
917 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
918 HasAllowedCUDADeviceStaticInitializer(S&: *this, VD,
919 CheckKind: CICK_DeviceOrConstant))) {
920 VD->addAttr(A: CUDAConstantAttr::CreateImplicit(Ctx&: getASTContext()));
921 }
922}
923
924SemaBase::SemaDiagnosticBuilder SemaCUDA::DiagIfDeviceCode(SourceLocation Loc,
925 unsigned DiagID) {
926 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
927 FunctionDecl *CurFunContext =
928 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
929 SemaDiagnosticBuilder::Kind DiagKind = [&] {
930 if (!CurFunContext)
931 return SemaDiagnosticBuilder::K_Nop;
932 switch (CurrentTarget()) {
933 case CUDAFunctionTarget::Global:
934 case CUDAFunctionTarget::Device:
935 return SemaDiagnosticBuilder::K_Immediate;
936 case CUDAFunctionTarget::HostDevice:
937 // An HD function counts as host code if we're compiling for host, and
938 // device code if we're compiling for device. Defer any errors in device
939 // mode until the function is known-emitted.
940 if (!getLangOpts().CUDAIsDevice)
941 return SemaDiagnosticBuilder::K_Nop;
942 if (SemaRef.IsLastErrorImmediate &&
943 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
944 return SemaDiagnosticBuilder::K_Immediate;
945 return (SemaRef.getEmissionStatus(Decl: CurFunContext) ==
946 Sema::FunctionEmissionStatus::Emitted)
947 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
948 : SemaDiagnosticBuilder::K_Deferred;
949 default:
950 return SemaDiagnosticBuilder::K_Nop;
951 }
952 }();
953 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
954}
955
956Sema::SemaDiagnosticBuilder SemaCUDA::DiagIfHostCode(SourceLocation Loc,
957 unsigned DiagID) {
958 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
959 FunctionDecl *CurFunContext =
960 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
961 SemaDiagnosticBuilder::Kind DiagKind = [&] {
962 if (!CurFunContext)
963 return SemaDiagnosticBuilder::K_Nop;
964 switch (CurrentTarget()) {
965 case CUDAFunctionTarget::Host:
966 return SemaDiagnosticBuilder::K_Immediate;
967 case CUDAFunctionTarget::HostDevice:
968 // An HD function counts as host code if we're compiling for host, and
969 // device code if we're compiling for device. Defer any errors in device
970 // mode until the function is known-emitted.
971 if (getLangOpts().CUDAIsDevice)
972 return SemaDiagnosticBuilder::K_Nop;
973 if (SemaRef.IsLastErrorImmediate &&
974 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
975 return SemaDiagnosticBuilder::K_Immediate;
976 return (SemaRef.getEmissionStatus(Decl: CurFunContext) ==
977 Sema::FunctionEmissionStatus::Emitted)
978 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
979 : SemaDiagnosticBuilder::K_Deferred;
980 default:
981 return SemaDiagnosticBuilder::K_Nop;
982 }
983 }();
984 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
985}
986
987bool SemaCUDA::CheckCall(SourceLocation Loc, FunctionDecl *Callee) {
988 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
989 assert(Callee && "Callee may not be null.");
990
991 const auto &ExprEvalCtx = SemaRef.currentEvaluationContext();
992 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
993 return true;
994
995 // C++ deduction guides participate in overload resolution but are not
996 // callable functions and are never codegen'ed. Treat them as always
997 // allowed for CUDA/HIP compatibility checking.
998 if (isa<CXXDeductionGuideDecl>(Val: Callee))
999 return true;
1000
1001 // FIXME: Is bailing out early correct here? Should we instead assume that
1002 // the caller is a global initializer?
1003 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1004 if (!Caller)
1005 return true;
1006
1007 // If the caller is known-emitted, mark the callee as known-emitted.
1008 // Otherwise, mark the call in our call graph so we can traverse it later.
1009 bool CallerKnownEmitted = SemaRef.getEmissionStatus(Decl: Caller) ==
1010 Sema::FunctionEmissionStatus::Emitted;
1011 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
1012 CallerKnownEmitted] {
1013 switch (IdentifyPreference(Caller, Callee)) {
1014 case CFP_Never:
1015 case CFP_WrongSide:
1016 assert(Caller && "Never/wrongSide calls require a non-null caller");
1017 // If we know the caller will be emitted, we know this wrong-side call
1018 // will be emitted, so it's an immediate error. Otherwise, defer the
1019 // error until we know the caller is emitted.
1020 return CallerKnownEmitted
1021 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
1022 : SemaDiagnosticBuilder::K_Deferred;
1023 default:
1024 return SemaDiagnosticBuilder::K_Nop;
1025 }
1026 }();
1027
1028 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
1029 // For -fgpu-rdc, keep track of external kernels used by host functions.
1030 if (getLangOpts().CUDAIsDevice && getLangOpts().GPURelocatableDeviceCode &&
1031 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined() &&
1032 (!Caller || (!Caller->getDescribedFunctionTemplate() &&
1033 getASTContext().GetGVALinkageForFunction(FD: Caller) ==
1034 GVA_StrongExternal)))
1035 getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Callee);
1036 return true;
1037 }
1038
1039 // Avoid emitting this error twice for the same location. Using a hashtable
1040 // like this is unfortunate, but because we must continue parsing as normal
1041 // after encountering a deferred error, it's otherwise very tricky for us to
1042 // ensure that we only emit this deferred error once.
1043 if (!LocsWithCUDACallDiags.insert(V: {.FD: Caller, .Loc: Loc}).second)
1044 return true;
1045
1046 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller,
1047 SemaRef)
1048 << IdentifyTarget(D: Callee) << /*function*/ 0 << Callee
1049 << IdentifyTarget(D: Caller);
1050 if (!Callee->getBuiltinID())
1051 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
1052 diag::note_previous_decl, Caller, SemaRef)
1053 << Callee;
1054 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
1055 DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
1056}
1057
1058// Check the wrong-sided reference capture of lambda for CUDA/HIP.
1059// A lambda function may capture a stack variable by reference when it is
1060// defined and uses the capture by reference when the lambda is called. When
1061// the capture and use happen on different sides, the capture is invalid and
1062// should be diagnosed.
1063void SemaCUDA::CheckLambdaCapture(CXXMethodDecl *Callee,
1064 const sema::Capture &Capture) {
1065 // In host compilation we only need to check lambda functions emitted on host
1066 // side. In such lambda functions, a reference capture is invalid only
1067 // if the lambda structure is populated by a device function or kernel then
1068 // is passed to and called by a host function. However that is impossible,
1069 // since a device function or kernel can only call a device function, also a
1070 // kernel cannot pass a lambda back to a host function since we cannot
1071 // define a kernel argument type which can hold the lambda before the lambda
1072 // itself is defined.
1073 if (!getLangOpts().CUDAIsDevice)
1074 return;
1075
1076 // File-scope lambda can only do init captures for global variables, which
1077 // results in passing by value for these global variables.
1078 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1079 if (!Caller)
1080 return;
1081
1082 // In device compilation, we only need to check lambda functions which are
1083 // emitted on device side. For such lambdas, a reference capture is invalid
1084 // only if the lambda structure is populated by a host function then passed
1085 // to and called in a device function or kernel.
1086 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
1087 bool CallerIsHost =
1088 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
1089 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
1090 if (!ShouldCheck || !Capture.isReferenceCapture())
1091 return;
1092 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
1093 if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
1094 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
1095 diag::err_capture_bad_target, Callee, SemaRef)
1096 << Capture.getVariable();
1097 } else if (Capture.isThisCapture()) {
1098 // Capture of this pointer is allowed since this pointer may be pointing to
1099 // managed memory which is accessible on both device and host sides. It only
1100 // results in invalid memory access if this pointer points to memory not
1101 // accessible on device side.
1102 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
1103 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
1104 SemaRef);
1105 }
1106}
1107
1108void SemaCUDA::SetLambdaAttrs(CXXMethodDecl *Method) {
1109 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1110 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
1111 return;
1112 Method->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
1113 Method->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
1114}
1115
1116void SemaCUDA::checkTargetOverload(FunctionDecl *NewFD,
1117 const LookupResult &Previous) {
1118 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1119 CUDAFunctionTarget NewTarget = IdentifyTarget(D: NewFD);
1120 for (NamedDecl *OldND : Previous) {
1121 FunctionDecl *OldFD = OldND->getAsFunction();
1122 if (!OldFD)
1123 continue;
1124
1125 CUDAFunctionTarget OldTarget = IdentifyTarget(D: OldFD);
1126 // Don't allow HD and global functions to overload other functions with the
1127 // same signature. We allow overloading based on CUDA attributes so that
1128 // functions can have different implementations on the host and device, but
1129 // HD/global functions "exist" in some sense on both the host and device, so
1130 // should have the same implementation on both sides.
1131 if (NewTarget != OldTarget &&
1132 !SemaRef.IsOverload(New: NewFD, Old: OldFD, /* UseMemberUsingDeclRules = */ false,
1133 /* ConsiderCudaAttrs = */ false)) {
1134 if ((NewTarget == CUDAFunctionTarget::HostDevice &&
1135 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1136 isImplicitHostDeviceFunction(D: NewFD) &&
1137 OldTarget == CUDAFunctionTarget::Device)) ||
1138 (OldTarget == CUDAFunctionTarget::HostDevice &&
1139 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1140 isImplicitHostDeviceFunction(D: OldFD) &&
1141 NewTarget == CUDAFunctionTarget::Device)) ||
1142 (NewTarget == CUDAFunctionTarget::Global) ||
1143 (OldTarget == CUDAFunctionTarget::Global)) {
1144 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cuda_ovl_target)
1145 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
1146 Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
1147 NewFD->setInvalidDecl();
1148 break;
1149 }
1150 if ((NewTarget == CUDAFunctionTarget::Host &&
1151 OldTarget == CUDAFunctionTarget::Device) ||
1152 (NewTarget == CUDAFunctionTarget::Device &&
1153 OldTarget == CUDAFunctionTarget::Host)) {
1154 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_offload_incompatible_redeclare)
1155 << NewTarget << OldTarget;
1156 Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
1157 }
1158 }
1159 }
1160}
1161
1162template <typename AttrTy>
1163static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
1164 const FunctionDecl &TemplateFD) {
1165 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
1166 AttrTy *Clone = Attribute->clone(S.Context);
1167 Clone->setInherited(true);
1168 FD->addAttr(A: Clone);
1169 }
1170}
1171
1172void SemaCUDA::inheritTargetAttrs(FunctionDecl *FD,
1173 const FunctionTemplateDecl &TD) {
1174 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
1175 copyAttrIfPresent<CUDAGlobalAttr>(S&: SemaRef, FD, TemplateFD);
1176 copyAttrIfPresent<CUDAHostAttr>(S&: SemaRef, FD, TemplateFD);
1177 copyAttrIfPresent<CUDADeviceAttr>(S&: SemaRef, FD, TemplateFD);
1178}
1179
1180std::string SemaCUDA::getConfigureFuncName() const {
1181 if (getLangOpts().OffloadViaLLVM)
1182 return "__llvmPushCallConfiguration";
1183
1184 if (getLangOpts().HIP)
1185 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
1186 : "hipConfigureCall";
1187
1188 // New CUDA kernel launch sequence.
1189 if (CudaFeatureEnabled(getASTContext().getTargetInfo().getSDKVersion(),
1190 CudaFeature::CUDA_USES_NEW_LAUNCH))
1191 return "__cudaPushCallConfiguration";
1192
1193 // Legacy CUDA kernel configuration call
1194 return "cudaConfigureCall";
1195}
1196
1197std::string SemaCUDA::getGetParameterBufferFuncName() const {
1198 return "cudaGetParameterBuffer";
1199}
1200
1201std::string SemaCUDA::getLaunchDeviceFuncName() const {
1202 return "cudaLaunchDevice";
1203}
1204
1205// Record any local constexpr variables that are passed one way on the host
1206// and another on the device.
1207void SemaCUDA::recordPotentialODRUsedVariable(
1208 MultiExprArg Arguments, OverloadCandidateSet &Candidates) {
1209 sema::LambdaScopeInfo *LambdaInfo = SemaRef.getCurLambda();
1210 if (!LambdaInfo)
1211 return;
1212
1213 for (unsigned I = 0; I < Arguments.size(); ++I) {
1214 auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Arguments[I]);
1215 if (!DeclRef)
1216 continue;
1217 auto *Variable = dyn_cast<VarDecl>(Val: DeclRef->getDecl());
1218 if (!Variable || !Variable->isLocalVarDecl() || !Variable->isConstexpr())
1219 continue;
1220
1221 bool HostByValue = false, HostByRef = false;
1222 bool DeviceByValue = false, DeviceByRef = false;
1223
1224 for (OverloadCandidate &Candidate : Candidates) {
1225 FunctionDecl *Callee = Candidate.Function;
1226 if (!Callee || I >= Callee->getNumParams())
1227 continue;
1228
1229 CUDAFunctionTarget Target = IdentifyTarget(D: Callee);
1230 if (Target == CUDAFunctionTarget::InvalidTarget ||
1231 Target == CUDAFunctionTarget::Global)
1232 continue;
1233
1234 bool CoversHost = (Target == CUDAFunctionTarget::Host ||
1235 Target == CUDAFunctionTarget::HostDevice);
1236 bool CoversDevice = (Target == CUDAFunctionTarget::Device ||
1237 Target == CUDAFunctionTarget::HostDevice);
1238
1239 bool IsRef = Callee->getParamDecl(i: I)->getType()->isReferenceType();
1240 HostByValue |= CoversHost && !IsRef;
1241 HostByRef |= CoversHost && IsRef;
1242 DeviceByValue |= CoversDevice && !IsRef;
1243 DeviceByRef |= CoversDevice && IsRef;
1244 }
1245
1246 if ((HostByValue && DeviceByRef) || (HostByRef && DeviceByValue))
1247 LambdaInfo->CUDAPotentialODRUsedVars.insert(Ptr: Variable);
1248 }
1249}
1250