SemaCUDA.cpp 30 KB

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