clang 17.0.0git
SemaLambda.cpp
Go to the documentation of this file.
1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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//
9// This file implements semantic analysis for C++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Sema/DeclSpec.h"
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/ExprCXX.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Scope.h"
23#include "llvm/ADT/STLExtras.h"
24#include <optional>
25using namespace clang;
26using namespace sema;
27
28/// Examines the FunctionScopeInfo stack to determine the nearest
29/// enclosing lambda (to the current lambda) that is 'capture-ready' for
30/// the variable referenced in the current lambda (i.e. \p VarToCapture).
31/// If successful, returns the index into Sema's FunctionScopeInfo stack
32/// of the capture-ready lambda's LambdaScopeInfo.
33///
34/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
35/// lambda - is on top) to determine the index of the nearest enclosing/outer
36/// lambda that is ready to capture the \p VarToCapture being referenced in
37/// the current lambda.
38/// As we climb down the stack, we want the index of the first such lambda -
39/// that is the lambda with the highest index that is 'capture-ready'.
40///
41/// A lambda 'L' is capture-ready for 'V' (var or this) if:
42/// - its enclosing context is non-dependent
43/// - and if the chain of lambdas between L and the lambda in which
44/// V is potentially used (i.e. the lambda at the top of the scope info
45/// stack), can all capture or have already captured V.
46/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
47///
48/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
49/// for whether it is 'capture-capable' (see
50/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
51/// capture.
52///
53/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
54/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
55/// is at the top of the stack and has the highest index.
56/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
57///
58/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
59/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
60/// lambda which is capture-ready. If the return value evaluates to 'false'
61/// then no lambda is capture-ready for \p VarToCapture.
62
63static inline std::optional<unsigned>
66 ValueDecl *VarToCapture) {
67 // Label failure to capture.
68 const std::optional<unsigned> NoLambdaIsCaptureReady;
69
70 // Ignore all inner captured regions.
71 unsigned CurScopeIndex = FunctionScopes.size() - 1;
72 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
73 FunctionScopes[CurScopeIndex]))
74 --CurScopeIndex;
75 assert(
76 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
77 "The function on the top of sema's function-info stack must be a lambda");
78
79 // If VarToCapture is null, we are attempting to capture 'this'.
80 const bool IsCapturingThis = !VarToCapture;
81 const bool IsCapturingVariable = !IsCapturingThis;
82
83 // Start with the current lambda at the top of the stack (highest index).
84 DeclContext *EnclosingDC =
85 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
86
87 do {
89 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
90 // IF we have climbed down to an intervening enclosing lambda that contains
91 // the variable declaration - it obviously can/must not capture the
92 // variable.
93 // Since its enclosing DC is dependent, all the lambdas between it and the
94 // innermost nested lambda are dependent (otherwise we wouldn't have
95 // arrived here) - so we don't yet have a lambda that can capture the
96 // variable.
97 if (IsCapturingVariable &&
98 VarToCapture->getDeclContext()->Equals(EnclosingDC))
99 return NoLambdaIsCaptureReady;
100
101 // For an enclosing lambda to be capture ready for an entity, all
102 // intervening lambda's have to be able to capture that entity. If even
103 // one of the intervening lambda's is not capable of capturing the entity
104 // then no enclosing lambda can ever capture that entity.
105 // For e.g.
106 // const int x = 10;
107 // [=](auto a) { #1
108 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
109 // [=](auto c) { #3
110 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
111 // }; }; };
112 // If they do not have a default implicit capture, check to see
113 // if the entity has already been explicitly captured.
114 // If even a single dependent enclosing lambda lacks the capability
115 // to ever capture this variable, there is no further enclosing
116 // non-dependent lambda that can capture this variable.
117 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
118 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
119 return NoLambdaIsCaptureReady;
120 if (IsCapturingThis && !LSI->isCXXThisCaptured())
121 return NoLambdaIsCaptureReady;
122 }
123 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
124
125 assert(CurScopeIndex);
126 --CurScopeIndex;
127 } while (!EnclosingDC->isTranslationUnit() &&
128 EnclosingDC->isDependentContext() &&
129 isLambdaCallOperator(EnclosingDC));
130
131 assert(CurScopeIndex < (FunctionScopes.size() - 1));
132 // If the enclosingDC is not dependent, then the immediately nested lambda
133 // (one index above) is capture-ready.
134 if (!EnclosingDC->isDependentContext())
135 return CurScopeIndex + 1;
136 return NoLambdaIsCaptureReady;
137}
138
139/// Examines the FunctionScopeInfo stack to determine the nearest
140/// enclosing lambda (to the current lambda) that is 'capture-capable' for
141/// the variable referenced in the current lambda (i.e. \p VarToCapture).
142/// If successful, returns the index into Sema's FunctionScopeInfo stack
143/// of the capture-capable lambda's LambdaScopeInfo.
144///
145/// Given the current stack of lambdas being processed by Sema and
146/// the variable of interest, to identify the nearest enclosing lambda (to the
147/// current lambda at the top of the stack) that can truly capture
148/// a variable, it has to have the following two properties:
149/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
150/// - climb down the stack (i.e. starting from the innermost and examining
151/// each outer lambda step by step) checking if each enclosing
152/// lambda can either implicitly or explicitly capture the variable.
153/// Record the first such lambda that is enclosed in a non-dependent
154/// context. If no such lambda currently exists return failure.
155/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
156/// capture the variable by checking all its enclosing lambdas:
157/// - check if all outer lambdas enclosing the 'capture-ready' lambda
158/// identified above in 'a' can also capture the variable (this is done
159/// via tryCaptureVariable for variables and CheckCXXThisCapture for
160/// 'this' by passing in the index of the Lambda identified in step 'a')
161///
162/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
163/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
164/// is at the top of the stack.
165///
166/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
167///
168///
169/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
170/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
171/// lambda which is capture-capable. If the return value evaluates to 'false'
172/// then no lambda is capture-capable for \p VarToCapture.
173
174std::optional<unsigned>
177 ValueDecl *VarToCapture, Sema &S) {
178
179 const std::optional<unsigned> NoLambdaIsCaptureCapable;
180
181 const std::optional<unsigned> OptionalStackIndex =
183 VarToCapture);
184 if (!OptionalStackIndex)
185 return NoLambdaIsCaptureCapable;
186
187 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
188 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
189 S.getCurGenericLambda()) &&
190 "The capture ready lambda for a potential capture can only be the "
191 "current lambda if it is a generic lambda");
192
193 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
194 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
195
196 // If VarToCapture is null, we are attempting to capture 'this'
197 const bool IsCapturingThis = !VarToCapture;
198 const bool IsCapturingVariable = !IsCapturingThis;
199
200 if (IsCapturingVariable) {
201 // Check if the capture-ready lambda can truly capture the variable, by
202 // checking whether all enclosing lambdas of the capture-ready lambda allow
203 // the capture - i.e. make sure it is capture-capable.
204 QualType CaptureType, DeclRefType;
205 const bool CanCaptureVariable =
206 !S.tryCaptureVariable(VarToCapture,
207 /*ExprVarIsUsedInLoc*/ SourceLocation(),
209 /*EllipsisLoc*/ SourceLocation(),
210 /*BuildAndDiagnose*/ false, CaptureType,
211 DeclRefType, &IndexOfCaptureReadyLambda);
212 if (!CanCaptureVariable)
213 return NoLambdaIsCaptureCapable;
214 } else {
215 // Check if the capture-ready lambda can truly capture 'this' by checking
216 // whether all enclosing lambdas of the capture-ready lambda can capture
217 // 'this'.
218 const bool CanCaptureThis =
220 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
221 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
222 &IndexOfCaptureReadyLambda);
223 if (!CanCaptureThis)
224 return NoLambdaIsCaptureCapable;
225 }
226 return IndexOfCaptureReadyLambda;
227}
228
229static inline TemplateParameterList *
231 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
232 LSI->GLTemplateParameterList = TemplateParameterList::Create(
233 SemaRef.Context,
234 /*Template kw loc*/ SourceLocation(),
235 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
236 LSI->TemplateParams,
237 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
238 LSI->RequiresClause.get());
239 }
240 return LSI->GLTemplateParameterList;
241}
242
245 unsigned LambdaDependencyKind,
246 LambdaCaptureDefault CaptureDefault) {
248 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
249 DC = DC->getParent();
250
251 bool IsGenericLambda =
253 // Start constructing the lambda class.
255 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
256 IsGenericLambda, CaptureDefault);
257 DC->addDecl(Class);
258
259 return Class;
260}
261
262/// Determine whether the given context is or is enclosed in an inline
263/// function.
264static bool isInInlineFunction(const DeclContext *DC) {
265 while (!DC->isFileContext()) {
266 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
267 if (FD->isInlined())
268 return true;
269
270 DC = DC->getLexicalParent();
271 }
272
273 return false;
274}
275
276std::tuple<MangleNumberingContext *, Decl *>
278 // Compute the context for allocating mangling numbers in the current
279 // expression, if the ABI requires them.
280 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
281
282 enum ContextKind {
283 Normal,
285 DataMember,
286 StaticDataMember,
287 InlineVariable,
288 VariableTemplate,
289 Concept
290 } Kind = Normal;
291
292 // Default arguments of member function parameters that appear in a class
293 // definition, as well as the initializers of data members, receive special
294 // treatment. Identify them.
295 if (ManglingContextDecl) {
296 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
297 if (const DeclContext *LexicalDC
298 = Param->getDeclContext()->getLexicalParent())
299 if (LexicalDC->isRecord())
300 Kind = DefaultArgument;
301 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
302 if (Var->getDeclContext()->isRecord())
303 Kind = StaticDataMember;
304 else if (Var->getMostRecentDecl()->isInline())
305 Kind = InlineVariable;
306 else if (Var->getDescribedVarTemplate())
307 Kind = VariableTemplate;
308 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
309 if (!VTS->isExplicitSpecialization())
310 Kind = VariableTemplate;
311 }
312 } else if (isa<FieldDecl>(ManglingContextDecl)) {
313 Kind = DataMember;
314 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
315 Kind = Concept;
316 }
317 }
318
319 // Itanium ABI [5.1.7]:
320 // In the following contexts [...] the one-definition rule requires closure
321 // types in different translation units to "correspond":
322 bool IsInNonspecializedTemplate =
324 switch (Kind) {
325 case Normal: {
326 // -- the bodies of non-exported nonspecialized template functions
327 // -- the bodies of inline functions
328 if ((IsInNonspecializedTemplate &&
329 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
331 while (auto *CD = dyn_cast<CapturedDecl>(DC))
332 DC = CD->getParent();
333 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
334 }
335
336 return std::make_tuple(nullptr, nullptr);
337 }
338
339 case Concept:
340 // Concept definitions aren't code generated and thus aren't mangled,
341 // however the ManglingContextDecl is important for the purposes of
342 // re-forming the template argument list of the lambda for constraint
343 // evaluation.
344 case StaticDataMember:
345 // -- the initializers of nonspecialized static members of template classes
346 if (!IsInNonspecializedTemplate)
347 return std::make_tuple(nullptr, ManglingContextDecl);
348 // Fall through to get the current context.
349 [[fallthrough]];
350
351 case DataMember:
352 // -- the in-class initializers of class members
353 case DefaultArgument:
354 // -- default arguments appearing in class definitions
355 case InlineVariable:
356 // -- the initializers of inline variables
357 case VariableTemplate:
358 // -- the initializers of templated variables
359 return std::make_tuple(
361 ManglingContextDecl),
362 ManglingContextDecl);
363 }
364
365 llvm_unreachable("unexpected context");
366}
367
368static QualType
370 TemplateParameterList *TemplateParams,
371 TypeSourceInfo *MethodTypeInfo) {
372 assert(MethodTypeInfo && "expected a non null type");
373
374 QualType MethodType = MethodTypeInfo->getType();
375 // If a lambda appears in a dependent context or is a generic lambda (has
376 // template parameters) and has an 'auto' return type, deduce it to a
377 // dependent type.
378 if (Class->isDependentContext() || TemplateParams) {
379 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
381 if (Result->isUndeducedType()) {
383 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
384 FPT->getExtProtoInfo());
385 }
386 }
387 return MethodType;
388}
389
391 CXXRecordDecl *Class, CXXMethodDecl *Method,
392 std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
393
394 ContextRAII ManglingContext(*this, Class->getDeclContext());
395
396 if (Mangling) {
397 bool HasKnownInternalLinkage;
398 unsigned ManglingNumber, DeviceManglingNumber;
399 Decl *ManglingContextDecl;
400 std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
401 ManglingContextDecl) = *Mangling;
402 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
403 HasKnownInternalLinkage);
404 Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
405 return;
406 }
407
408 auto getMangleNumberingContext =
409 [this](CXXRecordDecl *Class,
410 Decl *ManglingContextDecl) -> MangleNumberingContext * {
411 // Get mangle numbering context if there's any extra decl context.
412 if (ManglingContextDecl)
414 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
415 // Otherwise, from that lambda's decl context.
416 auto DC = Class->getDeclContext();
417 while (auto *CD = dyn_cast<CapturedDecl>(DC))
418 DC = CD->getParent();
420 };
421
423 Decl *ManglingContextDecl;
424 std::tie(MCtx, ManglingContextDecl) =
425 getCurrentMangleNumberContext(Class->getDeclContext());
426 bool HasKnownInternalLinkage = false;
427 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
428 getLangOpts().SYCLIsHost)) {
429 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
430 // ODR. Both device- and host-compilation need to have a consistent naming
431 // on kernel functions. As lambdas are potential part of these `__global__`
432 // function names, they needs numbering following ODR.
433 // Also force for SYCL, since we need this for the
434 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
435 // mangling.
436 MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
437 assert(MCtx && "Retrieving mangle numbering context failed!");
438 HasKnownInternalLinkage = true;
439 }
440 if (MCtx) {
441 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
442 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
443 HasKnownInternalLinkage);
444 Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
445 }
446}
447
449 CXXMethodDecl *CallOperator,
450 bool ExplicitResultType) {
451 if (ExplicitResultType) {
452 LSI->HasImplicitReturnType = false;
453 LSI->ReturnType = CallOperator->getReturnType();
454 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
455 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
456 diag::err_lambda_incomplete_result);
457 } else {
458 LSI->HasImplicitReturnType = true;
459 }
460}
461
463 SourceRange IntroducerRange,
464 LambdaCaptureDefault CaptureDefault,
465 SourceLocation CaptureDefaultLoc,
466 bool ExplicitParams, bool Mutable) {
467 LSI->CallOperator = CallOperator;
468 CXXRecordDecl *LambdaClass = CallOperator->getParent();
469 LSI->Lambda = LambdaClass;
470 if (CaptureDefault == LCD_ByCopy)
471 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
472 else if (CaptureDefault == LCD_ByRef)
473 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
474 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
475 LSI->IntroducerRange = IntroducerRange;
476 LSI->ExplicitParams = ExplicitParams;
477 LSI->Mutable = Mutable;
478}
479
482}
483
485 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
486 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
487 ExprResult RequiresClause) {
489 assert(LSI && "Expected a lambda scope");
490 assert(LSI->NumExplicitTemplateParams == 0 &&
491 "Already acted on explicit template parameters");
492 assert(LSI->TemplateParams.empty() &&
493 "Explicit template parameters should come "
494 "before invented (auto) ones");
495 assert(!TParams.empty() &&
496 "No template parameters to act on");
497 LSI->TemplateParams.append(TParams.begin(), TParams.end());
498 LSI->NumExplicitTemplateParams = TParams.size();
499 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
500 LSI->RequiresClause = RequiresClause;
501}
502
503/// If this expression is an enumerator-like expression of some type
504/// T, return the type T; otherwise, return null.
505///
506/// Pointer comparisons on the result here should always work because
507/// it's derived from either the parent of an EnumConstantDecl
508/// (i.e. the definition) or the declaration returned by
509/// EnumType::getDecl() (i.e. the definition).
511 // An expression is an enumerator-like expression of type T if,
512 // ignoring parens and parens-like expressions:
513 E = E->IgnoreParens();
514
515 // - it is an enumerator whose enum type is T or
516 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
517 if (EnumConstantDecl *D
518 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
519 return cast<EnumDecl>(D->getDeclContext());
520 }
521 return nullptr;
522 }
523
524 // - it is a comma expression whose RHS is an enumerator-like
525 // expression of type T or
526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
527 if (BO->getOpcode() == BO_Comma)
528 return findEnumForBlockReturn(BO->getRHS());
529 return nullptr;
530 }
531
532 // - it is a statement-expression whose value expression is an
533 // enumerator-like expression of type T or
534 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
535 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
536 return findEnumForBlockReturn(last);
537 return nullptr;
538 }
539
540 // - it is a ternary conditional operator (not the GNU ?:
541 // extension) whose second and third operands are
542 // enumerator-like expressions of type T or
543 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
544 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
545 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
546 return ED;
547 return nullptr;
548 }
549
550 // (implicitly:)
551 // - it is an implicit integral conversion applied to an
552 // enumerator-like expression of type T or
553 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
554 // We can sometimes see integral conversions in valid
555 // enumerator-like expressions.
556 if (ICE->getCastKind() == CK_IntegralCast)
557 return findEnumForBlockReturn(ICE->getSubExpr());
558
559 // Otherwise, just rely on the type.
560 }
561
562 // - it is an expression of that formal enum type.
563 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
564 return ET->getDecl();
565 }
566
567 // Otherwise, nope.
568 return nullptr;
569}
570
571/// Attempt to find a type T for which the returned expression of the
572/// given statement is an enumerator-like expression of that type.
574 if (Expr *retValue = ret->getRetValue())
575 return findEnumForBlockReturn(retValue);
576 return nullptr;
577}
578
579/// Attempt to find a common type T for which all of the returned
580/// expressions in a block are enumerator-like expressions of that
581/// type.
583 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
584
585 // Try to find one for the first return.
587 if (!ED) return nullptr;
588
589 // Check that the rest of the returns have the same enum.
590 for (++i; i != e; ++i) {
591 if (findEnumForBlockReturn(*i) != ED)
592 return nullptr;
593 }
594
595 // Never infer an anonymous enum type.
596 if (!ED->hasNameForLinkage()) return nullptr;
597
598 return ED;
599}
600
601/// Adjust the given return statements so that they formally return
602/// the given type. It should require, at most, an IntegralCast.
604 QualType returnType) {
606 i = returns.begin(), e = returns.end(); i != e; ++i) {
607 ReturnStmt *ret = *i;
608 Expr *retValue = ret->getRetValue();
609 if (S.Context.hasSameType(retValue->getType(), returnType))
610 continue;
611
612 // Right now we only support integral fixup casts.
613 assert(returnType->isIntegralOrUnscopedEnumerationType());
614 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
615
616 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
617
618 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
619 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
620 /*base path*/ nullptr, VK_PRValue,
622 if (cleanups) {
623 cleanups->setSubExpr(E);
624 } else {
625 ret->setRetValue(E);
626 }
627 }
628}
629
631 assert(CSI.HasImplicitReturnType);
632 // If it was ever a placeholder, it had to been deduced to DependentTy.
633 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
634 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
635 "lambda expressions use auto deduction in C++14 onwards");
636
637 // C++ core issue 975:
638 // If a lambda-expression does not include a trailing-return-type,
639 // it is as if the trailing-return-type denotes the following type:
640 // - if there are no return statements in the compound-statement,
641 // or all return statements return either an expression of type
642 // void or no expression or braced-init-list, the type void;
643 // - otherwise, if all return statements return an expression
644 // and the types of the returned expressions after
645 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
646 // array-to-pointer conversion (4.2 [conv.array]), and
647 // function-to-pointer conversion (4.3 [conv.func]) are the
648 // same, that common type;
649 // - otherwise, the program is ill-formed.
650 //
651 // C++ core issue 1048 additionally removes top-level cv-qualifiers
652 // from the types of returned expressions to match the C++14 auto
653 // deduction rules.
654 //
655 // In addition, in blocks in non-C++ modes, if all of the return
656 // statements are enumerator-like expressions of some type T, where
657 // T has a name for linkage, then we infer the return type of the
658 // block to be that type.
659
660 // First case: no return statements, implicit void return type.
661 ASTContext &Ctx = getASTContext();
662 if (CSI.Returns.empty()) {
663 // It's possible there were simply no /valid/ return statements.
664 // In this case, the first one we found may have at least given us a type.
665 if (CSI.ReturnType.isNull())
666 CSI.ReturnType = Ctx.VoidTy;
667 return;
668 }
669
670 // Second case: at least one return statement has dependent type.
671 // Delay type checking until instantiation.
672 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
673 if (CSI.ReturnType->isDependentType())
674 return;
675
676 // Try to apply the enum-fuzz rule.
677 if (!getLangOpts().CPlusPlus) {
678 assert(isa<BlockScopeInfo>(CSI));
680 if (ED) {
683 return;
684 }
685 }
686
687 // Third case: only one return statement. Don't bother doing extra work!
688 if (CSI.Returns.size() == 1)
689 return;
690
691 // General case: many return statements.
692 // Check that they all have compatible return types.
693
694 // We require the return types to strictly match here.
695 // Note that we've already done the required promotions as part of
696 // processing the return statement.
697 for (const ReturnStmt *RS : CSI.Returns) {
698 const Expr *RetE = RS->getRetValue();
699
700 QualType ReturnType =
701 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
702 if (Context.getCanonicalFunctionResultType(ReturnType) ==
704 // Use the return type with the strictest possible nullability annotation.
705 auto RetTyNullability = ReturnType->getNullability();
706 auto BlockNullability = CSI.ReturnType->getNullability();
707 if (BlockNullability &&
708 (!RetTyNullability ||
709 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
710 CSI.ReturnType = ReturnType;
711 continue;
712 }
713
714 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
715 // TODO: It's possible that the *first* return is the divergent one.
716 Diag(RS->getBeginLoc(),
717 diag::err_typecheck_missing_return_type_incompatible)
718 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
719 // Continue iterating so that we keep emitting diagnostics.
720 }
721}
722
724 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
725 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
726 bool IsDirectInit, Expr *&Init) {
727 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
728 // deduce against.
729 QualType DeductType = Context.getAutoDeductType();
730 TypeLocBuilder TLB;
731 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
732 TL.setNameLoc(Loc);
733 if (ByRef) {
734 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
735 assert(!DeductType.isNull() && "can't build reference to auto");
736 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
737 }
738 if (EllipsisLoc.isValid()) {
739 if (Init->containsUnexpandedParameterPack()) {
740 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
741 ? diag::warn_cxx17_compat_init_capture_pack
742 : diag::ext_init_capture_pack);
743 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
744 /*ExpectPackInType=*/false);
745 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
746 } else {
747 // Just ignore the ellipsis for now and form a non-pack variable. We'll
748 // diagnose this later when we try to capture it.
749 }
750 }
751 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
752
753 // Deduce the type of the init capture.
755 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
756 SourceRange(Loc, Loc), IsDirectInit, Init);
757 if (DeducedType.isNull())
758 return QualType();
759
760 // Are we a non-list direct initialization?
761 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
762
763 // Perform initialization analysis and ensure any implicit conversions
764 // (such as lvalue-to-rvalue) are enforced.
765 InitializedEntity Entity =
767 InitializationKind Kind =
768 IsDirectInit
769 ? (CXXDirectInit ? InitializationKind::CreateDirect(
770 Loc, Init->getBeginLoc(), Init->getEndLoc())
772 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
773
774 MultiExprArg Args = Init;
775 if (CXXDirectInit)
776 Args =
777 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
778 QualType DclT;
779 InitializationSequence InitSeq(*this, Entity, Kind, Args);
780 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
781
782 if (Result.isInvalid())
783 return QualType();
784
785 Init = Result.getAs<Expr>();
786 return DeducedType;
787}
788
790 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
791 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
792 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
793 // rather than reconstructing it here.
794 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
795 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
796 PETL.setEllipsisLoc(EllipsisLoc);
797
798 // Create a dummy variable representing the init-capture. This is not actually
799 // used as a variable, and only exists as a way to name and refer to the
800 // init-capture.
801 // FIXME: Pass in separate source locations for '&' and identifier.
802 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
803 InitCaptureType, TSI, SC_Auto);
804 NewVD->setInitCapture(true);
805 NewVD->setReferenced(true);
806 // FIXME: Pass in a VarDecl::InitializationStyle.
807 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
808 NewVD->markUsed(Context);
809 NewVD->setInit(Init);
810 if (NewVD->isParameterPack())
811 getCurLambda()->LocalPacks.push_back(NewVD);
812 return NewVD;
813}
814
816 bool isReferenceType) {
817 assert(Var->isInitCapture() && "init capture flag should be set");
818 LSI->addCapture(Var, /*isBlock*/ false, isReferenceType,
819 /*isNested*/ false, Var->getLocation(), SourceLocation(),
820 Var->getType(), /*Invalid*/ false);
821}
822
823// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
824// check that the current lambda is in a consistent or fully constructed state.
826 assert(!S.FunctionScopes.empty());
827 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
828}
829
830static TypeSourceInfo *
832 // C++11 [expr.prim.lambda]p4:
833 // If a lambda-expression does not include a lambda-declarator, it is as
834 // if the lambda-declarator were ().
836 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
837 EPI.HasTrailingReturn = true;
838 EPI.TypeQuals.addConst();
840 if (AS != LangAS::Default)
842
843 // C++1y [expr.prim.lambda]:
844 // The lambda return type is 'auto', which is replaced by the
845 // trailing-return type if provided and/or deduced from 'return'
846 // statements
847 // We don't do this before C++1y, because we don't support deduced return
848 // types there.
849 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
852 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
853 std::nullopt, EPI);
854 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
855}
856
858 Declarator &ParamInfo, Scope *CurScope,
859 SourceLocation Loc,
860 bool &ExplicitResultType) {
861
862 ExplicitResultType = false;
863
864 assert(
865 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
868 "Unexpected storage specifier");
869 bool IsLambdaStatic =
871
872 TypeSourceInfo *MethodTyInfo;
873
874 if (ParamInfo.getNumTypeObjects() == 0) {
875 MethodTyInfo = getDummyLambdaType(S, Loc);
876 } else {
878 ExplicitResultType = FTI.hasTrailingReturnType();
879 if (!FTI.hasMutableQualifier() && !IsLambdaStatic)
881
882 if (ExplicitResultType && S.getLangOpts().HLSL) {
883 QualType RetTy = FTI.getTrailingReturnType().get();
884 if (!RetTy.isNull()) {
885 // HLSL does not support specifying an address space on a lambda return
886 // type.
887 LangAS AddressSpace = RetTy.getAddressSpace();
888 if (AddressSpace != LangAS::Default)
890 diag::err_return_value_with_address_space);
891 }
892 }
893
894 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo, CurScope);
895 assert(MethodTyInfo && "no type from lambda-declarator");
896
897 // Check for unexpanded parameter packs in the method type.
898 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
899 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
901 }
902 return MethodTyInfo;
903}
904
906 CXXRecordDecl *Class) {
907
908 // C++20 [expr.prim.lambda.closure]p3:
909 // The closure type for a lambda-expression has a public inline function
910 // call operator (for a non-generic lambda) or function call operator
911 // template (for a generic lambda) whose parameters and return type are
912 // described by the lambda-expression's parameter-declaration-clause
913 // and trailing-return-type respectively.
914 DeclarationName MethodName =
916 DeclarationNameLoc MethodNameLoc =
919 Context, Class, SourceLocation(),
920 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
921 MethodNameLoc),
922 QualType(), /*Tinfo=*/nullptr, SC_None,
923 getCurFPFeatures().isFPConstrained(),
925 /*TrailingRequiresClause=*/nullptr);
926 Method->setAccess(AS_public);
927 return Method;
928}
929
931 CXXMethodDecl *Method, SourceLocation LambdaLoc,
932 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
933 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
935 bool HasExplicitResultType) {
936
938
939 if (TrailingRequiresClause)
940 Method->setTrailingRequiresClause(TrailingRequiresClause);
941
942 TemplateParameterList *TemplateParams =
944
945 DeclContext *DC = Method->getLexicalDeclContext();
946 Method->setLexicalDeclContext(LSI->Lambda);
947 if (TemplateParams) {
949 Context, LSI->Lambda, Method->getLocation(), Method->getDeclName(),
950 TemplateParams, Method);
951 TemplateMethod->setAccess(AS_public);
952 Method->setDescribedFunctionTemplate(TemplateMethod);
953 LSI->Lambda->addDecl(TemplateMethod);
954 TemplateMethod->setLexicalDeclContext(DC);
955 } else {
956 LSI->Lambda->addDecl(Method);
957 }
958 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
959 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
960
961 Method->setLexicalDeclContext(DC);
962 Method->setLocation(LambdaLoc);
963 Method->setInnerLocStart(CallOperatorLoc);
964 Method->setTypeSourceInfo(MethodTyInfo);
966 TemplateParams, MethodTyInfo));
967 Method->setConstexprKind(ConstexprKind);
968 Method->setStorageClass(SC);
969 if (!Params.empty()) {
970 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
971 Method->setParams(Params);
972 for (auto P : Method->parameters()) {
973 if (!P)
974 continue;
975 P->setOwningFunction(Method);
976 }
977 }
978
979 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
980}
981
983 Scope *CurrentScope) {
984
986 assert(LSI && "LambdaScopeInfo should be on stack!");
987
988 if (Intro.Default == LCD_ByCopy)
989 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
990 else if (Intro.Default == LCD_ByRef)
991 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
992 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
993 LSI->IntroducerRange = Intro.Range;
994 LSI->AfterParameterList = false;
995
996 assert(LSI->NumExplicitTemplateParams == 0);
997
998 // Determine if we're within a context where we know that the lambda will
999 // be dependent, because there are template parameters in scope.
1000 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1002 if (LSI->NumExplicitTemplateParams > 0) {
1003 Scope *TemplateParamScope = CurScope->getTemplateParamParent();
1004 assert(TemplateParamScope &&
1005 "Lambda with explicit template param list should establish a "
1006 "template param scope");
1007 assert(TemplateParamScope->getParent());
1008 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
1009 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1010 } else if (CurScope->getTemplateParamParent() != nullptr) {
1011 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1012 }
1013
1015 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1016 LSI->Lambda = Class;
1017
1018 CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class);
1019 LSI->CallOperator = Method;
1021
1022 PushDeclContext(CurScope, Method);
1023
1024 bool ContainsUnexpandedParameterPack = false;
1025
1026 // Distinct capture names, for diagnostics.
1027 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1028
1029 // Handle explicit captures.
1030 SourceLocation PrevCaptureLoc =
1031 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1032 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1033 PrevCaptureLoc = C->Loc, ++C) {
1034 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1035 if (C->Kind == LCK_StarThis)
1036 Diag(C->Loc, !getLangOpts().CPlusPlus17
1037 ? diag::ext_star_this_lambda_capture_cxx17
1038 : diag::warn_cxx14_compat_star_this_lambda_capture);
1039
1040 // C++11 [expr.prim.lambda]p8:
1041 // An identifier or this shall not appear more than once in a
1042 // lambda-capture.
1043 if (LSI->isCXXThisCaptured()) {
1044 Diag(C->Loc, diag::err_capture_more_than_once)
1045 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1047 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1048 continue;
1049 }
1050
1051 // C++20 [expr.prim.lambda]p8:
1052 // If a lambda-capture includes a capture-default that is =,
1053 // each simple-capture of that lambda-capture shall be of the form
1054 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1055 // redundant but accepted for compatibility with ISO C++14. --end note ]
1056 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1057 Diag(C->Loc, !getLangOpts().CPlusPlus20
1058 ? diag::ext_equals_this_lambda_capture_cxx20
1059 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1060
1061 // C++11 [expr.prim.lambda]p12:
1062 // If this is captured by a local lambda expression, its nearest
1063 // enclosing function shall be a non-static member function.
1064 QualType ThisCaptureType = getCurrentThisType();
1065 if (ThisCaptureType.isNull()) {
1066 Diag(C->Loc, diag::err_this_capture) << true;
1067 continue;
1068 }
1069
1070 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1071 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1072 C->Kind == LCK_StarThis);
1073 if (!LSI->Captures.empty())
1074 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1075 continue;
1076 }
1077
1078 assert(C->Id && "missing identifier for capture");
1079
1080 if (C->Init.isInvalid())
1081 continue;
1082
1083 ValueDecl *Var = nullptr;
1084 if (C->Init.isUsable()) {
1086 ? diag::warn_cxx11_compat_init_capture
1087 : diag::ext_init_capture);
1088
1089 // If the initializer expression is usable, but the InitCaptureType
1090 // is not, then an error has occurred - so ignore the capture for now.
1091 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1092 // FIXME: we should create the init capture variable and mark it invalid
1093 // in this case.
1094 if (C->InitCaptureType.get().isNull())
1095 continue;
1096
1097 if (C->Init.get()->containsUnexpandedParameterPack() &&
1098 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1100
1101 unsigned InitStyle;
1102 switch (C->InitKind) {
1104 llvm_unreachable("not an init-capture?");
1106 InitStyle = VarDecl::CInit;
1107 break;
1109 InitStyle = VarDecl::CallInit;
1110 break;
1112 InitStyle = VarDecl::ListInit;
1113 break;
1114 }
1115 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1116 C->EllipsisLoc, C->Id, InitStyle,
1117 C->Init.get(), Method);
1118 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1119 if (auto *V = dyn_cast<VarDecl>(Var))
1120 CheckShadow(CurrentScope, V);
1121 PushOnScopeChains(Var, CurrentScope, false);
1122 } else {
1123 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1124 "init capture has valid but null init?");
1125
1126 // C++11 [expr.prim.lambda]p8:
1127 // If a lambda-capture includes a capture-default that is &, the
1128 // identifiers in the lambda-capture shall not be preceded by &.
1129 // If a lambda-capture includes a capture-default that is =, [...]
1130 // each identifier it contains shall be preceded by &.
1131 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1132 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1134 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1135 continue;
1136 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1137 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1139 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1140 continue;
1141 }
1142
1143 // C++11 [expr.prim.lambda]p10:
1144 // The identifiers in a capture-list are looked up using the usual
1145 // rules for unqualified name lookup (3.4.1)
1146 DeclarationNameInfo Name(C->Id, C->Loc);
1147 LookupResult R(*this, Name, LookupOrdinaryName);
1148 LookupName(R, CurScope);
1149 if (R.isAmbiguous())
1150 continue;
1151 if (R.empty()) {
1152 // FIXME: Disable corrections that would add qualification?
1153 CXXScopeSpec ScopeSpec;
1154 DeclFilterCCC<VarDecl> Validator{};
1155 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1156 continue;
1157 }
1158
1159 if (auto *BD = R.getAsSingle<BindingDecl>())
1160 Var = BD;
1161 else
1162 Var = R.getAsSingle<VarDecl>();
1163 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1164 continue;
1165 }
1166
1167 // C++11 [expr.prim.lambda]p10:
1168 // [...] each such lookup shall find a variable with automatic storage
1169 // duration declared in the reaching scope of the local lambda expression.
1170 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1171 if (!Var) {
1172 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1173 continue;
1174 }
1175
1176 // C++11 [expr.prim.lambda]p8:
1177 // An identifier or this shall not appear more than once in a
1178 // lambda-capture.
1179 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1180 !Inserted) {
1181 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1182 !Var->isInitCapture()) {
1183 Diag(C->Loc, diag::err_capture_more_than_once)
1184 << C->Id << It->second->getBeginLoc()
1186 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1187 } else
1188 // Previous capture captured something different (one or both was
1189 // an init-capture): no fixit.
1190 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1191 continue;
1192 }
1193
1194 // Ignore invalid decls; they'll just confuse the code later.
1195 if (Var->isInvalidDecl())
1196 continue;
1197
1198 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1199
1200 if (!Underlying->hasLocalStorage()) {
1201 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1202 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1203 continue;
1204 }
1205
1206 // C++11 [expr.prim.lambda]p23:
1207 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1208 SourceLocation EllipsisLoc;
1209 if (C->EllipsisLoc.isValid()) {
1210 if (Var->isParameterPack()) {
1211 EllipsisLoc = C->EllipsisLoc;
1212 } else {
1213 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1214 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1215 : SourceRange(C->Loc));
1216
1217 // Just ignore the ellipsis.
1218 }
1219 } else if (Var->isParameterPack()) {
1220 ContainsUnexpandedParameterPack = true;
1221 }
1222
1223 if (C->Init.isUsable()) {
1224 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1225 PushOnScopeChains(Var, CurScope, false);
1226 } else {
1229 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1230 }
1231 if (!LSI->Captures.empty())
1232 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1233 }
1235 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1237}
1238
1240 SourceLocation MutableLoc) {
1241
1243 LSI->Mutable = MutableLoc.isValid();
1244 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1245
1246 // C++11 [expr.prim.lambda]p9:
1247 // A lambda-expression whose smallest enclosing scope is a block scope is a
1248 // local lambda expression; any other lambda expression shall not have a
1249 // capture-default or simple-capture in its lambda-introducer.
1250 //
1251 // For simple-captures, this is covered by the check below that any named
1252 // entity is a variable that can be captured.
1253 //
1254 // For DR1632, we also allow a capture-default in any context where we can
1255 // odr-use 'this' (in particular, in a default initializer for a non-static
1256 // data member).
1257 if (Intro.Default != LCD_None &&
1258 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1259 (getCurrentThisType().isNull() ||
1260 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1261 /*BuildAndDiagnose=*/false)))
1262 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1263}
1264
1268 PushDeclContext(LambdaScope, LSI->CallOperator);
1269
1270 for (const DeclaratorChunk::ParamInfo &P : Params) {
1271 auto *Param = cast<ParmVarDecl>(P.Param);
1272 Param->setOwningFunction(LSI->CallOperator);
1273 if (Param->getIdentifier())
1274 PushOnScopeChains(Param, LambdaScope, false);
1275 }
1276
1277 LSI->AfterParameterList = true;
1278}
1279
1281 Declarator &ParamInfo,
1282 const DeclSpec &DS) {
1283
1286
1288 bool ExplicitResultType;
1289
1290 SourceLocation TypeLoc, CallOperatorLoc;
1291 if (ParamInfo.getNumTypeObjects() == 0) {
1292 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1293 } else {
1294 unsigned Index;
1295 ParamInfo.isFunctionDeclarator(Index);
1296 const auto &Object = ParamInfo.getTypeObject(Index);
1297 TypeLoc =
1298 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1299 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1300 }
1301
1302 CXXRecordDecl *Class = LSI->Lambda;
1303 CXXMethodDecl *Method = LSI->CallOperator;
1304
1305 TypeSourceInfo *MethodTyInfo = getLambdaType(
1306 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1307
1308 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1309
1310 if (ParamInfo.isFunctionDeclarator() != 0 &&
1312 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1313 Params.reserve(Params.size());
1314 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1315 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1316 Param->setScopeInfo(0, Params.size());
1317 Params.push_back(Param);
1318 }
1319 }
1320
1321 bool IsLambdaStatic =
1323
1325 Method, Intro.Range.getBegin(), CallOperatorLoc,
1326 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1327 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1328 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1329
1331
1332 // This represents the function body for the lambda function, check if we
1333 // have to apply optnone due to a pragma.
1334 AddRangeBasedOptnone(Method);
1335
1336 // code_seg attribute on lambda apply to the method.
1338 Method, /*IsDefinition=*/true))
1339 Method->addAttr(A);
1340
1341 // Attributes on the lambda apply to the method.
1342 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1343
1344 // CUDA lambdas get implicit host and device attributes.
1345 if (getLangOpts().CUDA)
1346 CUDASetLambdaAttrs(Method);
1347
1348 // OpenMP lambdas might get assumumption attributes.
1349 if (LangOpts.OpenMP)
1351
1352 handleLambdaNumbering(Class, Method);
1353
1354 for (auto &&C : LSI->Captures) {
1355 if (!C.isVariableCapture())
1356 continue;
1357 ValueDecl *Var = C.getVariable();
1358 if (Var && Var->isInitCapture()) {
1359 PushOnScopeChains(Var, CurScope, false);
1360 }
1361 }
1362
1363 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1364 for (const auto &Capture : Intro.Captures) {
1365 if (Capture.Id == Param->getIdentifier()) {
1366 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1367 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1368 << Capture.Id << true;
1369 return false;
1370 }
1371 }
1372 return true;
1373 };
1374
1375 for (ParmVarDecl *P : Params) {
1376 if (!P->getIdentifier())
1377 continue;
1378 if (CheckRedefinition(P))
1379 CheckShadow(CurScope, P);
1380 PushOnScopeChains(P, CurScope);
1381 }
1382
1383 // Enter a new evaluation context to insulate the lambda from any
1384 // cleanups from the enclosing full-expression.
1389}
1390
1392 bool IsInstantiation) {
1393 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1394
1395 // Leave the expression-evaluation context.
1398
1399 // Leave the context of the lambda.
1400 if (!IsInstantiation)
1402
1403 // Finalize the lambda.
1404 CXXRecordDecl *Class = LSI->Lambda;
1405 Class->setInvalidDecl();
1406 SmallVector<Decl*, 4> Fields(Class->fields());
1407 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1409 CheckCompletedCXXClass(nullptr, Class);
1410
1412}
1413
1414template <typename Func>
1416 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1418 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1420 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1421 CallingConv CallOpCC = CallOpProto.getCallConv();
1422
1423 /// Implement emitting a version of the operator for many of the calling
1424 /// conventions for MSVC, as described here:
1425 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1426 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1427 /// vectorcall are generated by MSVC when it is supported by the target.
1428 /// Additionally, we are ensuring that the default-free/default-member and
1429 /// call-operator calling convention are generated as well.
1430 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1431 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1432 /// that someone who intentionally places 'thiscall' on the lambda call
1433 /// operator will still get that overload, since we don't have the a way of
1434 /// detecting the attribute by the time we get here.
1435 if (S.getLangOpts().MSVCCompat) {
1436 CallingConv Convs[] = {
1438 DefaultFree, DefaultMember, CallOpCC};
1439 llvm::sort(Convs);
1440 llvm::iterator_range<CallingConv *> Range(
1441 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1442 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1443
1444 for (CallingConv C : Range) {
1446 F(C);
1447 }
1448 return;
1449 }
1450
1451 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1452 F(DefaultFree);
1453 F(DefaultMember);
1454 } else {
1455 F(CallOpCC);
1456 }
1457}
1458
1459// Returns the 'standard' calling convention to be used for the lambda
1460// conversion function, that is, the 'free' function calling convention unless
1461// it is overridden by a non-default calling convention attribute.
1462static CallingConv
1464 const FunctionProtoType *CallOpProto) {
1466 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1468 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1469 CallingConv CallOpCC = CallOpProto->getCallConv();
1470
1471 // If the call-operator hasn't been changed, return both the 'free' and
1472 // 'member' function calling convention.
1473 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1474 return DefaultFree;
1475 return CallOpCC;
1476}
1477
1479 const FunctionProtoType *CallOpProto, CallingConv CC) {
1480 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1481 CallOpProto->getExtProtoInfo();
1482 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1483 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1484 InvokerExtInfo.TypeQuals = Qualifiers();
1485 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1486 "Lambda's call operator should not have a reference qualifier");
1487 return Context.getFunctionType(CallOpProto->getReturnType(),
1488 CallOpProto->getParamTypes(), InvokerExtInfo);
1489}
1490
1491/// Add a lambda's conversion to function pointer, as described in
1492/// C++11 [expr.prim.lambda]p6.
1493static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1494 CXXRecordDecl *Class,
1495 CXXMethodDecl *CallOperator,
1496 QualType InvokerFunctionTy) {
1497 // This conversion is explicitly disabled if the lambda's function has
1498 // pass_object_size attributes on any of its parameters.
1499 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1500 return P->hasAttr<PassObjectSizeAttr>();
1501 };
1502 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1503 return;
1504
1505 // Add the conversion to function pointer.
1506 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1507
1508 // Create the type of the conversion function.
1511 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1512 // The conversion function is always const and noexcept.
1513 ConvExtInfo.TypeQuals = Qualifiers();
1514 ConvExtInfo.TypeQuals.addConst();
1515 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1516 QualType ConvTy =
1517 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1518
1519 SourceLocation Loc = IntroducerRange.getBegin();
1520 DeclarationName ConversionName
1522 S.Context.getCanonicalType(PtrToFunctionTy));
1523 // Construct a TypeSourceInfo for the conversion function, and wire
1524 // all the parameters appropriately for the FunctionProtoTypeLoc
1525 // so that everything works during transformation/instantiation of
1526 // generic lambdas.
1527 // The main reason for wiring up the parameters of the conversion
1528 // function with that of the call operator is so that constructs
1529 // like the following work:
1530 // auto L = [](auto b) { <-- 1
1531 // return [](auto a) -> decltype(a) { <-- 2
1532 // return a;
1533 // };
1534 // };
1535 // int (*fp)(int) = L(5);
1536 // Because the trailing return type can contain DeclRefExprs that refer
1537 // to the original call operator's variables, we hijack the call
1538 // operators ParmVarDecls below.
1539 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1540 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1541 DeclarationNameLoc ConvNameLoc =
1542 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1543
1544 // The conversion function is a conversion to a pointer-to-function.
1545 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1546 FunctionProtoTypeLoc ConvTL =
1548 // Get the result of the conversion function which is a pointer-to-function.
1549 PointerTypeLoc PtrToFunctionTL =
1550 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1551 // Do the same for the TypeSourceInfo that is used to name the conversion
1552 // operator.
1553 PointerTypeLoc ConvNamePtrToFunctionTL =
1554 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1555
1556 // Get the underlying function types that the conversion function will
1557 // be converting to (should match the type of the call operator).
1558 FunctionProtoTypeLoc CallOpConvTL =
1559 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1560 FunctionProtoTypeLoc CallOpConvNameTL =
1561 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1562
1563 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1564 // These parameter's are essentially used to transform the name and
1565 // the type of the conversion operator. By using the same parameters
1566 // as the call operator's we don't have to fix any back references that
1567 // the trailing return type of the call operator's uses (such as
1568 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1569 // - we can simply use the return type of the call operator, and
1570 // everything should work.
1571 SmallVector<ParmVarDecl *, 4> InvokerParams;
1572 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1573 ParmVarDecl *From = CallOperator->getParamDecl(I);
1574
1575 InvokerParams.push_back(ParmVarDecl::Create(
1576 S.Context,
1577 // Temporarily add to the TU. This is set to the invoker below.
1579 From->getLocation(), From->getIdentifier(), From->getType(),
1580 From->getTypeSourceInfo(), From->getStorageClass(),
1581 /*DefArg=*/nullptr));
1582 CallOpConvTL.setParam(I, From);
1583 CallOpConvNameTL.setParam(I, From);
1584 }
1585
1587 S.Context, Class, Loc,
1588 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1590 /*isInline=*/true, ExplicitSpecifier(),
1593 CallOperator->getBody()->getEndLoc());
1594 Conversion->setAccess(AS_public);
1595 Conversion->setImplicit(true);
1596
1597 if (Class->isGenericLambda()) {
1598 // Create a template version of the conversion operator, using the template
1599 // parameter list of the function call operator.
1600 FunctionTemplateDecl *TemplateCallOperator =
1601 CallOperator->getDescribedFunctionTemplate();
1602 FunctionTemplateDecl *ConversionTemplate =
1604 Loc, ConversionName,
1605 TemplateCallOperator->getTemplateParameters(),
1606 Conversion);
1607 ConversionTemplate->setAccess(AS_public);
1608 ConversionTemplate->setImplicit(true);
1609 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1610 Class->addDecl(ConversionTemplate);
1611 } else
1612 Class->addDecl(Conversion);
1613
1614 // If the lambda is not static, we need to add a static member
1615 // function that will be the result of the conversion with a
1616 // certain unique ID.
1617 // When it is static we just return the static call operator instead.
1618 if (CallOperator->isInstance()) {
1619 DeclarationName InvokerName =
1621 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1622 // we should get a prebuilt TrivialTypeSourceInfo from Context
1623 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1624 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1625 // loop below and then use its Params to set Invoke->setParams(...) below.
1626 // This would avoid the 'const' qualifier of the calloperator from
1627 // contaminating the type of the invoker, which is currently adjusted
1628 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1629 // trailing return type of the invoker would require a visitor to rebuild
1630 // the trailing return type and adjusting all back DeclRefExpr's to refer
1631 // to the new static invoker parameters - not the call operator's.
1633 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1634 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1636 /*isInline=*/true, CallOperator->getConstexprKind(),
1637 CallOperator->getBody()->getEndLoc());
1638 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1639 InvokerParams[I]->setOwningFunction(Invoke);
1640 Invoke->setParams(InvokerParams);
1641 Invoke->setAccess(AS_private);
1642 Invoke->setImplicit(true);
1643 if (Class->isGenericLambda()) {
1644 FunctionTemplateDecl *TemplateCallOperator =
1645 CallOperator->getDescribedFunctionTemplate();
1646 FunctionTemplateDecl *StaticInvokerTemplate =
1648 S.Context, Class, Loc, InvokerName,
1649 TemplateCallOperator->getTemplateParameters(), Invoke);
1650 StaticInvokerTemplate->setAccess(AS_private);
1651 StaticInvokerTemplate->setImplicit(true);
1652 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1653 Class->addDecl(StaticInvokerTemplate);
1654 } else
1655 Class->addDecl(Invoke);
1656 }
1657}
1658
1659/// Add a lambda's conversion to function pointers, as described in
1660/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1661/// single pointer conversion. In the event that the default calling convention
1662/// for free and member functions is different, it will emit both conventions.
1663static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1664 CXXRecordDecl *Class,
1665 CXXMethodDecl *CallOperator) {
1666 const FunctionProtoType *CallOpProto =
1667 CallOperator->getType()->castAs<FunctionProtoType>();
1668
1670 S, *CallOpProto, [&](CallingConv CC) {
1671 QualType InvokerFunctionTy =
1672 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1673 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1674 InvokerFunctionTy);
1675 });
1676}
1677
1678/// Add a lambda's conversion to block pointer.
1680 SourceRange IntroducerRange,
1681 CXXRecordDecl *Class,
1682 CXXMethodDecl *CallOperator) {
1683 const FunctionProtoType *CallOpProto =
1684 CallOperator->getType()->castAs<FunctionProtoType>();
1686 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1687 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1688
1689 FunctionProtoType::ExtProtoInfo ConversionEPI(
1691 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1692 ConversionEPI.TypeQuals = Qualifiers();
1693 ConversionEPI.TypeQuals.addConst();
1694 QualType ConvTy =
1695 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1696
1697 SourceLocation Loc = IntroducerRange.getBegin();
1698 DeclarationName Name
1700 S.Context.getCanonicalType(BlockPtrTy));
1702 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1704 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1705 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1708 CallOperator->getBody()->getEndLoc());
1709 Conversion->setAccess(AS_public);
1710 Conversion->setImplicit(true);
1711 Class->addDecl(Conversion);
1712}
1713
1715 SourceLocation ImplicitCaptureLoc,
1716 bool IsOpenMPMapping) {
1717 // VLA captures don't have a stored initialization expression.
1718 if (Cap.isVLATypeCapture())
1719 return ExprResult();
1720
1721 // An init-capture is initialized directly from its stored initializer.
1722 if (Cap.isInitCapture())
1723 return cast<VarDecl>(Cap.getVariable())->getInit();
1724
1725 // For anything else, build an initialization expression. For an implicit
1726 // capture, the capture notionally happens at the capture-default, so use
1727 // that location here.
1728 SourceLocation Loc =
1729 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1730
1731 // C++11 [expr.prim.lambda]p21:
1732 // When the lambda-expression is evaluated, the entities that
1733 // are captured by copy are used to direct-initialize each
1734 // corresponding non-static data member of the resulting closure
1735 // object. (For array members, the array elements are
1736 // direct-initialized in increasing subscript order.) These
1737 // initializations are performed in the (unspecified) order in
1738 // which the non-static data members are declared.
1739
1740 // C++ [expr.prim.lambda]p12:
1741 // An entity captured by a lambda-expression is odr-used (3.2) in
1742 // the scope containing the lambda-expression.
1743 ExprResult Init;
1744 IdentifierInfo *Name = nullptr;
1745 if (Cap.isThisCapture()) {
1746 QualType ThisTy = getCurrentThisType();
1747 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1748 if (Cap.isCopyCapture())
1749 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1750 else
1751 Init = This;
1752 } else {
1753 assert(Cap.isVariableCapture() && "unknown kind of capture");
1754 ValueDecl *Var = Cap.getVariable();
1755 Name = Var->getIdentifier();
1757 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1758 }
1759
1760 // In OpenMP, the capture kind doesn't actually describe how to capture:
1761 // variables are "mapped" onto the device in a process that does not formally
1762 // make a copy, even for a "copy capture".
1763 if (IsOpenMPMapping)
1764 return Init;
1765
1766 if (Init.isInvalid())
1767 return ExprError();
1768
1769 Expr *InitExpr = Init.get();
1771 Name, Cap.getCaptureType(), Loc);
1772 InitializationKind InitKind =
1773 InitializationKind::CreateDirect(Loc, Loc, Loc);
1774 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1775 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1776}
1777
1779 Scope *CurScope) {
1780 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1782 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1783}
1784
1787 switch (ICS) {
1789 return LCD_None;
1791 return LCD_ByCopy;
1794 return LCD_ByRef;
1796 llvm_unreachable("block capture in lambda");
1797 }
1798 llvm_unreachable("Unknown implicit capture style");
1799}
1800
1802 if (From.isInitCapture()) {
1803 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1804 if (Init && Init->HasSideEffects(Context))
1805 return true;
1806 }
1807
1808 if (!From.isCopyCapture())
1809 return false;
1810
1811 const QualType T = From.isThisCapture()
1813 : From.getCaptureType();
1814
1815 if (T.isVolatileQualified())
1816 return true;
1817
1818 const Type *BaseT = T->getBaseElementTypeUnsafe();
1819 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1820 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1821 !RD->hasTrivialDestructor();
1822
1823 return false;
1824}
1825
1827 const Capture &From) {
1828 if (CaptureHasSideEffects(From))
1829 return false;
1830
1831 if (From.isVLATypeCapture())
1832 return false;
1833
1834 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1835 if (From.isThisCapture())
1836 diag << "'this'";
1837 else
1838 diag << From.getVariable();
1839 diag << From.isNonODRUsed();
1840 diag << FixItHint::CreateRemoval(CaptureRange);
1841 return true;
1842}
1843
1844/// Create a field within the lambda class or captured statement record for the
1845/// given capture.
1847 const sema::Capture &Capture) {
1849 QualType FieldType = Capture.getCaptureType();
1850
1851 TypeSourceInfo *TSI = nullptr;
1852 if (Capture.isVariableCapture()) {
1853 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1854 if (Var && Var->isInitCapture())
1855 TSI = Var->getTypeSourceInfo();
1856 }
1857
1858 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1859 // appropriate, at least for an implicit capture.
1860 if (!TSI)
1861 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1862
1863 // Build the non-static data member.
1864 FieldDecl *Field =
1865 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1866 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1867 /*Mutable=*/false, ICIS_NoInit);
1868 // If the variable being captured has an invalid type, mark the class as
1869 // invalid as well.
1870 if (!FieldType->isDependentType()) {
1871 if (RequireCompleteSizedType(Loc, FieldType,
1872 diag::err_field_incomplete_or_sizeless)) {
1873 RD->setInvalidDecl();
1874 Field->setInvalidDecl();
1875 } else {
1876 NamedDecl *Def;
1877 FieldType->isIncompleteType(&Def);
1878 if (Def && Def->isInvalidDecl()) {
1879 RD->setInvalidDecl();
1880 Field->setInvalidDecl();
1881 }
1882 }
1883 }
1884 Field->setImplicit(true);
1885 Field->setAccess(AS_private);
1886 RD->addDecl(Field);
1887
1889 Field->setCapturedVLAType(Capture.getCapturedVLAType());
1890
1891 return Field;
1892}
1893
1895 LambdaScopeInfo *LSI) {
1896 // Collect information from the lambda scope.
1898 SmallVector<Expr *, 4> CaptureInits;
1899 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1900 LambdaCaptureDefault CaptureDefault =
1902 CXXRecordDecl *Class;
1903 CXXMethodDecl *CallOperator;
1904 SourceRange IntroducerRange;
1905 bool ExplicitParams;
1906 bool ExplicitResultType;
1907 CleanupInfo LambdaCleanup;
1908 bool ContainsUnexpandedParameterPack;
1909 bool IsGenericLambda;
1910 {
1911 CallOperator = LSI->CallOperator;
1912 Class = LSI->Lambda;
1913 IntroducerRange = LSI->IntroducerRange;
1914 ExplicitParams = LSI->ExplicitParams;
1915 ExplicitResultType = !LSI->HasImplicitReturnType;
1916 LambdaCleanup = LSI->Cleanup;
1917 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1918 IsGenericLambda = Class->isGenericLambda();
1919
1920 CallOperator->setLexicalDeclContext(Class);
1921 Decl *TemplateOrNonTemplateCallOperatorDecl =
1922 CallOperator->getDescribedFunctionTemplate()
1923 ? CallOperator->getDescribedFunctionTemplate()
1924 : cast<Decl>(CallOperator);
1925
1926 // FIXME: Is this really the best choice? Keeping the lexical decl context
1927 // set as CurContext seems more faithful to the source.
1928 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1929
1931
1932 // True if the current capture has a used capture or default before it.
1933 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1934 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1935 CaptureDefaultLoc : IntroducerRange.getBegin();
1936
1937 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1938 const Capture &From = LSI->Captures[I];
1939
1940 if (From.isInvalid())
1941 return ExprError();
1942
1943 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1944 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1945 SourceLocation ImplicitCaptureLoc =
1946 IsImplicit ? CaptureDefaultLoc : SourceLocation();
1947
1948 // Use source ranges of explicit captures for fixits where available.
1949 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1950
1951 // Warn about unused explicit captures.
1952 bool IsCaptureUsed = true;
1953 if (!CurContext->isDependentContext() && !IsImplicit &&
1954 !From.isODRUsed()) {
1955 // Initialized captures that are non-ODR used may not be eliminated.
1956 // FIXME: Where did the IsGenericLambda here come from?
1957 bool NonODRUsedInitCapture =
1958 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
1959 if (!NonODRUsedInitCapture) {
1960 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1961 SourceRange FixItRange;
1962 if (CaptureRange.isValid()) {
1963 if (!CurHasPreviousCapture && !IsLast) {
1964 // If there are no captures preceding this capture, remove the
1965 // following comma.
1966 FixItRange = SourceRange(CaptureRange.getBegin(),
1967 getLocForEndOfToken(CaptureRange.getEnd()));
1968 } else {
1969 // Otherwise, remove the comma since the last used capture.
1970 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1971 CaptureRange.getEnd());
1972 }
1973 }
1974
1975 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1976 }
1977 }
1978
1979 if (CaptureRange.isValid()) {
1980 CurHasPreviousCapture |= IsCaptureUsed;
1981 PrevCaptureLoc = CaptureRange.getEnd();
1982 }
1983
1984 // Map the capture to our AST representation.
1985 LambdaCapture Capture = [&] {
1986 if (From.isThisCapture()) {
1987 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1988 // because it results in a reference capture. Don't warn prior to
1989 // C++2a; there's nothing that can be done about it before then.
1990 if (getLangOpts().CPlusPlus20 && IsImplicit &&
1991 CaptureDefault == LCD_ByCopy) {
1992 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1993 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1995 getLocForEndOfToken(CaptureDefaultLoc), ", this");
1996 }
1997 return LambdaCapture(From.getLocation(), IsImplicit,
1999 } else if (From.isVLATypeCapture()) {
2000 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2001 } else {
2002 assert(From.isVariableCapture() && "unknown kind of capture");
2003 ValueDecl *Var = From.getVariable();
2004 LambdaCaptureKind Kind =
2006 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2007 From.getEllipsisLoc());
2008 }
2009 }();
2010
2011 // Form the initializer for the capture field.
2012 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2013
2014 // FIXME: Skip this capture if the capture is not used, the initializer
2015 // has no side-effects, the type of the capture is trivial, and the
2016 // lambda is not externally visible.
2017
2018 // Add a FieldDecl for the capture and form its initializer.
2019 BuildCaptureField(Class, From);
2020 Captures.push_back(Capture);
2021 CaptureInits.push_back(Init.get());
2022
2023 if (LangOpts.CUDA)
2024 CUDACheckLambdaCapture(CallOperator, From);
2025 }
2026
2027 Class->setCaptures(Context, Captures);
2028
2029 // C++11 [expr.prim.lambda]p6:
2030 // The closure type for a lambda-expression with no lambda-capture
2031 // has a public non-virtual non-explicit const conversion function
2032 // to pointer to function having the same parameter and return
2033 // types as the closure type's function call operator.
2034 if (Captures.empty() && CaptureDefault == LCD_None)
2035 addFunctionPointerConversions(*this, IntroducerRange, Class,
2036 CallOperator);
2037
2038 // Objective-C++:
2039 // The closure type for a lambda-expression has a public non-virtual
2040 // non-explicit const conversion function to a block pointer having the
2041 // same parameter and return types as the closure type's function call
2042 // operator.
2043 // FIXME: Fix generic lambda to block conversions.
2044 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2045 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2046
2047 // Finalize the lambda class.
2048 SmallVector<Decl*, 4> Fields(Class->fields());
2049 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2051 CheckCompletedCXXClass(nullptr, Class);
2052 }
2053
2054 Cleanup.mergeFrom(LambdaCleanup);
2055
2056 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2057 CaptureDefault, CaptureDefaultLoc,
2058 ExplicitParams, ExplicitResultType,
2059 CaptureInits, EndLoc,
2060 ContainsUnexpandedParameterPack);
2061 // If the lambda expression's call operator is not explicitly marked constexpr
2062 // and we are not in a dependent context, analyze the call operator to infer
2063 // its constexpr-ness, suppressing diagnostics while doing so.
2064 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2065 !CallOperator->isConstexpr() &&
2066 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2067 !Class->getDeclContext()->isDependentContext()) {
2068 CallOperator->setConstexprKind(
2073 }
2074
2075 // Emit delayed shadowing warnings now that the full capture list is known.
2077
2079 switch (ExprEvalContexts.back().Context) {
2080 // C++11 [expr.prim.lambda]p2:
2081 // A lambda-expression shall not appear in an unevaluated operand
2082 // (Clause 5).
2086 // C++1y [expr.const]p2:
2087 // A conditional-expression e is a core constant expression unless the
2088 // evaluation of e, following the rules of the abstract machine, would
2089 // evaluate [...] a lambda-expression.
2090 //
2091 // This is technically incorrect, there are some constant evaluated contexts
2092 // where this should be allowed. We should probably fix this when DR1607 is
2093 // ratified, it lays out the exact set of conditions where we shouldn't
2094 // allow a lambda-expression.
2097 // We don't actually diagnose this case immediately, because we
2098 // could be within a context where we might find out later that
2099 // the expression is potentially evaluated (e.g., for typeid).
2100 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2101 break;
2102
2106 break;
2107 }
2108 }
2109
2110 return MaybeBindToTemporary(Lambda);
2111}
2112
2114 SourceLocation ConvLocation,
2115 CXXConversionDecl *Conv,
2116 Expr *Src) {
2117 // Make sure that the lambda call operator is marked used.
2118 CXXRecordDecl *Lambda = Conv->getParent();
2119 CXXMethodDecl *CallOperator
2120 = cast<CXXMethodDecl>(
2121 Lambda->lookup(
2123 CallOperator->setReferenced();
2124 CallOperator->markUsed(Context);
2125
2128 CurrentLocation, Src);
2129 if (!Init.isInvalid())
2130 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2131
2132 if (Init.isInvalid())
2133 return ExprError();
2134
2135 // Create the new block to be returned.
2137
2138 // Set the type information.
2139 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2140 Block->setIsVariadic(CallOperator->isVariadic());
2141 Block->setBlockMissingReturnType(false);
2142
2143 // Add parameters.
2145 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2146 ParmVarDecl *From = CallOperator->getParamDecl(I);
2147 BlockParams.push_back(ParmVarDecl::Create(
2148 Context, Block, From->getBeginLoc(), From->getLocation(),
2149 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2150 From->getStorageClass(),
2151 /*DefArg=*/nullptr));
2152 }
2153 Block->setParams(BlockParams);
2154
2155 Block->setIsConversionFromLambda(true);
2156
2157 // Add capture. The capture uses a fake variable, which doesn't correspond
2158 // to any actual memory location. However, the initializer copy-initializes
2159 // the lambda object.
2160 TypeSourceInfo *CapVarTSI =
2162 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2163 ConvLocation, nullptr,
2164 Src->getType(), CapVarTSI,
2165 SC_None);
2166 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2167 /*nested=*/false, /*copy=*/Init.get());
2168 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2169
2170 // Add a fake function body to the block. IR generation is responsible
2171 // for filling in the actual body, which cannot be expressed as an AST.
2172 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2173
2174 // Create the block literal expression.
2175 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2176 ExprCleanupObjects.push_back(Block);
2178
2179 return BuildBlock;
2180}
#define V(N, I)
Definition: ASTContext.h:3217
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the clang::Expr interface and subclasses for C++ expressions.
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static CallingConv getLambdaConversionFunctionCallConv(Sema &S, const FunctionProtoType *CallOpProto)
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise,...
Definition: SemaLambda.cpp:510
static EnumDecl * findCommonEnumForBlockReturns(ArrayRef< ReturnStmt * > returns)
Attempt to find a common type T for which all of the returned expressions in a block are enumerator-l...
Definition: SemaLambda.cpp:582
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:857
static std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:64
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:825
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Definition: SemaLambda.cpp:603
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:230
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, bool ExplicitResultType)
Definition: SemaLambda.cpp:448
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:831
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:369
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:264
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointers, as described in C++11 [expr.prim.lambda]p6.
static void repeatForLambdaConversionFunctionCallingConvs(Sema &S, const FunctionProtoType &CallOpProto, Func F)
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator, QualType InvokerFunctionTy)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
This file provides some common utility functions for processing Lambdas.
tok::TokenKind ContextKind
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1060
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:635
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2505
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2521
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1106
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1559
IdentifierTable & Idents
Definition: ASTContext.h:631
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1078
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1537
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:744
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
PtrTy get() const
Definition: Ownership.h:169
Attr - This represents one attribute.
Definition: Attr.h:40
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3814
A binding in a decomposition declaration.
Definition: DeclCXX.h:4043
A class which contains all the information about a particular captured value.
Definition: Decl.h:4340
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4334
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5111
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5975
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2801
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2821
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2841
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2018
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2133
bool isInstance() const
Definition: DeclCXX.h:2045
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2230
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition: DeclCXX.h:1838
void setLambdaIsGeneric(bool IsGeneric)
Definition: DeclCXX.h:1845
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:147
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1420
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4152
reference front() const
Definition: DeclBase.h:1361
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1393
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1933
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2057
bool isFileContext() const
Definition: DeclBase.h:2003
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1186
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1949
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1705
bool isTranslationUnit() const
Definition: DeclBase.h:2008
bool isRecord() const
Definition: DeclBase.h:2012
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1619
bool isFunctionOrMethod() const
Definition: DeclBase.h:1985
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1238
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
SCS getStorageClassSpec() const
Definition: DeclSpec.h:475
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:980
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:793
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
void addAttr(Attr *A)
Definition: DeclBase.cpp:903
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:472
bool isInvalidDecl() const
Definition: DeclBase.h:571
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:486
SourceLocation getLocation() const
Definition: DeclBase.h:432
void setImplicit(bool I=true)
Definition: DeclBase.h:577
void setReferenced(bool R=true)
Definition: DeclBase.h:606
void setLocation(SourceLocation L)
Definition: DeclBase.h:433
DeclContext * getDeclContext()
Definition: DeclBase.h:441
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:883
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:809
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:817
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:800
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:1963
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:794
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1850
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2377
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2319
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1985
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2554
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2315
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2020
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2408
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5233
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3160
Represents an enum.
Definition: Decl.h:3720
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4861
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1865
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3420
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3042
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:806
bool isFPConstrained() const
Definition: LangOptions.h:736
Represents a member of a struct/union/class.
Definition: Decl.h:2941
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4298
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition: Expr.h:1033
const Expr * getSubExpr() const
Definition: Expr.h:1028
Represents a function declaration or definition.
Definition: Decl.h:1917
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2605
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3134
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2371
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:3830
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3825
QualType getReturnType() const
Definition: Decl.h:2636
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2582
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3022
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2365
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2368
bool isConsteval() const
Definition: Decl.h:2377
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2684
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3489
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2613
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4041
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4368
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4257
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4253
Declaration of a template function.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1467
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3920
CallingConv getCallConv() const
Definition: Type.h:3970
QualType getReturnType() const
Definition: Type.h:3959
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3629
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2063
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8307
Describes an entity that is being initialized.
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1924
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition: ExprCXX.cpp:1234
Represents the results of name lookup.
Definition: Lookup.h:46
DeclClass * getAsSingle() const
Definition: Lookup.h:533
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
bool isAmbiguous() const
Definition: Lookup.h:301
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *)
Retrieve the mangling number of a new lambda expression with the given call operator within the devic...
This represents a decl that may have a name.
Definition: Decl.h:247
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
PtrTy get() const
Definition: Ownership.h:80
Represents a pack expansion of types.
Definition: Type.h:5858
Expr ** getExprs()
Definition: Expr.h:5581
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5570
Represents a parameter to a function.
Definition: Decl.h:1722
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2850
Wrapper for source info for pointers.
Definition: TypeLoc.h:1259
A (possibly-)qualified type.
Definition: Type.h:736
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6732
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:803
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6783
The collection of all-type qualifiers we support.
Definition: Type.h:146
void addAddressSpace(LangAS space)
Definition: Type.h:403
void addConst()
Definition: Type.h:266
Represents a struct/union/class.
Definition: Decl.h:3998
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2806
void setRetValue(Expr *E)
Definition: Stmt.h:2839
SourceLocation getBeginLoc() const
Definition: Stmt.h:2863
Expr * getRetValue()
Definition: Stmt.h:2837
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:254
Scope * getTemplateParamParent()
Definition: Scope.h:299
A RAII object to temporarily push a declaration context.
Definition: Sema.h:998
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:356
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10781
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:13789
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15826
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4289
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12568
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
Definition: SemaLambda.cpp:789
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1884
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Definition: SemaLambda.cpp:244
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17718
void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:850
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:803
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2241
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
Definition: SemaLambda.cpp:982
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1168
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
ASTContext & Context
Definition: Sema.h:407
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1537
ASTContext & getASTContext() const
Definition: Sema.h:1652
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:19087
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18014
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2379
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< std::tuple< bool, unsigned, unsigned, Decl * > > Mangling=std::nullopt)
Number lambda for linkage purposes if necessary.
Definition: SemaLambda.cpp:390
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1483
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition: Sema.h:1647
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:57
@ UPPC_Initializer
An initializer.
Definition: Sema.h:8648
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:8621
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
Definition: SemaLambda.cpp:462
const LangOptions & getLangOpts() const
Definition: Sema.h:1645
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & LangOpts
Definition: Sema.h:405
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2354
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2276
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
Definition: SemaLambda.cpp:723
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:784
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8287
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2225
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool isReferenceType)
Add an init-capture to a lambda scope.
Definition: SemaLambda.cpp:815
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3230
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:419
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:9665
TryCaptureKind
Definition: Sema.h:5443
@ TryCapture_Implicit
Definition: Sema.h:5444
@ TryCapture_ExplicitByVal
Definition: Sema.h:5444
@ TryCapture_ExplicitByRef
Definition: Sema.h:5444
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
Definition: SemaLambda.cpp:484
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15388
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:222
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8185
@ Normal
A normal translation unit fragment.
Definition: Sema.h:1932
void CUDASetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:895
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:788
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8773
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18570
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18082
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1393
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1344
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
Definition: SemaLambda.cpp:905
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:630
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10261
void PopDeclContext()
Definition: SemaDecl.cpp:1351
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args)
Definition: Sema.h:2504
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:277
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
Definition: SemaLambda.cpp:930
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5938
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
Definition: SemaLambda.cpp:480
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6877
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4356
Stmt - This represents one statement.
Definition: Stmt.h:72
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:349
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3662
Exposes information about the current target.
Definition: TargetInfo.h:206
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1573
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:426
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
A container of type source information.
Definition: Type.h:6620
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6631
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
The base class of the type hierarchy.
Definition: Type.h:1566
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1783
bool isVoidType() const
Definition: Type.h:7218
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1967
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7491
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:629
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2317
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2005
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7374
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7340
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2259
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7424
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4222
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:701
void setType(QualType newType)
Definition: Decl.h:713
QualType getType() const
Definition: Decl.h:712
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3252
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5066
Represents a variable declaration or definition.
Definition: Decl.h:913
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2095
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1402
void setInitCapture(bool IC)
Definition: Decl.h:1531
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1528
InitializationStyle
Initialization styles.
Definition: Decl.h:916
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:924
@ CInit
C-style initialization with assignment.
Definition: Decl.h:918
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:921
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1141
void setInit(Expr *I)
Definition: Decl.cpp:2399
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1125
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2598
ValueDecl * getVariable() const
Definition: ScopeInfo.h:646
bool isVariableCapture() const
Definition: ScopeInfo.h:621
bool isBlockCapture() const
Definition: ScopeInfo.h:627
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:657
bool isNonODRUsed() const
Definition: ScopeInfo.h:638
bool isODRUsed() const
Definition: ScopeInfo.h:637
bool isInitCapture() const
Determine whether this capture is an init-capture.
Definition: ScopeInfo.cpp:221
bool isInvalid() const
Definition: ScopeInfo.h:632
bool isVLATypeCapture() const
Definition: ScopeInfo.h:628
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:620
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:666
bool isCopyCapture() const
Definition: ScopeInfo.h:625
const VariableArrayType * getCapturedVLAType() const
Definition: ScopeInfo.h:651
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:700
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:692
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:679
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:723
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:720
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:702
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Definition: ScopeInfo.h:205
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:919
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition: ScopeInfo.h:927
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
Definition: ScopeInfo.h:868
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this lambda, if any.
Definition: ScopeInfo.h:871
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition: ScopeInfo.h:865
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:847
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition: ScopeInfo.h:862
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:884
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition: ScopeInfo.h:879
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition: ScopeInfo.h:874
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:836
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:855
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition: ScopeInfo.h:851
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition: ScopeInfo.h:908
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:844
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:839
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:859
Defines the clang::TargetInfo interface.
@ CPlusPlus20
Definition: LangStandard.h:57
@ CPlusPlus
Definition: LangStandard.h:53
@ CPlusPlus14
Definition: LangStandard.h:55
@ CPlusPlus17
Definition: LangStandard.h:56
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:80
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:175
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:32
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:260
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1519
LambdaCaptureKind
The different capture forms in a lambda introducer.
Definition: Lambda.h:33
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
Definition: Lambda.h:36
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_VLAType
Capturing variable-length array type.
Definition: Lambda.h:38
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ LCK_This
Capturing the *this object by reference.
Definition: Lambda.h:34
StorageClass
Storage classes.
Definition: Specifiers.h:236
@ SC_Auto
Definition: Specifiers.h:244
@ SC_Static
Definition: Specifiers.h:240
@ SC_None
Definition: Specifiers.h:238
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:29
@ CopyInit
[a = b], [a = {b}]
@ C
Languages that the frontend can parse and compile.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition: Specifiers.h:339
ActionResult< Expr * > ExprResult
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:278
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:123
StringRef getLambdaStaticInvokerName()
Definition: ASTLambda.h:22
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:266
@ CC_C
Definition: Specifiers.h:267
@ CC_X86VectorCall
Definition: Specifiers.h:271
@ CC_X86StdCall
Definition: Specifiers.h:268
@ CC_X86FastCall
Definition: Specifiers.h:269
@ EST_BasicNoexcept
noexcept
@ AS_public
Definition: Specifiers.h:112
@ AS_private
Definition: Specifiers.h:114
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:272
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition: DeclSpec.h:1546
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1537
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1540
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1509
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1290
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4094
Extra information about a function prototype.
Definition: Type.h:4118
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4124
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4119
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2807
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2820
Represents a complete lambda introducer.
Definition: DeclSpec.h:2755
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2780
SourceLocation DefaultLoc
Definition: DeclSpec.h:2778
LambdaCaptureDefault Default
Definition: DeclSpec.h:2779