Thanks to visit codestin.com
Credit goes to clang.llvm.org

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