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/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/Cuda.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/Sema.h"
21 #include "clang/Sema/SemaDiagnostic.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "clang/Sema/Template.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/SmallVector.h"
26 using namespace clang;
27 
28 void Sema::PushForceCUDAHostDevice() {
29   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
30   ForceCUDAHostDeviceDepth++;
31 }
32 
33 bool Sema::PopForceCUDAHostDevice() {
34   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
35   if (ForceCUDAHostDeviceDepth == 0)
36     return false;
37   ForceCUDAHostDeviceDepth--;
38   return true;
39 }
40 
41 ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
42                                          MultiExprArg ExecConfig,
43                                          SourceLocation GGGLoc) {
44   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
45   if (!ConfigDecl)
46     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
47                      << getCudaConfigureFuncName());
48   QualType ConfigQTy = ConfigDecl->getType();
49 
50   DeclRefExpr *ConfigDR = new (Context)
51       DeclRefExpr(Context, ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
52   MarkFunctionReferenced(LLLLoc, ConfigDecl);
53 
54   return BuildCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
55                        /*IsExecConfig=*/true);
56 }
57 
58 Sema::CUDAFunctionTarget
59 Sema::IdentifyCUDATarget(const ParsedAttributesView &Attrs) {
60   bool HasHostAttr = false;
61   bool HasDeviceAttr = false;
62   bool HasGlobalAttr = false;
63   bool HasInvalidTargetAttr = false;
64   for (const ParsedAttr &AL : Attrs) {
65     switch (AL.getKind()) {
66     case ParsedAttr::AT_CUDAGlobal:
67       HasGlobalAttr = true;
68       break;
69     case ParsedAttr::AT_CUDAHost:
70       HasHostAttr = true;
71       break;
72     case ParsedAttr::AT_CUDADevice:
73       HasDeviceAttr = true;
74       break;
75     case ParsedAttr::AT_CUDAInvalidTarget:
76       HasInvalidTargetAttr = true;
77       break;
78     default:
79       break;
80     }
81   }
82 
83   if (HasInvalidTargetAttr)
84     return CFT_InvalidTarget;
85 
86   if (HasGlobalAttr)
87     return CFT_Global;
88 
89   if (HasHostAttr && HasDeviceAttr)
90     return CFT_HostDevice;
91 
92   if (HasDeviceAttr)
93     return CFT_Device;
94 
95   return CFT_Host;
96 }
97 
98 template <typename A>
99 static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr) {
100   return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
101            return isa<A>(Attribute) &&
102                   !(IgnoreImplicitAttr && Attribute->isImplicit());
103          });
104 }
105 
106 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
107 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D,
108                                                   bool IgnoreImplicitHDAttr) {
109   // Code that lives outside a function is run on the host.
110   if (D == nullptr)
111     return CFT_Host;
112 
113   if (D->hasAttr<CUDAInvalidTargetAttr>())
114     return CFT_InvalidTarget;
115 
116   if (D->hasAttr<CUDAGlobalAttr>())
117     return CFT_Global;
118 
119   if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
120     if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
121       return CFT_HostDevice;
122     return CFT_Device;
123   } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
124     return CFT_Host;
125   } else if (D->isImplicit() && !IgnoreImplicitHDAttr) {
126     // Some implicit declarations (like intrinsic functions) are not marked.
127     // Set the most lenient target on them for maximal flexibility.
128     return CFT_HostDevice;
129   }
130 
131   return CFT_Host;
132 }
133 
134 // * CUDA Call preference table
135 //
136 // F - from,
137 // T - to
138 // Ph - preference in host mode
139 // Pd - preference in device mode
140 // H  - handled in (x)
141 // Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
142 //
143 // | F  | T  | Ph  | Pd  |  H  |
144 // |----+----+-----+-----+-----+
145 // | d  | d  | N   | N   | (c) |
146 // | d  | g  | --  | --  | (a) |
147 // | d  | h  | --  | --  | (e) |
148 // | d  | hd | HD  | HD  | (b) |
149 // | g  | d  | N   | N   | (c) |
150 // | g  | g  | --  | --  | (a) |
151 // | g  | h  | --  | --  | (e) |
152 // | g  | hd | HD  | HD  | (b) |
153 // | h  | d  | --  | --  | (e) |
154 // | h  | g  | N   | N   | (c) |
155 // | h  | h  | N   | N   | (c) |
156 // | h  | hd | HD  | HD  | (b) |
157 // | hd | d  | WS  | SS  | (d) |
158 // | hd | g  | SS  | --  |(d/a)|
159 // | hd | h  | SS  | WS  | (d) |
160 // | hd | hd | HD  | HD  | (b) |
161 
162 Sema::CUDAFunctionPreference
163 Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
164                              const FunctionDecl *Callee) {
165   assert(Callee && "Callee must be valid.");
166   CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
167   CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
168 
169   // If one of the targets is invalid, the check always fails, no matter what
170   // the other target is.
171   if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
172     return CFP_Never;
173 
174   // (a) Can't call global from some contexts until we support CUDA's
175   // dynamic parallelism.
176   if (CalleeTarget == CFT_Global &&
177       (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
178     return CFP_Never;
179 
180   // (b) Calling HostDevice is OK for everyone.
181   if (CalleeTarget == CFT_HostDevice)
182     return CFP_HostDevice;
183 
184   // (c) Best case scenarios
185   if (CalleeTarget == CallerTarget ||
186       (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
187       (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
188     return CFP_Native;
189 
190   // (d) HostDevice behavior depends on compilation mode.
191   if (CallerTarget == CFT_HostDevice) {
192     // It's OK to call a compilation-mode matching function from an HD one.
193     if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
194         (!getLangOpts().CUDAIsDevice &&
195          (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
196       return CFP_SameSide;
197 
198     // Calls from HD to non-mode-matching functions (i.e., to host functions
199     // when compiling in device mode or to device functions when compiling in
200     // host mode) are allowed at the sema level, but eventually rejected if
201     // they're ever codegened.  TODO: Reject said calls earlier.
202     return CFP_WrongSide;
203   }
204 
205   // (e) Calling across device/host boundary is not something you should do.
206   if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
207       (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
208       (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
209     return CFP_Never;
210 
211   llvm_unreachable("All cases should've been handled by now.");
212 }
213 
214 void Sema::EraseUnwantedCUDAMatches(
215     const FunctionDecl *Caller,
216     SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
217   if (Matches.size() <= 1)
218     return;
219 
220   using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
221 
222   // Gets the CUDA function preference for a call from Caller to Match.
223   auto GetCFP = [&](const Pair &Match) {
224     return IdentifyCUDAPreference(Caller, Match.second);
225   };
226 
227   // Find the best call preference among the functions in Matches.
228   CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
229       Matches.begin(), Matches.end(),
230       [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
231 
232   // Erase all functions with lower priority.
233   llvm::erase_if(Matches,
234                  [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
235 }
236 
237 /// When an implicitly-declared special member has to invoke more than one
238 /// base/field special member, conflicts may occur in the targets of these
239 /// members. For example, if one base's member __host__ and another's is
240 /// __device__, it's a conflict.
241 /// This function figures out if the given targets \param Target1 and
242 /// \param Target2 conflict, and if they do not it fills in
243 /// \param ResolvedTarget with a target that resolves for both calls.
244 /// \return true if there's a conflict, false otherwise.
245 static bool
246 resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
247                                 Sema::CUDAFunctionTarget Target2,
248                                 Sema::CUDAFunctionTarget *ResolvedTarget) {
249   // Only free functions and static member functions may be global.
250   assert(Target1 != Sema::CFT_Global);
251   assert(Target2 != Sema::CFT_Global);
252 
253   if (Target1 == Sema::CFT_HostDevice) {
254     *ResolvedTarget = Target2;
255   } else if (Target2 == Sema::CFT_HostDevice) {
256     *ResolvedTarget = Target1;
257   } else if (Target1 != Target2) {
258     return true;
259   } else {
260     *ResolvedTarget = Target1;
261   }
262 
263   return false;
264 }
265 
266 bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
267                                                    CXXSpecialMember CSM,
268                                                    CXXMethodDecl *MemberDecl,
269                                                    bool ConstRHS,
270                                                    bool Diagnose) {
271   // If the defaulted special member is defined lexically outside of its
272   // owning class, or the special member already has explicit device or host
273   // attributes, do not infer.
274   bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
275   bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
276   bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
277   bool HasExplicitAttr =
278       (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
279       (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
280   if (!InClass || HasExplicitAttr)
281     return false;
282 
283   llvm::Optional<CUDAFunctionTarget> InferredTarget;
284 
285   // We're going to invoke special member lookup; mark that these special
286   // members are called from this one, and not from its caller.
287   ContextRAII MethodContext(*this, MemberDecl);
288 
289   // Look for special members in base classes that should be invoked from here.
290   // Infer the target of this member base on the ones it should call.
291   // Skip direct and indirect virtual bases for abstract classes.
292   llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
293   for (const auto &B : ClassDecl->bases()) {
294     if (!B.isVirtual()) {
295       Bases.push_back(&B);
296     }
297   }
298 
299   if (!ClassDecl->isAbstract()) {
300     for (const auto &VB : ClassDecl->vbases()) {
301       Bases.push_back(&VB);
302     }
303   }
304 
305   for (const auto *B : Bases) {
306     const RecordType *BaseType = B->getType()->getAs<RecordType>();
307     if (!BaseType) {
308       continue;
309     }
310 
311     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
312     Sema::SpecialMemberOverloadResult SMOR =
313         LookupSpecialMember(BaseClassDecl, CSM,
314                             /* ConstArg */ ConstRHS,
315                             /* VolatileArg */ false,
316                             /* RValueThis */ false,
317                             /* ConstThis */ false,
318                             /* VolatileThis */ false);
319 
320     if (!SMOR.getMethod())
321       continue;
322 
323     CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
324     if (!InferredTarget.hasValue()) {
325       InferredTarget = BaseMethodTarget;
326     } else {
327       bool ResolutionError = resolveCalleeCUDATargetConflict(
328           InferredTarget.getValue(), BaseMethodTarget,
329           InferredTarget.getPointer());
330       if (ResolutionError) {
331         if (Diagnose) {
332           Diag(ClassDecl->getLocation(),
333                diag::note_implicit_member_target_infer_collision)
334               << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
335         }
336         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
337         return true;
338       }
339     }
340   }
341 
342   // Same as for bases, but now for special members of fields.
343   for (const auto *F : ClassDecl->fields()) {
344     if (F->isInvalidDecl()) {
345       continue;
346     }
347 
348     const RecordType *FieldType =
349         Context.getBaseElementType(F->getType())->getAs<RecordType>();
350     if (!FieldType) {
351       continue;
352     }
353 
354     CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
355     Sema::SpecialMemberOverloadResult SMOR =
356         LookupSpecialMember(FieldRecDecl, CSM,
357                             /* ConstArg */ ConstRHS && !F->isMutable(),
358                             /* VolatileArg */ false,
359                             /* RValueThis */ false,
360                             /* ConstThis */ false,
361                             /* VolatileThis */ false);
362 
363     if (!SMOR.getMethod())
364       continue;
365 
366     CUDAFunctionTarget FieldMethodTarget =
367         IdentifyCUDATarget(SMOR.getMethod());
368     if (!InferredTarget.hasValue()) {
369       InferredTarget = FieldMethodTarget;
370     } else {
371       bool ResolutionError = resolveCalleeCUDATargetConflict(
372           InferredTarget.getValue(), FieldMethodTarget,
373           InferredTarget.getPointer());
374       if (ResolutionError) {
375         if (Diagnose) {
376           Diag(ClassDecl->getLocation(),
377                diag::note_implicit_member_target_infer_collision)
378               << (unsigned)CSM << InferredTarget.getValue()
379               << FieldMethodTarget;
380         }
381         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
382         return true;
383       }
384     }
385   }
386 
387 
388   // If no target was inferred, mark this member as __host__ __device__;
389   // it's the least restrictive option that can be invoked from any target.
390   bool NeedsH = true, NeedsD = true;
391   if (InferredTarget.hasValue()) {
392     if (InferredTarget.getValue() == CFT_Device)
393       NeedsH = false;
394     else if (InferredTarget.getValue() == CFT_Host)
395       NeedsD = false;
396   }
397 
398   // We either setting attributes first time, or the inferred ones must match
399   // previously set ones.
400   if (NeedsD && !HasD)
401     MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
402   if (NeedsH && !HasH)
403     MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
404 
405   return false;
406 }
407 
408 bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
409   if (!CD->isDefined() && CD->isTemplateInstantiation())
410     InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
411 
412   // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
413   // empty at a point in the translation unit, if it is either a
414   // trivial constructor
415   if (CD->isTrivial())
416     return true;
417 
418   // ... or it satisfies all of the following conditions:
419   // The constructor function has been defined.
420   // The constructor function has no parameters,
421   // and the function body is an empty compound statement.
422   if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
423     return false;
424 
425   // Its class has no virtual functions and no virtual base classes.
426   if (CD->getParent()->isDynamicClass())
427     return false;
428 
429   // The only form of initializer allowed is an empty constructor.
430   // This will recursively check all base classes and member initializers
431   if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
432         if (const CXXConstructExpr *CE =
433                 dyn_cast<CXXConstructExpr>(CI->getInit()))
434           return isEmptyCudaConstructor(Loc, CE->getConstructor());
435         return false;
436       }))
437     return false;
438 
439   return true;
440 }
441 
442 bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
443   // No destructor -> no problem.
444   if (!DD)
445     return true;
446 
447   if (!DD->isDefined() && DD->isTemplateInstantiation())
448     InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
449 
450   // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
451   // empty at a point in the translation unit, if it is either a
452   // trivial constructor
453   if (DD->isTrivial())
454     return true;
455 
456   // ... or it satisfies all of the following conditions:
457   // The destructor function has been defined.
458   // and the function body is an empty compound statement.
459   if (!DD->hasTrivialBody())
460     return false;
461 
462   const CXXRecordDecl *ClassDecl = DD->getParent();
463 
464   // Its class has no virtual functions and no virtual base classes.
465   if (ClassDecl->isDynamicClass())
466     return false;
467 
468   // Only empty destructors are allowed. This will recursively check
469   // destructors for all base classes...
470   if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
471         if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
472           return isEmptyCudaDestructor(Loc, RD->getDestructor());
473         return true;
474       }))
475     return false;
476 
477   // ... and member fields.
478   if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
479         if (CXXRecordDecl *RD = Field->getType()
480                                     ->getBaseElementTypeUnsafe()
481                                     ->getAsCXXRecordDecl())
482           return isEmptyCudaDestructor(Loc, RD->getDestructor());
483         return true;
484       }))
485     return false;
486 
487   return true;
488 }
489 
490 void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
491   if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage())
492     return;
493   const Expr *Init = VD->getInit();
494   if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
495       VD->hasAttr<CUDASharedAttr>()) {
496     if (LangOpts.GPUAllowDeviceInit)
497       return;
498     assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
499     bool AllowedInit = false;
500     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
501       AllowedInit =
502           isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
503     // We'll allow constant initializers even if it's a non-empty
504     // constructor according to CUDA rules. This deviates from NVCC,
505     // but allows us to handle things like constexpr constructors.
506     if (!AllowedInit &&
507         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
508       AllowedInit = VD->getInit()->isConstantInitializer(
509           Context, VD->getType()->isReferenceType());
510 
511     // Also make sure that destructor, if there is one, is empty.
512     if (AllowedInit)
513       if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
514         AllowedInit =
515             isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
516 
517     if (!AllowedInit) {
518       Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
519                                   ? diag::err_shared_var_init
520                                   : diag::err_dynamic_var_init)
521           << Init->getSourceRange();
522       VD->setInvalidDecl();
523     }
524   } else {
525     // This is a host-side global variable.  Check that the initializer is
526     // callable from the host side.
527     const FunctionDecl *InitFn = nullptr;
528     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
529       InitFn = CE->getConstructor();
530     } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
531       InitFn = CE->getDirectCallee();
532     }
533     if (InitFn) {
534       CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
535       if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
536         Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
537             << InitFnTarget << InitFn;
538         Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
539         VD->setInvalidDecl();
540       }
541     }
542   }
543 }
544 
545 // With -fcuda-host-device-constexpr, an unattributed constexpr function is
546 // treated as implicitly __host__ __device__, unless:
547 //  * it is a variadic function (device-side variadic functions are not
548 //    allowed), or
549 //  * a __device__ function with this signature was already declared, in which
550 //    case in which case we output an error, unless the __device__ decl is in a
551 //    system header, in which case we leave the constexpr function unattributed.
552 //
553 // In addition, all function decls are treated as __host__ __device__ when
554 // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
555 //   #pragma clang force_cuda_host_device_begin/end
556 // pair).
557 void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
558                                        const LookupResult &Previous) {
559   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
560 
561   if (ForceCUDAHostDeviceDepth > 0) {
562     if (!NewD->hasAttr<CUDAHostAttr>())
563       NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
564     if (!NewD->hasAttr<CUDADeviceAttr>())
565       NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
566     return;
567   }
568 
569   if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
570       NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
571       NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
572     return;
573 
574   // Is D a __device__ function with the same signature as NewD, ignoring CUDA
575   // attributes?
576   auto IsMatchingDeviceFn = [&](NamedDecl *D) {
577     if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
578       D = Using->getTargetDecl();
579     FunctionDecl *OldD = D->getAsFunction();
580     return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
581            !OldD->hasAttr<CUDAHostAttr>() &&
582            !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
583                        /* ConsiderCudaAttrs = */ false);
584   };
585   auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
586   if (It != Previous.end()) {
587     // We found a __device__ function with the same name and signature as NewD
588     // (ignoring CUDA attrs).  This is an error unless that function is defined
589     // in a system header, in which case we simply return without making NewD
590     // host+device.
591     NamedDecl *Match = *It;
592     if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
593       Diag(NewD->getLocation(),
594            diag::err_cuda_unattributed_constexpr_cannot_overload_device)
595           << NewD;
596       Diag(Match->getLocation(),
597            diag::note_cuda_conflicting_device_function_declared_here);
598     }
599     return;
600   }
601 
602   NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
603   NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
604 }
605 
606 Sema::DeviceDiagBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
607                                                    unsigned DiagID) {
608   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
609   DeviceDiagBuilder::Kind DiagKind = [this] {
610     switch (CurrentCUDATarget()) {
611     case CFT_Global:
612     case CFT_Device:
613       return DeviceDiagBuilder::K_Immediate;
614     case CFT_HostDevice:
615       // An HD function counts as host code if we're compiling for host, and
616       // device code if we're compiling for device.  Defer any errors in device
617       // mode until the function is known-emitted.
618       if (getLangOpts().CUDAIsDevice) {
619         return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
620                 FunctionEmissionStatus::Emitted)
621                    ? DeviceDiagBuilder::K_ImmediateWithCallStack
622                    : DeviceDiagBuilder::K_Deferred;
623       }
624       return DeviceDiagBuilder::K_Nop;
625 
626     default:
627       return DeviceDiagBuilder::K_Nop;
628     }
629   }();
630   return DeviceDiagBuilder(DiagKind, Loc, DiagID,
631                            dyn_cast<FunctionDecl>(CurContext), *this);
632 }
633 
634 Sema::DeviceDiagBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
635                                                  unsigned DiagID) {
636   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
637   DeviceDiagBuilder::Kind DiagKind = [this] {
638     switch (CurrentCUDATarget()) {
639     case CFT_Host:
640       return DeviceDiagBuilder::K_Immediate;
641     case CFT_HostDevice:
642       // An HD function counts as host code if we're compiling for host, and
643       // device code if we're compiling for device.  Defer any errors in device
644       // mode until the function is known-emitted.
645       if (getLangOpts().CUDAIsDevice)
646         return DeviceDiagBuilder::K_Nop;
647 
648       return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
649               FunctionEmissionStatus::Emitted)
650                  ? DeviceDiagBuilder::K_ImmediateWithCallStack
651                  : DeviceDiagBuilder::K_Deferred;
652     default:
653       return DeviceDiagBuilder::K_Nop;
654     }
655   }();
656   return DeviceDiagBuilder(DiagKind, Loc, DiagID,
657                            dyn_cast<FunctionDecl>(CurContext), *this);
658 }
659 
660 bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
661   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
662   assert(Callee && "Callee may not be null.");
663 
664   auto &ExprEvalCtx = ExprEvalContexts.back();
665   if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
666     return true;
667 
668   // FIXME: Is bailing out early correct here?  Should we instead assume that
669   // the caller is a global initializer?
670   FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
671   if (!Caller)
672     return true;
673 
674   // If the caller is known-emitted, mark the callee as known-emitted.
675   // Otherwise, mark the call in our call graph so we can traverse it later.
676   bool CallerKnownEmitted =
677       getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted;
678   if (CallerKnownEmitted) {
679     // Host-side references to a __global__ function refer to the stub, so the
680     // function itself is never emitted and therefore should not be marked.
681     if (!shouldIgnoreInHostDeviceCheck(Callee))
682       markKnownEmitted(
683           *this, Caller, Callee, Loc, [](Sema &S, FunctionDecl *FD) {
684             return S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
685           });
686   } else {
687     // If we have
688     //   host fn calls kernel fn calls host+device,
689     // the HD function does not get instantiated on the host.  We model this by
690     // omitting at the call to the kernel from the callgraph.  This ensures
691     // that, when compiling for host, only HD functions actually called from the
692     // host get marked as known-emitted.
693     if (!shouldIgnoreInHostDeviceCheck(Callee))
694       DeviceCallGraph[Caller].insert({Callee, Loc});
695   }
696 
697   DeviceDiagBuilder::Kind DiagKind = [this, Caller, Callee,
698                                       CallerKnownEmitted] {
699     switch (IdentifyCUDAPreference(Caller, Callee)) {
700     case CFP_Never:
701       return DeviceDiagBuilder::K_Immediate;
702     case CFP_WrongSide:
703       assert(Caller && "WrongSide calls require a non-null caller");
704       // If we know the caller will be emitted, we know this wrong-side call
705       // will be emitted, so it's an immediate error.  Otherwise, defer the
706       // error until we know the caller is emitted.
707       return CallerKnownEmitted ? DeviceDiagBuilder::K_ImmediateWithCallStack
708                                 : DeviceDiagBuilder::K_Deferred;
709     default:
710       return DeviceDiagBuilder::K_Nop;
711     }
712   }();
713 
714   if (DiagKind == DeviceDiagBuilder::K_Nop)
715     return true;
716 
717   // Avoid emitting this error twice for the same location.  Using a hashtable
718   // like this is unfortunate, but because we must continue parsing as normal
719   // after encountering a deferred error, it's otherwise very tricky for us to
720   // ensure that we only emit this deferred error once.
721   if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
722     return true;
723 
724   DeviceDiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
725       << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
726   DeviceDiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
727                     Caller, *this)
728       << Callee;
729   return DiagKind != DeviceDiagBuilder::K_Immediate &&
730          DiagKind != DeviceDiagBuilder::K_ImmediateWithCallStack;
731 }
732 
733 void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
734   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
735   if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
736     return;
737   FunctionDecl *CurFn = dyn_cast<FunctionDecl>(CurContext);
738   if (!CurFn)
739     return;
740   CUDAFunctionTarget Target = IdentifyCUDATarget(CurFn);
741   if (Target == CFT_Global || Target == CFT_Device) {
742     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
743   } else if (Target == CFT_HostDevice) {
744     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
745     Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
746   }
747 }
748 
749 void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
750                                    const LookupResult &Previous) {
751   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
752   CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
753   for (NamedDecl *OldND : Previous) {
754     FunctionDecl *OldFD = OldND->getAsFunction();
755     if (!OldFD)
756       continue;
757 
758     CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
759     // Don't allow HD and global functions to overload other functions with the
760     // same signature.  We allow overloading based on CUDA attributes so that
761     // functions can have different implementations on the host and device, but
762     // HD/global functions "exist" in some sense on both the host and device, so
763     // should have the same implementation on both sides.
764     if (NewTarget != OldTarget &&
765         ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
766          (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
767         !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
768                     /* ConsiderCudaAttrs = */ false)) {
769       Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
770           << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
771       Diag(OldFD->getLocation(), diag::note_previous_declaration);
772       NewFD->setInvalidDecl();
773       break;
774     }
775   }
776 }
777 
778 template <typename AttrTy>
779 static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
780                               const FunctionDecl &TemplateFD) {
781   if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
782     AttrTy *Clone = Attribute->clone(S.Context);
783     Clone->setInherited(true);
784     FD->addAttr(Clone);
785   }
786 }
787 
788 void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
789                                   const FunctionTemplateDecl &TD) {
790   const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
791   copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
792   copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
793   copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
794 }
795 
796 std::string Sema::getCudaConfigureFuncName() const {
797   if (getLangOpts().HIP)
798     return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
799                                             : "hipConfigureCall";
800 
801   // New CUDA kernel launch sequence.
802   if (CudaFeatureEnabled(Context.getTargetInfo().getSDKVersion(),
803                          CudaFeature::CUDA_USES_NEW_LAUNCH))
804     return "__cudaPushCallConfiguration";
805 
806   // Legacy CUDA kernel configuration call
807   return "cudaConfigureCall";
808 }
809