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_) {
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)
139
140 if (D->hasAttr<CUDAInvalidTargetAttr>())
142
143 if (D->hasAttr<CUDAGlobalAttr>())
145
146 if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
147 if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
150 } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
152 } else if ((D->isImplicit() || !D->isUserProvided()) &&
153 !IgnoreImplicitHDAttr) {
154 // Some implicit declarations (like intrinsic functions) are not marked.
155 // Set the most lenient target on them for maximal flexibility.
157 }
158
160}
161
162/// IdentifyTarget - Determine the CUDA compilation target for this variable.
164 if (Var->hasAttr<HIPManagedAttr>())
165 return CVT_Unified;
166 // Only constexpr and const variabless with implicit constant attribute
167 // are emitted on both sides. Such variables are promoted to device side
168 // only if they have static constant intializers on device side.
169 if ((Var->isConstexpr() || Var->getType().isConstQualified()) &&
170 Var->hasAttr<CUDAConstantAttr>() &&
171 !hasExplicitAttr<CUDAConstantAttr>(Var))
172 return CVT_Both;
173 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
174 Var->hasAttr<CUDASharedAttr>() ||
177 return CVT_Device;
178 // Function-scope static variable without explicit device or constant
179 // attribute are emitted
180 // - on both sides in host device functions
181 // - on device side in device or global functions
182 if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) {
183 switch (IdentifyTarget(FD)) {
185 return CVT_Both;
188 return CVT_Device;
189 default:
190 return CVT_Host;
191 }
192 }
193 return CVT_Host;
194}
195
196// * CUDA Call preference table
197//
198// F - from,
199// T - to
200// Ph - preference in host mode
201// Pd - preference in device mode
202// H - handled in (x)
203// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
204//
205// | F | T | Ph | Pd | H |
206// |----+----+-----+-----+-----+
207// | d | d | N | N | (c) |
208// | d | g | -- | -- | (a) |
209// | d | h | -- | -- | (e) |
210// | d | hd | HD | HD | (b) |
211// | g | d | N | N | (c) |
212// | g | g | -- | -- | (a) |
213// | g | h | -- | -- | (e) |
214// | g | hd | HD | HD | (b) |
215// | h | d | -- | -- | (e) |
216// | h | g | N | N | (c) |
217// | h | h | N | N | (c) |
218// | h | hd | HD | HD | (b) |
219// | hd | d | WS | SS | (d) |
220// | hd | g | SS | -- |(d/a)|
221// | hd | h | SS | WS | (d) |
222// | hd | hd | HD | HD | (b) |
223
226 const FunctionDecl *Callee) {
227 assert(Callee && "Callee must be valid.");
228
229 // Treat ctor/dtor as host device function in device var initializer to allow
230 // trivial ctor/dtor without device attr to be used. Non-trivial ctor/dtor
231 // will be diagnosed by checkAllowedInitializer.
232 if (Caller == nullptr && CurCUDATargetCtx.Kind == CTCK_InitGlobalVar &&
234 (isa<CXXConstructorDecl>(Callee) || isa<CXXDestructorDecl>(Callee)))
235 return CFP_HostDevice;
236
237 CUDAFunctionTarget CallerTarget = IdentifyTarget(Caller);
238 CUDAFunctionTarget CalleeTarget = IdentifyTarget(Callee);
239
240 // If one of the targets is invalid, the check always fails, no matter what
241 // the other target is.
242 if (CallerTarget == CUDAFunctionTarget::InvalidTarget ||
243 CalleeTarget == CUDAFunctionTarget::InvalidTarget)
244 return CFP_Never;
245
246 // (a) Can't call global from some contexts until we support CUDA's
247 // dynamic parallelism.
248 if (CalleeTarget == CUDAFunctionTarget::Global &&
249 (CallerTarget == CUDAFunctionTarget::Global ||
250 CallerTarget == CUDAFunctionTarget::Device))
251 return CFP_Never;
252
253 // (b) Calling HostDevice is OK for everyone.
254 if (CalleeTarget == CUDAFunctionTarget::HostDevice)
255 return CFP_HostDevice;
256
257 // (c) Best case scenarios
258 if (CalleeTarget == CallerTarget ||
259 (CallerTarget == CUDAFunctionTarget::Host &&
260 CalleeTarget == CUDAFunctionTarget::Global) ||
261 (CallerTarget == CUDAFunctionTarget::Global &&
262 CalleeTarget == CUDAFunctionTarget::Device))
263 return CFP_Native;
264
265 // HipStdPar mode is special, in that assessing whether a device side call to
266 // a host target is deferred to a subsequent pass, and cannot unambiguously be
267 // adjudicated in the AST, hence we optimistically allow them to pass here.
268 if (getLangOpts().HIPStdPar &&
269 (CallerTarget == CUDAFunctionTarget::Global ||
270 CallerTarget == CUDAFunctionTarget::Device ||
271 CallerTarget == CUDAFunctionTarget::HostDevice) &&
272 CalleeTarget == CUDAFunctionTarget::Host)
273 return CFP_HostDevice;
274
275 // (d) HostDevice behavior depends on compilation mode.
276 if (CallerTarget == CUDAFunctionTarget::HostDevice) {
277 // It's OK to call a compilation-mode matching function from an HD one.
278 if ((getLangOpts().CUDAIsDevice &&
279 CalleeTarget == CUDAFunctionTarget::Device) ||
280 (!getLangOpts().CUDAIsDevice &&
281 (CalleeTarget == CUDAFunctionTarget::Host ||
282 CalleeTarget == CUDAFunctionTarget::Global)))
283 return CFP_SameSide;
284
285 // Calls from HD to non-mode-matching functions (i.e., to host functions
286 // when compiling in device mode or to device functions when compiling in
287 // host mode) are allowed at the sema level, but eventually rejected if
288 // they're ever codegened. TODO: Reject said calls earlier.
289 return CFP_WrongSide;
290 }
291
292 // (e) Calling across device/host boundary is not something you should do.
293 if ((CallerTarget == CUDAFunctionTarget::Host &&
294 CalleeTarget == CUDAFunctionTarget::Device) ||
295 (CallerTarget == CUDAFunctionTarget::Device &&
296 CalleeTarget == CUDAFunctionTarget::Host) ||
297 (CallerTarget == CUDAFunctionTarget::Global &&
298 CalleeTarget == CUDAFunctionTarget::Host))
299 return CFP_Never;
300
301 llvm_unreachable("All cases should've been handled by now.");
302}
303
304template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
305 if (!D)
306 return false;
307 if (auto *A = D->getAttr<AttrT>())
308 return A->isImplicit();
309 return D->isImplicit();
310}
311
313 bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
314 bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
315 return IsImplicitDevAttr && IsImplicitHostAttr;
316}
317
319 const FunctionDecl *Caller,
320 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
321 if (Matches.size() <= 1)
322 return;
323
324 using Pair = std::pair<DeclAccessPair, FunctionDecl *>;
325
326 // Gets the CUDA function preference for a call from Caller to Match.
327 auto GetCFP = [&](const Pair &Match) {
328 return IdentifyPreference(Caller, Match.second);
329 };
330
331 // Find the best call preference among the functions in Matches.
332 CUDAFunctionPreference BestCFP =
333 GetCFP(*llvm::max_element(Matches, [&](const Pair &M1, const Pair &M2) {
334 return GetCFP(M1) < GetCFP(M2);
335 }));
336
337 // Erase all functions with lower priority.
338 llvm::erase_if(Matches,
339 [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
340}
341
342/// When an implicitly-declared special member has to invoke more than one
343/// base/field special member, conflicts may occur in the targets of these
344/// members. For example, if one base's member __host__ and another's is
345/// __device__, it's a conflict.
346/// This function figures out if the given targets \param Target1 and
347/// \param Target2 conflict, and if they do not it fills in
348/// \param ResolvedTarget with a target that resolves for both calls.
349/// \return true if there's a conflict, false otherwise.
350static bool
352 CUDAFunctionTarget Target2,
353 CUDAFunctionTarget *ResolvedTarget) {
354 // Only free functions and static member functions may be global.
355 assert(Target1 != CUDAFunctionTarget::Global);
356 assert(Target2 != CUDAFunctionTarget::Global);
357
358 if (Target1 == CUDAFunctionTarget::HostDevice) {
359 *ResolvedTarget = Target2;
360 } else if (Target2 == CUDAFunctionTarget::HostDevice) {
361 *ResolvedTarget = Target1;
362 } else if (Target1 != Target2) {
363 return true;
364 } else {
365 *ResolvedTarget = Target1;
366 }
367
368 return false;
369}
370
373 CXXMethodDecl *MemberDecl,
374 bool ConstRHS,
375 bool Diagnose) {
376 // If MemberDecl is virtual destructor of an explicit template class
377 // instantiation, it must be emitted, therefore it needs to be inferred
378 // conservatively by ignoring implicit host/device attrs of member and parent
379 // dtors called by it. Also, it needs to be checed by deferred diag visitor.
380 bool IsExpVDtor = false;
381 if (isa<CXXDestructorDecl>(MemberDecl) && MemberDecl->isVirtual()) {
382 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(ClassDecl)) {
383 TemplateSpecializationKind TSK = Spec->getTemplateSpecializationKind();
384 IsExpVDtor = TSK == TSK_ExplicitInstantiationDeclaration ||
386 }
387 }
388 if (IsExpVDtor)
389 SemaRef.DeclsToCheckForDeferredDiags.insert(MemberDecl);
390
391 // If the defaulted special member is defined lexically outside of its
392 // owning class, or the special member already has explicit device or host
393 // attributes, do not infer.
394 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
395 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
396 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
397 bool HasExplicitAttr =
398 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
399 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
400 if (!InClass || HasExplicitAttr)
401 return false;
402
403 std::optional<CUDAFunctionTarget> InferredTarget;
404
405 // We're going to invoke special member lookup; mark that these special
406 // members are called from this one, and not from its caller.
407 Sema::ContextRAII MethodContext(SemaRef, MemberDecl);
408
409 // Look for special members in base classes that should be invoked from here.
410 // Infer the target of this member base on the ones it should call.
411 // Skip direct and indirect virtual bases for abstract classes.
413 for (const auto &B : ClassDecl->bases()) {
414 if (!B.isVirtual()) {
415 Bases.push_back(&B);
416 }
417 }
418
419 if (!ClassDecl->isAbstract()) {
420 llvm::append_range(Bases, llvm::make_pointer_range(ClassDecl->vbases()));
421 }
422
423 for (const auto *B : Bases) {
424 auto *BaseClassDecl = B->getType()->getAsCXXRecordDecl();
425 if (!BaseClassDecl)
426 continue;
427
429 SemaRef.LookupSpecialMember(BaseClassDecl, CSM,
430 /* ConstArg */ ConstRHS,
431 /* VolatileArg */ false,
432 /* RValueThis */ false,
433 /* ConstThis */ false,
434 /* VolatileThis */ false);
435
436 if (!SMOR.getMethod())
437 continue;
438
439 CUDAFunctionTarget BaseMethodTarget =
440 IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
441
442 if (!InferredTarget) {
443 InferredTarget = BaseMethodTarget;
444 } else {
445 bool ResolutionError = resolveCalleeCUDATargetConflict(
446 *InferredTarget, BaseMethodTarget, &*InferredTarget);
447 if (ResolutionError) {
448 if (Diagnose) {
449 Diag(ClassDecl->getLocation(),
450 diag::note_implicit_member_target_infer_collision)
451 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
452 }
453 MemberDecl->addAttr(
454 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
455 return true;
456 }
457 }
458 }
459
460 // Same as for bases, but now for special members of fields.
461 for (const auto *F : ClassDecl->fields()) {
462 if (F->isInvalidDecl()) {
463 continue;
464 }
465
466 auto *FieldRecDecl =
468 if (!FieldRecDecl)
469 continue;
470
472 SemaRef.LookupSpecialMember(FieldRecDecl, CSM,
473 /* ConstArg */ ConstRHS && !F->isMutable(),
474 /* VolatileArg */ false,
475 /* RValueThis */ false,
476 /* ConstThis */ false,
477 /* VolatileThis */ false);
478
479 if (!SMOR.getMethod())
480 continue;
481
482 CUDAFunctionTarget FieldMethodTarget =
483 IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
484
485 if (!InferredTarget) {
486 InferredTarget = FieldMethodTarget;
487 } else {
488 bool ResolutionError = resolveCalleeCUDATargetConflict(
489 *InferredTarget, FieldMethodTarget, &*InferredTarget);
490 if (ResolutionError) {
491 if (Diagnose) {
492 Diag(ClassDecl->getLocation(),
493 diag::note_implicit_member_target_infer_collision)
494 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
495 }
496 MemberDecl->addAttr(
497 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
498 return true;
499 }
500 }
501 }
502
503 // If no target was inferred, mark this member as __host__ __device__;
504 // it's the least restrictive option that can be invoked from any target.
505 bool NeedsH = true, NeedsD = true;
506 if (InferredTarget) {
507 if (*InferredTarget == CUDAFunctionTarget::Device)
508 NeedsH = false;
509 else if (*InferredTarget == CUDAFunctionTarget::Host)
510 NeedsD = false;
511 }
512
513 // We either setting attributes first time, or the inferred ones must match
514 // previously set ones.
515 if (NeedsD && !HasD)
516 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
517 if (NeedsH && !HasH)
518 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
519
520 return false;
521}
522
524 if (!CD->isDefined() && CD->isTemplateInstantiation())
526
527 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
528 // empty at a point in the translation unit, if it is either a
529 // trivial constructor
530 if (CD->isTrivial())
531 return true;
532
533 // ... or it satisfies all of the following conditions:
534 // The constructor function has been defined.
535 // The constructor function has no parameters,
536 // and the function body is an empty compound statement.
537 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
538 return false;
539
540 // Its class has no virtual functions and no virtual base classes.
541 if (CD->getParent()->isDynamicClass())
542 return false;
543
544 // Union ctor does not call ctors of its data members.
545 if (CD->getParent()->isUnion())
546 return true;
547
548 // The only form of initializer allowed is an empty constructor.
549 // This will recursively check all base classes and member initializers
550 if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
551 if (const CXXConstructExpr *CE =
552 dyn_cast<CXXConstructExpr>(CI->getInit()))
553 return isEmptyConstructor(Loc, CE->getConstructor());
554 return false;
555 }))
556 return false;
557
558 return true;
559}
560
562 // No destructor -> no problem.
563 if (!DD)
564 return true;
565
566 if (!DD->isDefined() && DD->isTemplateInstantiation())
568
569 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
570 // empty at a point in the translation unit, if it is either a
571 // trivial constructor
572 if (DD->isTrivial())
573 return true;
574
575 // ... or it satisfies all of the following conditions:
576 // The destructor function has been defined.
577 // and the function body is an empty compound statement.
578 if (!DD->hasTrivialBody())
579 return false;
580
581 const CXXRecordDecl *ClassDecl = DD->getParent();
582
583 // Its class has no virtual functions and no virtual base classes.
584 if (ClassDecl->isDynamicClass())
585 return false;
586
587 // Union does not have base class and union dtor does not call dtors of its
588 // data members.
589 if (DD->getParent()->isUnion())
590 return true;
591
592 // Only empty destructors are allowed. This will recursively check
593 // destructors for all base classes...
594 if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
595 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
596 return isEmptyDestructor(Loc, RD->getDestructor());
597 return true;
598 }))
599 return false;
600
601 // ... and member fields.
602 if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
603 if (CXXRecordDecl *RD = Field->getType()
604 ->getBaseElementTypeUnsafe()
605 ->getAsCXXRecordDecl())
606 return isEmptyDestructor(Loc, RD->getDestructor());
607 return true;
608 }))
609 return false;
610
611 return true;
612}
613
614namespace {
615enum CUDAInitializerCheckKind {
616 CICK_DeviceOrConstant, // Check initializer for device/constant variable
617 CICK_Shared, // Check initializer for shared variable
618};
619
620bool IsDependentVar(VarDecl *VD) {
621 if (VD->getType()->isDependentType())
622 return true;
623 if (const auto *Init = VD->getInit())
624 return Init->isValueDependent();
625 return false;
626}
627
628// Check whether a variable has an allowed initializer for a CUDA device side
629// variable with global storage. \p VD may be a host variable to be checked for
630// potential promotion to device side variable.
631//
632// CUDA/HIP allows only empty constructors as initializers for global
633// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
634// __shared__ variables whether they are local or not (they all are implicitly
635// static in CUDA). One exception is that CUDA allows constant initializers
636// for __constant__ and __device__ variables.
637bool HasAllowedCUDADeviceStaticInitializer(SemaCUDA &S, VarDecl *VD,
638 CUDAInitializerCheckKind CheckKind) {
639 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
640 assert(!IsDependentVar(VD) && "do not check dependent var");
641 const Expr *Init = VD->getInit();
642 auto IsEmptyInit = [&](const Expr *Init) {
643 if (!Init)
644 return true;
645 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
646 return S.isEmptyConstructor(VD->getLocation(), CE->getConstructor());
647 }
648 return false;
649 };
650 auto IsConstantInit = [&](const Expr *Init) {
651 assert(Init);
653 /*NoWronSidedVars=*/true);
654 return Init->isConstantInitializer(S.getASTContext(),
655 VD->getType()->isReferenceType());
656 };
657 auto HasEmptyDtor = [&](VarDecl *VD) {
658 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
659 return S.isEmptyDestructor(VD->getLocation(), RD->getDestructor());
660 return true;
661 };
662 if (CheckKind == CICK_Shared)
663 return IsEmptyInit(Init) && HasEmptyDtor(VD);
664 return S.getLangOpts().GPUAllowDeviceInit ||
665 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
666}
667} // namespace
668
670 // Return early if VD is inside a non-instantiated template function since
671 // the implicit constructor is not defined yet.
672 if (const FunctionDecl *FD =
673 dyn_cast_or_null<FunctionDecl>(VD->getDeclContext());
674 FD && FD->isDependentContext())
675 return;
676
677 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
678 bool IsDeviceOrConstantVar =
679 !IsSharedVar &&
680 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
681 if ((IsSharedVar || IsDeviceOrConstantVar) &&
683 Diag(VD->getLocation(), diag::err_cuda_address_space_gpuvar);
684 VD->setInvalidDecl();
685 return;
686 }
687 // Do not check dependent variables since the ctor/dtor/initializer are not
688 // determined. Do it after instantiation.
689 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
690 IsDependentVar(VD))
691 return;
692 const Expr *Init = VD->getInit();
693 if (IsDeviceOrConstantVar || IsSharedVar) {
694 if (HasAllowedCUDADeviceStaticInitializer(
695 *this, VD, IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
696 return;
697 Diag(VD->getLocation(),
698 IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
699 << Init->getSourceRange();
700 VD->setInvalidDecl();
701 } else {
702 // This is a host-side global variable. Check that the initializer is
703 // callable from the host side.
704 const FunctionDecl *InitFn = nullptr;
705 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
706 InitFn = CE->getConstructor();
707 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
708 InitFn = CE->getDirectCallee();
709 }
710 if (InitFn) {
711 CUDAFunctionTarget InitFnTarget = IdentifyTarget(InitFn);
712 if (InitFnTarget != CUDAFunctionTarget::Host &&
713 InitFnTarget != CUDAFunctionTarget::HostDevice) {
714 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
715 << InitFnTarget << InitFn;
716 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
717 VD->setInvalidDecl();
718 }
719 }
720 }
721}
722
724 const FunctionDecl *Callee) {
725 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
726 if (!Caller)
727 return;
728
729 if (!isImplicitHostDeviceFunction(Callee))
730 return;
731
732 CUDAFunctionTarget CallerTarget = IdentifyTarget(Caller);
733
734 // Record whether an implicit host device function is used on device side.
735 if (CallerTarget != CUDAFunctionTarget::Device &&
736 CallerTarget != CUDAFunctionTarget::Global &&
737 (CallerTarget != CUDAFunctionTarget::HostDevice ||
739 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Caller))))
740 return;
741
743}
744
745// With -fcuda-host-device-constexpr, an unattributed constexpr function is
746// treated as implicitly __host__ __device__, unless:
747// * it is a variadic function (device-side variadic functions are not
748// allowed), or
749// * a __device__ function with this signature was already declared, in which
750// case in which case we output an error, unless the __device__ decl is in a
751// system header, in which case we leave the constexpr function unattributed.
752//
753// In addition, all function decls are treated as __host__ __device__ when
754// ForceHostDeviceDepth > 0 (corresponding to code within a
755// #pragma clang force_cuda_host_device_begin/end
756// pair).
758 const LookupResult &Previous) {
759 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
760
761 if (ForceHostDeviceDepth > 0) {
762 if (!NewD->hasAttr<CUDAHostAttr>())
763 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
764 if (!NewD->hasAttr<CUDADeviceAttr>())
765 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
766 return;
767 }
768
769 // If a template function has no host/device/global attributes,
770 // make it implicitly host device function.
771 if (getLangOpts().OffloadImplicitHostDeviceTemplates &&
772 !NewD->hasAttr<CUDAHostAttr>() && !NewD->hasAttr<CUDADeviceAttr>() &&
773 !NewD->hasAttr<CUDAGlobalAttr>() &&
776 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
777 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
778 return;
779 }
780
781 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
782 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
783 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
784 return;
785
786 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
787 // attributes?
788 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
789 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
790 D = Using->getTargetDecl();
791 FunctionDecl *OldD = D->getAsFunction();
792 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
793 !OldD->hasAttr<CUDAHostAttr>() &&
794 !SemaRef.IsOverload(NewD, OldD,
795 /* UseMemberUsingDeclRules = */ false,
796 /* ConsiderCudaAttrs = */ false);
797 };
798 auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
799 if (It != Previous.end()) {
800 // We found a __device__ function with the same name and signature as NewD
801 // (ignoring CUDA attrs). This is an error unless that function is defined
802 // in a system header, in which case we simply return without making NewD
803 // host+device.
804 NamedDecl *Match = *It;
805 if (!SemaRef.getSourceManager().isInSystemHeader(Match->getLocation())) {
806 Diag(NewD->getLocation(),
807 diag::err_cuda_unattributed_constexpr_cannot_overload_device)
808 << NewD;
809 Diag(Match->getLocation(),
810 diag::note_cuda_conflicting_device_function_declared_here);
811 }
812 return;
813 }
814
815 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
816 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
817}
818
819// TODO: `__constant__` memory may be a limited resource for certain targets.
820// A safeguard may be needed at the end of compilation pipeline if
821// `__constant__` memory usage goes beyond limit.
823 // Do not promote dependent variables since the cotr/dtor/initializer are
824 // not determined. Do it after instantiation.
825 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
826 !VD->hasAttr<CUDASharedAttr>() &&
827 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
828 !IsDependentVar(VD) &&
829 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
830 HasAllowedCUDADeviceStaticInitializer(*this, VD,
831 CICK_DeviceOrConstant))) {
832 VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
833 }
834}
835
837 unsigned DiagID) {
838 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
839 FunctionDecl *CurFunContext =
840 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
841 SemaDiagnosticBuilder::Kind DiagKind = [&] {
842 if (!CurFunContext)
843 return SemaDiagnosticBuilder::K_Nop;
844 switch (CurrentTarget()) {
847 return SemaDiagnosticBuilder::K_Immediate;
849 // An HD function counts as host code if we're compiling for host, and
850 // device code if we're compiling for device. Defer any errors in device
851 // mode until the function is known-emitted.
852 if (!getLangOpts().CUDAIsDevice)
853 return SemaDiagnosticBuilder::K_Nop;
855 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
856 return SemaDiagnosticBuilder::K_Immediate;
857 return (SemaRef.getEmissionStatus(CurFunContext) ==
859 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
860 : SemaDiagnosticBuilder::K_Deferred;
861 default:
862 return SemaDiagnosticBuilder::K_Nop;
863 }
864 }();
865 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
866}
867
869 unsigned DiagID) {
870 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
871 FunctionDecl *CurFunContext =
872 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
873 SemaDiagnosticBuilder::Kind DiagKind = [&] {
874 if (!CurFunContext)
875 return SemaDiagnosticBuilder::K_Nop;
876 switch (CurrentTarget()) {
878 return SemaDiagnosticBuilder::K_Immediate;
880 // An HD function counts as host code if we're compiling for host, and
881 // device code if we're compiling for device. Defer any errors in device
882 // mode until the function is known-emitted.
883 if (getLangOpts().CUDAIsDevice)
884 return SemaDiagnosticBuilder::K_Nop;
886 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
887 return SemaDiagnosticBuilder::K_Immediate;
888 return (SemaRef.getEmissionStatus(CurFunContext) ==
890 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
891 : SemaDiagnosticBuilder::K_Deferred;
892 default:
893 return SemaDiagnosticBuilder::K_Nop;
894 }
895 }();
896 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
897}
898
900 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
901 assert(Callee && "Callee may not be null.");
902
903 const auto &ExprEvalCtx = SemaRef.currentEvaluationContext();
904 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
905 return true;
906
907 // FIXME: Is bailing out early correct here? Should we instead assume that
908 // the caller is a global initializer?
909 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
910 if (!Caller)
911 return true;
912
913 // If the caller is known-emitted, mark the callee as known-emitted.
914 // Otherwise, mark the call in our call graph so we can traverse it later.
915 bool CallerKnownEmitted = SemaRef.getEmissionStatus(Caller) ==
917 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
918 CallerKnownEmitted] {
919 switch (IdentifyPreference(Caller, Callee)) {
920 case CFP_Never:
921 case CFP_WrongSide:
922 assert(Caller && "Never/wrongSide calls require a non-null caller");
923 // If we know the caller will be emitted, we know this wrong-side call
924 // will be emitted, so it's an immediate error. Otherwise, defer the
925 // error until we know the caller is emitted.
926 return CallerKnownEmitted
927 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
928 : SemaDiagnosticBuilder::K_Deferred;
929 default:
930 return SemaDiagnosticBuilder::K_Nop;
931 }
932 }();
933
934 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
935 // For -fgpu-rdc, keep track of external kernels used by host functions.
936 if (getLangOpts().CUDAIsDevice && getLangOpts().GPURelocatableDeviceCode &&
937 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined() &&
938 (!Caller || (!Caller->getDescribedFunctionTemplate() &&
942 return true;
943 }
944
945 // Avoid emitting this error twice for the same location. Using a hashtable
946 // like this is unfortunate, but because we must continue parsing as normal
947 // after encountering a deferred error, it's otherwise very tricky for us to
948 // ensure that we only emit this deferred error once.
949 if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
950 return true;
951
952 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller,
953 SemaRef)
954 << IdentifyTarget(Callee) << /*function*/ 0 << Callee
955 << IdentifyTarget(Caller);
956 if (!Callee->getBuiltinID())
957 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
958 diag::note_previous_decl, Caller, SemaRef)
959 << Callee;
960 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
961 DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
962}
963
964// Check the wrong-sided reference capture of lambda for CUDA/HIP.
965// A lambda function may capture a stack variable by reference when it is
966// defined and uses the capture by reference when the lambda is called. When
967// the capture and use happen on different sides, the capture is invalid and
968// should be diagnosed.
970 const sema::Capture &Capture) {
971 // In host compilation we only need to check lambda functions emitted on host
972 // side. In such lambda functions, a reference capture is invalid only
973 // if the lambda structure is populated by a device function or kernel then
974 // is passed to and called by a host function. However that is impossible,
975 // since a device function or kernel can only call a device function, also a
976 // kernel cannot pass a lambda back to a host function since we cannot
977 // define a kernel argument type which can hold the lambda before the lambda
978 // itself is defined.
979 if (!getLangOpts().CUDAIsDevice)
980 return;
981
982 // File-scope lambda can only do init captures for global variables, which
983 // results in passing by value for these global variables.
984 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
985 if (!Caller)
986 return;
987
988 // In device compilation, we only need to check lambda functions which are
989 // emitted on device side. For such lambdas, a reference capture is invalid
990 // only if the lambda structure is populated by a host function then passed
991 // to and called in a device function or kernel.
992 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
993 bool CallerIsHost =
994 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
995 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
996 if (!ShouldCheck || !Capture.isReferenceCapture())
997 return;
998 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
999 if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
1001 diag::err_capture_bad_target, Callee, SemaRef)
1002 << Capture.getVariable();
1003 } else if (Capture.isThisCapture()) {
1004 // Capture of this pointer is allowed since this pointer may be pointing to
1005 // managed memory which is accessible on both device and host sides. It only
1006 // results in invalid memory access if this pointer points to memory not
1007 // accessible on device side.
1009 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
1010 SemaRef);
1011 }
1012}
1013
1015 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1016 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
1017 return;
1018 Method->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
1019 Method->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
1020}
1021
1023 const LookupResult &Previous) {
1024 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1025 CUDAFunctionTarget NewTarget = IdentifyTarget(NewFD);
1026 for (NamedDecl *OldND : Previous) {
1027 FunctionDecl *OldFD = OldND->getAsFunction();
1028 if (!OldFD)
1029 continue;
1030
1031 CUDAFunctionTarget OldTarget = IdentifyTarget(OldFD);
1032 // Don't allow HD and global functions to overload other functions with the
1033 // same signature. We allow overloading based on CUDA attributes so that
1034 // functions can have different implementations on the host and device, but
1035 // HD/global functions "exist" in some sense on both the host and device, so
1036 // should have the same implementation on both sides.
1037 if (NewTarget != OldTarget &&
1038 !SemaRef.IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
1039 /* ConsiderCudaAttrs = */ false)) {
1040 if ((NewTarget == CUDAFunctionTarget::HostDevice &&
1041 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1043 OldTarget == CUDAFunctionTarget::Device)) ||
1044 (OldTarget == CUDAFunctionTarget::HostDevice &&
1045 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1047 NewTarget == CUDAFunctionTarget::Device)) ||
1048 (NewTarget == CUDAFunctionTarget::Global) ||
1049 (OldTarget == CUDAFunctionTarget::Global)) {
1050 Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
1051 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
1052 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1053 NewFD->setInvalidDecl();
1054 break;
1055 }
1056 if ((NewTarget == CUDAFunctionTarget::Host &&
1057 OldTarget == CUDAFunctionTarget::Device) ||
1058 (NewTarget == CUDAFunctionTarget::Device &&
1059 OldTarget == CUDAFunctionTarget::Host)) {
1060 Diag(NewFD->getLocation(), diag::warn_offload_incompatible_redeclare)
1061 << NewTarget << OldTarget;
1062 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1063 }
1064 }
1065 }
1066}
1067
1068template <typename AttrTy>
1070 const FunctionDecl &TemplateFD) {
1071 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
1072 AttrTy *Clone = Attribute->clone(S.Context);
1073 Clone->setInherited(true);
1074 FD->addAttr(Clone);
1075 }
1076}
1077
1079 const FunctionTemplateDecl &TD) {
1080 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
1081 copyAttrIfPresent<CUDAGlobalAttr>(SemaRef, FD, TemplateFD);
1082 copyAttrIfPresent<CUDAHostAttr>(SemaRef, FD, TemplateFD);
1083 copyAttrIfPresent<CUDADeviceAttr>(SemaRef, FD, TemplateFD);
1084}
1085
1087 if (getLangOpts().OffloadViaLLVM)
1088 return "__llvmPushCallConfiguration";
1089
1090 if (getLangOpts().HIP)
1091 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
1092 : "hipConfigureCall";
1093
1094 // New CUDA kernel launch sequence.
1095 if (CudaFeatureEnabled(getASTContext().getTargetInfo().getSDKVersion(),
1097 return "__cudaPushCallConfiguration";
1098
1099 // Legacy CUDA kernel configuration call
1100 return "cudaConfigureCall";
1101}
1102
1103// Record any local constexpr variables that are passed one way on the host
1104// and another on the device.
1106 MultiExprArg Arguments, OverloadCandidateSet &Candidates) {
1108 if (!LambdaInfo)
1109 return;
1110
1111 for (unsigned I = 0; I < Arguments.size(); ++I) {
1112 auto *DeclRef = dyn_cast<DeclRefExpr>(Arguments[I]);
1113 if (!DeclRef)
1114 continue;
1115 auto *Variable = dyn_cast<VarDecl>(DeclRef->getDecl());
1117 continue;
1118
1119 bool HostByValue = false, HostByRef = false;
1120 bool DeviceByValue = false, DeviceByRef = false;
1121
1122 for (OverloadCandidate &Candidate : Candidates) {
1123 FunctionDecl *Callee = Candidate.Function;
1124 if (!Callee || I >= Callee->getNumParams())
1125 continue;
1126
1130 continue;
1131
1132 bool CoversHost = (Target == CUDAFunctionTarget::Host ||
1134 bool CoversDevice = (Target == CUDAFunctionTarget::Device ||
1136
1137 bool IsRef = Callee->getParamDecl(I)->getType()->isReferenceType();
1138 HostByValue |= CoversHost && !IsRef;
1139 HostByRef |= CoversHost && IsRef;
1140 DeviceByValue |= CoversDevice && !IsRef;
1141 DeviceByRef |= CoversDevice && IsRef;
1142 }
1143
1144 if ((HostByValue && DeviceByRef) || (HostByRef && DeviceByValue))
1145 LambdaInfo->CUDAPotentialODRUsedVars.insert(Variable);
1146 }
1147}
Defines the clang::ASTContext interface.
const Decl * D
static bool hasImplicitAttr(const ValueDecl *D)
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Target Target
Definition: MachO.h:51
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:351
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition: SemaCUDA.cpp:109
static void copyAttrIfPresent(Sema &S, FunctionDecl *FD, const FunctionDecl &TemplateFD)
Definition: SemaCUDA.cpp:1069
static bool hasExplicitAttr(const VarDecl *D)
Definition: SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
VarDecl * Variable
Definition: SemaObjC.cpp:752
SourceLocation Loc
Definition: SemaObjC.cpp:754
StateNode * Previous
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.
Definition: ASTContext.h:1306
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1310
FunctionDecl * getcudaConfigureCallDecl()
Definition: ASTContext.h:1608
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:2879
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2125
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
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)
Definition: DeclBase.cpp:1022
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:3153
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:4142
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4130
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:4194
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2469
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3763
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.
Definition: DeclTemplate.h:952
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
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:8383
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
LangAS getAddressSpace() const
Definition: TypeBase.h:571
field_range fields() const
Definition: Decl.h:4508
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
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
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:669
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:723
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1086
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:757
ExprResult ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition: SemaCUDA.cpp:52
bool isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD)
Definition: SemaCUDA.cpp:523
bool isEmptyDestructor(SourceLocation Loc, CXXDestructorDecl *CD)
Definition: SemaCUDA.cpp:561
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1022
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:868
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:371
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:836
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:899
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1078
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:312
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:969
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:822
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:318
SemaCUDA(Sema &S)
Definition: SemaCUDA.cpp:29
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:1014
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:225
void recordPotentialODRUsedVariable(MultiExprArg Args, OverloadCandidateSet &CandidateSet)
Record variables that are potentially ODR-used in CUDA/HIP.
Definition: SemaCUDA.cpp:1105
@ 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:3468
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:9239
CXXMethodDecl * getMethod() const
Definition: Sema.h:9251
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition: Sema.h:1339
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6882
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1647
ASTContext & Context
Definition: Sema.h:1276
ASTContext & getASTContext() const
Definition: Sema.h:918
const LangOptions & getLangOpts() const
Definition: Sema.h:911
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6572
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2557
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition: Sema.h:4736
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20751
SourceManager & getSourceManager() const
Definition: Sema.h:916
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18397
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isUnion() const
Definition: Decl.h:3915
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:8604
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition: Type.cpp:5379
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition: Type.cpp:5388
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3393
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
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1252
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.
@ GVA_StrongExternal
Definition: Linkage.h:76
CUDAFunctionTarget
Definition: Cuda.h:60
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition: Cuda.cpp:155
ExprResult ExprError()
Definition: Ownership.h:265
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
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
CUDATargetContextKind Kind
Definition: SemaCUDA.h:139