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/DynamicRecursiveASTVisitor.h"
17#include "clang/AST/EvaluatedExprVisitor.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/Cuda.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/Overload.h"
24#include "clang/Sema/ScopeInfo.h"
25#include "clang/Sema/Sema.h"
26#include "clang/Sema/Template.h"
27#include "llvm/ADT/SmallVector.h"
28#include <optional>
29using namespace clang;
30
31SemaCUDA::SemaCUDA(Sema &S) : SemaBase(S) {}
32
33template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
34 if (!D)
35 return false;
36 if (auto *A = D->getAttr<AttrT>())
37 return !A->isImplicit();
38 return false;
39}
40
41void SemaCUDA::PushForceHostDevice() {
42 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
43 ForceHostDeviceDepth++;
44}
45
46bool SemaCUDA::PopForceHostDevice() {
47 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
48 if (ForceHostDeviceDepth == 0)
49 return false;
50 ForceHostDeviceDepth--;
51 return true;
52}
53
54ExprResult SemaCUDA::ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc,
55 MultiExprArg ExecConfig,
56 SourceLocation GGGLoc) {
57 bool IsDeviceKernelCall = false;
58 switch (CurrentTarget()) {
59 case CUDAFunctionTarget::Global:
60 case CUDAFunctionTarget::Device:
61 IsDeviceKernelCall = true;
62 break;
63 case CUDAFunctionTarget::HostDevice:
64 if (getLangOpts().CUDAIsDevice) {
65 IsDeviceKernelCall = true;
66 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
67 if (Caller && isImplicitHostDeviceFunction(D: Caller)) {
68 // Under the device compilation, config call under an HD function should
69 // be treated as a device kernel call. But, for implicit HD ones (such
70 // as lambdas), need to check whether RDC is enabled or not.
71 if (!getLangOpts().GPURelocatableDeviceCode)
72 IsDeviceKernelCall = false;
73 // HIP doesn't support device-side kernel call yet. Still treat it as
74 // the host-side kernel call.
75 if (getLangOpts().HIP)
76 IsDeviceKernelCall = false;
77 } else if (getLangOpts().HIP && getLangOpts().IncrementalExtensions &&
78 isa<TopLevelStmtDecl>(Val: SemaRef.getCurLexicalContext())) {
79 IsDeviceKernelCall = false;
80 }
81 }
82 break;
83 default:
84 break;
85 }
86
87 if (IsDeviceKernelCall && getLangOpts().HIP)
88 return ExprError(
89 Diag(Loc: LLLLoc, DiagID: diag::err_cuda_device_kernel_launch_not_supported));
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 (const FunctionDecl *FD = Var->getDeclContext()->getEnclosingFunction()) {
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
406bool SemaCUDA::isImplicitHDExplicitInstantiation(const FunctionDecl *FD) {
407 return FD && FD->isImplicitHDExplicitInstantiation();
408}
409
410void SemaCUDA::EraseUnwantedMatches(
411 const FunctionDecl *Caller,
412 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
413 if (Matches.size() <= 1)
414 return;
415
416 using Pair = std::pair<DeclAccessPair, FunctionDecl *>;
417
418 // Gets the CUDA function preference for a call from Caller to Match.
419 auto GetCFP = [&](const Pair &Match) {
420 return IdentifyPreference(Caller, Callee: Match.second);
421 };
422
423 // Find the best call preference among the functions in Matches.
424 CUDAFunctionPreference BestCFP =
425 GetCFP(*llvm::max_element(Range&: Matches, C: [&](const Pair &M1, const Pair &M2) {
426 return GetCFP(M1) < GetCFP(M2);
427 }));
428
429 // Erase all functions with lower priority.
430 llvm::erase_if(C&: Matches,
431 P: [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
432}
433
434/// When an implicitly-declared special member has to invoke more than one
435/// base/field special member, conflicts may occur in the targets of these
436/// members. For example, if one base's member __host__ and another's is
437/// __device__, it's a conflict.
438/// This function figures out if the given targets \param Target1 and
439/// \param Target2 conflict, and if they do not it fills in
440/// \param ResolvedTarget with a target that resolves for both calls.
441/// \return true if there's a conflict, false otherwise.
442static bool
443resolveCalleeCUDATargetConflict(CUDAFunctionTarget Target1,
444 CUDAFunctionTarget Target2,
445 CUDAFunctionTarget *ResolvedTarget) {
446 // Only free functions and static member functions may be global.
447 assert(Target1 != CUDAFunctionTarget::Global);
448 assert(Target2 != CUDAFunctionTarget::Global);
449
450 if (Target1 == CUDAFunctionTarget::HostDevice) {
451 *ResolvedTarget = Target2;
452 } else if (Target2 == CUDAFunctionTarget::HostDevice) {
453 *ResolvedTarget = Target1;
454 } else if (Target1 != Target2) {
455 return true;
456 } else {
457 *ResolvedTarget = Target1;
458 }
459
460 return false;
461}
462
463bool SemaCUDA::inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
464 CXXSpecialMemberKind CSM,
465 CXXMethodDecl *MemberDecl,
466 bool ConstRHS,
467 bool Diagnose) {
468 // If the defaulted special member is defined lexically outside of its
469 // owning class, or the special member already has explicit device or host
470 // attributes, do not infer.
471 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
472 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
473 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
474 bool HasExplicitAttr =
475 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
476 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
477 if (!InClass || HasExplicitAttr)
478 return false;
479
480 std::optional<CUDAFunctionTarget> InferredTarget;
481
482 // We're going to invoke special member lookup; mark that these special
483 // members are called from this one, and not from its caller.
484 Sema::ContextRAII MethodContext(SemaRef, MemberDecl);
485
486 // Look for special members in base classes that should be invoked from here.
487 // Infer the target of this member base on the ones it should call.
488 // Skip direct and indirect virtual bases for abstract classes, except for
489 // destructors — the complete destructor variant destroys virtual bases
490 // regardless of whether the class is abstract.
491 llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
492 for (const auto &B : ClassDecl->bases()) {
493 if (!B.isVirtual()) {
494 Bases.push_back(Elt: &B);
495 }
496 }
497
498 if (!ClassDecl->isAbstract() || CSM == CXXSpecialMemberKind::Destructor)
499 llvm::append_range(C&: Bases, R: llvm::make_pointer_range(Range: ClassDecl->vbases()));
500
501 for (const auto *B : Bases) {
502 auto *BaseClassDecl = B->getType()->getAsCXXRecordDecl();
503 if (!BaseClassDecl)
504 continue;
505
506 Sema::SpecialMemberOverloadResult SMOR =
507 SemaRef.LookupSpecialMember(D: BaseClassDecl, SM: CSM,
508 /* ConstArg */ ConstRHS,
509 /* VolatileArg */ false,
510 /* RValueThis */ false,
511 /* ConstThis */ false,
512 /* VolatileThis */ false);
513
514 if (!SMOR.getMethod())
515 continue;
516
517 CUDAFunctionTarget BaseMethodTarget = IdentifyTarget(D: SMOR.getMethod());
518
519 if (!InferredTarget) {
520 InferredTarget = BaseMethodTarget;
521 } else {
522 bool ResolutionError = resolveCalleeCUDATargetConflict(
523 Target1: *InferredTarget, Target2: BaseMethodTarget, ResolvedTarget: &*InferredTarget);
524 if (ResolutionError) {
525 if (Diagnose) {
526 Diag(Loc: ClassDecl->getLocation(),
527 DiagID: diag::note_implicit_member_target_infer_collision)
528 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
529 }
530 MemberDecl->addAttr(
531 A: CUDAInvalidTargetAttr::CreateImplicit(Ctx&: getASTContext()));
532 return true;
533 }
534 }
535 }
536
537 // Same as for bases, but now for special members of fields.
538 for (const auto *F : ClassDecl->fields()) {
539 if (F->isInvalidDecl()) {
540 continue;
541 }
542
543 auto *FieldRecDecl =
544 getASTContext().getBaseElementType(QT: F->getType())->getAsCXXRecordDecl();
545 if (!FieldRecDecl)
546 continue;
547
548 Sema::SpecialMemberOverloadResult SMOR =
549 SemaRef.LookupSpecialMember(D: FieldRecDecl, SM: CSM,
550 /* ConstArg */ ConstRHS && !F->isMutable(),
551 /* VolatileArg */ false,
552 /* RValueThis */ false,
553 /* ConstThis */ false,
554 /* VolatileThis */ false);
555
556 if (!SMOR.getMethod())
557 continue;
558
559 CUDAFunctionTarget FieldMethodTarget = IdentifyTarget(D: SMOR.getMethod());
560
561 if (!InferredTarget) {
562 InferredTarget = FieldMethodTarget;
563 } else {
564 bool ResolutionError = resolveCalleeCUDATargetConflict(
565 Target1: *InferredTarget, Target2: FieldMethodTarget, ResolvedTarget: &*InferredTarget);
566 if (ResolutionError) {
567 if (Diagnose) {
568 Diag(Loc: ClassDecl->getLocation(),
569 DiagID: diag::note_implicit_member_target_infer_collision)
570 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
571 }
572 MemberDecl->addAttr(
573 A: CUDAInvalidTargetAttr::CreateImplicit(Ctx&: getASTContext()));
574 return true;
575 }
576 }
577 }
578
579 // If no target was inferred, mark this member as __host__ __device__;
580 // it's the least restrictive option that can be invoked from any target.
581 bool NeedsH = true, NeedsD = true;
582 if (InferredTarget) {
583 if (*InferredTarget == CUDAFunctionTarget::Device)
584 NeedsH = false;
585 else if (*InferredTarget == CUDAFunctionTarget::Host)
586 NeedsD = false;
587 }
588
589 // We either setting attributes first time, or the inferred ones must match
590 // previously set ones.
591 if (NeedsD && !HasD)
592 MemberDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
593 if (NeedsH && !HasH)
594 MemberDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
595
596 return false;
597}
598
599bool SemaCUDA::isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
600 if (!CD->isDefined() && CD->isTemplateInstantiation())
601 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CD->getFirstDecl());
602
603 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
604 // empty at a point in the translation unit, if it is either a
605 // trivial constructor
606 if (CD->isTrivial())
607 return true;
608
609 // ... or it satisfies all of the following conditions:
610 // The constructor function has been defined.
611 // The constructor function has no parameters,
612 // and the function body is an empty compound statement.
613 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
614 return false;
615
616 // Its class has no virtual functions and no virtual base classes.
617 if (CD->getParent()->isDynamicClass())
618 return false;
619
620 // Union ctor does not call ctors of its data members.
621 if (CD->getParent()->isUnion())
622 return true;
623
624 // The only form of initializer allowed is an empty constructor.
625 // This will recursively check all base classes and member initializers
626 if (!llvm::all_of(Range: CD->inits(), P: [&](const CXXCtorInitializer *CI) {
627 if (const CXXConstructExpr *CE =
628 dyn_cast<CXXConstructExpr>(Val: CI->getInit()))
629 return isEmptyConstructor(Loc, CD: CE->getConstructor());
630 return false;
631 }))
632 return false;
633
634 return true;
635}
636
637bool SemaCUDA::isEmptyDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
638 // No destructor -> no problem.
639 if (!DD)
640 return true;
641
642 if (!DD->isDefined() && DD->isTemplateInstantiation())
643 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: DD->getFirstDecl());
644
645 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
646 // empty at a point in the translation unit, if it is either a
647 // trivial constructor
648 if (DD->isTrivial())
649 return true;
650
651 // ... or it satisfies all of the following conditions:
652 // The destructor function has been defined.
653 // and the function body is an empty compound statement.
654 if (!DD->hasTrivialBody())
655 return false;
656
657 const CXXRecordDecl *ClassDecl = DD->getParent();
658
659 // Its class has no virtual functions and no virtual base classes.
660 if (ClassDecl->isDynamicClass())
661 return false;
662
663 // Union does not have base class and union dtor does not call dtors of its
664 // data members.
665 if (DD->getParent()->isUnion())
666 return true;
667
668 // Only empty destructors are allowed. This will recursively check
669 // destructors for all base classes...
670 if (!llvm::all_of(Range: ClassDecl->bases(), P: [&](const CXXBaseSpecifier &BS) {
671 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
672 return isEmptyDestructor(Loc, DD: RD->getDestructor());
673 return true;
674 }))
675 return false;
676
677 // ... and member fields.
678 if (!llvm::all_of(Range: ClassDecl->fields(), P: [&](const FieldDecl *Field) {
679 if (CXXRecordDecl *RD = Field->getType()
680 ->getBaseElementTypeUnsafe()
681 ->getAsCXXRecordDecl())
682 return isEmptyDestructor(Loc, DD: RD->getDestructor());
683 return true;
684 }))
685 return false;
686
687 return true;
688}
689
690namespace {
691enum CUDAInitializerCheckKind {
692 CICK_DeviceOrConstant, // Check initializer for device/constant variable
693 CICK_Shared, // Check initializer for shared variable
694};
695
696bool IsDependentVar(VarDecl *VD) {
697 if (VD->getType()->isDependentType())
698 return true;
699 if (const auto *Init = VD->getInit())
700 return Init->isValueDependent();
701 return false;
702}
703
704// Check whether a variable has an allowed initializer for a CUDA device side
705// variable with global storage. \p VD may be a host variable to be checked for
706// potential promotion to device side variable.
707//
708// CUDA/HIP allows only empty constructors as initializers for global
709// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
710// __shared__ variables whether they are local or not (they all are implicitly
711// static in CUDA). One exception is that CUDA allows constant initializers
712// for __constant__ and __device__ variables.
713bool HasAllowedCUDADeviceStaticInitializer(SemaCUDA &S, VarDecl *VD,
714 CUDAInitializerCheckKind CheckKind) {
715 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
716 assert(!IsDependentVar(VD) && "do not check dependent var");
717 const Expr *Init = VD->getInit();
718 auto IsEmptyInit = [&](const Expr *Init) {
719 if (!Init)
720 return true;
721 if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: Init)) {
722 return S.isEmptyConstructor(Loc: VD->getLocation(), CD: CE->getConstructor());
723 }
724 return false;
725 };
726 auto IsConstantInit = [&](const Expr *Init) {
727 assert(Init);
728 ASTContext::CUDAConstantEvalContextRAII EvalCtx(S.getASTContext(),
729 /*NoWronSidedVars=*/true);
730 return Init->isConstantInitializer(Ctx&: S.getASTContext(),
731 ForRef: VD->getType()->isReferenceType());
732 };
733 auto HasEmptyDtor = [&](VarDecl *VD) {
734 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
735 return S.isEmptyDestructor(Loc: VD->getLocation(), DD: RD->getDestructor());
736 return true;
737 };
738 if (CheckKind == CICK_Shared)
739 return IsEmptyInit(Init) && HasEmptyDtor(VD);
740 return S.getLangOpts().GPUAllowDeviceInit ||
741 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
742}
743} // namespace
744
745void SemaCUDA::checkAllowedInitializer(VarDecl *VD) {
746 // Return early if VD is inside a non-instantiated template function since
747 // the implicit constructor is not defined yet.
748 if (const FunctionDecl *FD = VD->getDeclContext()->getEnclosingFunction();
749 FD && FD->isDependentContext())
750 return;
751
752 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
753 bool IsDeviceOrConstantVar =
754 !IsSharedVar &&
755 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
756 if ((IsSharedVar || IsDeviceOrConstantVar) &&
757 VD->getType().getQualifiers().getAddressSpace() != LangAS::Default) {
758 Diag(Loc: VD->getLocation(), DiagID: diag::err_cuda_address_space_gpuvar);
759 VD->setInvalidDecl();
760 return;
761 }
762 // Do not check dependent variables since the ctor/dtor/initializer are not
763 // determined. Do it after instantiation.
764 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
765 IsDependentVar(VD))
766 return;
767 const Expr *Init = VD->getInit();
768 if (IsDeviceOrConstantVar || IsSharedVar) {
769 if (HasAllowedCUDADeviceStaticInitializer(
770 S&: *this, VD, CheckKind: IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
771 return;
772 Diag(Loc: VD->getLocation(),
773 DiagID: IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
774 << Init->getSourceRange();
775 VD->setInvalidDecl();
776 } else {
777 // This is a host-side global variable. Check that the initializer is
778 // callable from the host side.
779
780 struct GlobVarInitChecker : ConstEvaluatedExprVisitor<GlobVarInitChecker> {
781 private:
782 using Base = ConstEvaluatedExprVisitor<GlobVarInitChecker>;
783 SemaCUDA &SCRef;
784 VarDecl *VD;
785 void CheckForWrongSidedCall(const FunctionDecl *FD) {
786 CUDAFunctionTarget InitFnTarget = SCRef.IdentifyTarget(D: FD);
787 if (InitFnTarget != CUDAFunctionTarget::Host &&
788 InitFnTarget != CUDAFunctionTarget::HostDevice &&
789 !VD->isInvalidDecl()) {
790 SCRef.Diag(Loc: VD->getLocation(),
791 DiagID: diag::err_ref_bad_target_global_initializer)
792 << InitFnTarget << FD;
793 SCRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_previous_decl) << FD;
794 VD->setInvalidDecl();
795 }
796 }
797
798 public:
799 GlobVarInitChecker(SemaCUDA &S, VarDecl *VD)
800 : Base(S.getASTContext()), SCRef(S), VD(VD) {}
801 void VisitDeclRefExpr(const DeclRefExpr *DRE) {
802 if (auto *VarD = dyn_cast<VarDecl>(Val: DRE->getDecl());
803 VarD && VarD->hasAttr<HIPManagedAttr>()) {
804 SCRef.Diag(Loc: DRE->getLocation(),
805 DiagID: diag::err_cuda_invalid_use_of_managedvar);
806 SCRef.Diag(Loc: VD->getLocation(),
807 DiagID: diag::note_cuda_managed_var_in_glob_init);
808 }
809 }
810 void VisitCallExpr(const CallExpr *CE) {
811 const FunctionDecl *InitFn = CE->getDirectCallee();
812 if (InitFn)
813 CheckForWrongSidedCall(FD: InitFn);
814 Base::VisitCallExpr(CE);
815 }
816
817 void VisitCXXConstructExpr(const CXXConstructExpr *CE) {
818 const CXXConstructorDecl *Ctor = CE->getConstructor();
819 if (Ctor) {
820 CheckForWrongSidedCall(FD: Ctor);
821 for (auto *I : Ctor->inits())
822 Visit(S: I->getInit());
823 }
824 Base::VisitCXXConstructExpr(S: CE);
825 }
826
827 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
828 Visit(S: E->getExpr());
829 }
830
831 void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
832 Visit(S: E->getExpr());
833 }
834 };
835 GlobVarInitChecker Checker(*this, VD);
836 Checker.Visit(S: Init);
837 }
838}
839
840void SemaCUDA::RecordImplicitHostDeviceFuncUsedByDevice(
841 const FunctionDecl *Callee) {
842 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
843 if (!Caller)
844 return;
845
846 if (!isImplicitHostDeviceFunction(D: Callee))
847 return;
848
849 CUDAFunctionTarget CallerTarget = IdentifyTarget(D: Caller);
850
851 // Record whether an implicit host device function is used on device side.
852 if (CallerTarget != CUDAFunctionTarget::Device &&
853 CallerTarget != CUDAFunctionTarget::Global &&
854 (CallerTarget != CUDAFunctionTarget::HostDevice ||
855 (isImplicitHostDeviceFunction(D: Caller) &&
856 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Caller))))
857 return;
858
859 getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.insert(V: Callee);
860}
861
862// With -fcuda-host-device-constexpr, an unattributed constexpr function is
863// treated as implicitly __host__ __device__, unless:
864// * it is a variadic function (device-side variadic functions are not
865// allowed), or
866// * a __device__ function with this signature was already declared, in which
867// case in which case we output an error, unless the __device__ decl is in a
868// system header, in which case we leave the constexpr function unattributed.
869//
870// In addition, all function decls are treated as __host__ __device__ when
871// ForceHostDeviceDepth > 0 (corresponding to code within a
872// #pragma clang force_cuda_host_device_begin/end
873// pair).
874void SemaCUDA::maybeAddHostDeviceAttrs(FunctionDecl *NewD,
875 const LookupResult &Previous) {
876 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
877
878 if (ForceHostDeviceDepth > 0) {
879 if (!NewD->hasAttr<CUDAHostAttr>())
880 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
881 if (!NewD->hasAttr<CUDADeviceAttr>())
882 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
883 return;
884 }
885
886 // If a template function has no host/device/global attributes,
887 // make it implicitly host device function.
888 if (getLangOpts().OffloadImplicitHostDeviceTemplates &&
889 !NewD->hasAttr<CUDAHostAttr>() && !NewD->hasAttr<CUDADeviceAttr>() &&
890 !NewD->hasAttr<CUDAGlobalAttr>() &&
891 (NewD->getDescribedFunctionTemplate() ||
892 NewD->isFunctionTemplateSpecialization())) {
893 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
894 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
895 return;
896 }
897
898 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
899 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
900 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
901 return;
902
903 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
904 // attributes?
905 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
906 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(Val: D))
907 D = Using->getTargetDecl();
908 FunctionDecl *OldD = D->getAsFunction();
909 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
910 !OldD->hasAttr<CUDAHostAttr>() &&
911 !SemaRef.IsOverload(New: NewD, Old: OldD,
912 /* UseMemberUsingDeclRules = */ false,
913 /* ConsiderCudaAttrs = */ false);
914 };
915 auto It = llvm::find_if(Range: Previous, P: IsMatchingDeviceFn);
916 if (It != Previous.end()) {
917 // We found a __device__ function with the same name and signature as NewD
918 // (ignoring CUDA attrs). This is an error unless that function is defined
919 // in a system header, in which case we simply return without making NewD
920 // host+device.
921 NamedDecl *Match = *It;
922 if (!SemaRef.getSourceManager().isInSystemHeader(Loc: Match->getLocation())) {
923 Diag(Loc: NewD->getLocation(),
924 DiagID: diag::err_cuda_unattributed_constexpr_cannot_overload_device)
925 << NewD;
926 Diag(Loc: Match->getLocation(),
927 DiagID: diag::note_cuda_conflicting_device_function_declared_here);
928 }
929 return;
930 }
931
932 NewD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
933 NewD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
934}
935
936// TODO: `__constant__` memory may be a limited resource for certain targets.
937// A safeguard may be needed at the end of compilation pipeline if
938// `__constant__` memory usage goes beyond limit.
939void SemaCUDA::MaybeAddConstantAttr(VarDecl *VD) {
940 // Do not promote dependent variables since the cotr/dtor/initializer are
941 // not determined. Do it after instantiation.
942 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
943 !VD->hasAttr<CUDASharedAttr>() &&
944 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
945 !IsDependentVar(VD) &&
946 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
947 HasAllowedCUDADeviceStaticInitializer(S&: *this, VD,
948 CheckKind: CICK_DeviceOrConstant))) {
949 VD->addAttr(A: CUDAConstantAttr::CreateImplicit(Ctx&: getASTContext()));
950 }
951}
952
953SemaBase::SemaDiagnosticBuilder SemaCUDA::DiagIfDeviceCode(SourceLocation Loc,
954 unsigned DiagID) {
955 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
956 FunctionDecl *CurFunContext =
957 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
958 SemaDiagnosticBuilder::Kind DiagKind = [&] {
959 if (!CurFunContext)
960 return SemaDiagnosticBuilder::K_Nop;
961 switch (CurrentTarget()) {
962 case CUDAFunctionTarget::Global:
963 case CUDAFunctionTarget::Device:
964 return SemaDiagnosticBuilder::K_Immediate;
965 case CUDAFunctionTarget::HostDevice:
966 // An HD function counts as host code if we're compiling for host, and
967 // device code if we're compiling for device. Defer any errors in device
968 // mode until the function is known-emitted.
969 if (!getLangOpts().CUDAIsDevice)
970 return SemaDiagnosticBuilder::K_Nop;
971 if (SemaRef.IsLastErrorImmediate &&
972 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
973 return SemaDiagnosticBuilder::K_Immediate;
974 if (isImplicitHDExplicitInstantiation(FD: CurFunContext))
975 return SemaDiagnosticBuilder::K_Deferred;
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
987Sema::SemaDiagnosticBuilder SemaCUDA::DiagIfHostCode(SourceLocation Loc,
988 unsigned DiagID) {
989 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
990 FunctionDecl *CurFunContext =
991 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
992 SemaDiagnosticBuilder::Kind DiagKind = [&] {
993 if (!CurFunContext)
994 return SemaDiagnosticBuilder::K_Nop;
995 switch (CurrentTarget()) {
996 case CUDAFunctionTarget::Host:
997 return SemaDiagnosticBuilder::K_Immediate;
998 case CUDAFunctionTarget::HostDevice:
999 // An HD function counts as host code if we're compiling for host, and
1000 // device code if we're compiling for device. Defer any errors in device
1001 // mode until the function is known-emitted.
1002 if (getLangOpts().CUDAIsDevice)
1003 return SemaDiagnosticBuilder::K_Nop;
1004 if (SemaRef.IsLastErrorImmediate &&
1005 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
1006 return SemaDiagnosticBuilder::K_Immediate;
1007 return (SemaRef.getEmissionStatus(Decl: CurFunContext) ==
1008 Sema::FunctionEmissionStatus::Emitted)
1009 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
1010 : SemaDiagnosticBuilder::K_Deferred;
1011 default:
1012 return SemaDiagnosticBuilder::K_Nop;
1013 }
1014 }();
1015 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
1016}
1017
1018bool SemaCUDA::isDeviceVarInit() const {
1019 return CurCUDATargetCtx.Kind == CTCK_InitGlobalVar &&
1020 CurCUDATargetCtx.Target == CUDAFunctionTarget::Device;
1021}
1022
1023void SemaCUDA::checkRTTIUse(SourceLocation Loc, StringRef Op) {
1024 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1025 // A default argument is checked where it is used.
1026 if (isa_and_present<ParmVarDecl>(
1027 Val: SemaRef.currentEvaluationContext().ManglingContextDecl))
1028 return;
1029
1030 if (SemaRef.getCurFunctionDecl(/*AllowLambda=*/true)) {
1031 DiagIfDeviceCode(Loc, DiagID: diag::err_cuda_device_rtti) << Op << CurrentTarget();
1032 return;
1033 }
1034
1035 // Outside a function, only the initializer of a device variable is device
1036 // code. A default member initializer is checked where it is used.
1037 if (isDeviceVarInit())
1038 Diag(Loc, DiagID: diag::err_cuda_device_rtti_var_init) << Op;
1039}
1040
1041namespace {
1042/// Finds a use of RTTI in a default argument or default member initializer.
1043struct RTTIUseFinder : ConstDynamicRecursiveASTVisitor {
1044 const Expr *Use = nullptr;
1045
1046 RTTIUseFinder() {
1047 // Look into nested default arguments and default member initializers.
1048 ShouldVisitImplicitCode = true;
1049 // Lambda bodies are checked as functions of their own.
1050 ShouldVisitLambdaBody = false;
1051 }
1052
1053 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E) override {
1054 Use = E;
1055 return false;
1056 }
1057
1058 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) override {
1059 // As with -fno-rtti, upcasts and dynamic_cast to void* don't use RTTI.
1060 QualType DestTy = E->getType();
1061 if (E->getCastKind() != CK_Dynamic ||
1062 (DestTy->isPointerType() && DestTy->getPointeeType()->isVoidType()))
1063 return true;
1064 Use = E;
1065 return false;
1066 }
1067};
1068} // namespace
1069
1070void SemaCUDA::checkRTTIInDefaultInit(const ValueDecl *D, const Expr *Init,
1071 SourceLocation UseLoc) {
1072 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1073 assert((isa<FieldDecl, ParmVarDecl>(D)) &&
1074 "Expected a default member initializer or default argument");
1075 const FunctionDecl *CurFn = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1076 if (!CurFn && !isDeviceVarInit())
1077 return;
1078 RTTIUseFinder Finder;
1079 Finder.TraverseStmt(S: Init);
1080 const Expr *Use = Finder.Use;
1081 if (!Use)
1082 return;
1083 // An initializer can be built more than once for the same use.
1084 if (!RTTICheckedDefaultInits.insert(V: {D, CurFn}).second)
1085 return;
1086
1087 StringRef Op = isa<CXXTypeidExpr>(Val: Use) ? "typeid" : "dynamic_cast";
1088 bool IsDefaultArg = isa<ParmVarDecl>(Val: D);
1089 if (!CurFn) {
1090 Diag(Loc: Use->getBeginLoc(), DiagID: diag::err_cuda_device_rtti_var_init) << Op;
1091 Diag(Loc: UseLoc, DiagID: diag::note_cuda_device_rtti_default_used_here) << IsDefaultArg;
1092 return;
1093 }
1094 {
1095 SemaDiagnosticBuilder DB =
1096 DiagIfDeviceCode(Loc: Use->getBeginLoc(), DiagID: diag::err_cuda_device_rtti);
1097 DB << Op << CurrentTarget();
1098 // Let the note below follow the error.
1099 SemaRef.IsLastErrorImmediate = DB.isImmediate();
1100 }
1101 DiagIfDeviceCode(Loc: UseLoc, DiagID: diag::note_cuda_device_rtti_default_used_here)
1102 << IsDefaultArg;
1103}
1104
1105bool SemaCUDA::CheckCall(SourceLocation Loc, FunctionDecl *Callee) {
1106 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1107 assert(Callee && "Callee may not be null.");
1108
1109 const auto &ExprEvalCtx = SemaRef.currentEvaluationContext();
1110 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated() ||
1111 ExprEvalCtx.isDiscardedStatementContext())
1112 return true;
1113
1114 // C++ deduction guides participate in overload resolution but are not
1115 // callable functions and are never codegen'ed. Treat them as always
1116 // allowed for CUDA/HIP compatibility checking.
1117 if (isa<CXXDeductionGuideDecl>(Val: Callee))
1118 return true;
1119
1120 // FIXME: Is bailing out early correct here? Should we instead assume that
1121 // the caller is a global initializer?
1122 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1123 if (!Caller)
1124 return true;
1125
1126 // If the caller is known-emitted, mark the callee as known-emitted.
1127 // Otherwise, mark the call in our call graph so we can traverse it later.
1128 bool CallerKnownEmitted = SemaRef.getEmissionStatus(Decl: Caller) ==
1129 Sema::FunctionEmissionStatus::Emitted;
1130 bool CallerIsImplicitHDExplicitInst =
1131 isImplicitHDExplicitInstantiation(FD: Caller);
1132 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
1133 CallerKnownEmitted,
1134 CallerIsImplicitHDExplicitInst] {
1135 switch (IdentifyPreference(Caller, Callee)) {
1136 case CFP_Never:
1137 case CFP_WrongSide:
1138 assert(Caller && "Never/wrongSide calls require a non-null caller");
1139 // If we know the caller will be emitted, we know this wrong-side call
1140 // will be emitted, so it's an immediate error. Otherwise, defer the
1141 // error until we know the caller is emitted.
1142 return (CallerKnownEmitted && !CallerIsImplicitHDExplicitInst)
1143 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
1144 : SemaDiagnosticBuilder::K_Deferred;
1145 default:
1146 return SemaDiagnosticBuilder::K_Nop;
1147 }
1148 }();
1149
1150 bool IsDeviceKernelCall = Callee == getASTContext().getcudaLaunchDeviceDecl();
1151 bool CallerHD = Caller && Caller->hasAttr<CUDAHostAttr>() &&
1152 Caller->hasAttr<CUDADeviceAttr>();
1153 bool CallerDiscard = SemaRef.getEmissionStatus(Decl: Caller) ==
1154 Sema::FunctionEmissionStatus::TemplateDiscarded;
1155 bool RDC = getLangOpts().GPURelocatableDeviceCode;
1156 if (IsDeviceKernelCall && !(CallerHD && CallerDiscard) && !RDC) {
1157 Diag(Loc, DiagID: diag::err_cuda_device_kernel_launch_require_rdc);
1158 return false;
1159 }
1160
1161 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
1162 // For -fgpu-rdc, keep track of external kernels used by host functions.
1163 if (getLangOpts().CUDAIsDevice && RDC &&
1164 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined() &&
1165 (!Caller || (!Caller->getDescribedFunctionTemplate() &&
1166 getASTContext().GetGVALinkageForFunction(FD: Caller) ==
1167 GVA_StrongExternal)))
1168 getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Callee);
1169 return true;
1170 }
1171
1172 // Avoid emitting this error twice for the same location. Using a hashtable
1173 // like this is unfortunate, but because we must continue parsing as normal
1174 // after encountering a deferred error, it's otherwise very tricky for us to
1175 // ensure that we only emit this deferred error once.
1176 if (!LocsWithCUDACallDiags.insert(V: {.FD: Caller, .Loc: Loc}).second)
1177 return true;
1178
1179 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller,
1180 SemaRef)
1181 << IdentifyTarget(D: Callee) << /*function*/ 0 << Callee
1182 << IdentifyTarget(D: Caller);
1183 if (!Callee->getBuiltinID())
1184 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
1185 diag::note_previous_decl, Caller, SemaRef)
1186 << Callee;
1187 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
1188 DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
1189}
1190
1191// Check the wrong-sided reference capture of lambda for CUDA/HIP.
1192// A lambda function may capture a stack variable by reference when it is
1193// defined and uses the capture by reference when the lambda is called. When
1194// the capture and use happen on different sides, the capture is invalid and
1195// should be diagnosed.
1196void SemaCUDA::CheckLambdaCapture(CXXMethodDecl *Callee,
1197 const sema::Capture &Capture) {
1198 // In host compilation we only need to check lambda functions emitted on host
1199 // side. In such lambda functions, a reference capture is invalid only
1200 // if the lambda structure is populated by a device function or kernel then
1201 // is passed to and called by a host function. However that is impossible,
1202 // since a device function or kernel can only call a device function, also a
1203 // kernel cannot pass a lambda back to a host function since we cannot
1204 // define a kernel argument type which can hold the lambda before the lambda
1205 // itself is defined.
1206 if (!getLangOpts().CUDAIsDevice)
1207 return;
1208
1209 // File-scope lambda can only do init captures for global variables, which
1210 // results in passing by value for these global variables.
1211 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1212 if (!Caller)
1213 return;
1214
1215 // In device compilation, we only need to check lambda functions which are
1216 // emitted on device side. For such lambdas, a reference capture is invalid
1217 // only if the lambda structure is populated by a host function then passed
1218 // to and called in a device function or kernel.
1219 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
1220 bool CallerIsHost =
1221 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
1222 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
1223 if (!ShouldCheck || !Capture.isReferenceCapture())
1224 return;
1225 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
1226 if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
1227 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
1228 diag::err_capture_bad_target, Callee, SemaRef)
1229 << Capture.getVariable();
1230 } else if (Capture.isThisCapture()) {
1231 // Capture of this pointer is allowed since this pointer may be pointing to
1232 // managed memory which is accessible on both device and host sides. It only
1233 // results in invalid memory access if this pointer points to memory not
1234 // accessible on device side.
1235 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
1236 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
1237 SemaRef);
1238 }
1239}
1240
1241void SemaCUDA::SetLambdaAttrs(CXXMethodDecl *Method) {
1242 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1243 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
1244 return;
1245 Method->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: getASTContext()));
1246 Method->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: getASTContext()));
1247}
1248
1249void SemaCUDA::checkTargetOverload(FunctionDecl *NewFD,
1250 const LookupResult &Previous) {
1251 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1252 CUDAFunctionTarget NewTarget = IdentifyTarget(D: NewFD);
1253 for (NamedDecl *OldND : Previous) {
1254 FunctionDecl *OldFD = OldND->getAsFunction();
1255 if (!OldFD)
1256 continue;
1257
1258 CUDAFunctionTarget OldTarget = IdentifyTarget(D: OldFD);
1259 // Don't allow HD and global functions to overload other functions with the
1260 // same signature. We allow overloading based on CUDA attributes so that
1261 // functions can have different implementations on the host and device, but
1262 // HD/global functions "exist" in some sense on both the host and device, so
1263 // should have the same implementation on both sides.
1264 if (NewTarget != OldTarget &&
1265 !SemaRef.IsOverload(New: NewFD, Old: OldFD, /* UseMemberUsingDeclRules = */ false,
1266 /* ConsiderCudaAttrs = */ false)) {
1267 if ((NewTarget == CUDAFunctionTarget::HostDevice &&
1268 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1269 isImplicitHostDeviceFunction(D: NewFD) &&
1270 OldTarget == CUDAFunctionTarget::Device)) ||
1271 (OldTarget == CUDAFunctionTarget::HostDevice &&
1272 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1273 isImplicitHostDeviceFunction(D: OldFD) &&
1274 NewTarget == CUDAFunctionTarget::Device)) ||
1275 (NewTarget == CUDAFunctionTarget::Global) ||
1276 (OldTarget == CUDAFunctionTarget::Global)) {
1277 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cuda_ovl_target)
1278 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
1279 Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
1280 NewFD->setInvalidDecl();
1281 break;
1282 }
1283 if ((NewTarget == CUDAFunctionTarget::Host &&
1284 OldTarget == CUDAFunctionTarget::Device) ||
1285 (NewTarget == CUDAFunctionTarget::Device &&
1286 OldTarget == CUDAFunctionTarget::Host)) {
1287 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_offload_incompatible_redeclare)
1288 << NewTarget << OldTarget;
1289 Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
1290 }
1291 }
1292 }
1293}
1294
1295template <typename AttrTy>
1296static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
1297 const FunctionDecl &TemplateFD) {
1298 if (FD->hasAttr<AttrTy>())
1299 return;
1300 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
1301 AttrTy *Clone = Attribute->clone(S.Context);
1302 Clone->setInherited(true);
1303 FD->addAttr(A: Clone);
1304 }
1305}
1306
1307void SemaCUDA::inheritTargetAttrs(FunctionDecl *FD,
1308 const FunctionTemplateDecl &TD) {
1309 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
1310 copyAttrIfPresent<CUDAGlobalAttr>(S&: SemaRef, FD, TemplateFD);
1311 copyAttrIfPresent<CUDAHostAttr>(S&: SemaRef, FD, TemplateFD);
1312 copyAttrIfPresent<CUDADeviceAttr>(S&: SemaRef, FD, TemplateFD);
1313}
1314
1315std::string SemaCUDA::getConfigureFuncName() const {
1316 if (getLangOpts().OffloadViaLLVM)
1317 return "__llvmPushCallConfiguration";
1318
1319 if (getLangOpts().HIP)
1320 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
1321 : "hipConfigureCall";
1322
1323 // New CUDA kernel launch sequence.
1324 if (CudaFeatureEnabled(getASTContext().getTargetInfo().getSDKVersion(),
1325 CudaFeature::CUDA_USES_NEW_LAUNCH))
1326 return "__cudaPushCallConfiguration";
1327
1328 // Legacy CUDA kernel configuration call
1329 return "cudaConfigureCall";
1330}
1331
1332std::string SemaCUDA::getGetParameterBufferFuncName() const {
1333 return "cudaGetParameterBuffer";
1334}
1335
1336std::string SemaCUDA::getLaunchDeviceFuncName() const {
1337 return "cudaLaunchDevice";
1338}
1339
1340// Record any local constexpr variables that are passed one way on the host
1341// and another on the device.
1342void SemaCUDA::recordPotentialODRUsedVariable(
1343 MultiExprArg Arguments, OverloadCandidateSet &Candidates) {
1344 sema::LambdaScopeInfo *LambdaInfo = SemaRef.getCurLambda();
1345 if (!LambdaInfo)
1346 return;
1347
1348 for (unsigned I = 0; I < Arguments.size(); ++I) {
1349 auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Arguments[I]);
1350 if (!DeclRef)
1351 continue;
1352 auto *Variable = dyn_cast<VarDecl>(Val: DeclRef->getDecl());
1353 if (!Variable || !Variable->isLocalVarDecl() || !Variable->isConstexpr())
1354 continue;
1355
1356 bool HostByValue = false, HostByRef = false;
1357 bool DeviceByValue = false, DeviceByRef = false;
1358
1359 for (OverloadCandidate &Candidate : Candidates) {
1360 FunctionDecl *Callee = Candidate.Function;
1361 if (!Callee || I >= Callee->getNumParams())
1362 continue;
1363
1364 CUDAFunctionTarget Target = IdentifyTarget(D: Callee);
1365 if (Target == CUDAFunctionTarget::InvalidTarget ||
1366 Target == CUDAFunctionTarget::Global)
1367 continue;
1368
1369 bool CoversHost = (Target == CUDAFunctionTarget::Host ||
1370 Target == CUDAFunctionTarget::HostDevice);
1371 bool CoversDevice = (Target == CUDAFunctionTarget::Device ||
1372 Target == CUDAFunctionTarget::HostDevice);
1373
1374 bool IsRef = Callee->getParamDecl(i: I)->getType()->isReferenceType();
1375 HostByValue |= CoversHost && !IsRef;
1376 HostByRef |= CoversHost && IsRef;
1377 DeviceByValue |= CoversDevice && !IsRef;
1378 DeviceByRef |= CoversDevice && IsRef;
1379 }
1380
1381 if ((HostByValue && DeviceByRef) || (HostByRef && DeviceByValue))
1382 LambdaInfo->CUDAPotentialODRUsedVars.insert(Ptr: Variable);
1383 }
1384}
1385