1//===- SemaSYCL.cpp - Semantic Analysis for SYCL 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// This implements Semantic Analysis for SYCL constructs.
9//===----------------------------------------------------------------------===//
10
11#include "clang/Sema/SemaSYCL.h"
12#include "TreeTransform.h"
13#include "clang/AST/Mangle.h"
14#include "clang/AST/SYCLKernelInfo.h"
15#include "clang/AST/StmtSYCL.h"
16#include "clang/AST/SubobjectVisitor.h"
17#include "clang/AST/TypeOrdering.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Sema/Attr.h"
20#include "clang/Sema/ParsedAttr.h"
21#include "clang/Sema/Sema.h"
22
23using namespace clang;
24
25// -----------------------------------------------------------------------------
26// SYCL device specific diagnostics implementation
27// -----------------------------------------------------------------------------
28
29SemaSYCL::SemaSYCL(Sema &S) : SemaBase(S) {}
30
31Sema::SemaDiagnosticBuilder SemaSYCL::DiagIfDeviceCode(SourceLocation Loc,
32 unsigned DiagID) {
33 assert(getLangOpts().SYCLIsDevice &&
34 "Device diagnostics Should only be issued during device compilation");
35 SemaDiagnosticBuilder::Kind DiagKind = SemaDiagnosticBuilder::K_Nop;
36 FunctionDecl *FD = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
37 if (FD) {
38 Sema::FunctionEmissionStatus FES = SemaRef.getEmissionStatus(Decl: FD);
39 switch (FES) {
40 case Sema::FunctionEmissionStatus::Emitted:
41 DiagKind = SemaDiagnosticBuilder::K_ImmediateWithCallStack;
42 break;
43 case Sema::FunctionEmissionStatus::Unknown:
44 case Sema::FunctionEmissionStatus::TemplateDiscarded:
45 DiagKind = SemaDiagnosticBuilder::K_Deferred;
46 break;
47 case Sema::FunctionEmissionStatus::OMPDiscarded:
48 llvm_unreachable("OMPDiscarded unexpected in SYCL device compilation");
49 case Sema::FunctionEmissionStatus::CUDADiscarded:
50 llvm_unreachable("CUDADiscarded unexpected in SYCL device compilation");
51 }
52 }
53 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, FD, SemaRef);
54}
55
56static bool isZeroSizedArray(SemaSYCL &S, QualType Ty) {
57 if (const auto *CAT = S.getASTContext().getAsConstantArrayType(T: Ty))
58 return CAT->isZeroSize();
59 return false;
60}
61
62void SemaSYCL::deepTypeCheckForDevice(SourceLocation UsedAt,
63 llvm::DenseSet<QualType> Visited,
64 ValueDecl *DeclToCheck) {
65 assert(getLangOpts().SYCLIsDevice &&
66 "Should only be called during SYCL compilation");
67 // Emit notes only for the first discovered declaration of unsupported type
68 // to avoid mess of notes. This flag is to track that error already happened.
69 bool NeedToEmitNotes = true;
70
71 auto Check = [&](QualType TypeToCheck, const ValueDecl *D) {
72 bool ErrorFound = false;
73 if (isZeroSizedArray(S&: *this, Ty: TypeToCheck)) {
74 DiagIfDeviceCode(Loc: UsedAt, DiagID: diag::err_typecheck_zero_array_size) << 1;
75 ErrorFound = true;
76 }
77 // Checks for other types can also be done here.
78 if (ErrorFound) {
79 if (NeedToEmitNotes) {
80 if (auto *FD = dyn_cast<FieldDecl>(Val: D))
81 DiagIfDeviceCode(Loc: FD->getLocation(),
82 DiagID: diag::note_illegal_field_declared_here)
83 << FD->getType()->isPointerType() << FD->getType();
84 else
85 DiagIfDeviceCode(Loc: D->getLocation(), DiagID: diag::note_declared_at);
86 }
87 }
88
89 return ErrorFound;
90 };
91
92 // In case we have a Record used do the DFS for a bad field.
93 SmallVector<const ValueDecl *, 4> StackForRecursion;
94 StackForRecursion.push_back(Elt: DeclToCheck);
95
96 // While doing DFS save how we get there to emit a nice set of notes.
97 SmallVector<const FieldDecl *, 4> History;
98 History.push_back(Elt: nullptr);
99
100 do {
101 const ValueDecl *Next = StackForRecursion.pop_back_val();
102 if (!Next) {
103 assert(!History.empty());
104 // Found a marker, we have gone up a level.
105 History.pop_back();
106 continue;
107 }
108 QualType NextTy = Next->getType();
109
110 if (!Visited.insert(V: NextTy).second)
111 continue;
112
113 auto EmitHistory = [&]() {
114 // The first element is always nullptr.
115 for (uint64_t Index = 1; Index < History.size(); ++Index) {
116 DiagIfDeviceCode(Loc: History[Index]->getLocation(),
117 DiagID: diag::note_within_field_of_type)
118 << History[Index]->getType();
119 }
120 };
121
122 if (Check(NextTy, Next)) {
123 if (NeedToEmitNotes)
124 EmitHistory();
125 NeedToEmitNotes = false;
126 }
127
128 // In case pointer/array/reference type is met get pointee type, then
129 // proceed with that type.
130 while (NextTy->isAnyPointerType() || NextTy->isArrayType() ||
131 NextTy->isReferenceType()) {
132 if (NextTy->isArrayType())
133 NextTy = QualType{NextTy->getArrayElementTypeNoTypeQual(), 0};
134 else
135 NextTy = NextTy->getPointeeType();
136 if (Check(NextTy, Next)) {
137 if (NeedToEmitNotes)
138 EmitHistory();
139 NeedToEmitNotes = false;
140 }
141 }
142
143 if (const auto *RecDecl = NextTy->getAsRecordDecl()) {
144 if (auto *NextFD = dyn_cast<FieldDecl>(Val: Next))
145 History.push_back(Elt: NextFD);
146 // When nullptr is discovered, this means we've gone back up a level, so
147 // the history should be cleaned.
148 StackForRecursion.push_back(Elt: nullptr);
149 llvm::append_range(C&: StackForRecursion, R: RecDecl->fields());
150 }
151 } while (!StackForRecursion.empty());
152}
153
154ExprResult SemaSYCL::BuildUniqueStableNameExpr(SourceLocation OpLoc,
155 SourceLocation LParen,
156 SourceLocation RParen,
157 TypeSourceInfo *TSI) {
158 return SYCLUniqueStableNameExpr::Create(Ctx: getASTContext(), OpLoc, LParen,
159 RParen, TSI);
160}
161
162ExprResult SemaSYCL::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
163 SourceLocation LParen,
164 SourceLocation RParen,
165 ParsedType ParsedTy) {
166 TypeSourceInfo *TSI = nullptr;
167 QualType Ty = SemaRef.GetTypeFromParser(Ty: ParsedTy, TInfo: &TSI);
168
169 if (Ty.isNull())
170 return ExprError();
171 if (!TSI)
172 TSI = getASTContext().getTrivialTypeSourceInfo(T: Ty, Loc: LParen);
173
174 return BuildUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
175}
176
177void SemaSYCL::handleKernelAttr(Decl *D, const ParsedAttr &AL) {
178 // The 'sycl_kernel' attribute applies only to function templates.
179 const auto *FD = cast<FunctionDecl>(Val: D);
180 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
181 assert(FT && "Function template is expected");
182
183 // Function template must have at least two template parameters.
184 const TemplateParameterList *TL = FT->getTemplateParameters();
185 if (TL->size() < 2) {
186 Diag(Loc: FT->getLocation(), DiagID: diag::warn_sycl_kernel_num_of_template_params);
187 return;
188 }
189
190 // Template parameters must be typenames.
191 for (unsigned I = 0; I < 2; ++I) {
192 const NamedDecl *TParam = TL->getParam(Idx: I);
193 if (isa<NonTypeTemplateParmDecl>(Val: TParam)) {
194 Diag(Loc: FT->getLocation(),
195 DiagID: diag::warn_sycl_kernel_invalid_template_param_type);
196 return;
197 }
198 }
199
200 // Function must have at least one argument.
201 if (getFunctionOrMethodNumParams(D) != 1) {
202 Diag(Loc: FT->getLocation(), DiagID: diag::warn_sycl_kernel_num_of_function_params);
203 return;
204 }
205
206 // Function must return void.
207 QualType RetTy = getFunctionOrMethodResultType(D);
208 if (!RetTy->isVoidType()) {
209 Diag(Loc: FT->getLocation(), DiagID: diag::warn_sycl_kernel_return_type);
210 return;
211 }
212
213 handleSimpleAttribute<SYCLKernelAttr>(S&: *this, D, CI: AL);
214}
215
216void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const ParsedAttr &AL) {
217 ParsedType PT = AL.getTypeArg();
218 TypeSourceInfo *TSI = nullptr;
219 (void)SemaRef.GetTypeFromParser(Ty: PT, TInfo: &TSI);
220 assert(TSI && "no type source info for attribute argument");
221 D->addAttr(A: ::new (SemaRef.Context)
222 SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
223}
224
225void SemaSYCL::CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc) {
226 assert(getLangOpts().SYCLIsDevice &&
227 "Should only be called during SYCL device compilation");
228
229 // Function declarations with the sycl_kernel_entry_point attribute cannot
230 // be ODR-used in a potentially evaluated context.
231 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: ND)) {
232 if (const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>()) {
233 if (SemaRef.currentEvaluationContext().isPotentiallyEvaluated()) {
234 DiagIfDeviceCode(Loc, DiagID: diag::err_sycl_entry_point_device_use)
235 << FD << SKEPAttr;
236 DiagIfDeviceCode(Loc: SKEPAttr->getLocation(), DiagID: diag::note_attribute) << FD;
237 }
238 }
239 }
240}
241
242// Given a potentially qualified type, SourceLocationForUserDeclaredType()
243// returns the source location of the canonical declaration of the unqualified
244// desugared user declared type, if any. For non-user declared types, an
245// invalid source location is returned. The intended usage of this function
246// is to identify an appropriate source location, if any, for a
247// "entity declared here" diagnostic note.
248static SourceLocation SourceLocationForUserDeclaredType(QualType QT) {
249 SourceLocation Loc;
250 const Type *T = QT->getUnqualifiedDesugaredType();
251 if (const TagType *TT = dyn_cast<TagType>(Val: T))
252 Loc = TT->getDecl()->getLocation();
253 else if (const auto *ObjCIT = dyn_cast<ObjCInterfaceType>(Val: T))
254 Loc = ObjCIT->getDecl()->getLocation();
255 return Loc;
256}
257
258static bool CheckSYCLKernelName(Sema &S, SourceLocation Loc,
259 QualType KernelName) {
260 assert(!KernelName->isDependentType());
261
262 if (!KernelName->isStructureOrClassType()) {
263 // SYCL 2020 section 5.2, "Naming of kernels", only requires that the
264 // kernel name be a C++ typename. However, the definition of "kernel name"
265 // in the glossary states that a kernel name is a class type. Neither
266 // section explicitly states whether the kernel name type can be
267 // cv-qualified. For now, kernel name types are required to be class types
268 // and that they may be cv-qualified. The following issue requests
269 // clarification from the SYCL WG.
270 // https://github.com/KhronosGroup/SYCL-Docs/issues/568
271 S.Diag(Loc, DiagID: diag::warn_sycl_kernel_name_not_a_class_type) << KernelName;
272 SourceLocation DeclTypeLoc = SourceLocationForUserDeclaredType(QT: KernelName);
273 if (DeclTypeLoc.isValid())
274 S.Diag(Loc: DeclTypeLoc, DiagID: diag::note_entity_declared_at) << KernelName;
275 return true;
276 }
277
278 return false;
279}
280
281void SemaSYCL::handleSYCLExternalAttr(Decl *D, const ParsedAttr &AL) {
282 // SYCL 2020 section 5.4 prohibits calling a variadic function from device
283 // code, so the attribute cannot be honored; declaring one is not prohibited,
284 // so ignore the attribute rather than reject the declaration.
285 if (cast<FunctionDecl>(Val: D)->isVariadic()) {
286 Diag(Loc: AL.getLoc(), DiagID: diag::warn_sycl_external_ignored_variadic_function) << AL;
287 return;
288 }
289
290 handleSimpleAttribute<SYCLExternalAttr>(S&: *this, D, CI: AL);
291}
292
293void SemaSYCL::CheckSYCLExternalFunctionDecl(FunctionDecl *FD) {
294 const auto *SEAttr = FD->getAttr<SYCLExternalAttr>();
295 assert(SEAttr && "Missing sycl_external attribute");
296 if (!FD->isInvalidDecl() && !FD->isTemplated()) {
297 if (!FD->isExternallyVisible())
298 if (!FD->isFunctionTemplateSpecialization() ||
299 FD->getTemplateSpecializationInfo()->isExplicitSpecialization())
300 Diag(Loc: SEAttr->getLocation(), DiagID: diag::err_sycl_external_invalid_linkage)
301 << SEAttr;
302 }
303 if (FD->isDeletedAsWritten()) {
304 Diag(Loc: SEAttr->getLocation(),
305 DiagID: diag::err_sycl_external_invalid_deleted_function)
306 << SEAttr;
307 }
308}
309
310void SemaSYCL::CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD) {
311 // Ensure that all attributes present on the declaration are consistent
312 // and warn about any redundant ones.
313 SYCLKernelEntryPointAttr *SKEPAttr = nullptr;
314 for (auto *SAI : FD->specific_attrs<SYCLKernelEntryPointAttr>()) {
315 if (!SKEPAttr) {
316 SKEPAttr = SAI;
317 continue;
318 }
319 if (!getASTContext().hasSameType(T1: SAI->getKernelName(),
320 T2: SKEPAttr->getKernelName())) {
321 Diag(Loc: SAI->getLocation(), DiagID: diag::err_sycl_entry_point_invalid_redeclaration)
322 << SKEPAttr << SAI->getKernelName() << SKEPAttr->getKernelName();
323 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::note_previous_attribute);
324 SAI->setInvalidAttr();
325 } else {
326 Diag(Loc: SAI->getLocation(),
327 DiagID: diag::warn_sycl_entry_point_redundant_declaration)
328 << SAI;
329 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::note_previous_attribute);
330 }
331 }
332 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
333
334 // Ensure the kernel name type is valid.
335 if (!SKEPAttr->getKernelName()->isDependentType() &&
336 CheckSYCLKernelName(S&: SemaRef, Loc: SKEPAttr->getLocation(),
337 KernelName: SKEPAttr->getKernelName()))
338 SKEPAttr->setInvalidAttr();
339
340 // Ensure that an attribute present on the previous declaration
341 // matches the one on this declaration.
342 FunctionDecl *PrevFD = FD->getPreviousDecl();
343 if (PrevFD && !PrevFD->isInvalidDecl()) {
344 const auto *PrevSKEPAttr = PrevFD->getAttr<SYCLKernelEntryPointAttr>();
345 if (PrevSKEPAttr && !PrevSKEPAttr->isInvalidAttr()) {
346 if (!getASTContext().hasSameType(T1: SKEPAttr->getKernelName(),
347 T2: PrevSKEPAttr->getKernelName())) {
348 Diag(Loc: SKEPAttr->getLocation(),
349 DiagID: diag::err_sycl_entry_point_invalid_redeclaration)
350 << SKEPAttr << SKEPAttr->getKernelName()
351 << PrevSKEPAttr->getKernelName();
352 Diag(Loc: PrevSKEPAttr->getLocation(), DiagID: diag::note_previous_decl) << PrevFD;
353 SKEPAttr->setInvalidAttr();
354 }
355 }
356 }
357
358 if (isa<CXXConstructorDecl>(Val: FD)) {
359 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
360 << SKEPAttr << diag::InvalidSKEPReason::Constructor;
361 SKEPAttr->setInvalidAttr();
362 }
363 if (isa<CXXDestructorDecl>(Val: FD)) {
364 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
365 << SKEPAttr << diag::InvalidSKEPReason::Destructor;
366 SKEPAttr->setInvalidAttr();
367 }
368 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
369 if (MD->isExplicitObjectMemberFunction()) {
370 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
371 << SKEPAttr << diag::InvalidSKEPReason::ExplicitObjectFn;
372 SKEPAttr->setInvalidAttr();
373 }
374 }
375
376 if (FD->isVariadic()) {
377 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
378 << SKEPAttr << diag::InvalidSKEPReason::VariadicFn;
379 SKEPAttr->setInvalidAttr();
380 }
381
382 if (FD->isDefaulted()) {
383 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
384 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
385 SKEPAttr->setInvalidAttr();
386 } else if (FD->isDeleted()) {
387 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
388 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
389 SKEPAttr->setInvalidAttr();
390 }
391
392 if (FD->isConsteval()) {
393 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
394 << SKEPAttr << diag::InvalidSKEPReason::ConstevalFn;
395 SKEPAttr->setInvalidAttr();
396 } else if (FD->isConstexpr()) {
397 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
398 << SKEPAttr << diag::InvalidSKEPReason::ConstexprFn;
399 SKEPAttr->setInvalidAttr();
400 }
401
402 if (FD->isNoReturn()) {
403 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
404 << SKEPAttr << diag::InvalidSKEPReason::NoreturnFn;
405 SKEPAttr->setInvalidAttr();
406 }
407
408 if (FD->getReturnType()->isUndeducedType()) {
409 Diag(Loc: SKEPAttr->getLocation(),
410 DiagID: diag::err_sycl_entry_point_deduced_return_type)
411 << SKEPAttr;
412 SKEPAttr->setInvalidAttr();
413 } else if (!FD->getReturnType()->isDependentType() &&
414 !FD->getReturnType()->isVoidType()) {
415 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_return_type)
416 << SKEPAttr;
417 SKEPAttr->setInvalidAttr();
418 }
419
420 if (!FD->isInvalidDecl() && !FD->isTemplated() &&
421 !SKEPAttr->isInvalidAttr()) {
422 const SYCLKernelInfo *SKI =
423 getASTContext().findSYCLKernelInfo(T: SKEPAttr->getKernelName());
424 if (SKI) {
425 if (!declaresSameEntity(D1: FD, D2: SKI->getKernelEntryPointDecl())) {
426 // FIXME: This diagnostic should include the origin of the kernel
427 // FIXME: names; not just the locations of the conflicting declarations.
428 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_kernel_name_conflict)
429 << SKEPAttr;
430 Diag(Loc: SKI->getKernelEntryPointDecl()->getLocation(),
431 DiagID: diag::note_previous_declaration);
432 SKEPAttr->setInvalidAttr();
433 }
434 } else {
435 getASTContext().registerSYCLEntryPointFunction(FD);
436 }
437 }
438}
439
440ExprResult SemaSYCL::BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD,
441 QualType KNT) {
442 // The current context must be the function definition context to ensure
443 // that name lookup is performed within the correct scope.
444 assert(SemaRef.CurContext == FD && "The current declaration context does not "
445 "match the requested function context");
446
447 // An appropriate source location is required to emit diagnostics if
448 // lookup fails to produce an overload set. The desired location is the
449 // start of the function body, but that is not yet available since the
450 // body of the function has not yet been set when this function is called.
451 // The general location of the function is used instead.
452 SourceLocation Loc = FD->getLocation();
453
454 ASTContext &Ctx = SemaRef.getASTContext();
455 IdentifierInfo &SYCLKernelLaunchID =
456 Ctx.Idents.get(Name: "sycl_kernel_launch", TokenCode: tok::TokenKind::identifier);
457
458 // Establish a code synthesis context for the implicit name lookup of
459 // a template named 'sycl_kernel_launch'. In the event of an error, this
460 // ensures an appropriate diagnostic note is issued to explain why the
461 // lookup was performed.
462 Sema::CodeSynthesisContext CSC;
463 CSC.Kind = Sema::CodeSynthesisContext::SYCLKernelLaunchLookup;
464 CSC.Entity = FD;
465 Sema::ScopedCodeSynthesisContext ScopedCSC(SemaRef, CSC);
466
467 // Perform ordinary name lookup for a function or variable template that
468 // accepts a single type template argument.
469 LookupResult Result(SemaRef, &SYCLKernelLaunchID, Loc,
470 Sema::LookupOrdinaryName);
471 CXXScopeSpec EmptySS;
472 if (SemaRef.LookupTemplateName(R&: Result, S: SemaRef.getCurScope(), SS&: EmptySS,
473 /*ObjectType*/ QualType(),
474 /*EnteringContext*/ false,
475 RequiredTemplate: Sema::TemplateNameIsRequired))
476 return ExprError();
477 if (Result.isAmbiguous())
478 return ExprError();
479
480 TemplateArgumentListInfo TALI{Loc, Loc};
481 TemplateArgument KNTA = TemplateArgument(KNT);
482 TemplateArgumentLoc TAL =
483 SemaRef.getTrivialTemplateArgumentLoc(Arg: KNTA, NTTPType: QualType(), Loc);
484 TALI.addArgument(Loc: TAL);
485
486 ExprResult IdExpr;
487 if (SemaRef.isPotentialImplicitMemberAccess(SS: EmptySS, R&: Result,
488 /*IsAddressOfOperand*/ false)) {
489 // The lookup result allows for a possible implicit member access that
490 // would require an implicit or explicit 'this' argument.
491 IdExpr = SemaRef.BuildPossibleImplicitMemberExpr(
492 SS: EmptySS, TemplateKWLoc: SourceLocation(), R&: Result, TemplateArgs: &TALI, S: SemaRef.getCurScope());
493 } else {
494 IdExpr = SemaRef.BuildTemplateIdExpr(SS: EmptySS, TemplateKWLoc: SourceLocation(), R&: Result,
495 /*RequiresADL*/ true, TemplateArgs: &TALI);
496 }
497
498 // The resulting expression may be invalid if, for example, 'FD' is a
499 // non-static member function and sycl_kernel_launch lookup selects a
500 // member function (which would require a 'this' argument which is
501 // not available).
502 if (IdExpr.isInvalid())
503 return ExprError();
504
505 return IdExpr;
506}
507
508namespace {
509
510// Constructs the arguments to be passed for the SYCL kernel launch call.
511// The first argument is a string literal that contains the SYCL kernel
512// name. The remaining arguments are the parameters of 'FD' passed as
513// move-elligible xvalues. Returns true on error and false otherwise.
514bool BuildSYCLKernelLaunchCallArgs(Sema &SemaRef, FunctionDecl *FD,
515 const SYCLKernelInfo *SKI,
516 SmallVectorImpl<Expr *> &Args,
517 SourceLocation Loc) {
518 // The current context must be the function definition context to ensure
519 // that parameter references occur within the correct scope.
520 assert(SemaRef.CurContext == FD && "The current declaration context does not "
521 "match the requested function context");
522
523 // Prepare a string literal that contains the kernel name.
524 ASTContext &Ctx = SemaRef.getASTContext();
525 const std::string &KernelName = SKI->GetKernelName();
526 QualType KernelNameCharTy = Ctx.CharTy.withConst();
527 llvm::APInt KernelNameSize(Ctx.getTypeSize(T: Ctx.getSizeType()),
528 KernelName.size() + 1);
529 QualType KernelNameArrayTy = Ctx.getConstantArrayType(
530 EltTy: KernelNameCharTy, ArySize: KernelNameSize, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
531 Expr *KernelNameExpr =
532 StringLiteral::Create(Ctx, Str: KernelName, Kind: StringLiteralKind::Ordinary,
533 /*Pascal*/ false, Ty: KernelNameArrayTy, Locs: Loc);
534 Args.push_back(Elt: KernelNameExpr);
535
536 // Forward all parameters of 'FD' to the SYCL kernel launch function as if
537 // by std::move().
538 for (ParmVarDecl *PVD : FD->parameters()) {
539 QualType ParamType = PVD->getOriginalType().getNonReferenceType();
540 ExprResult E = SemaRef.BuildDeclRefExpr(D: PVD, Ty: ParamType, VK: VK_LValue, Loc);
541 if (E.isInvalid())
542 return true;
543 if (!PVD->getType()->isLValueReferenceType())
544 E = ImplicitCastExpr::Create(Context: SemaRef.Context, T: E.get()->getType(), Kind: CK_NoOp,
545 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
546 FPO: FPOptionsOverride());
547 if (E.isInvalid())
548 return true;
549 Args.push_back(Elt: E.get());
550 }
551
552 return false;
553}
554
555// Constructs the SYCL kernel launch call.
556StmtResult BuildSYCLKernelLaunchCallStmt(Sema &SemaRef, FunctionDecl *FD,
557 const SYCLKernelInfo *SKI,
558 Expr *IdExpr, SourceLocation Loc) {
559 SmallVector<Stmt *> Stmts;
560 // IdExpr may be null if name lookup failed.
561 if (IdExpr) {
562 llvm::SmallVector<Expr *, 12> Args;
563
564 // Establish a code synthesis context for construction of the arguments
565 // for the implicit call to 'sycl_kernel_launch'.
566 {
567 Sema::CodeSynthesisContext CSC;
568 CSC.Kind = Sema::CodeSynthesisContext::SYCLKernelLaunchLookup;
569 CSC.Entity = FD;
570 Sema::ScopedCodeSynthesisContext ScopedCSC(SemaRef, CSC);
571
572 if (BuildSYCLKernelLaunchCallArgs(SemaRef, FD, SKI, Args, Loc))
573 return StmtError();
574 }
575
576 // Establish a code synthesis context for the implicit call to
577 // 'sycl_kernel_launch'.
578 {
579 Sema::CodeSynthesisContext CSC;
580 CSC.Kind = Sema::CodeSynthesisContext::SYCLKernelLaunchOverloadResolution;
581 CSC.Entity = FD;
582 CSC.CallArgs = Args.data();
583 CSC.NumCallArgs = Args.size();
584 Sema::ScopedCodeSynthesisContext ScopedCSC(SemaRef, CSC);
585
586 ExprResult LaunchResult =
587 SemaRef.BuildCallExpr(S: SemaRef.getCurScope(), Fn: IdExpr, LParenLoc: Loc, ArgExprs: Args, RParenLoc: Loc);
588 if (LaunchResult.isInvalid())
589 return StmtError();
590
591 Stmts.push_back(Elt: SemaRef.MaybeCreateExprWithCleanups(SubExpr: LaunchResult).get());
592 }
593 }
594
595 return CompoundStmt::Create(C: SemaRef.getASTContext(), Stmts,
596 FPFeatures: FPOptionsOverride(), LB: Loc, RB: Loc);
597}
598
599// The body of a function declared with the [[sycl_kernel_entry_point]]
600// attribute is cloned and transformed to substitute references to the original
601// function parameters with references to replacement variables that stand in
602// for SYCL kernel parameters or local variables that reconstitute a decomposed
603// SYCL kernel argument.
604class OutlinedFunctionDeclBodyInstantiator
605 : public TreeTransform<OutlinedFunctionDeclBodyInstantiator> {
606public:
607 using ParmDeclMap = llvm::DenseMap<ParmVarDecl *, VarDecl *>;
608
609 OutlinedFunctionDeclBodyInstantiator(Sema &S, ParmDeclMap &M,
610 FunctionDecl *FD)
611 : TreeTransform<OutlinedFunctionDeclBodyInstantiator>(S), SemaRef(S),
612 MapRef(M), FD(FD) {}
613
614 // A new set of AST nodes is always required.
615 bool AlwaysRebuild() { return true; }
616
617 // Transform ParmVarDecl references to the supplied replacement variables.
618 ExprResult TransformDeclRefExpr(DeclRefExpr *DRE) {
619 const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl());
620 if (PVD) {
621 ParmDeclMap::iterator I = MapRef.find(Val: PVD);
622 if (I != MapRef.end()) {
623 VarDecl *VD = I->second;
624 assert(SemaRef.getASTContext().hasSameUnqualifiedType(
625 PVD->getType().getNonReferenceType(), VD->getType()));
626 assert(!VD->getType().isMoreQualifiedThan(
627 PVD->getType().getNonReferenceType(), SemaRef.getASTContext()));
628 VD->setIsUsed();
629 return DeclRefExpr::Create(
630 Context: SemaRef.getASTContext(), QualifierLoc: DRE->getQualifierLoc(),
631 TemplateKWLoc: DRE->getTemplateKeywordLoc(), D: VD, RefersToEnclosingVariableOrCapture: false, NameInfo: DRE->getNameInfo(),
632 T: DRE->getType(), VK: DRE->getValueKind());
633 }
634 }
635 return DRE;
636 }
637
638 // Diagnose CXXThisExpr in a potentially evaluated expression.
639 ExprResult TransformCXXThisExpr(CXXThisExpr *CTE) {
640 if (SemaRef.currentEvaluationContext().isPotentiallyEvaluated()) {
641 SemaRef.Diag(Loc: CTE->getExprLoc(), DiagID: diag::err_sycl_entry_point_invalid_this)
642 << (CTE->isImplicitCXXThis() ? /* implicit */ 1 : /* empty */ 0)
643 << FD->getAttr<SYCLKernelEntryPointAttr>();
644 }
645 return CTE;
646 }
647
648private:
649 Sema &SemaRef;
650 ParmDeclMap &MapRef;
651 FunctionDecl *FD;
652};
653
654OutlinedFunctionDecl *BuildSYCLKernelEntryPointOutline(Sema &SemaRef,
655 FunctionDecl *FD,
656 CompoundStmt *Body) {
657 using ParmDeclMap = OutlinedFunctionDeclBodyInstantiator::ParmDeclMap;
658 ParmDeclMap ParmMap;
659
660 OutlinedFunctionDecl *OFD = OutlinedFunctionDecl::Create(
661 C&: SemaRef.getASTContext(), DC: FD, NumParams: FD->getNumParams());
662 unsigned i = 0;
663 for (ParmVarDecl *PVD : FD->parameters()) {
664 ImplicitParamDecl *IPD = ImplicitParamDecl::Create(
665 C&: SemaRef.getASTContext(), DC: OFD, IdLoc: SourceLocation(), Id: PVD->getIdentifier(),
666 T: PVD->getType().getNonReferenceType(), ParamKind: ImplicitParamKind::Other);
667 OFD->setParam(i, P: IPD);
668 ParmMap[PVD] = IPD;
669 ++i;
670 }
671
672 OutlinedFunctionDeclBodyInstantiator OFDBodyInstantiator(SemaRef, ParmMap,
673 FD);
674 Stmt *OFDBody = OFDBodyInstantiator.TransformStmt(S: Body).get();
675 OFD->setBody(OFDBody);
676 OFD->setNothrow();
677
678 return OFD;
679}
680
681class KernelParamsChecker : public ConstSubobjectVisitor<KernelParamsChecker> {
682 SemaSYCL &SemaSYCLRef;
683 bool IsValid = true;
684 using ObjectAccess =
685 llvm::PointerUnion<const ParmVarDecl *, const CXXBaseSpecifier *,
686 const FieldDecl *>;
687 SmallVector<ObjectAccess, 4> ObjectAccessPath;
688
689 void emitObjectAccessPathNotes() {
690 for (auto Parent : llvm::reverse(C&: ObjectAccessPath)) {
691 if (auto *FD = dyn_cast<const FieldDecl *>(Val&: Parent)) {
692 const CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Val: FD->getParent());
693 if (ParentRD->isLambda()) {
694 SemaSYCLRef.Diag(Loc: ParentRD->getLocation(), DiagID: diag::note_within_capture)
695 << ParentRD->getCapture(I: FD->getFieldIndex())->getCapturedVar();
696 } else {
697 SemaSYCLRef.Diag(Loc: ParentRD->getLocation(),
698 DiagID: diag::note_within_field_of_type)
699 << ParentRD;
700 }
701 } else if (auto *BS = dyn_cast<const CXXBaseSpecifier *>(Val&: Parent)) {
702 CXXRecordDecl *RD = BS->getType()->getAsCXXRecordDecl();
703 assert(RD);
704 SemaSYCLRef.Diag(Loc: BS->getBeginLoc(), DiagID: diag::note_within_base_of_type)
705 << RD;
706 } else {
707 auto *Param = cast<const ParmVarDecl *>(Val&: Parent);
708 SemaSYCLRef.Diag(Loc: Param->getBeginLoc(), DiagID: diag::note_within_param_of_type)
709 << Param << Param->getType();
710 }
711 }
712 }
713
714public:
715 KernelParamsChecker(SemaSYCL &SR, SourceLocation Loc)
716 : ConstSubobjectVisitor<KernelParamsChecker>(SR.getASTContext()),
717 SemaSYCLRef(SR) {}
718
719 void checkParameter(const ParmVarDecl *PVD) {
720 ObjectAccessPath.push_back(Elt: PVD);
721 // Check the immediate type of the parameter.
722 if (checkType(Ty: PVD->getType())) {
723 // If type checking wasn't short circuited, visit subobjects to check
724 // them.
725 visit(QT: PVD->getType());
726 }
727 ObjectAccessPath.pop_back();
728 assert(ObjectAccessPath.empty());
729 }
730
731 bool visitBaseSpecifierPre(const CXXBaseSpecifier *BS) {
732 ObjectAccessPath.push_back(Elt: BS);
733 return checkType(Ty: BS->getType());
734 }
735
736 bool visitFieldDeclPre(const FieldDecl *FD) {
737 ObjectAccessPath.push_back(Elt: FD);
738 return checkType(Ty: FD->getType());
739 }
740
741 // Returns true if subobjects should be visited and false otherwise.
742 bool checkType(QualType Ty) {
743 if (Ty->isReferenceType()) {
744 auto DirectParent = ObjectAccessPath.back();
745 // Reference cannot be a base, so just assume we came via a FieldDecl.
746 if (isa<const ParmVarDecl *>(Val: DirectParent)) {
747 // If reference is a kernel parameter, there is nothing to do. We allow
748 // references in direct kernel parameters for better performance of the
749 // host code and we eliminate them when building actual kernel.
750 return true;
751 }
752
753 auto *DirectFieldParent = cast<const FieldDecl *>(Val&: DirectParent);
754 SemaSYCLRef.Diag(Loc: DirectFieldParent->getLocation(),
755 DiagID: diag::err_bad_kernel_param_type)
756 << DirectFieldParent->getType();
757 emitObjectAccessPathNotes();
758
759 // Don't visit the type of the reference since any further invalid
760 // kernel parameter types contained within the referenced type
761 // might not be relevant once the programmer addresses the
762 // invalid use of a reference.
763 IsValid = false;
764 return false;
765 }
766 return true;
767 }
768
769 void visitFieldDeclPost(const FieldDecl *FD) { ObjectAccessPath.pop_back(); }
770 void visitBaseSpecifierPost(const CXXBaseSpecifier *BS) {
771 ObjectAccessPath.pop_back();
772 }
773
774 bool isInvalid() { return !IsValid; }
775};
776
777bool verifyKernelParams(FunctionDecl *FD, SemaSYCL &SemaSYCLRef) {
778 KernelParamsChecker KAC(SemaSYCLRef, FD->getLocation());
779 for (auto Param : FD->parameters())
780 KAC.checkParameter(PVD: Param);
781 return KAC.isInvalid();
782}
783
784} // unnamed namespace
785
786StmtResult SemaSYCL::BuildSYCLKernelCallStmt(FunctionDecl *FD,
787 CompoundStmt *Body,
788 Expr *LaunchIdExpr) {
789 assert(!FD->isInvalidDecl());
790 assert(!FD->isTemplated());
791 assert(FD->hasPrototype());
792 // The current context must be the function definition context to ensure
793 // that name lookup and parameter and local variable creation are performed
794 // within the correct scope.
795 assert(SemaRef.CurContext == FD && "The current declaration context does not "
796 "match the requested function context");
797
798 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
799 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
800 assert(!SKEPAttr->isInvalidAttr() &&
801 "sycl_kernel_entry_point attribute is invalid");
802
803 // Ensure that the kernel name was previously registered and that the
804 // stored declaration matches.
805 const SYCLKernelInfo &SKI =
806 getASTContext().getSYCLKernelInfo(T: SKEPAttr->getKernelName());
807 assert(declaresSameEntity(SKI.getKernelEntryPointDecl(), FD) &&
808 "SYCL kernel name conflict");
809 if (verifyKernelParams(FD, SemaSYCLRef&: *this))
810 return StmtError();
811
812 // Build the outline of the synthesized device entry point function.
813 OutlinedFunctionDecl *OFD =
814 BuildSYCLKernelEntryPointOutline(SemaRef, FD, Body);
815 assert(OFD);
816
817 // Build the host kernel launch statement. An appropriate source location
818 // is required to emit diagnostics.
819 SourceLocation Loc = Body->getLBracLoc();
820 StmtResult LaunchResult =
821 BuildSYCLKernelLaunchCallStmt(SemaRef, FD, SKI: &SKI, IdExpr: LaunchIdExpr, Loc);
822 if (LaunchResult.isInvalid())
823 return StmtError();
824
825 Stmt *NewBody =
826 new (getASTContext()) SYCLKernelCallStmt(Body, LaunchResult.get(), OFD);
827
828 return NewBody;
829}
830
831StmtResult SemaSYCL::BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body,
832 Expr *LaunchIdExpr) {
833 return UnresolvedSYCLKernelCallStmt::Create(C: SemaRef.getASTContext(), CS: Body,
834 IdExpr: LaunchIdExpr);
835}
836