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 template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
215   if (!D)
216     return false;
217   if (auto *A = D->getAttr<AttrT>())
218     return A->isImplicit();
219   return D->isImplicit();
220 }
221 
222 bool Sema::isCUDAImplicitHostDeviceFunction(const FunctionDecl *D) {
223   bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
224   bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
225   return IsImplicitDevAttr && IsImplicitHostAttr;
226 }
227 
228 void Sema::EraseUnwantedCUDAMatches(
229     const FunctionDecl *Caller,
230     SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
231   if (Matches.size() <= 1)
232     return;
233 
234   using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
235 
236   // Gets the CUDA function preference for a call from Caller to Match.
237   auto GetCFP = [&](const Pair &Match) {
238     return IdentifyCUDAPreference(Caller, Match.second);
239   };
240 
241   // Find the best call preference among the functions in Matches.
242   CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
243       Matches.begin(), Matches.end(),
244       [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
245 
246   // Erase all functions with lower priority.
247   llvm::erase_if(Matches,
248                  [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
249 }
250 
251 /// When an implicitly-declared special member has to invoke more than one
252 /// base/field special member, conflicts may occur in the targets of these
253 /// members. For example, if one base's member __host__ and another's is
254 /// __device__, it's a conflict.
255 /// This function figures out if the given targets \param Target1 and
256 /// \param Target2 conflict, and if they do not it fills in
257 /// \param ResolvedTarget with a target that resolves for both calls.
258 /// \return true if there's a conflict, false otherwise.
259 static bool
260 resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
261                                 Sema::CUDAFunctionTarget Target2,
262                                 Sema::CUDAFunctionTarget *ResolvedTarget) {
263   // Only free functions and static member functions may be global.
264   assert(Target1 != Sema::CFT_Global);
265   assert(Target2 != Sema::CFT_Global);
266 
267   if (Target1 == Sema::CFT_HostDevice) {
268     *ResolvedTarget = Target2;
269   } else if (Target2 == Sema::CFT_HostDevice) {
270     *ResolvedTarget = Target1;
271   } else if (Target1 != Target2) {
272     return true;
273   } else {
274     *ResolvedTarget = Target1;
275   }
276 
277   return false;
278 }
279 
280 bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
281                                                    CXXSpecialMember CSM,
282                                                    CXXMethodDecl *MemberDecl,
283                                                    bool ConstRHS,
284                                                    bool Diagnose) {
285   // If the defaulted special member is defined lexically outside of its
286   // owning class, or the special member already has explicit device or host
287   // attributes, do not infer.
288   bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
289   bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
290   bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
291   bool HasExplicitAttr =
292       (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
293       (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
294   if (!InClass || HasExplicitAttr)
295     return false;
296 
297   llvm::Optional<CUDAFunctionTarget> InferredTarget;
298 
299   // We're going to invoke special member lookup; mark that these special
300   // members are called from this one, and not from its caller.
301   ContextRAII MethodContext(*this, MemberDecl);
302 
303   // Look for special members in base classes that should be invoked from here.
304   // Infer the target of this member base on the ones it should call.
305   // Skip direct and indirect virtual bases for abstract classes.
306   llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
307   for (const auto &B : ClassDecl->bases()) {
308     if (!B.isVirtual()) {
309       Bases.push_back(&B);
310     }
311   }
312 
313   if (!ClassDecl->isAbstract()) {
314     for (const auto &VB : ClassDecl->vbases()) {
315       Bases.push_back(&VB);
316     }
317   }
318 
319   for (const auto *B : Bases) {
320     const RecordType *BaseType = B->getType()->getAs<RecordType>();
321     if (!BaseType) {
322       continue;
323     }
324 
325     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
326     Sema::SpecialMemberOverloadResult SMOR =
327         LookupSpecialMember(BaseClassDecl, CSM,
328                             /* ConstArg */ ConstRHS,
329                             /* VolatileArg */ false,
330                             /* RValueThis */ false,
331                             /* ConstThis */ false,
332                             /* VolatileThis */ false);
333 
334     if (!SMOR.getMethod())
335       continue;
336 
337     CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
338     if (!InferredTarget.hasValue()) {
339       InferredTarget = BaseMethodTarget;
340     } else {
341       bool ResolutionError = resolveCalleeCUDATargetConflict(
342           InferredTarget.getValue(), BaseMethodTarget,
343           InferredTarget.getPointer());
344       if (ResolutionError) {
345         if (Diagnose) {
346           Diag(ClassDecl->getLocation(),
347                diag::note_implicit_member_target_infer_collision)
348               << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
349         }
350         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
351         return true;
352       }
353     }
354   }
355 
356   // Same as for bases, but now for special members of fields.
357   for (const auto *F : ClassDecl->fields()) {
358     if (F->isInvalidDecl()) {
359       continue;
360     }
361 
362     const RecordType *FieldType =
363         Context.getBaseElementType(F->getType())->getAs<RecordType>();
364     if (!FieldType) {
365       continue;
366     }
367 
368     CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
369     Sema::SpecialMemberOverloadResult SMOR =
370         LookupSpecialMember(FieldRecDecl, CSM,
371                             /* ConstArg */ ConstRHS && !F->isMutable(),
372                             /* VolatileArg */ false,
373                             /* RValueThis */ false,
374                             /* ConstThis */ false,
375                             /* VolatileThis */ false);
376 
377     if (!SMOR.getMethod())
378       continue;
379 
380     CUDAFunctionTarget FieldMethodTarget =
381         IdentifyCUDATarget(SMOR.getMethod());
382     if (!InferredTarget.hasValue()) {
383       InferredTarget = FieldMethodTarget;
384     } else {
385       bool ResolutionError = resolveCalleeCUDATargetConflict(
386           InferredTarget.getValue(), FieldMethodTarget,
387           InferredTarget.getPointer());
388       if (ResolutionError) {
389         if (Diagnose) {
390           Diag(ClassDecl->getLocation(),
391                diag::note_implicit_member_target_infer_collision)
392               << (unsigned)CSM << InferredTarget.getValue()
393               << FieldMethodTarget;
394         }
395         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
396         return true;
397       }
398     }
399   }
400 
401 
402   // If no target was inferred, mark this member as __host__ __device__;
403   // it's the least restrictive option that can be invoked from any target.
404   bool NeedsH = true, NeedsD = true;
405   if (InferredTarget.hasValue()) {
406     if (InferredTarget.getValue() == CFT_Device)
407       NeedsH = false;
408     else if (InferredTarget.getValue() == CFT_Host)
409       NeedsD = false;
410   }
411 
412   // We either setting attributes first time, or the inferred ones must match
413   // previously set ones.
414   if (NeedsD && !HasD)
415     MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
416   if (NeedsH && !HasH)
417     MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
418 
419   return false;
420 }
421 
422 bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
423   if (!CD->isDefined() && CD->isTemplateInstantiation())
424     InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
425 
426   // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
427   // empty at a point in the translation unit, if it is either a
428   // trivial constructor
429   if (CD->isTrivial())
430     return true;
431 
432   // ... or it satisfies all of the following conditions:
433   // The constructor function has been defined.
434   // The constructor function has no parameters,
435   // and the function body is an empty compound statement.
436   if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
437     return false;
438 
439   // Its class has no virtual functions and no virtual base classes.
440   if (CD->getParent()->isDynamicClass())
441     return false;
442 
443   // Union ctor does not call ctors of its data members.
444   if (CD->getParent()->isUnion())
445     return true;
446 
447   // The only form of initializer allowed is an empty constructor.
448   // This will recursively check all base classes and member initializers
449   if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
450         if (const CXXConstructExpr *CE =
451                 dyn_cast<CXXConstructExpr>(CI->getInit()))
452           return isEmptyCudaConstructor(Loc, CE->getConstructor());
453         return false;
454       }))
455     return false;
456 
457   return true;
458 }
459 
460 bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
461   // No destructor -> no problem.
462   if (!DD)
463     return true;
464 
465   if (!DD->isDefined() && DD->isTemplateInstantiation())
466     InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
467 
468   // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
469   // empty at a point in the translation unit, if it is either a
470   // trivial constructor
471   if (DD->isTrivial())
472     return true;
473 
474   // ... or it satisfies all of the following conditions:
475   // The destructor function has been defined.
476   // and the function body is an empty compound statement.
477   if (!DD->hasTrivialBody())
478     return false;
479 
480   const CXXRecordDecl *ClassDecl = DD->getParent();
481 
482   // Its class has no virtual functions and no virtual base classes.
483   if (ClassDecl->isDynamicClass())
484     return false;
485 
486   // Union does not have base class and union dtor does not call dtors of its
487   // data members.
488   if (DD->getParent()->isUnion())
489     return true;
490 
491   // Only empty destructors are allowed. This will recursively check
492   // destructors for all base classes...
493   if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
494         if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
495           return isEmptyCudaDestructor(Loc, RD->getDestructor());
496         return true;
497       }))
498     return false;
499 
500   // ... and member fields.
501   if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
502         if (CXXRecordDecl *RD = Field->getType()
503                                     ->getBaseElementTypeUnsafe()
504                                     ->getAsCXXRecordDecl())
505           return isEmptyCudaDestructor(Loc, RD->getDestructor());
506         return true;
507       }))
508     return false;
509 
510   return true;
511 }
512 
513 void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
514   if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage())
515     return;
516   const Expr *Init = VD->getInit();
517   if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
518       VD->hasAttr<CUDASharedAttr>()) {
519     if (LangOpts.GPUAllowDeviceInit)
520       return;
521     assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
522     bool AllowedInit = false;
523     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
524       AllowedInit =
525           isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
526     // We'll allow constant initializers even if it's a non-empty
527     // constructor according to CUDA rules. This deviates from NVCC,
528     // but allows us to handle things like constexpr constructors.
529     if (!AllowedInit &&
530         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) {
531       auto *Init = VD->getInit();
532       AllowedInit =
533           ((VD->getType()->isDependentType() || Init->isValueDependent()) &&
534            VD->isConstexpr()) ||
535           Init->isConstantInitializer(Context,
536                                       VD->getType()->isReferenceType());
537     }
538 
539     // Also make sure that destructor, if there is one, is empty.
540     if (AllowedInit)
541       if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
542         AllowedInit =
543             isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
544 
545     if (!AllowedInit) {
546       Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
547                                   ? diag::err_shared_var_init
548                                   : diag::err_dynamic_var_init)
549           << Init->getSourceRange();
550       VD->setInvalidDecl();
551     }
552   } else {
553     // This is a host-side global variable.  Check that the initializer is
554     // callable from the host side.
555     const FunctionDecl *InitFn = nullptr;
556     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
557       InitFn = CE->getConstructor();
558     } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
559       InitFn = CE->getDirectCallee();
560     }
561     if (InitFn) {
562       CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
563       if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
564         Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
565             << InitFnTarget << InitFn;
566         Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
567         VD->setInvalidDecl();
568       }
569     }
570   }
571 }
572 
573 // With -fcuda-host-device-constexpr, an unattributed constexpr function is
574 // treated as implicitly __host__ __device__, unless:
575 //  * it is a variadic function (device-side variadic functions are not
576 //    allowed), or
577 //  * a __device__ function with this signature was already declared, in which
578 //    case in which case we output an error, unless the __device__ decl is in a
579 //    system header, in which case we leave the constexpr function unattributed.
580 //
581 // In addition, all function decls are treated as __host__ __device__ when
582 // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
583 //   #pragma clang force_cuda_host_device_begin/end
584 // pair).
585 void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
586                                        const LookupResult &Previous) {
587   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
588 
589   if (ForceCUDAHostDeviceDepth > 0) {
590     if (!NewD->hasAttr<CUDAHostAttr>())
591       NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
592     if (!NewD->hasAttr<CUDADeviceAttr>())
593       NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
594     return;
595   }
596 
597   if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
598       NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
599       NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
600     return;
601 
602   // Is D a __device__ function with the same signature as NewD, ignoring CUDA
603   // attributes?
604   auto IsMatchingDeviceFn = [&](NamedDecl *D) {
605     if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
606       D = Using->getTargetDecl();
607     FunctionDecl *OldD = D->getAsFunction();
608     return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
609            !OldD->hasAttr<CUDAHostAttr>() &&
610            !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
611                        /* ConsiderCudaAttrs = */ false);
612   };
613   auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
614   if (It != Previous.end()) {
615     // We found a __device__ function with the same name and signature as NewD
616     // (ignoring CUDA attrs).  This is an error unless that function is defined
617     // in a system header, in which case we simply return without making NewD
618     // host+device.
619     NamedDecl *Match = *It;
620     if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
621       Diag(NewD->getLocation(),
622            diag::err_cuda_unattributed_constexpr_cannot_overload_device)
623           << NewD;
624       Diag(Match->getLocation(),
625            diag::note_cuda_conflicting_device_function_declared_here);
626     }
627     return;
628   }
629 
630   NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
631   NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
632 }
633 
634 void Sema::MaybeAddCUDAConstantAttr(VarDecl *VD) {
635   if (getLangOpts().CUDAIsDevice && VD->isConstexpr() &&
636       (VD->isFileVarDecl() || VD->isStaticDataMember())) {
637     VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
638   }
639 }
640 
641 Sema::DeviceDiagBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
642                                                    unsigned DiagID) {
643   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
644   DeviceDiagBuilder::Kind DiagKind = [this] {
645     switch (CurrentCUDATarget()) {
646     case CFT_Global:
647     case CFT_Device:
648       return DeviceDiagBuilder::K_Immediate;
649     case CFT_HostDevice:
650       // An HD function counts as host code if we're compiling for host, and
651       // device code if we're compiling for device.  Defer any errors in device
652       // mode until the function is known-emitted.
653       if (getLangOpts().CUDAIsDevice) {
654         return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
655                 FunctionEmissionStatus::Emitted)
656                    ? DeviceDiagBuilder::K_ImmediateWithCallStack
657                    : DeviceDiagBuilder::K_Deferred;
658       }
659       return DeviceDiagBuilder::K_Nop;
660 
661     default:
662       return DeviceDiagBuilder::K_Nop;
663     }
664   }();
665   return DeviceDiagBuilder(DiagKind, Loc, DiagID,
666                            dyn_cast<FunctionDecl>(CurContext), *this);
667 }
668 
669 Sema::DeviceDiagBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
670                                                  unsigned DiagID) {
671   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
672   DeviceDiagBuilder::Kind DiagKind = [this] {
673     switch (CurrentCUDATarget()) {
674     case CFT_Host:
675       return DeviceDiagBuilder::K_Immediate;
676     case CFT_HostDevice:
677       // An HD function counts as host code if we're compiling for host, and
678       // device code if we're compiling for device.  Defer any errors in device
679       // mode until the function is known-emitted.
680       if (getLangOpts().CUDAIsDevice)
681         return DeviceDiagBuilder::K_Nop;
682 
683       return (getEmissionStatus(cast<FunctionDecl>(CurContext)) ==
684               FunctionEmissionStatus::Emitted)
685                  ? DeviceDiagBuilder::K_ImmediateWithCallStack
686                  : DeviceDiagBuilder::K_Deferred;
687     default:
688       return DeviceDiagBuilder::K_Nop;
689     }
690   }();
691   return DeviceDiagBuilder(DiagKind, Loc, DiagID,
692                            dyn_cast<FunctionDecl>(CurContext), *this);
693 }
694 
695 bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
696   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
697   assert(Callee && "Callee may not be null.");
698 
699   auto &ExprEvalCtx = ExprEvalContexts.back();
700   if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
701     return true;
702 
703   // FIXME: Is bailing out early correct here?  Should we instead assume that
704   // the caller is a global initializer?
705   FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
706   if (!Caller)
707     return true;
708 
709   // If the caller is known-emitted, mark the callee as known-emitted.
710   // Otherwise, mark the call in our call graph so we can traverse it later.
711   bool CallerKnownEmitted =
712       getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted;
713   DeviceDiagBuilder::Kind DiagKind = [this, Caller, Callee,
714                                       CallerKnownEmitted] {
715     switch (IdentifyCUDAPreference(Caller, Callee)) {
716     case CFP_Never:
717       return DeviceDiagBuilder::K_Immediate;
718     case CFP_WrongSide:
719       assert(Caller && "WrongSide calls require a non-null caller");
720       // If we know the caller will be emitted, we know this wrong-side call
721       // will be emitted, so it's an immediate error.  Otherwise, defer the
722       // error until we know the caller is emitted.
723       return CallerKnownEmitted ? DeviceDiagBuilder::K_ImmediateWithCallStack
724                                 : DeviceDiagBuilder::K_Deferred;
725     default:
726       return DeviceDiagBuilder::K_Nop;
727     }
728   }();
729 
730   if (DiagKind == DeviceDiagBuilder::K_Nop)
731     return true;
732 
733   // Avoid emitting this error twice for the same location.  Using a hashtable
734   // like this is unfortunate, but because we must continue parsing as normal
735   // after encountering a deferred error, it's otherwise very tricky for us to
736   // ensure that we only emit this deferred error once.
737   if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
738     return true;
739 
740   DeviceDiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
741       << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
742   DeviceDiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
743                     Caller, *this)
744       << Callee;
745   return DiagKind != DeviceDiagBuilder::K_Immediate &&
746          DiagKind != DeviceDiagBuilder::K_ImmediateWithCallStack;
747 }
748 
749 void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
750   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
751   if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
752     return;
753   FunctionDecl *CurFn = dyn_cast<FunctionDecl>(CurContext);
754   if (!CurFn)
755     return;
756   CUDAFunctionTarget Target = IdentifyCUDATarget(CurFn);
757   if (Target == CFT_Global || Target == CFT_Device) {
758     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
759   } else if (Target == CFT_HostDevice) {
760     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
761     Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
762   }
763 }
764 
765 void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
766                                    const LookupResult &Previous) {
767   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
768   CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
769   for (NamedDecl *OldND : Previous) {
770     FunctionDecl *OldFD = OldND->getAsFunction();
771     if (!OldFD)
772       continue;
773 
774     CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
775     // Don't allow HD and global functions to overload other functions with the
776     // same signature.  We allow overloading based on CUDA attributes so that
777     // functions can have different implementations on the host and device, but
778     // HD/global functions "exist" in some sense on both the host and device, so
779     // should have the same implementation on both sides.
780     if (NewTarget != OldTarget &&
781         ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
782          (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
783         !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
784                     /* ConsiderCudaAttrs = */ false)) {
785       Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
786           << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
787       Diag(OldFD->getLocation(), diag::note_previous_declaration);
788       NewFD->setInvalidDecl();
789       break;
790     }
791   }
792 }
793 
794 template <typename AttrTy>
795 static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
796                               const FunctionDecl &TemplateFD) {
797   if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
798     AttrTy *Clone = Attribute->clone(S.Context);
799     Clone->setInherited(true);
800     FD->addAttr(Clone);
801   }
802 }
803 
804 void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
805                                   const FunctionTemplateDecl &TD) {
806   const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
807   copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
808   copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
809   copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
810 }
811 
812 std::string Sema::getCudaConfigureFuncName() const {
813   if (getLangOpts().HIP)
814     return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
815                                             : "hipConfigureCall";
816 
817   // New CUDA kernel launch sequence.
818   if (CudaFeatureEnabled(Context.getTargetInfo().getSDKVersion(),
819                          CudaFeature::CUDA_USES_NEW_LAUNCH))
820     return "__cudaPushCallConfiguration";
821 
822   // Legacy CUDA kernel configuration call
823   return "cudaConfigureCall";
824 }
825