17330f729Sjoerg //===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg /// \file
97330f729Sjoerg /// This file implements semantic analysis for CUDA constructs.
107330f729Sjoerg ///
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "clang/AST/ASTContext.h"
147330f729Sjoerg #include "clang/AST/Decl.h"
157330f729Sjoerg #include "clang/AST/ExprCXX.h"
167330f729Sjoerg #include "clang/Basic/Cuda.h"
17*e038c9c4Sjoerg #include "clang/Basic/TargetInfo.h"
187330f729Sjoerg #include "clang/Lex/Preprocessor.h"
197330f729Sjoerg #include "clang/Sema/Lookup.h"
20*e038c9c4Sjoerg #include "clang/Sema/ScopeInfo.h"
217330f729Sjoerg #include "clang/Sema/Sema.h"
227330f729Sjoerg #include "clang/Sema/SemaDiagnostic.h"
237330f729Sjoerg #include "clang/Sema/SemaInternal.h"
247330f729Sjoerg #include "clang/Sema/Template.h"
257330f729Sjoerg #include "llvm/ADT/Optional.h"
267330f729Sjoerg #include "llvm/ADT/SmallVector.h"
277330f729Sjoerg using namespace clang;
287330f729Sjoerg
hasExplicitAttr(const VarDecl * D)29*e038c9c4Sjoerg template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
30*e038c9c4Sjoerg if (!D)
31*e038c9c4Sjoerg return false;
32*e038c9c4Sjoerg if (auto *A = D->getAttr<AttrT>())
33*e038c9c4Sjoerg return !A->isImplicit();
34*e038c9c4Sjoerg return false;
35*e038c9c4Sjoerg }
36*e038c9c4Sjoerg
PushForceCUDAHostDevice()377330f729Sjoerg void Sema::PushForceCUDAHostDevice() {
387330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
397330f729Sjoerg ForceCUDAHostDeviceDepth++;
407330f729Sjoerg }
417330f729Sjoerg
PopForceCUDAHostDevice()427330f729Sjoerg bool Sema::PopForceCUDAHostDevice() {
437330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
447330f729Sjoerg if (ForceCUDAHostDeviceDepth == 0)
457330f729Sjoerg return false;
467330f729Sjoerg ForceCUDAHostDeviceDepth--;
477330f729Sjoerg return true;
487330f729Sjoerg }
497330f729Sjoerg
ActOnCUDAExecConfigExpr(Scope * S,SourceLocation LLLLoc,MultiExprArg ExecConfig,SourceLocation GGGLoc)507330f729Sjoerg ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
517330f729Sjoerg MultiExprArg ExecConfig,
527330f729Sjoerg SourceLocation GGGLoc) {
537330f729Sjoerg FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
547330f729Sjoerg if (!ConfigDecl)
557330f729Sjoerg return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
567330f729Sjoerg << getCudaConfigureFuncName());
577330f729Sjoerg QualType ConfigQTy = ConfigDecl->getType();
587330f729Sjoerg
597330f729Sjoerg DeclRefExpr *ConfigDR = new (Context)
607330f729Sjoerg DeclRefExpr(Context, ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
617330f729Sjoerg MarkFunctionReferenced(LLLLoc, ConfigDecl);
627330f729Sjoerg
637330f729Sjoerg return BuildCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
647330f729Sjoerg /*IsExecConfig=*/true);
657330f729Sjoerg }
667330f729Sjoerg
677330f729Sjoerg Sema::CUDAFunctionTarget
IdentifyCUDATarget(const ParsedAttributesView & Attrs)687330f729Sjoerg Sema::IdentifyCUDATarget(const ParsedAttributesView &Attrs) {
697330f729Sjoerg bool HasHostAttr = false;
707330f729Sjoerg bool HasDeviceAttr = false;
717330f729Sjoerg bool HasGlobalAttr = false;
727330f729Sjoerg bool HasInvalidTargetAttr = false;
737330f729Sjoerg for (const ParsedAttr &AL : Attrs) {
747330f729Sjoerg switch (AL.getKind()) {
757330f729Sjoerg case ParsedAttr::AT_CUDAGlobal:
767330f729Sjoerg HasGlobalAttr = true;
777330f729Sjoerg break;
787330f729Sjoerg case ParsedAttr::AT_CUDAHost:
797330f729Sjoerg HasHostAttr = true;
807330f729Sjoerg break;
817330f729Sjoerg case ParsedAttr::AT_CUDADevice:
827330f729Sjoerg HasDeviceAttr = true;
837330f729Sjoerg break;
847330f729Sjoerg case ParsedAttr::AT_CUDAInvalidTarget:
857330f729Sjoerg HasInvalidTargetAttr = true;
867330f729Sjoerg break;
877330f729Sjoerg default:
887330f729Sjoerg break;
897330f729Sjoerg }
907330f729Sjoerg }
917330f729Sjoerg
927330f729Sjoerg if (HasInvalidTargetAttr)
937330f729Sjoerg return CFT_InvalidTarget;
947330f729Sjoerg
957330f729Sjoerg if (HasGlobalAttr)
967330f729Sjoerg return CFT_Global;
977330f729Sjoerg
987330f729Sjoerg if (HasHostAttr && HasDeviceAttr)
997330f729Sjoerg return CFT_HostDevice;
1007330f729Sjoerg
1017330f729Sjoerg if (HasDeviceAttr)
1027330f729Sjoerg return CFT_Device;
1037330f729Sjoerg
1047330f729Sjoerg return CFT_Host;
1057330f729Sjoerg }
1067330f729Sjoerg
1077330f729Sjoerg template <typename A>
hasAttr(const FunctionDecl * D,bool IgnoreImplicitAttr)1087330f729Sjoerg static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr) {
1097330f729Sjoerg return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
1107330f729Sjoerg return isa<A>(Attribute) &&
1117330f729Sjoerg !(IgnoreImplicitAttr && Attribute->isImplicit());
1127330f729Sjoerg });
1137330f729Sjoerg }
1147330f729Sjoerg
1157330f729Sjoerg /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
IdentifyCUDATarget(const FunctionDecl * D,bool IgnoreImplicitHDAttr)1167330f729Sjoerg Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D,
1177330f729Sjoerg bool IgnoreImplicitHDAttr) {
1187330f729Sjoerg // Code that lives outside a function is run on the host.
1197330f729Sjoerg if (D == nullptr)
1207330f729Sjoerg return CFT_Host;
1217330f729Sjoerg
1227330f729Sjoerg if (D->hasAttr<CUDAInvalidTargetAttr>())
1237330f729Sjoerg return CFT_InvalidTarget;
1247330f729Sjoerg
1257330f729Sjoerg if (D->hasAttr<CUDAGlobalAttr>())
1267330f729Sjoerg return CFT_Global;
1277330f729Sjoerg
1287330f729Sjoerg if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
1297330f729Sjoerg if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
1307330f729Sjoerg return CFT_HostDevice;
1317330f729Sjoerg return CFT_Device;
1327330f729Sjoerg } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
1337330f729Sjoerg return CFT_Host;
134*e038c9c4Sjoerg } else if ((D->isImplicit() || !D->isUserProvided()) &&
135*e038c9c4Sjoerg !IgnoreImplicitHDAttr) {
1367330f729Sjoerg // Some implicit declarations (like intrinsic functions) are not marked.
1377330f729Sjoerg // Set the most lenient target on them for maximal flexibility.
1387330f729Sjoerg return CFT_HostDevice;
1397330f729Sjoerg }
1407330f729Sjoerg
1417330f729Sjoerg return CFT_Host;
1427330f729Sjoerg }
1437330f729Sjoerg
144*e038c9c4Sjoerg /// IdentifyTarget - Determine the CUDA compilation target for this variable.
IdentifyCUDATarget(const VarDecl * Var)145*e038c9c4Sjoerg Sema::CUDAVariableTarget Sema::IdentifyCUDATarget(const VarDecl *Var) {
146*e038c9c4Sjoerg if (Var->hasAttr<HIPManagedAttr>())
147*e038c9c4Sjoerg return CVT_Unified;
148*e038c9c4Sjoerg if (Var->isConstexpr() && !hasExplicitAttr<CUDAConstantAttr>(Var))
149*e038c9c4Sjoerg return CVT_Both;
150*e038c9c4Sjoerg if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
151*e038c9c4Sjoerg Var->hasAttr<CUDASharedAttr>() ||
152*e038c9c4Sjoerg Var->getType()->isCUDADeviceBuiltinSurfaceType() ||
153*e038c9c4Sjoerg Var->getType()->isCUDADeviceBuiltinTextureType())
154*e038c9c4Sjoerg return CVT_Device;
155*e038c9c4Sjoerg // Function-scope static variable without explicit device or constant
156*e038c9c4Sjoerg // attribute are emitted
157*e038c9c4Sjoerg // - on both sides in host device functions
158*e038c9c4Sjoerg // - on device side in device or global functions
159*e038c9c4Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) {
160*e038c9c4Sjoerg switch (IdentifyCUDATarget(FD)) {
161*e038c9c4Sjoerg case CFT_HostDevice:
162*e038c9c4Sjoerg return CVT_Both;
163*e038c9c4Sjoerg case CFT_Device:
164*e038c9c4Sjoerg case CFT_Global:
165*e038c9c4Sjoerg return CVT_Device;
166*e038c9c4Sjoerg default:
167*e038c9c4Sjoerg return CVT_Host;
168*e038c9c4Sjoerg }
169*e038c9c4Sjoerg }
170*e038c9c4Sjoerg return CVT_Host;
171*e038c9c4Sjoerg }
172*e038c9c4Sjoerg
1737330f729Sjoerg // * CUDA Call preference table
1747330f729Sjoerg //
1757330f729Sjoerg // F - from,
1767330f729Sjoerg // T - to
1777330f729Sjoerg // Ph - preference in host mode
1787330f729Sjoerg // Pd - preference in device mode
1797330f729Sjoerg // H - handled in (x)
1807330f729Sjoerg // Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
1817330f729Sjoerg //
1827330f729Sjoerg // | F | T | Ph | Pd | H |
1837330f729Sjoerg // |----+----+-----+-----+-----+
1847330f729Sjoerg // | d | d | N | N | (c) |
1857330f729Sjoerg // | d | g | -- | -- | (a) |
1867330f729Sjoerg // | d | h | -- | -- | (e) |
1877330f729Sjoerg // | d | hd | HD | HD | (b) |
1887330f729Sjoerg // | g | d | N | N | (c) |
1897330f729Sjoerg // | g | g | -- | -- | (a) |
1907330f729Sjoerg // | g | h | -- | -- | (e) |
1917330f729Sjoerg // | g | hd | HD | HD | (b) |
1927330f729Sjoerg // | h | d | -- | -- | (e) |
1937330f729Sjoerg // | h | g | N | N | (c) |
1947330f729Sjoerg // | h | h | N | N | (c) |
1957330f729Sjoerg // | h | hd | HD | HD | (b) |
1967330f729Sjoerg // | hd | d | WS | SS | (d) |
1977330f729Sjoerg // | hd | g | SS | -- |(d/a)|
1987330f729Sjoerg // | hd | h | SS | WS | (d) |
1997330f729Sjoerg // | hd | hd | HD | HD | (b) |
2007330f729Sjoerg
2017330f729Sjoerg Sema::CUDAFunctionPreference
IdentifyCUDAPreference(const FunctionDecl * Caller,const FunctionDecl * Callee)2027330f729Sjoerg Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
2037330f729Sjoerg const FunctionDecl *Callee) {
2047330f729Sjoerg assert(Callee && "Callee must be valid.");
2057330f729Sjoerg CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
2067330f729Sjoerg CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
2077330f729Sjoerg
2087330f729Sjoerg // If one of the targets is invalid, the check always fails, no matter what
2097330f729Sjoerg // the other target is.
2107330f729Sjoerg if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
2117330f729Sjoerg return CFP_Never;
2127330f729Sjoerg
2137330f729Sjoerg // (a) Can't call global from some contexts until we support CUDA's
2147330f729Sjoerg // dynamic parallelism.
2157330f729Sjoerg if (CalleeTarget == CFT_Global &&
2167330f729Sjoerg (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
2177330f729Sjoerg return CFP_Never;
2187330f729Sjoerg
2197330f729Sjoerg // (b) Calling HostDevice is OK for everyone.
2207330f729Sjoerg if (CalleeTarget == CFT_HostDevice)
2217330f729Sjoerg return CFP_HostDevice;
2227330f729Sjoerg
2237330f729Sjoerg // (c) Best case scenarios
2247330f729Sjoerg if (CalleeTarget == CallerTarget ||
2257330f729Sjoerg (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
2267330f729Sjoerg (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
2277330f729Sjoerg return CFP_Native;
2287330f729Sjoerg
2297330f729Sjoerg // (d) HostDevice behavior depends on compilation mode.
2307330f729Sjoerg if (CallerTarget == CFT_HostDevice) {
2317330f729Sjoerg // It's OK to call a compilation-mode matching function from an HD one.
2327330f729Sjoerg if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
2337330f729Sjoerg (!getLangOpts().CUDAIsDevice &&
2347330f729Sjoerg (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
2357330f729Sjoerg return CFP_SameSide;
2367330f729Sjoerg
2377330f729Sjoerg // Calls from HD to non-mode-matching functions (i.e., to host functions
2387330f729Sjoerg // when compiling in device mode or to device functions when compiling in
2397330f729Sjoerg // host mode) are allowed at the sema level, but eventually rejected if
2407330f729Sjoerg // they're ever codegened. TODO: Reject said calls earlier.
2417330f729Sjoerg return CFP_WrongSide;
2427330f729Sjoerg }
2437330f729Sjoerg
2447330f729Sjoerg // (e) Calling across device/host boundary is not something you should do.
2457330f729Sjoerg if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
2467330f729Sjoerg (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
2477330f729Sjoerg (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
2487330f729Sjoerg return CFP_Never;
2497330f729Sjoerg
2507330f729Sjoerg llvm_unreachable("All cases should've been handled by now.");
2517330f729Sjoerg }
2527330f729Sjoerg
hasImplicitAttr(const FunctionDecl * D)253*e038c9c4Sjoerg template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
254*e038c9c4Sjoerg if (!D)
255*e038c9c4Sjoerg return false;
256*e038c9c4Sjoerg if (auto *A = D->getAttr<AttrT>())
257*e038c9c4Sjoerg return A->isImplicit();
258*e038c9c4Sjoerg return D->isImplicit();
259*e038c9c4Sjoerg }
260*e038c9c4Sjoerg
isCUDAImplicitHostDeviceFunction(const FunctionDecl * D)261*e038c9c4Sjoerg bool Sema::isCUDAImplicitHostDeviceFunction(const FunctionDecl *D) {
262*e038c9c4Sjoerg bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
263*e038c9c4Sjoerg bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
264*e038c9c4Sjoerg return IsImplicitDevAttr && IsImplicitHostAttr;
265*e038c9c4Sjoerg }
266*e038c9c4Sjoerg
EraseUnwantedCUDAMatches(const FunctionDecl * Caller,SmallVectorImpl<std::pair<DeclAccessPair,FunctionDecl * >> & Matches)2677330f729Sjoerg void Sema::EraseUnwantedCUDAMatches(
2687330f729Sjoerg const FunctionDecl *Caller,
2697330f729Sjoerg SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
2707330f729Sjoerg if (Matches.size() <= 1)
2717330f729Sjoerg return;
2727330f729Sjoerg
2737330f729Sjoerg using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
2747330f729Sjoerg
2757330f729Sjoerg // Gets the CUDA function preference for a call from Caller to Match.
2767330f729Sjoerg auto GetCFP = [&](const Pair &Match) {
2777330f729Sjoerg return IdentifyCUDAPreference(Caller, Match.second);
2787330f729Sjoerg };
2797330f729Sjoerg
2807330f729Sjoerg // Find the best call preference among the functions in Matches.
2817330f729Sjoerg CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
2827330f729Sjoerg Matches.begin(), Matches.end(),
2837330f729Sjoerg [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
2847330f729Sjoerg
2857330f729Sjoerg // Erase all functions with lower priority.
2867330f729Sjoerg llvm::erase_if(Matches,
2877330f729Sjoerg [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
2887330f729Sjoerg }
2897330f729Sjoerg
2907330f729Sjoerg /// When an implicitly-declared special member has to invoke more than one
2917330f729Sjoerg /// base/field special member, conflicts may occur in the targets of these
2927330f729Sjoerg /// members. For example, if one base's member __host__ and another's is
2937330f729Sjoerg /// __device__, it's a conflict.
2947330f729Sjoerg /// This function figures out if the given targets \param Target1 and
2957330f729Sjoerg /// \param Target2 conflict, and if they do not it fills in
2967330f729Sjoerg /// \param ResolvedTarget with a target that resolves for both calls.
2977330f729Sjoerg /// \return true if there's a conflict, false otherwise.
2987330f729Sjoerg static bool
resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,Sema::CUDAFunctionTarget Target2,Sema::CUDAFunctionTarget * ResolvedTarget)2997330f729Sjoerg resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
3007330f729Sjoerg Sema::CUDAFunctionTarget Target2,
3017330f729Sjoerg Sema::CUDAFunctionTarget *ResolvedTarget) {
3027330f729Sjoerg // Only free functions and static member functions may be global.
3037330f729Sjoerg assert(Target1 != Sema::CFT_Global);
3047330f729Sjoerg assert(Target2 != Sema::CFT_Global);
3057330f729Sjoerg
3067330f729Sjoerg if (Target1 == Sema::CFT_HostDevice) {
3077330f729Sjoerg *ResolvedTarget = Target2;
3087330f729Sjoerg } else if (Target2 == Sema::CFT_HostDevice) {
3097330f729Sjoerg *ResolvedTarget = Target1;
3107330f729Sjoerg } else if (Target1 != Target2) {
3117330f729Sjoerg return true;
3127330f729Sjoerg } else {
3137330f729Sjoerg *ResolvedTarget = Target1;
3147330f729Sjoerg }
3157330f729Sjoerg
3167330f729Sjoerg return false;
3177330f729Sjoerg }
3187330f729Sjoerg
inferCUDATargetForImplicitSpecialMember(CXXRecordDecl * ClassDecl,CXXSpecialMember CSM,CXXMethodDecl * MemberDecl,bool ConstRHS,bool Diagnose)3197330f729Sjoerg bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
3207330f729Sjoerg CXXSpecialMember CSM,
3217330f729Sjoerg CXXMethodDecl *MemberDecl,
3227330f729Sjoerg bool ConstRHS,
3237330f729Sjoerg bool Diagnose) {
3247330f729Sjoerg // If the defaulted special member is defined lexically outside of its
3257330f729Sjoerg // owning class, or the special member already has explicit device or host
3267330f729Sjoerg // attributes, do not infer.
3277330f729Sjoerg bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
3287330f729Sjoerg bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
3297330f729Sjoerg bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
3307330f729Sjoerg bool HasExplicitAttr =
3317330f729Sjoerg (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
3327330f729Sjoerg (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
3337330f729Sjoerg if (!InClass || HasExplicitAttr)
3347330f729Sjoerg return false;
3357330f729Sjoerg
3367330f729Sjoerg llvm::Optional<CUDAFunctionTarget> InferredTarget;
3377330f729Sjoerg
3387330f729Sjoerg // We're going to invoke special member lookup; mark that these special
3397330f729Sjoerg // members are called from this one, and not from its caller.
3407330f729Sjoerg ContextRAII MethodContext(*this, MemberDecl);
3417330f729Sjoerg
3427330f729Sjoerg // Look for special members in base classes that should be invoked from here.
3437330f729Sjoerg // Infer the target of this member base on the ones it should call.
3447330f729Sjoerg // Skip direct and indirect virtual bases for abstract classes.
3457330f729Sjoerg llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
3467330f729Sjoerg for (const auto &B : ClassDecl->bases()) {
3477330f729Sjoerg if (!B.isVirtual()) {
3487330f729Sjoerg Bases.push_back(&B);
3497330f729Sjoerg }
3507330f729Sjoerg }
3517330f729Sjoerg
3527330f729Sjoerg if (!ClassDecl->isAbstract()) {
3537330f729Sjoerg for (const auto &VB : ClassDecl->vbases()) {
3547330f729Sjoerg Bases.push_back(&VB);
3557330f729Sjoerg }
3567330f729Sjoerg }
3577330f729Sjoerg
3587330f729Sjoerg for (const auto *B : Bases) {
3597330f729Sjoerg const RecordType *BaseType = B->getType()->getAs<RecordType>();
3607330f729Sjoerg if (!BaseType) {
3617330f729Sjoerg continue;
3627330f729Sjoerg }
3637330f729Sjoerg
3647330f729Sjoerg CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3657330f729Sjoerg Sema::SpecialMemberOverloadResult SMOR =
3667330f729Sjoerg LookupSpecialMember(BaseClassDecl, CSM,
3677330f729Sjoerg /* ConstArg */ ConstRHS,
3687330f729Sjoerg /* VolatileArg */ false,
3697330f729Sjoerg /* RValueThis */ false,
3707330f729Sjoerg /* ConstThis */ false,
3717330f729Sjoerg /* VolatileThis */ false);
3727330f729Sjoerg
3737330f729Sjoerg if (!SMOR.getMethod())
3747330f729Sjoerg continue;
3757330f729Sjoerg
3767330f729Sjoerg CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
3777330f729Sjoerg if (!InferredTarget.hasValue()) {
3787330f729Sjoerg InferredTarget = BaseMethodTarget;
3797330f729Sjoerg } else {
3807330f729Sjoerg bool ResolutionError = resolveCalleeCUDATargetConflict(
3817330f729Sjoerg InferredTarget.getValue(), BaseMethodTarget,
3827330f729Sjoerg InferredTarget.getPointer());
3837330f729Sjoerg if (ResolutionError) {
3847330f729Sjoerg if (Diagnose) {
3857330f729Sjoerg Diag(ClassDecl->getLocation(),
3867330f729Sjoerg diag::note_implicit_member_target_infer_collision)
3877330f729Sjoerg << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
3887330f729Sjoerg }
3897330f729Sjoerg MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
3907330f729Sjoerg return true;
3917330f729Sjoerg }
3927330f729Sjoerg }
3937330f729Sjoerg }
3947330f729Sjoerg
3957330f729Sjoerg // Same as for bases, but now for special members of fields.
3967330f729Sjoerg for (const auto *F : ClassDecl->fields()) {
3977330f729Sjoerg if (F->isInvalidDecl()) {
3987330f729Sjoerg continue;
3997330f729Sjoerg }
4007330f729Sjoerg
4017330f729Sjoerg const RecordType *FieldType =
4027330f729Sjoerg Context.getBaseElementType(F->getType())->getAs<RecordType>();
4037330f729Sjoerg if (!FieldType) {
4047330f729Sjoerg continue;
4057330f729Sjoerg }
4067330f729Sjoerg
4077330f729Sjoerg CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
4087330f729Sjoerg Sema::SpecialMemberOverloadResult SMOR =
4097330f729Sjoerg LookupSpecialMember(FieldRecDecl, CSM,
4107330f729Sjoerg /* ConstArg */ ConstRHS && !F->isMutable(),
4117330f729Sjoerg /* VolatileArg */ false,
4127330f729Sjoerg /* RValueThis */ false,
4137330f729Sjoerg /* ConstThis */ false,
4147330f729Sjoerg /* VolatileThis */ false);
4157330f729Sjoerg
4167330f729Sjoerg if (!SMOR.getMethod())
4177330f729Sjoerg continue;
4187330f729Sjoerg
4197330f729Sjoerg CUDAFunctionTarget FieldMethodTarget =
4207330f729Sjoerg IdentifyCUDATarget(SMOR.getMethod());
4217330f729Sjoerg if (!InferredTarget.hasValue()) {
4227330f729Sjoerg InferredTarget = FieldMethodTarget;
4237330f729Sjoerg } else {
4247330f729Sjoerg bool ResolutionError = resolveCalleeCUDATargetConflict(
4257330f729Sjoerg InferredTarget.getValue(), FieldMethodTarget,
4267330f729Sjoerg InferredTarget.getPointer());
4277330f729Sjoerg if (ResolutionError) {
4287330f729Sjoerg if (Diagnose) {
4297330f729Sjoerg Diag(ClassDecl->getLocation(),
4307330f729Sjoerg diag::note_implicit_member_target_infer_collision)
4317330f729Sjoerg << (unsigned)CSM << InferredTarget.getValue()
4327330f729Sjoerg << FieldMethodTarget;
4337330f729Sjoerg }
4347330f729Sjoerg MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
4357330f729Sjoerg return true;
4367330f729Sjoerg }
4377330f729Sjoerg }
4387330f729Sjoerg }
4397330f729Sjoerg
4407330f729Sjoerg
4417330f729Sjoerg // If no target was inferred, mark this member as __host__ __device__;
4427330f729Sjoerg // it's the least restrictive option that can be invoked from any target.
4437330f729Sjoerg bool NeedsH = true, NeedsD = true;
4447330f729Sjoerg if (InferredTarget.hasValue()) {
4457330f729Sjoerg if (InferredTarget.getValue() == CFT_Device)
4467330f729Sjoerg NeedsH = false;
4477330f729Sjoerg else if (InferredTarget.getValue() == CFT_Host)
4487330f729Sjoerg NeedsD = false;
4497330f729Sjoerg }
4507330f729Sjoerg
4517330f729Sjoerg // We either setting attributes first time, or the inferred ones must match
4527330f729Sjoerg // previously set ones.
4537330f729Sjoerg if (NeedsD && !HasD)
4547330f729Sjoerg MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
4557330f729Sjoerg if (NeedsH && !HasH)
4567330f729Sjoerg MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
4577330f729Sjoerg
4587330f729Sjoerg return false;
4597330f729Sjoerg }
4607330f729Sjoerg
isEmptyCudaConstructor(SourceLocation Loc,CXXConstructorDecl * CD)4617330f729Sjoerg bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
4627330f729Sjoerg if (!CD->isDefined() && CD->isTemplateInstantiation())
4637330f729Sjoerg InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
4647330f729Sjoerg
4657330f729Sjoerg // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
4667330f729Sjoerg // empty at a point in the translation unit, if it is either a
4677330f729Sjoerg // trivial constructor
4687330f729Sjoerg if (CD->isTrivial())
4697330f729Sjoerg return true;
4707330f729Sjoerg
4717330f729Sjoerg // ... or it satisfies all of the following conditions:
4727330f729Sjoerg // The constructor function has been defined.
4737330f729Sjoerg // The constructor function has no parameters,
4747330f729Sjoerg // and the function body is an empty compound statement.
4757330f729Sjoerg if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
4767330f729Sjoerg return false;
4777330f729Sjoerg
4787330f729Sjoerg // Its class has no virtual functions and no virtual base classes.
4797330f729Sjoerg if (CD->getParent()->isDynamicClass())
4807330f729Sjoerg return false;
4817330f729Sjoerg
482*e038c9c4Sjoerg // Union ctor does not call ctors of its data members.
483*e038c9c4Sjoerg if (CD->getParent()->isUnion())
484*e038c9c4Sjoerg return true;
485*e038c9c4Sjoerg
4867330f729Sjoerg // The only form of initializer allowed is an empty constructor.
4877330f729Sjoerg // This will recursively check all base classes and member initializers
4887330f729Sjoerg if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
4897330f729Sjoerg if (const CXXConstructExpr *CE =
4907330f729Sjoerg dyn_cast<CXXConstructExpr>(CI->getInit()))
4917330f729Sjoerg return isEmptyCudaConstructor(Loc, CE->getConstructor());
4927330f729Sjoerg return false;
4937330f729Sjoerg }))
4947330f729Sjoerg return false;
4957330f729Sjoerg
4967330f729Sjoerg return true;
4977330f729Sjoerg }
4987330f729Sjoerg
isEmptyCudaDestructor(SourceLocation Loc,CXXDestructorDecl * DD)4997330f729Sjoerg bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
5007330f729Sjoerg // No destructor -> no problem.
5017330f729Sjoerg if (!DD)
5027330f729Sjoerg return true;
5037330f729Sjoerg
5047330f729Sjoerg if (!DD->isDefined() && DD->isTemplateInstantiation())
5057330f729Sjoerg InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
5067330f729Sjoerg
5077330f729Sjoerg // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
5087330f729Sjoerg // empty at a point in the translation unit, if it is either a
5097330f729Sjoerg // trivial constructor
5107330f729Sjoerg if (DD->isTrivial())
5117330f729Sjoerg return true;
5127330f729Sjoerg
5137330f729Sjoerg // ... or it satisfies all of the following conditions:
5147330f729Sjoerg // The destructor function has been defined.
5157330f729Sjoerg // and the function body is an empty compound statement.
5167330f729Sjoerg if (!DD->hasTrivialBody())
5177330f729Sjoerg return false;
5187330f729Sjoerg
5197330f729Sjoerg const CXXRecordDecl *ClassDecl = DD->getParent();
5207330f729Sjoerg
5217330f729Sjoerg // Its class has no virtual functions and no virtual base classes.
5227330f729Sjoerg if (ClassDecl->isDynamicClass())
5237330f729Sjoerg return false;
5247330f729Sjoerg
525*e038c9c4Sjoerg // Union does not have base class and union dtor does not call dtors of its
526*e038c9c4Sjoerg // data members.
527*e038c9c4Sjoerg if (DD->getParent()->isUnion())
528*e038c9c4Sjoerg return true;
529*e038c9c4Sjoerg
5307330f729Sjoerg // Only empty destructors are allowed. This will recursively check
5317330f729Sjoerg // destructors for all base classes...
5327330f729Sjoerg if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
5337330f729Sjoerg if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
5347330f729Sjoerg return isEmptyCudaDestructor(Loc, RD->getDestructor());
5357330f729Sjoerg return true;
5367330f729Sjoerg }))
5377330f729Sjoerg return false;
5387330f729Sjoerg
5397330f729Sjoerg // ... and member fields.
5407330f729Sjoerg if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
5417330f729Sjoerg if (CXXRecordDecl *RD = Field->getType()
5427330f729Sjoerg ->getBaseElementTypeUnsafe()
5437330f729Sjoerg ->getAsCXXRecordDecl())
5447330f729Sjoerg return isEmptyCudaDestructor(Loc, RD->getDestructor());
5457330f729Sjoerg return true;
5467330f729Sjoerg }))
5477330f729Sjoerg return false;
5487330f729Sjoerg
5497330f729Sjoerg return true;
5507330f729Sjoerg }
5517330f729Sjoerg
checkAllowedCUDAInitializer(VarDecl * VD)5527330f729Sjoerg void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
5537330f729Sjoerg if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage())
5547330f729Sjoerg return;
5557330f729Sjoerg const Expr *Init = VD->getInit();
5567330f729Sjoerg if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
5577330f729Sjoerg VD->hasAttr<CUDASharedAttr>()) {
5587330f729Sjoerg if (LangOpts.GPUAllowDeviceInit)
5597330f729Sjoerg return;
5607330f729Sjoerg bool AllowedInit = false;
5617330f729Sjoerg if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
5627330f729Sjoerg AllowedInit =
5637330f729Sjoerg isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
5647330f729Sjoerg // We'll allow constant initializers even if it's a non-empty
5657330f729Sjoerg // constructor according to CUDA rules. This deviates from NVCC,
5667330f729Sjoerg // but allows us to handle things like constexpr constructors.
5677330f729Sjoerg if (!AllowedInit &&
568*e038c9c4Sjoerg (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) {
569*e038c9c4Sjoerg auto *Init = VD->getInit();
570*e038c9c4Sjoerg // isConstantInitializer cannot be called with dependent value, therefore
571*e038c9c4Sjoerg // we skip checking dependent value here. This is OK since
572*e038c9c4Sjoerg // checkAllowedCUDAInitializer is called again when the template is
573*e038c9c4Sjoerg // instantiated.
574*e038c9c4Sjoerg AllowedInit =
575*e038c9c4Sjoerg VD->getType()->isDependentType() || Init->isValueDependent() ||
576*e038c9c4Sjoerg Init->isConstantInitializer(Context,
577*e038c9c4Sjoerg VD->getType()->isReferenceType());
578*e038c9c4Sjoerg }
5797330f729Sjoerg
5807330f729Sjoerg // Also make sure that destructor, if there is one, is empty.
5817330f729Sjoerg if (AllowedInit)
5827330f729Sjoerg if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
5837330f729Sjoerg AllowedInit =
5847330f729Sjoerg isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
5857330f729Sjoerg
5867330f729Sjoerg if (!AllowedInit) {
5877330f729Sjoerg Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
5887330f729Sjoerg ? diag::err_shared_var_init
5897330f729Sjoerg : diag::err_dynamic_var_init)
5907330f729Sjoerg << Init->getSourceRange();
5917330f729Sjoerg VD->setInvalidDecl();
5927330f729Sjoerg }
5937330f729Sjoerg } else {
5947330f729Sjoerg // This is a host-side global variable. Check that the initializer is
5957330f729Sjoerg // callable from the host side.
5967330f729Sjoerg const FunctionDecl *InitFn = nullptr;
5977330f729Sjoerg if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
5987330f729Sjoerg InitFn = CE->getConstructor();
5997330f729Sjoerg } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
6007330f729Sjoerg InitFn = CE->getDirectCallee();
6017330f729Sjoerg }
6027330f729Sjoerg if (InitFn) {
6037330f729Sjoerg CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
6047330f729Sjoerg if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
6057330f729Sjoerg Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
6067330f729Sjoerg << InitFnTarget << InitFn;
6077330f729Sjoerg Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
6087330f729Sjoerg VD->setInvalidDecl();
6097330f729Sjoerg }
6107330f729Sjoerg }
6117330f729Sjoerg }
6127330f729Sjoerg }
6137330f729Sjoerg
6147330f729Sjoerg // With -fcuda-host-device-constexpr, an unattributed constexpr function is
6157330f729Sjoerg // treated as implicitly __host__ __device__, unless:
6167330f729Sjoerg // * it is a variadic function (device-side variadic functions are not
6177330f729Sjoerg // allowed), or
6187330f729Sjoerg // * a __device__ function with this signature was already declared, in which
6197330f729Sjoerg // case in which case we output an error, unless the __device__ decl is in a
6207330f729Sjoerg // system header, in which case we leave the constexpr function unattributed.
6217330f729Sjoerg //
6227330f729Sjoerg // In addition, all function decls are treated as __host__ __device__ when
6237330f729Sjoerg // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
6247330f729Sjoerg // #pragma clang force_cuda_host_device_begin/end
6257330f729Sjoerg // pair).
maybeAddCUDAHostDeviceAttrs(FunctionDecl * NewD,const LookupResult & Previous)6267330f729Sjoerg void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
6277330f729Sjoerg const LookupResult &Previous) {
6287330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
6297330f729Sjoerg
6307330f729Sjoerg if (ForceCUDAHostDeviceDepth > 0) {
6317330f729Sjoerg if (!NewD->hasAttr<CUDAHostAttr>())
6327330f729Sjoerg NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
6337330f729Sjoerg if (!NewD->hasAttr<CUDADeviceAttr>())
6347330f729Sjoerg NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6357330f729Sjoerg return;
6367330f729Sjoerg }
6377330f729Sjoerg
6387330f729Sjoerg if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
6397330f729Sjoerg NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
6407330f729Sjoerg NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
6417330f729Sjoerg return;
6427330f729Sjoerg
6437330f729Sjoerg // Is D a __device__ function with the same signature as NewD, ignoring CUDA
6447330f729Sjoerg // attributes?
6457330f729Sjoerg auto IsMatchingDeviceFn = [&](NamedDecl *D) {
6467330f729Sjoerg if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
6477330f729Sjoerg D = Using->getTargetDecl();
6487330f729Sjoerg FunctionDecl *OldD = D->getAsFunction();
6497330f729Sjoerg return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
6507330f729Sjoerg !OldD->hasAttr<CUDAHostAttr>() &&
6517330f729Sjoerg !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
6527330f729Sjoerg /* ConsiderCudaAttrs = */ false);
6537330f729Sjoerg };
6547330f729Sjoerg auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
6557330f729Sjoerg if (It != Previous.end()) {
6567330f729Sjoerg // We found a __device__ function with the same name and signature as NewD
6577330f729Sjoerg // (ignoring CUDA attrs). This is an error unless that function is defined
6587330f729Sjoerg // in a system header, in which case we simply return without making NewD
6597330f729Sjoerg // host+device.
6607330f729Sjoerg NamedDecl *Match = *It;
6617330f729Sjoerg if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
6627330f729Sjoerg Diag(NewD->getLocation(),
6637330f729Sjoerg diag::err_cuda_unattributed_constexpr_cannot_overload_device)
6647330f729Sjoerg << NewD;
6657330f729Sjoerg Diag(Match->getLocation(),
6667330f729Sjoerg diag::note_cuda_conflicting_device_function_declared_here);
6677330f729Sjoerg }
6687330f729Sjoerg return;
6697330f729Sjoerg }
6707330f729Sjoerg
6717330f729Sjoerg NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
6727330f729Sjoerg NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6737330f729Sjoerg }
6747330f729Sjoerg
MaybeAddCUDAConstantAttr(VarDecl * VD)675*e038c9c4Sjoerg void Sema::MaybeAddCUDAConstantAttr(VarDecl *VD) {
676*e038c9c4Sjoerg if (getLangOpts().CUDAIsDevice && VD->isConstexpr() &&
677*e038c9c4Sjoerg (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
678*e038c9c4Sjoerg !VD->hasAttr<CUDAConstantAttr>()) {
679*e038c9c4Sjoerg VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
680*e038c9c4Sjoerg }
681*e038c9c4Sjoerg }
682*e038c9c4Sjoerg
CUDADiagIfDeviceCode(SourceLocation Loc,unsigned DiagID)683*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
6847330f729Sjoerg unsigned DiagID) {
6857330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
686*e038c9c4Sjoerg SemaDiagnosticBuilder::Kind DiagKind = [&] {
687*e038c9c4Sjoerg if (!isa<FunctionDecl>(CurContext))
688*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
6897330f729Sjoerg switch (CurrentCUDATarget()) {
6907330f729Sjoerg case CFT_Global:
6917330f729Sjoerg case CFT_Device:
692*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Immediate;
6937330f729Sjoerg case CFT_HostDevice:
6947330f729Sjoerg // An HD function counts as host code if we're compiling for host, and
6957330f729Sjoerg // device code if we're compiling for device. Defer any errors in device
6967330f729Sjoerg // mode until the function is known-emitted.
697*e038c9c4Sjoerg if (!getLangOpts().CUDAIsDevice)
698*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
699*e038c9c4Sjoerg if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
700*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Immediate;
7017330f729Sjoerg return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
7027330f729Sjoerg FunctionEmissionStatus::Emitted)
703*e038c9c4Sjoerg ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
704*e038c9c4Sjoerg : SemaDiagnosticBuilder::K_Deferred;
7057330f729Sjoerg default:
706*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
7077330f729Sjoerg }
7087330f729Sjoerg }();
709*e038c9c4Sjoerg return SemaDiagnosticBuilder(DiagKind, Loc, DiagID,
7107330f729Sjoerg dyn_cast<FunctionDecl>(CurContext), *this);
7117330f729Sjoerg }
7127330f729Sjoerg
CUDADiagIfHostCode(SourceLocation Loc,unsigned DiagID)713*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
7147330f729Sjoerg unsigned DiagID) {
7157330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
716*e038c9c4Sjoerg SemaDiagnosticBuilder::Kind DiagKind = [&] {
717*e038c9c4Sjoerg if (!isa<FunctionDecl>(CurContext))
718*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
7197330f729Sjoerg switch (CurrentCUDATarget()) {
7207330f729Sjoerg case CFT_Host:
721*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Immediate;
7227330f729Sjoerg case CFT_HostDevice:
7237330f729Sjoerg // An HD function counts as host code if we're compiling for host, and
7247330f729Sjoerg // device code if we're compiling for device. Defer any errors in device
7257330f729Sjoerg // mode until the function is known-emitted.
7267330f729Sjoerg if (getLangOpts().CUDAIsDevice)
727*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
728*e038c9c4Sjoerg if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
729*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Immediate;
7307330f729Sjoerg return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
7317330f729Sjoerg FunctionEmissionStatus::Emitted)
732*e038c9c4Sjoerg ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
733*e038c9c4Sjoerg : SemaDiagnosticBuilder::K_Deferred;
7347330f729Sjoerg default:
735*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
7367330f729Sjoerg }
7377330f729Sjoerg }();
738*e038c9c4Sjoerg return SemaDiagnosticBuilder(DiagKind, Loc, DiagID,
7397330f729Sjoerg dyn_cast<FunctionDecl>(CurContext), *this);
7407330f729Sjoerg }
7417330f729Sjoerg
CheckCUDACall(SourceLocation Loc,FunctionDecl * Callee)7427330f729Sjoerg bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
7437330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
7447330f729Sjoerg assert(Callee && "Callee may not be null.");
7457330f729Sjoerg
7467330f729Sjoerg auto &ExprEvalCtx = ExprEvalContexts.back();
7477330f729Sjoerg if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
7487330f729Sjoerg return true;
7497330f729Sjoerg
7507330f729Sjoerg // FIXME: Is bailing out early correct here? Should we instead assume that
7517330f729Sjoerg // the caller is a global initializer?
7527330f729Sjoerg FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
7537330f729Sjoerg if (!Caller)
7547330f729Sjoerg return true;
7557330f729Sjoerg
7567330f729Sjoerg // If the caller is known-emitted, mark the callee as known-emitted.
7577330f729Sjoerg // Otherwise, mark the call in our call graph so we can traverse it later.
7587330f729Sjoerg bool CallerKnownEmitted =
7597330f729Sjoerg getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted;
760*e038c9c4Sjoerg SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
7617330f729Sjoerg CallerKnownEmitted] {
7627330f729Sjoerg switch (IdentifyCUDAPreference(Caller, Callee)) {
7637330f729Sjoerg case CFP_Never:
7647330f729Sjoerg case CFP_WrongSide:
765*e038c9c4Sjoerg assert(Caller && "Never/wrongSide calls require a non-null caller");
7667330f729Sjoerg // If we know the caller will be emitted, we know this wrong-side call
7677330f729Sjoerg // will be emitted, so it's an immediate error. Otherwise, defer the
7687330f729Sjoerg // error until we know the caller is emitted.
769*e038c9c4Sjoerg return CallerKnownEmitted
770*e038c9c4Sjoerg ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
771*e038c9c4Sjoerg : SemaDiagnosticBuilder::K_Deferred;
7727330f729Sjoerg default:
773*e038c9c4Sjoerg return SemaDiagnosticBuilder::K_Nop;
7747330f729Sjoerg }
7757330f729Sjoerg }();
7767330f729Sjoerg
777*e038c9c4Sjoerg if (DiagKind == SemaDiagnosticBuilder::K_Nop)
7787330f729Sjoerg return true;
7797330f729Sjoerg
7807330f729Sjoerg // Avoid emitting this error twice for the same location. Using a hashtable
7817330f729Sjoerg // like this is unfortunate, but because we must continue parsing as normal
7827330f729Sjoerg // after encountering a deferred error, it's otherwise very tricky for us to
7837330f729Sjoerg // ensure that we only emit this deferred error once.
7847330f729Sjoerg if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
7857330f729Sjoerg return true;
7867330f729Sjoerg
787*e038c9c4Sjoerg SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
788*e038c9c4Sjoerg << IdentifyCUDATarget(Callee) << /*function*/ 0 << Callee
789*e038c9c4Sjoerg << IdentifyCUDATarget(Caller);
790*e038c9c4Sjoerg if (!Callee->getBuiltinID())
791*e038c9c4Sjoerg SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
792*e038c9c4Sjoerg diag::note_previous_decl, Caller, *this)
7937330f729Sjoerg << Callee;
794*e038c9c4Sjoerg return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
795*e038c9c4Sjoerg DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
796*e038c9c4Sjoerg }
797*e038c9c4Sjoerg
798*e038c9c4Sjoerg // Check the wrong-sided reference capture of lambda for CUDA/HIP.
799*e038c9c4Sjoerg // A lambda function may capture a stack variable by reference when it is
800*e038c9c4Sjoerg // defined and uses the capture by reference when the lambda is called. When
801*e038c9c4Sjoerg // the capture and use happen on different sides, the capture is invalid and
802*e038c9c4Sjoerg // should be diagnosed.
CUDACheckLambdaCapture(CXXMethodDecl * Callee,const sema::Capture & Capture)803*e038c9c4Sjoerg void Sema::CUDACheckLambdaCapture(CXXMethodDecl *Callee,
804*e038c9c4Sjoerg const sema::Capture &Capture) {
805*e038c9c4Sjoerg // In host compilation we only need to check lambda functions emitted on host
806*e038c9c4Sjoerg // side. In such lambda functions, a reference capture is invalid only
807*e038c9c4Sjoerg // if the lambda structure is populated by a device function or kernel then
808*e038c9c4Sjoerg // is passed to and called by a host function. However that is impossible,
809*e038c9c4Sjoerg // since a device function or kernel can only call a device function, also a
810*e038c9c4Sjoerg // kernel cannot pass a lambda back to a host function since we cannot
811*e038c9c4Sjoerg // define a kernel argument type which can hold the lambda before the lambda
812*e038c9c4Sjoerg // itself is defined.
813*e038c9c4Sjoerg if (!LangOpts.CUDAIsDevice)
814*e038c9c4Sjoerg return;
815*e038c9c4Sjoerg
816*e038c9c4Sjoerg // File-scope lambda can only do init captures for global variables, which
817*e038c9c4Sjoerg // results in passing by value for these global variables.
818*e038c9c4Sjoerg FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
819*e038c9c4Sjoerg if (!Caller)
820*e038c9c4Sjoerg return;
821*e038c9c4Sjoerg
822*e038c9c4Sjoerg // In device compilation, we only need to check lambda functions which are
823*e038c9c4Sjoerg // emitted on device side. For such lambdas, a reference capture is invalid
824*e038c9c4Sjoerg // only if the lambda structure is populated by a host function then passed
825*e038c9c4Sjoerg // to and called in a device function or kernel.
826*e038c9c4Sjoerg bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
827*e038c9c4Sjoerg bool CallerIsHost =
828*e038c9c4Sjoerg !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
829*e038c9c4Sjoerg bool ShouldCheck = CalleeIsDevice && CallerIsHost;
830*e038c9c4Sjoerg if (!ShouldCheck || !Capture.isReferenceCapture())
831*e038c9c4Sjoerg return;
832*e038c9c4Sjoerg auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
833*e038c9c4Sjoerg if (Capture.isVariableCapture()) {
834*e038c9c4Sjoerg SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
835*e038c9c4Sjoerg diag::err_capture_bad_target, Callee, *this)
836*e038c9c4Sjoerg << Capture.getVariable();
837*e038c9c4Sjoerg } else if (Capture.isThisCapture()) {
838*e038c9c4Sjoerg SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
839*e038c9c4Sjoerg diag::err_capture_bad_target_this_ptr, Callee, *this);
840*e038c9c4Sjoerg }
841*e038c9c4Sjoerg return;
8427330f729Sjoerg }
8437330f729Sjoerg
CUDASetLambdaAttrs(CXXMethodDecl * Method)8447330f729Sjoerg void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
8457330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
8467330f729Sjoerg if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
8477330f729Sjoerg return;
8487330f729Sjoerg Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
8497330f729Sjoerg Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
8507330f729Sjoerg }
8517330f729Sjoerg
checkCUDATargetOverload(FunctionDecl * NewFD,const LookupResult & Previous)8527330f729Sjoerg void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
8537330f729Sjoerg const LookupResult &Previous) {
8547330f729Sjoerg assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
8557330f729Sjoerg CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
8567330f729Sjoerg for (NamedDecl *OldND : Previous) {
8577330f729Sjoerg FunctionDecl *OldFD = OldND->getAsFunction();
8587330f729Sjoerg if (!OldFD)
8597330f729Sjoerg continue;
8607330f729Sjoerg
8617330f729Sjoerg CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
8627330f729Sjoerg // Don't allow HD and global functions to overload other functions with the
8637330f729Sjoerg // same signature. We allow overloading based on CUDA attributes so that
8647330f729Sjoerg // functions can have different implementations on the host and device, but
8657330f729Sjoerg // HD/global functions "exist" in some sense on both the host and device, so
8667330f729Sjoerg // should have the same implementation on both sides.
8677330f729Sjoerg if (NewTarget != OldTarget &&
8687330f729Sjoerg ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
8697330f729Sjoerg (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
8707330f729Sjoerg !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
8717330f729Sjoerg /* ConsiderCudaAttrs = */ false)) {
8727330f729Sjoerg Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
8737330f729Sjoerg << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
8747330f729Sjoerg Diag(OldFD->getLocation(), diag::note_previous_declaration);
8757330f729Sjoerg NewFD->setInvalidDecl();
8767330f729Sjoerg break;
8777330f729Sjoerg }
8787330f729Sjoerg }
8797330f729Sjoerg }
8807330f729Sjoerg
8817330f729Sjoerg template <typename AttrTy>
copyAttrIfPresent(Sema & S,FunctionDecl * FD,const FunctionDecl & TemplateFD)8827330f729Sjoerg static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
8837330f729Sjoerg const FunctionDecl &TemplateFD) {
8847330f729Sjoerg if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
8857330f729Sjoerg AttrTy *Clone = Attribute->clone(S.Context);
8867330f729Sjoerg Clone->setInherited(true);
8877330f729Sjoerg FD->addAttr(Clone);
8887330f729Sjoerg }
8897330f729Sjoerg }
8907330f729Sjoerg
inheritCUDATargetAttrs(FunctionDecl * FD,const FunctionTemplateDecl & TD)8917330f729Sjoerg void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
8927330f729Sjoerg const FunctionTemplateDecl &TD) {
8937330f729Sjoerg const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
8947330f729Sjoerg copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
8957330f729Sjoerg copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
8967330f729Sjoerg copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
8977330f729Sjoerg }
8987330f729Sjoerg
getCudaConfigureFuncName() const8997330f729Sjoerg std::string Sema::getCudaConfigureFuncName() const {
9007330f729Sjoerg if (getLangOpts().HIP)
9017330f729Sjoerg return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
9027330f729Sjoerg : "hipConfigureCall";
9037330f729Sjoerg
9047330f729Sjoerg // New CUDA kernel launch sequence.
9057330f729Sjoerg if (CudaFeatureEnabled(Context.getTargetInfo().getSDKVersion(),
9067330f729Sjoerg CudaFeature::CUDA_USES_NEW_LAUNCH))
9077330f729Sjoerg return "__cudaPushCallConfiguration";
9087330f729Sjoerg
9097330f729Sjoerg // Legacy CUDA kernel configuration call
9107330f729Sjoerg return "cudaConfigureCall";
9117330f729Sjoerg }
912