SemaCUDA.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. llvm::Optional<CUDAFunctionTarget> InferredTarget;
  234. // We're going to invoke special member lookup; mark that these special
  235. // members are called from this one, and not from its caller.
  236. ContextRAII MethodContext(*this, MemberDecl);
  237. // Look for special members in base classes that should be invoked from here.
  238. // Infer the target of this member base on the ones it should call.
  239. // Skip direct and indirect virtual bases for abstract classes.
  240. llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
  241. for (const auto &B : ClassDecl->bases()) {
  242. if (!B.isVirtual()) {
  243. Bases.push_back(&B);
  244. }
  245. }
  246. if (!ClassDecl->isAbstract()) {
  247. for (const auto &VB : ClassDecl->vbases()) {
  248. Bases.push_back(&VB);
  249. }
  250. }
  251. for (const auto *B : Bases) {
  252. const RecordType *BaseType = B->getType()->getAs<RecordType>();
  253. if (!BaseType) {
  254. continue;
  255. }
  256. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  257. Sema::SpecialMemberOverloadResult SMOR =
  258. LookupSpecialMember(BaseClassDecl, CSM,
  259. /* ConstArg */ ConstRHS,
  260. /* VolatileArg */ false,
  261. /* RValueThis */ false,
  262. /* ConstThis */ false,
  263. /* VolatileThis */ false);
  264. if (!SMOR.getMethod())
  265. continue;
  266. CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
  267. if (!InferredTarget.hasValue()) {
  268. InferredTarget = BaseMethodTarget;
  269. } else {
  270. bool ResolutionError = resolveCalleeCUDATargetConflict(
  271. InferredTarget.getValue(), BaseMethodTarget,
  272. InferredTarget.getPointer());
  273. if (ResolutionError) {
  274. if (Diagnose) {
  275. Diag(ClassDecl->getLocation(),
  276. diag::note_implicit_member_target_infer_collision)
  277. << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
  278. }
  279. MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
  280. return true;
  281. }
  282. }
  283. }
  284. // Same as for bases, but now for special members of fields.
  285. for (const auto *F : ClassDecl->fields()) {
  286. if (F->isInvalidDecl()) {
  287. continue;
  288. }
  289. const RecordType *FieldType =
  290. Context.getBaseElementType(F->getType())->getAs<RecordType>();
  291. if (!FieldType) {
  292. continue;
  293. }
  294. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
  295. Sema::SpecialMemberOverloadResult SMOR =
  296. LookupSpecialMember(FieldRecDecl, CSM,
  297. /* ConstArg */ ConstRHS && !F->isMutable(),
  298. /* VolatileArg */ false,
  299. /* RValueThis */ false,
  300. /* ConstThis */ false,
  301. /* VolatileThis */ false);
  302. if (!SMOR.getMethod())
  303. continue;
  304. CUDAFunctionTarget FieldMethodTarget =
  305. IdentifyCUDATarget(SMOR.getMethod());
  306. if (!InferredTarget.hasValue()) {
  307. InferredTarget = FieldMethodTarget;
  308. } else {
  309. bool ResolutionError = resolveCalleeCUDATargetConflict(
  310. InferredTarget.getValue(), FieldMethodTarget,
  311. InferredTarget.getPointer());
  312. if (ResolutionError) {
  313. if (Diagnose) {
  314. Diag(ClassDecl->getLocation(),
  315. diag::note_implicit_member_target_infer_collision)
  316. << (unsigned)CSM << InferredTarget.getValue()
  317. << FieldMethodTarget;
  318. }
  319. MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
  320. return true;
  321. }
  322. }
  323. }
  324. if (InferredTarget.hasValue()) {
  325. if (InferredTarget.getValue() == CFT_Device) {
  326. MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  327. } else if (InferredTarget.getValue() == CFT_Host) {
  328. MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
  329. } else {
  330. MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  331. MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
  332. }
  333. } else {
  334. // If no target was inferred, mark this member as __host__ __device__;
  335. // it's the least restrictive option that can be invoked from any target.
  336. MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  337. MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
  338. }
  339. return false;
  340. }
  341. bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
  342. if (!CD->isDefined() && CD->isTemplateInstantiation())
  343. InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
  344. // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
  345. // empty at a point in the translation unit, if it is either a
  346. // trivial constructor
  347. if (CD->isTrivial())
  348. return true;
  349. // ... or it satisfies all of the following conditions:
  350. // The constructor function has been defined.
  351. // The constructor function has no parameters,
  352. // and the function body is an empty compound statement.
  353. if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
  354. return false;
  355. // Its class has no virtual functions and no virtual base classes.
  356. if (CD->getParent()->isDynamicClass())
  357. return false;
  358. // The only form of initializer allowed is an empty constructor.
  359. // This will recursively check all base classes and member initializers
  360. if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
  361. if (const CXXConstructExpr *CE =
  362. dyn_cast<CXXConstructExpr>(CI->getInit()))
  363. return isEmptyCudaConstructor(Loc, CE->getConstructor());
  364. return false;
  365. }))
  366. return false;
  367. return true;
  368. }
  369. bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
  370. // No destructor -> no problem.
  371. if (!DD)
  372. return true;
  373. if (!DD->isDefined() && DD->isTemplateInstantiation())
  374. InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
  375. // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
  376. // empty at a point in the translation unit, if it is either a
  377. // trivial constructor
  378. if (DD->isTrivial())
  379. return true;
  380. // ... or it satisfies all of the following conditions:
  381. // The destructor function has been defined.
  382. // and the function body is an empty compound statement.
  383. if (!DD->hasTrivialBody())
  384. return false;
  385. const CXXRecordDecl *ClassDecl = DD->getParent();
  386. // Its class has no virtual functions and no virtual base classes.
  387. if (ClassDecl->isDynamicClass())
  388. return false;
  389. // Only empty destructors are allowed. This will recursively check
  390. // destructors for all base classes...
  391. if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
  392. if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
  393. return isEmptyCudaDestructor(Loc, RD->getDestructor());
  394. return true;
  395. }))
  396. return false;
  397. // ... and member fields.
  398. if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
  399. if (CXXRecordDecl *RD = Field->getType()
  400. ->getBaseElementTypeUnsafe()
  401. ->getAsCXXRecordDecl())
  402. return isEmptyCudaDestructor(Loc, RD->getDestructor());
  403. return true;
  404. }))
  405. return false;
  406. return true;
  407. }
  408. void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
  409. if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage())
  410. return;
  411. const Expr *Init = VD->getInit();
  412. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  413. VD->hasAttr<CUDASharedAttr>()) {
  414. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  415. bool AllowedInit = false;
  416. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  417. AllowedInit =
  418. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  419. // We'll allow constant initializers even if it's a non-empty
  420. // constructor according to CUDA rules. This deviates from NVCC,
  421. // but allows us to handle things like constexpr constructors.
  422. if (!AllowedInit &&
  423. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  424. AllowedInit = VD->getInit()->isConstantInitializer(
  425. Context, VD->getType()->isReferenceType());
  426. // Also make sure that destructor, if there is one, is empty.
  427. if (AllowedInit)
  428. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  429. AllowedInit =
  430. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  431. if (!AllowedInit) {
  432. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  433. ? diag::err_shared_var_init
  434. : diag::err_dynamic_var_init)
  435. << Init->getSourceRange();
  436. VD->setInvalidDecl();
  437. }
  438. } else {
  439. // This is a host-side global variable. Check that the initializer is
  440. // callable from the host side.
  441. const FunctionDecl *InitFn = nullptr;
  442. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  443. InitFn = CE->getConstructor();
  444. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  445. InitFn = CE->getDirectCallee();
  446. }
  447. if (InitFn) {
  448. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  449. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  450. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  451. << InitFnTarget << InitFn;
  452. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  453. VD->setInvalidDecl();
  454. }
  455. }
  456. }
  457. }
  458. // With -fcuda-host-device-constexpr, an unattributed constexpr function is
  459. // treated as implicitly __host__ __device__, unless:
  460. // * it is a variadic function (device-side variadic functions are not
  461. // allowed), or
  462. // * a __device__ function with this signature was already declared, in which
  463. // case in which case we output an error, unless the __device__ decl is in a
  464. // system header, in which case we leave the constexpr function unattributed.
  465. //
  466. // In addition, all function decls are treated as __host__ __device__ when
  467. // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
  468. // #pragma clang force_cuda_host_device_begin/end
  469. // pair).
  470. void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
  471. const LookupResult &Previous) {
  472. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  473. if (ForceCUDAHostDeviceDepth > 0) {
  474. if (!NewD->hasAttr<CUDAHostAttr>())
  475. NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
  476. if (!NewD->hasAttr<CUDADeviceAttr>())
  477. NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  478. return;
  479. }
  480. if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
  481. NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
  482. NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
  483. return;
  484. // Is D a __device__ function with the same signature as NewD, ignoring CUDA
  485. // attributes?
  486. auto IsMatchingDeviceFn = [&](NamedDecl *D) {
  487. if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
  488. D = Using->getTargetDecl();
  489. FunctionDecl *OldD = D->getAsFunction();
  490. return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
  491. !OldD->hasAttr<CUDAHostAttr>() &&
  492. !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
  493. /* ConsiderCudaAttrs = */ false);
  494. };
  495. auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
  496. if (It != Previous.end()) {
  497. // We found a __device__ function with the same name and signature as NewD
  498. // (ignoring CUDA attrs). This is an error unless that function is defined
  499. // in a system header, in which case we simply return without making NewD
  500. // host+device.
  501. NamedDecl *Match = *It;
  502. if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
  503. Diag(NewD->getLocation(),
  504. diag::err_cuda_unattributed_constexpr_cannot_overload_device)
  505. << NewD;
  506. Diag(Match->getLocation(),
  507. diag::note_cuda_conflicting_device_function_declared_here);
  508. }
  509. return;
  510. }
  511. NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
  512. NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  513. }
  514. // Do we know that we will eventually codegen the given function?
  515. static bool IsKnownEmitted(Sema &S, FunctionDecl *FD) {
  516. // Templates are emitted when they're instantiated.
  517. if (FD->isDependentContext())
  518. return false;
  519. // When compiling for device, host functions are never emitted. Similarly,
  520. // when compiling for host, device and global functions are never emitted.
  521. // (Technically, we do emit a host-side stub for global functions, but this
  522. // doesn't count for our purposes here.)
  523. Sema::CUDAFunctionTarget T = S.IdentifyCUDATarget(FD);
  524. if (S.getLangOpts().CUDAIsDevice && T == Sema::CFT_Host)
  525. return false;
  526. if (!S.getLangOpts().CUDAIsDevice &&
  527. (T == Sema::CFT_Device || T == Sema::CFT_Global))
  528. return false;
  529. // Check whether this function is externally visible -- if so, it's
  530. // known-emitted.
  531. //
  532. // We have to check the GVA linkage of the function's *definition* -- if we
  533. // only have a declaration, we don't know whether or not the function will be
  534. // emitted, because (say) the definition could include "inline".
  535. FunctionDecl *Def = FD->getDefinition();
  536. if (Def &&
  537. !isDiscardableGVALinkage(S.getASTContext().GetGVALinkageForFunction(Def)))
  538. return true;
  539. // Otherwise, the function is known-emitted if it's in our set of
  540. // known-emitted functions.
  541. return S.DeviceKnownEmittedFns.count(FD) > 0;
  542. }
  543. Sema::DeviceDiagBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
  544. unsigned DiagID) {
  545. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  546. DeviceDiagBuilder::Kind DiagKind = [this] {
  547. switch (CurrentCUDATarget()) {
  548. case CFT_Global:
  549. case CFT_Device:
  550. return DeviceDiagBuilder::K_Immediate;
  551. case CFT_HostDevice:
  552. // An HD function counts as host code if we're compiling for host, and
  553. // device code if we're compiling for device. Defer any errors in device
  554. // mode until the function is known-emitted.
  555. if (getLangOpts().CUDAIsDevice) {
  556. return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
  557. ? DeviceDiagBuilder::K_ImmediateWithCallStack
  558. : DeviceDiagBuilder::K_Deferred;
  559. }
  560. return DeviceDiagBuilder::K_Nop;
  561. default:
  562. return DeviceDiagBuilder::K_Nop;
  563. }
  564. }();
  565. return DeviceDiagBuilder(DiagKind, Loc, DiagID,
  566. dyn_cast<FunctionDecl>(CurContext), *this);
  567. }
  568. Sema::DeviceDiagBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
  569. unsigned DiagID) {
  570. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  571. DeviceDiagBuilder::Kind DiagKind = [this] {
  572. switch (CurrentCUDATarget()) {
  573. case CFT_Host:
  574. return DeviceDiagBuilder::K_Immediate;
  575. case CFT_HostDevice:
  576. // An HD function counts as host code if we're compiling for host, and
  577. // device code if we're compiling for device. Defer any errors in device
  578. // mode until the function is known-emitted.
  579. if (getLangOpts().CUDAIsDevice)
  580. return DeviceDiagBuilder::K_Nop;
  581. return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
  582. ? DeviceDiagBuilder::K_ImmediateWithCallStack
  583. : DeviceDiagBuilder::K_Deferred;
  584. default:
  585. return DeviceDiagBuilder::K_Nop;
  586. }
  587. }();
  588. return DeviceDiagBuilder(DiagKind, Loc, DiagID,
  589. dyn_cast<FunctionDecl>(CurContext), *this);
  590. }
  591. bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
  592. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  593. assert(Callee && "Callee may not be null.");
  594. auto &ExprEvalCtx = ExprEvalContexts.back();
  595. if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
  596. return true;
  597. // FIXME: Is bailing out early correct here? Should we instead assume that
  598. // the caller is a global initializer?
  599. FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
  600. if (!Caller)
  601. return true;
  602. // If the caller is known-emitted, mark the callee as known-emitted.
  603. // Otherwise, mark the call in our call graph so we can traverse it later.
  604. bool CallerKnownEmitted = IsKnownEmitted(*this, Caller);
  605. if (CallerKnownEmitted) {
  606. // Host-side references to a __global__ function refer to the stub, so the
  607. // function itself is never emitted and therefore should not be marked.
  608. if (getLangOpts().CUDAIsDevice || IdentifyCUDATarget(Callee) != CFT_Global)
  609. markKnownEmitted(*this, Caller, Callee, Loc, IsKnownEmitted);
  610. } else {
  611. // If we have
  612. // host fn calls kernel fn calls host+device,
  613. // the HD function does not get instantiated on the host. We model this by
  614. // omitting at the call to the kernel from the callgraph. This ensures
  615. // that, when compiling for host, only HD functions actually called from the
  616. // host get marked as known-emitted.
  617. if (getLangOpts().CUDAIsDevice || IdentifyCUDATarget(Callee) != CFT_Global)
  618. DeviceCallGraph[Caller].insert({Callee, Loc});
  619. }
  620. DeviceDiagBuilder::Kind DiagKind = [this, Caller, Callee,
  621. CallerKnownEmitted] {
  622. switch (IdentifyCUDAPreference(Caller, Callee)) {
  623. case CFP_Never:
  624. return DeviceDiagBuilder::K_Immediate;
  625. case CFP_WrongSide:
  626. assert(Caller && "WrongSide calls require a non-null caller");
  627. // If we know the caller will be emitted, we know this wrong-side call
  628. // will be emitted, so it's an immediate error. Otherwise, defer the
  629. // error until we know the caller is emitted.
  630. return CallerKnownEmitted ? DeviceDiagBuilder::K_ImmediateWithCallStack
  631. : DeviceDiagBuilder::K_Deferred;
  632. default:
  633. return DeviceDiagBuilder::K_Nop;
  634. }
  635. }();
  636. if (DiagKind == DeviceDiagBuilder::K_Nop)
  637. return true;
  638. // Avoid emitting this error twice for the same location. Using a hashtable
  639. // like this is unfortunate, but because we must continue parsing as normal
  640. // after encountering a deferred error, it's otherwise very tricky for us to
  641. // ensure that we only emit this deferred error once.
  642. if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
  643. return true;
  644. DeviceDiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
  645. << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
  646. DeviceDiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
  647. Caller, *this)
  648. << Callee;
  649. return DiagKind != DeviceDiagBuilder::K_Immediate &&
  650. DiagKind != DeviceDiagBuilder::K_ImmediateWithCallStack;
  651. }
  652. void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
  653. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  654. if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
  655. return;
  656. FunctionDecl *CurFn = dyn_cast<FunctionDecl>(CurContext);
  657. if (!CurFn)
  658. return;
  659. CUDAFunctionTarget Target = IdentifyCUDATarget(CurFn);
  660. if (Target == CFT_Global || Target == CFT_Device) {
  661. Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  662. } else if (Target == CFT_HostDevice) {
  663. Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  664. Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
  665. }
  666. }
  667. void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
  668. const LookupResult &Previous) {
  669. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  670. CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
  671. for (NamedDecl *OldND : Previous) {
  672. FunctionDecl *OldFD = OldND->getAsFunction();
  673. if (!OldFD)
  674. continue;
  675. CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
  676. // Don't allow HD and global functions to overload other functions with the
  677. // same signature. We allow overloading based on CUDA attributes so that
  678. // functions can have different implementations on the host and device, but
  679. // HD/global functions "exist" in some sense on both the host and device, so
  680. // should have the same implementation on both sides.
  681. if (NewTarget != OldTarget &&
  682. ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
  683. (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
  684. !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
  685. /* ConsiderCudaAttrs = */ false)) {
  686. Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
  687. << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
  688. Diag(OldFD->getLocation(), diag::note_previous_declaration);
  689. NewFD->setInvalidDecl();
  690. break;
  691. }
  692. }
  693. }
  694. template <typename AttrTy>
  695. static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
  696. const FunctionDecl &TemplateFD) {
  697. if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
  698. AttrTy *Clone = Attribute->clone(S.Context);
  699. Clone->setInherited(true);
  700. FD->addAttr(Clone);
  701. }
  702. }
  703. void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
  704. const FunctionTemplateDecl &TD) {
  705. const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
  706. copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
  707. copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
  708. copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
  709. }
  710. std::string Sema::getCudaConfigureFuncName() const {
  711. if (getLangOpts().HIP)
  712. return "hipConfigureCall";
  713. // New CUDA kernel launch sequence.
  714. if (CudaFeatureEnabled(Context.getTargetInfo().getSDKVersion(),
  715. CudaFeature::CUDA_USES_NEW_LAUNCH))
  716. return "__cudaPushCallConfiguration";
  717. // Legacy CUDA kernel configuration call
  718. return "cudaConfigureCall";
  719. }