1 //===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// \brief This file implements semantic analysis for CUDA constructs.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Sema.h"
20 #include "clang/Sema/SemaDiagnostic.h"
21 #include "clang/Sema/SemaInternal.h"
22 #include "clang/Sema/Template.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/SmallVector.h"
25 using namespace clang;
26 
27 void Sema::PushForceCUDAHostDevice() {
28   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
29   ForceCUDAHostDeviceDepth++;
30 }
31 
32 bool Sema::PopForceCUDAHostDevice() {
33   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
34   if (ForceCUDAHostDeviceDepth == 0)
35     return false;
36   ForceCUDAHostDeviceDepth--;
37   return true;
38 }
39 
40 ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
41                                          MultiExprArg ExecConfig,
42                                          SourceLocation GGGLoc) {
43   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
44   if (!ConfigDecl)
45     return ExprError(
46         Diag(LLLLoc, diag::err_undeclared_var_use)
47         << (getLangOpts().HIP ? "hipConfigureCall" : "cudaConfigureCall"));
48   QualType ConfigQTy = ConfigDecl->getType();
49 
50   DeclRefExpr *ConfigDR = new (Context)
51       DeclRefExpr(ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
52   MarkFunctionReferenced(LLLLoc, ConfigDecl);
53 
54   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
55                        /*IsExecConfig=*/true);
56 }
57 
58 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const AttributeList *Attr) {
59   bool HasHostAttr = false;
60   bool HasDeviceAttr = false;
61   bool HasGlobalAttr = false;
62   bool HasInvalidTargetAttr = false;
63   while (Attr) {
64     switch(Attr->getKind()){
65     case AttributeList::AT_CUDAGlobal:
66       HasGlobalAttr = true;
67       break;
68     case AttributeList::AT_CUDAHost:
69       HasHostAttr = true;
70       break;
71     case AttributeList::AT_CUDADevice:
72       HasDeviceAttr = true;
73       break;
74     case AttributeList::AT_CUDAInvalidTarget:
75       HasInvalidTargetAttr = true;
76       break;
77     default:
78       break;
79     }
80     Attr = Attr->getNext();
81   }
82   if (HasInvalidTargetAttr)
83     return CFT_InvalidTarget;
84 
85   if (HasGlobalAttr)
86     return CFT_Global;
87 
88   if (HasHostAttr && HasDeviceAttr)
89     return CFT_HostDevice;
90 
91   if (HasDeviceAttr)
92     return CFT_Device;
93 
94   return CFT_Host;
95 }
96 
97 template <typename A>
98 static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr) {
99   return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
100            return isa<A>(Attribute) &&
101                   !(IgnoreImplicitAttr && Attribute->isImplicit());
102          });
103 }
104 
105 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
106 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D,
107                                                   bool IgnoreImplicitHDAttr) {
108   // Code that lives outside a function is run on the host.
109   if (D == nullptr)
110     return CFT_Host;
111 
112   if (D->hasAttr<CUDAInvalidTargetAttr>())
113     return CFT_InvalidTarget;
114 
115   if (D->hasAttr<CUDAGlobalAttr>())
116     return CFT_Global;
117 
118   if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
119     if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
120       return CFT_HostDevice;
121     return CFT_Device;
122   } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
123     return CFT_Host;
124   } else if (D->isImplicit() && !IgnoreImplicitHDAttr) {
125     // Some implicit declarations (like intrinsic functions) are not marked.
126     // Set the most lenient target on them for maximal flexibility.
127     return CFT_HostDevice;
128   }
129 
130   return CFT_Host;
131 }
132 
133 // * CUDA Call preference table
134 //
135 // F - from,
136 // T - to
137 // Ph - preference in host mode
138 // Pd - preference in device mode
139 // H  - handled in (x)
140 // Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
141 //
142 // | F  | T  | Ph  | Pd  |  H  |
143 // |----+----+-----+-----+-----+
144 // | d  | d  | N   | N   | (c) |
145 // | d  | g  | --  | --  | (a) |
146 // | d  | h  | --  | --  | (e) |
147 // | d  | hd | HD  | HD  | (b) |
148 // | g  | d  | N   | N   | (c) |
149 // | g  | g  | --  | --  | (a) |
150 // | g  | h  | --  | --  | (e) |
151 // | g  | hd | HD  | HD  | (b) |
152 // | h  | d  | --  | --  | (e) |
153 // | h  | g  | N   | N   | (c) |
154 // | h  | h  | N   | N   | (c) |
155 // | h  | hd | HD  | HD  | (b) |
156 // | hd | d  | WS  | SS  | (d) |
157 // | hd | g  | SS  | --  |(d/a)|
158 // | hd | h  | SS  | WS  | (d) |
159 // | hd | hd | HD  | HD  | (b) |
160 
161 Sema::CUDAFunctionPreference
162 Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
163                              const FunctionDecl *Callee) {
164   assert(Callee && "Callee must be valid.");
165   CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
166   CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
167 
168   // If one of the targets is invalid, the check always fails, no matter what
169   // the other target is.
170   if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
171     return CFP_Never;
172 
173   // (a) Can't call global from some contexts until we support CUDA's
174   // dynamic parallelism.
175   if (CalleeTarget == CFT_Global &&
176       (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
177     return CFP_Never;
178 
179   // (b) Calling HostDevice is OK for everyone.
180   if (CalleeTarget == CFT_HostDevice)
181     return CFP_HostDevice;
182 
183   // (c) Best case scenarios
184   if (CalleeTarget == CallerTarget ||
185       (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
186       (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
187     return CFP_Native;
188 
189   // (d) HostDevice behavior depends on compilation mode.
190   if (CallerTarget == CFT_HostDevice) {
191     // It's OK to call a compilation-mode matching function from an HD one.
192     if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
193         (!getLangOpts().CUDAIsDevice &&
194          (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
195       return CFP_SameSide;
196 
197     // Calls from HD to non-mode-matching functions (i.e., to host functions
198     // when compiling in device mode or to device functions when compiling in
199     // host mode) are allowed at the sema level, but eventually rejected if
200     // they're ever codegened.  TODO: Reject said calls earlier.
201     return CFP_WrongSide;
202   }
203 
204   // (e) Calling across device/host boundary is not something you should do.
205   if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
206       (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
207       (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
208     return CFP_Never;
209 
210   llvm_unreachable("All cases should've been handled by now.");
211 }
212 
213 void Sema::EraseUnwantedCUDAMatches(
214     const FunctionDecl *Caller,
215     SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
216   if (Matches.size() <= 1)
217     return;
218 
219   using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
220 
221   // Gets the CUDA function preference for a call from Caller to Match.
222   auto GetCFP = [&](const Pair &Match) {
223     return IdentifyCUDAPreference(Caller, Match.second);
224   };
225 
226   // Find the best call preference among the functions in Matches.
227   CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
228       Matches.begin(), Matches.end(),
229       [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
230 
231   // Erase all functions with lower priority.
232   llvm::erase_if(Matches,
233                  [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
234 }
235 
236 /// When an implicitly-declared special member has to invoke more than one
237 /// base/field special member, conflicts may occur in the targets of these
238 /// members. For example, if one base's member __host__ and another's is
239 /// __device__, it's a conflict.
240 /// This function figures out if the given targets \param Target1 and
241 /// \param Target2 conflict, and if they do not it fills in
242 /// \param ResolvedTarget with a target that resolves for both calls.
243 /// \return true if there's a conflict, false otherwise.
244 static bool
245 resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
246                                 Sema::CUDAFunctionTarget Target2,
247                                 Sema::CUDAFunctionTarget *ResolvedTarget) {
248   // Only free functions and static member functions may be global.
249   assert(Target1 != Sema::CFT_Global);
250   assert(Target2 != Sema::CFT_Global);
251 
252   if (Target1 == Sema::CFT_HostDevice) {
253     *ResolvedTarget = Target2;
254   } else if (Target2 == Sema::CFT_HostDevice) {
255     *ResolvedTarget = Target1;
256   } else if (Target1 != Target2) {
257     return true;
258   } else {
259     *ResolvedTarget = Target1;
260   }
261 
262   return false;
263 }
264 
265 bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
266                                                    CXXSpecialMember CSM,
267                                                    CXXMethodDecl *MemberDecl,
268                                                    bool ConstRHS,
269                                                    bool Diagnose) {
270   llvm::Optional<CUDAFunctionTarget> InferredTarget;
271 
272   // We're going to invoke special member lookup; mark that these special
273   // members are called from this one, and not from its caller.
274   ContextRAII MethodContext(*this, MemberDecl);
275 
276   // Look for special members in base classes that should be invoked from here.
277   // Infer the target of this member base on the ones it should call.
278   // Skip direct and indirect virtual bases for abstract classes.
279   llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
280   for (const auto &B : ClassDecl->bases()) {
281     if (!B.isVirtual()) {
282       Bases.push_back(&B);
283     }
284   }
285 
286   if (!ClassDecl->isAbstract()) {
287     for (const auto &VB : ClassDecl->vbases()) {
288       Bases.push_back(&VB);
289     }
290   }
291 
292   for (const auto *B : Bases) {
293     const RecordType *BaseType = B->getType()->getAs<RecordType>();
294     if (!BaseType) {
295       continue;
296     }
297 
298     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
299     Sema::SpecialMemberOverloadResult SMOR =
300         LookupSpecialMember(BaseClassDecl, CSM,
301                             /* ConstArg */ ConstRHS,
302                             /* VolatileArg */ false,
303                             /* RValueThis */ false,
304                             /* ConstThis */ false,
305                             /* VolatileThis */ false);
306 
307     if (!SMOR.getMethod())
308       continue;
309 
310     CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
311     if (!InferredTarget.hasValue()) {
312       InferredTarget = BaseMethodTarget;
313     } else {
314       bool ResolutionError = resolveCalleeCUDATargetConflict(
315           InferredTarget.getValue(), BaseMethodTarget,
316           InferredTarget.getPointer());
317       if (ResolutionError) {
318         if (Diagnose) {
319           Diag(ClassDecl->getLocation(),
320                diag::note_implicit_member_target_infer_collision)
321               << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
322         }
323         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
324         return true;
325       }
326     }
327   }
328 
329   // Same as for bases, but now for special members of fields.
330   for (const auto *F : ClassDecl->fields()) {
331     if (F->isInvalidDecl()) {
332       continue;
333     }
334 
335     const RecordType *FieldType =
336         Context.getBaseElementType(F->getType())->getAs<RecordType>();
337     if (!FieldType) {
338       continue;
339     }
340 
341     CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
342     Sema::SpecialMemberOverloadResult SMOR =
343         LookupSpecialMember(FieldRecDecl, CSM,
344                             /* ConstArg */ ConstRHS && !F->isMutable(),
345                             /* VolatileArg */ false,
346                             /* RValueThis */ false,
347                             /* ConstThis */ false,
348                             /* VolatileThis */ false);
349 
350     if (!SMOR.getMethod())
351       continue;
352 
353     CUDAFunctionTarget FieldMethodTarget =
354         IdentifyCUDATarget(SMOR.getMethod());
355     if (!InferredTarget.hasValue()) {
356       InferredTarget = FieldMethodTarget;
357     } else {
358       bool ResolutionError = resolveCalleeCUDATargetConflict(
359           InferredTarget.getValue(), FieldMethodTarget,
360           InferredTarget.getPointer());
361       if (ResolutionError) {
362         if (Diagnose) {
363           Diag(ClassDecl->getLocation(),
364                diag::note_implicit_member_target_infer_collision)
365               << (unsigned)CSM << InferredTarget.getValue()
366               << FieldMethodTarget;
367         }
368         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
369         return true;
370       }
371     }
372   }
373 
374   if (InferredTarget.hasValue()) {
375     if (InferredTarget.getValue() == CFT_Device) {
376       MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
377     } else if (InferredTarget.getValue() == CFT_Host) {
378       MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
379     } else {
380       MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
381       MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
382     }
383   } else {
384     // If no target was inferred, mark this member as __host__ __device__;
385     // it's the least restrictive option that can be invoked from any target.
386     MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
387     MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
388   }
389 
390   return false;
391 }
392 
393 bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
394   if (!CD->isDefined() && CD->isTemplateInstantiation())
395     InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
396 
397   // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
398   // empty at a point in the translation unit, if it is either a
399   // trivial constructor
400   if (CD->isTrivial())
401     return true;
402 
403   // ... or it satisfies all of the following conditions:
404   // The constructor function has been defined.
405   // The constructor function has no parameters,
406   // and the function body is an empty compound statement.
407   if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
408     return false;
409 
410   // Its class has no virtual functions and no virtual base classes.
411   if (CD->getParent()->isDynamicClass())
412     return false;
413 
414   // The only form of initializer allowed is an empty constructor.
415   // This will recursively check all base classes and member initializers
416   if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
417         if (const CXXConstructExpr *CE =
418                 dyn_cast<CXXConstructExpr>(CI->getInit()))
419           return isEmptyCudaConstructor(Loc, CE->getConstructor());
420         return false;
421       }))
422     return false;
423 
424   return true;
425 }
426 
427 bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
428   // No destructor -> no problem.
429   if (!DD)
430     return true;
431 
432   if (!DD->isDefined() && DD->isTemplateInstantiation())
433     InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
434 
435   // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
436   // empty at a point in the translation unit, if it is either a
437   // trivial constructor
438   if (DD->isTrivial())
439     return true;
440 
441   // ... or it satisfies all of the following conditions:
442   // The destructor function has been defined.
443   // and the function body is an empty compound statement.
444   if (!DD->hasTrivialBody())
445     return false;
446 
447   const CXXRecordDecl *ClassDecl = DD->getParent();
448 
449   // Its class has no virtual functions and no virtual base classes.
450   if (ClassDecl->isDynamicClass())
451     return false;
452 
453   // Only empty destructors are allowed. This will recursively check
454   // destructors for all base classes...
455   if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
456         if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
457           return isEmptyCudaDestructor(Loc, RD->getDestructor());
458         return true;
459       }))
460     return false;
461 
462   // ... and member fields.
463   if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
464         if (CXXRecordDecl *RD = Field->getType()
465                                     ->getBaseElementTypeUnsafe()
466                                     ->getAsCXXRecordDecl())
467           return isEmptyCudaDestructor(Loc, RD->getDestructor());
468         return true;
469       }))
470     return false;
471 
472   return true;
473 }
474 
475 // With -fcuda-host-device-constexpr, an unattributed constexpr function is
476 // treated as implicitly __host__ __device__, unless:
477 //  * it is a variadic function (device-side variadic functions are not
478 //    allowed), or
479 //  * a __device__ function with this signature was already declared, in which
480 //    case in which case we output an error, unless the __device__ decl is in a
481 //    system header, in which case we leave the constexpr function unattributed.
482 //
483 // In addition, all function decls are treated as __host__ __device__ when
484 // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
485 //   #pragma clang force_cuda_host_device_begin/end
486 // pair).
487 void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
488                                        const LookupResult &Previous) {
489   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
490 
491   if (ForceCUDAHostDeviceDepth > 0) {
492     if (!NewD->hasAttr<CUDAHostAttr>())
493       NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
494     if (!NewD->hasAttr<CUDADeviceAttr>())
495       NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
496     return;
497   }
498 
499   if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
500       NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
501       NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
502     return;
503 
504   // Is D a __device__ function with the same signature as NewD, ignoring CUDA
505   // attributes?
506   auto IsMatchingDeviceFn = [&](NamedDecl *D) {
507     if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
508       D = Using->getTargetDecl();
509     FunctionDecl *OldD = D->getAsFunction();
510     return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
511            !OldD->hasAttr<CUDAHostAttr>() &&
512            !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
513                        /* ConsiderCudaAttrs = */ false);
514   };
515   auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
516   if (It != Previous.end()) {
517     // We found a __device__ function with the same name and signature as NewD
518     // (ignoring CUDA attrs).  This is an error unless that function is defined
519     // in a system header, in which case we simply return without making NewD
520     // host+device.
521     NamedDecl *Match = *It;
522     if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
523       Diag(NewD->getLocation(),
524            diag::err_cuda_unattributed_constexpr_cannot_overload_device)
525           << NewD;
526       Diag(Match->getLocation(),
527            diag::note_cuda_conflicting_device_function_declared_here);
528     }
529     return;
530   }
531 
532   NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
533   NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
534 }
535 
536 // In CUDA, there are some constructs which may appear in semantically-valid
537 // code, but trigger errors if we ever generate code for the function in which
538 // they appear.  Essentially every construct you're not allowed to use on the
539 // device falls into this category, because you are allowed to use these
540 // constructs in a __host__ __device__ function, but only if that function is
541 // never codegen'ed on the device.
542 //
543 // To handle semantic checking for these constructs, we keep track of the set of
544 // functions we know will be emitted, either because we could tell a priori that
545 // they would be emitted, or because they were transitively called by a
546 // known-emitted function.
547 //
548 // We also keep a partial call graph of which not-known-emitted functions call
549 // which other not-known-emitted functions.
550 //
551 // When we see something which is illegal if the current function is emitted
552 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
553 // CheckCUDACall), we first check if the current function is known-emitted.  If
554 // so, we immediately output the diagnostic.
555 //
556 // Otherwise, we "defer" the diagnostic.  It sits in Sema::CUDADeferredDiags
557 // until we discover that the function is known-emitted, at which point we take
558 // it out of this map and emit the diagnostic.
559 
560 Sema::CUDADiagBuilder::CUDADiagBuilder(Kind K, SourceLocation Loc,
561                                        unsigned DiagID, FunctionDecl *Fn,
562                                        Sema &S)
563     : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
564       ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
565   switch (K) {
566   case K_Nop:
567     break;
568   case K_Immediate:
569   case K_ImmediateWithCallStack:
570     ImmediateDiag.emplace(S.Diag(Loc, DiagID));
571     break;
572   case K_Deferred:
573     assert(Fn && "Must have a function to attach the deferred diag to.");
574     PartialDiag.emplace(S.PDiag(DiagID));
575     break;
576   }
577 }
578 
579 // Print notes showing how we can reach FD starting from an a priori
580 // known-callable function.
581 static void EmitCallStackNotes(Sema &S, FunctionDecl *FD) {
582   auto FnIt = S.CUDAKnownEmittedFns.find(FD);
583   while (FnIt != S.CUDAKnownEmittedFns.end()) {
584     DiagnosticBuilder Builder(
585         S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
586     Builder << FnIt->second.FD;
587     Builder.setForceEmit();
588 
589     FnIt = S.CUDAKnownEmittedFns.find(FnIt->second.FD);
590   }
591 }
592 
593 Sema::CUDADiagBuilder::~CUDADiagBuilder() {
594   if (ImmediateDiag) {
595     // Emit our diagnostic and, if it was a warning or error, output a callstack
596     // if Fn isn't a priori known-emitted.
597     bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
598                                 DiagID, Loc) >= DiagnosticsEngine::Warning;
599     ImmediateDiag.reset(); // Emit the immediate diag.
600     if (IsWarningOrError && ShowCallStack)
601       EmitCallStackNotes(S, Fn);
602   } else if (PartialDiag) {
603     assert(ShowCallStack && "Must always show call stack for deferred diags.");
604     S.CUDADeferredDiags[Fn].push_back({Loc, std::move(*PartialDiag)});
605   }
606 }
607 
608 // Do we know that we will eventually codegen the given function?
609 static bool IsKnownEmitted(Sema &S, FunctionDecl *FD) {
610   // Templates are emitted when they're instantiated.
611   if (FD->isDependentContext())
612     return false;
613 
614   // When compiling for device, host functions are never emitted.  Similarly,
615   // when compiling for host, device and global functions are never emitted.
616   // (Technically, we do emit a host-side stub for global functions, but this
617   // doesn't count for our purposes here.)
618   Sema::CUDAFunctionTarget T = S.IdentifyCUDATarget(FD);
619   if (S.getLangOpts().CUDAIsDevice && T == Sema::CFT_Host)
620     return false;
621   if (!S.getLangOpts().CUDAIsDevice &&
622       (T == Sema::CFT_Device || T == Sema::CFT_Global))
623     return false;
624 
625   // Check whether this function is externally visible -- if so, it's
626   // known-emitted.
627   //
628   // We have to check the GVA linkage of the function's *definition* -- if we
629   // only have a declaration, we don't know whether or not the function will be
630   // emitted, because (say) the definition could include "inline".
631   FunctionDecl *Def = FD->getDefinition();
632 
633   if (Def &&
634       !isDiscardableGVALinkage(S.getASTContext().GetGVALinkageForFunction(Def)))
635     return true;
636 
637   // Otherwise, the function is known-emitted if it's in our set of
638   // known-emitted functions.
639   return S.CUDAKnownEmittedFns.count(FD) > 0;
640 }
641 
642 Sema::CUDADiagBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
643                                                  unsigned DiagID) {
644   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
645   CUDADiagBuilder::Kind DiagKind = [&] {
646     switch (CurrentCUDATarget()) {
647     case CFT_Global:
648     case CFT_Device:
649       return CUDADiagBuilder::K_Immediate;
650     case CFT_HostDevice:
651       // An HD function counts as host code if we're compiling for host, and
652       // device code if we're compiling for device.  Defer any errors in device
653       // mode until the function is known-emitted.
654       if (getLangOpts().CUDAIsDevice) {
655         return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
656                    ? CUDADiagBuilder::K_ImmediateWithCallStack
657                    : CUDADiagBuilder::K_Deferred;
658       }
659       return CUDADiagBuilder::K_Nop;
660 
661     default:
662       return CUDADiagBuilder::K_Nop;
663     }
664   }();
665   return CUDADiagBuilder(DiagKind, Loc, DiagID,
666                          dyn_cast<FunctionDecl>(CurContext), *this);
667 }
668 
669 Sema::CUDADiagBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
670                                                unsigned DiagID) {
671   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
672   CUDADiagBuilder::Kind DiagKind = [&] {
673     switch (CurrentCUDATarget()) {
674     case CFT_Host:
675       return CUDADiagBuilder::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 CUDADiagBuilder::K_Nop;
682 
683       return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
684                  ? CUDADiagBuilder::K_ImmediateWithCallStack
685                  : CUDADiagBuilder::K_Deferred;
686     default:
687       return CUDADiagBuilder::K_Nop;
688     }
689   }();
690   return CUDADiagBuilder(DiagKind, Loc, DiagID,
691                          dyn_cast<FunctionDecl>(CurContext), *this);
692 }
693 
694 // Emit any deferred diagnostics for FD and erase them from the map in which
695 // they're stored.
696 static void EmitDeferredDiags(Sema &S, FunctionDecl *FD) {
697   auto It = S.CUDADeferredDiags.find(FD);
698   if (It == S.CUDADeferredDiags.end())
699     return;
700   bool HasWarningOrError = false;
701   for (PartialDiagnosticAt &PDAt : It->second) {
702     const SourceLocation &Loc = PDAt.first;
703     const PartialDiagnostic &PD = PDAt.second;
704     HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel(
705                              PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning;
706     DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
707     Builder.setForceEmit();
708     PD.Emit(Builder);
709   }
710   S.CUDADeferredDiags.erase(It);
711 
712   // FIXME: Should this be called after every warning/error emitted in the loop
713   // above, instead of just once per function?  That would be consistent with
714   // how we handle immediate errors, but it also seems like a bit much.
715   if (HasWarningOrError)
716     EmitCallStackNotes(S, FD);
717 }
718 
719 // Indicate that this function (and thus everything it transtively calls) will
720 // be codegen'ed, and emit any deferred diagnostics on this function and its
721 // (transitive) callees.
722 static void MarkKnownEmitted(Sema &S, FunctionDecl *OrigCaller,
723                              FunctionDecl *OrigCallee, SourceLocation OrigLoc) {
724   // Nothing to do if we already know that FD is emitted.
725   if (IsKnownEmitted(S, OrigCallee)) {
726     assert(!S.CUDACallGraph.count(OrigCallee));
727     return;
728   }
729 
730   // We've just discovered that OrigCallee is known-emitted.  Walk our call
731   // graph to see what else we can now discover also must be emitted.
732 
733   struct CallInfo {
734     FunctionDecl *Caller;
735     FunctionDecl *Callee;
736     SourceLocation Loc;
737   };
738   llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}};
739   llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen;
740   Seen.insert(OrigCallee);
741   while (!Worklist.empty()) {
742     CallInfo C = Worklist.pop_back_val();
743     assert(!IsKnownEmitted(S, C.Callee) &&
744            "Worklist should not contain known-emitted functions.");
745     S.CUDAKnownEmittedFns[C.Callee] = {C.Caller, C.Loc};
746     EmitDeferredDiags(S, C.Callee);
747 
748     // If this is a template instantiation, explore its callgraph as well:
749     // Non-dependent calls are part of the template's callgraph, while dependent
750     // calls are part of to the instantiation's call graph.
751     if (auto *Templ = C.Callee->getPrimaryTemplate()) {
752       FunctionDecl *TemplFD = Templ->getAsFunction();
753       if (!Seen.count(TemplFD) && !S.CUDAKnownEmittedFns.count(TemplFD)) {
754         Seen.insert(TemplFD);
755         Worklist.push_back(
756             {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc});
757       }
758     }
759 
760     // Add all functions called by Callee to our worklist.
761     auto CGIt = S.CUDACallGraph.find(C.Callee);
762     if (CGIt == S.CUDACallGraph.end())
763       continue;
764 
765     for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc :
766          CGIt->second) {
767       FunctionDecl *NewCallee = FDLoc.first;
768       SourceLocation CallLoc = FDLoc.second;
769       if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee))
770         continue;
771       Seen.insert(NewCallee);
772       Worklist.push_back(
773           {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc});
774     }
775 
776     // C.Callee is now known-emitted, so we no longer need to maintain its list
777     // of callees in CUDACallGraph.
778     S.CUDACallGraph.erase(CGIt);
779   }
780 }
781 
782 bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
783   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
784   assert(Callee && "Callee may not be null.");
785   // FIXME: Is bailing out early correct here?  Should we instead assume that
786   // the caller is a global initializer?
787   FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
788   if (!Caller)
789     return true;
790 
791   // If the caller is known-emitted, mark the callee as known-emitted.
792   // Otherwise, mark the call in our call graph so we can traverse it later.
793   bool CallerKnownEmitted = IsKnownEmitted(*this, Caller);
794   if (CallerKnownEmitted) {
795     // Host-side references to a __global__ function refer to the stub, so the
796     // function itself is never emitted and therefore should not be marked.
797     if (getLangOpts().CUDAIsDevice || IdentifyCUDATarget(Callee) != CFT_Global)
798       MarkKnownEmitted(*this, Caller, Callee, Loc);
799   } else {
800     // If we have
801     //   host fn calls kernel fn calls host+device,
802     // the HD function does not get instantiated on the host.  We model this by
803     // omitting at the call to the kernel from the callgraph.  This ensures
804     // that, when compiling for host, only HD functions actually called from the
805     // host get marked as known-emitted.
806     if (getLangOpts().CUDAIsDevice || IdentifyCUDATarget(Callee) != CFT_Global)
807       CUDACallGraph[Caller].insert({Callee, Loc});
808   }
809 
810   CUDADiagBuilder::Kind DiagKind = [&] {
811     switch (IdentifyCUDAPreference(Caller, Callee)) {
812     case CFP_Never:
813       return CUDADiagBuilder::K_Immediate;
814     case CFP_WrongSide:
815       assert(Caller && "WrongSide calls require a non-null caller");
816       // If we know the caller will be emitted, we know this wrong-side call
817       // will be emitted, so it's an immediate error.  Otherwise, defer the
818       // error until we know the caller is emitted.
819       return CallerKnownEmitted ? CUDADiagBuilder::K_ImmediateWithCallStack
820                                 : CUDADiagBuilder::K_Deferred;
821     default:
822       return CUDADiagBuilder::K_Nop;
823     }
824   }();
825 
826   if (DiagKind == CUDADiagBuilder::K_Nop)
827     return true;
828 
829   // Avoid emitting this error twice for the same location.  Using a hashtable
830   // like this is unfortunate, but because we must continue parsing as normal
831   // after encountering a deferred error, it's otherwise very tricky for us to
832   // ensure that we only emit this deferred error once.
833   if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
834     return true;
835 
836   CUDADiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
837       << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
838   CUDADiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
839                   Caller, *this)
840       << Callee;
841   return DiagKind != CUDADiagBuilder::K_Immediate &&
842          DiagKind != CUDADiagBuilder::K_ImmediateWithCallStack;
843 }
844 
845 void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
846   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
847   if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
848     return;
849   FunctionDecl *CurFn = dyn_cast<FunctionDecl>(CurContext);
850   if (!CurFn)
851     return;
852   CUDAFunctionTarget Target = IdentifyCUDATarget(CurFn);
853   if (Target == CFT_Global || Target == CFT_Device) {
854     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
855   } else if (Target == CFT_HostDevice) {
856     Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
857     Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
858   }
859 }
860 
861 void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
862                                    const LookupResult &Previous) {
863   assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
864   CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
865   for (NamedDecl *OldND : Previous) {
866     FunctionDecl *OldFD = OldND->getAsFunction();
867     if (!OldFD)
868       continue;
869 
870     CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
871     // Don't allow HD and global functions to overload other functions with the
872     // same signature.  We allow overloading based on CUDA attributes so that
873     // functions can have different implementations on the host and device, but
874     // HD/global functions "exist" in some sense on both the host and device, so
875     // should have the same implementation on both sides.
876     if (NewTarget != OldTarget &&
877         ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
878          (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
879         !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
880                     /* ConsiderCudaAttrs = */ false)) {
881       Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
882           << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
883       Diag(OldFD->getLocation(), diag::note_previous_declaration);
884       NewFD->setInvalidDecl();
885       break;
886     }
887   }
888 }
889 
890 template <typename AttrTy>
891 static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
892                               const FunctionDecl &TemplateFD) {
893   if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
894     AttrTy *Clone = Attribute->clone(S.Context);
895     Clone->setInherited(true);
896     FD->addAttr(Clone);
897   }
898 }
899 
900 void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
901                                   const FunctionTemplateDecl &TD) {
902   const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
903   copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
904   copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
905   copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
906 }
907