1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ lambda expressions.
11 //===----------------------------------------------------------------------===//
12 #include "clang/Sema/DeclSpec.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Sema/SemaInternal.h"
22 #include "clang/Sema/SemaLambda.h"
23 #include "llvm/ADT/STLExtras.h"
25 using namespace clang
;
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.
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'.
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'.
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
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'.
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.
63 static inline std::optional
<unsigned>
64 getStackIndexOfNearestEnclosingCaptureReadyLambda(
65 ArrayRef
<const clang::sema::FunctionScopeInfo
*> FunctionScopes
,
66 ValueDecl
*VarToCapture
) {
67 // Label failure to capture.
68 const std::optional
<unsigned> NoLambdaIsCaptureReady
;
70 // Ignore all inner captured regions.
71 unsigned CurScopeIndex
= FunctionScopes
.size() - 1;
72 while (CurScopeIndex
> 0 && isa
<clang::sema::CapturedRegionScopeInfo
>(
73 FunctionScopes
[CurScopeIndex
]))
76 isa
<clang::sema::LambdaScopeInfo
>(FunctionScopes
[CurScopeIndex
]) &&
77 "The function on the top of sema's function-info stack must be a lambda");
79 // If VarToCapture is null, we are attempting to capture 'this'.
80 const bool IsCapturingThis
= !VarToCapture
;
81 const bool IsCapturingVariable
= !IsCapturingThis
;
83 // Start with the current lambda at the top of the stack (highest index).
84 DeclContext
*EnclosingDC
=
85 cast
<sema::LambdaScopeInfo
>(FunctionScopes
[CurScopeIndex
])->CallOperator
;
88 const clang::sema::LambdaScopeInfo
*LSI
=
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
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
97 if (IsCapturingVariable
&&
98 VarToCapture
->getDeclContext()->Equals(EnclosingDC
))
99 return NoLambdaIsCaptureReady
;
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.
108 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
110 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
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
;
123 EnclosingDC
= getLambdaAwareParentOfDeclContext(EnclosingDC
);
125 assert(CurScopeIndex
);
127 } while (!EnclosingDC
->isTranslationUnit() &&
128 EnclosingDC
->isDependentContext() &&
129 isLambdaCallOperator(EnclosingDC
));
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
;
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.
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')
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.
166 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
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.
174 std::optional
<unsigned>
175 clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
176 ArrayRef
<const sema::FunctionScopeInfo
*> FunctionScopes
,
177 ValueDecl
*VarToCapture
, Sema
&S
) {
179 const std::optional
<unsigned> NoLambdaIsCaptureCapable
;
181 const std::optional
<unsigned> OptionalStackIndex
=
182 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes
,
184 if (!OptionalStackIndex
)
185 return NoLambdaIsCaptureCapable
;
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");
193 const sema::LambdaScopeInfo
*const CaptureReadyLambdaLSI
=
194 cast
<sema::LambdaScopeInfo
>(FunctionScopes
[IndexOfCaptureReadyLambda
]);
196 // If VarToCapture is null, we are attempting to capture 'this'
197 const bool IsCapturingThis
= !VarToCapture
;
198 const bool IsCapturingVariable
= !IsCapturingThis
;
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(),
208 clang::Sema::TryCapture_Implicit
,
209 /*EllipsisLoc*/ SourceLocation(),
210 /*BuildAndDiagnose*/ false, CaptureType
,
211 DeclRefType
, &IndexOfCaptureReadyLambda
);
212 if (!CanCaptureVariable
)
213 return NoLambdaIsCaptureCapable
;
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
218 const bool CanCaptureThis
=
219 !S
.CheckCXXThisCapture(
220 CaptureReadyLambdaLSI
->PotentialThisCaptureLocation
,
221 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
222 &IndexOfCaptureReadyLambda
);
224 return NoLambdaIsCaptureCapable
;
226 return IndexOfCaptureReadyLambda
;
229 static inline TemplateParameterList
*
230 getGenericLambdaTemplateParameterList(LambdaScopeInfo
*LSI
, Sema
&SemaRef
) {
231 if (!LSI
->GLTemplateParameterList
&& !LSI
->TemplateParams
.empty()) {
232 LSI
->GLTemplateParameterList
= TemplateParameterList::Create(
234 /*Template kw loc*/ SourceLocation(),
235 /*L angle loc*/ LSI
->ExplicitTemplateParamsRange
.getBegin(),
237 /*R angle loc*/LSI
->ExplicitTemplateParamsRange
.getEnd(),
238 LSI
->RequiresClause
.get());
240 return LSI
->GLTemplateParameterList
;
244 Sema::createLambdaClosureType(SourceRange IntroducerRange
, TypeSourceInfo
*Info
,
245 unsigned LambdaDependencyKind
,
246 LambdaCaptureDefault CaptureDefault
) {
247 DeclContext
*DC
= CurContext
;
248 while (!(DC
->isFunctionOrMethod() || DC
->isRecord() || DC
->isFileContext()))
249 DC
= DC
->getParent();
251 bool IsGenericLambda
=
252 Info
&& getGenericLambdaTemplateParameterList(getCurLambda(), *this);
253 // Start constructing the lambda class.
254 CXXRecordDecl
*Class
= CXXRecordDecl::CreateLambda(
255 Context
, DC
, Info
, IntroducerRange
.getBegin(), LambdaDependencyKind
,
256 IsGenericLambda
, CaptureDefault
);
262 /// Determine whether the given context is or is enclosed in an inline
264 static bool isInInlineFunction(const DeclContext
*DC
) {
265 while (!DC
->isFileContext()) {
266 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DC
))
270 DC
= DC
->getLexicalParent();
276 std::tuple
<MangleNumberingContext
*, Decl
*>
277 Sema::getCurrentMangleNumberContext(const DeclContext
*DC
) {
278 // Compute the context for allocating mangling numbers in the current
279 // expression, if the ABI requires them.
280 Decl
*ManglingContextDecl
= ExprEvalContexts
.back().ManglingContextDecl
;
291 bool IsInNonspecializedTemplate
=
292 inTemplateInstantiation() || CurContext
->isDependentContext();
294 // Default arguments of member function parameters that appear in a class
295 // definition, as well as the initializers of data members, receive special
296 // treatment. Identify them.
297 if (ManglingContextDecl
) {
298 if (ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(ManglingContextDecl
)) {
299 if (const DeclContext
*LexicalDC
300 = Param
->getDeclContext()->getLexicalParent())
301 if (LexicalDC
->isRecord())
302 Kind
= DefaultArgument
;
303 } else if (VarDecl
*Var
= dyn_cast
<VarDecl
>(ManglingContextDecl
)) {
304 if (Var
->getMostRecentDecl()->isInline())
305 Kind
= InlineVariable
;
306 else if (Var
->getDeclContext()->isRecord() && IsInNonspecializedTemplate
)
307 Kind
= TemplatedVariable
;
308 else if (Var
->getDescribedVarTemplate())
309 Kind
= TemplatedVariable
;
310 else if (auto *VTS
= dyn_cast
<VarTemplateSpecializationDecl
>(Var
)) {
311 if (!VTS
->isExplicitSpecialization())
312 Kind
= TemplatedVariable
;
314 } else if (isa
<FieldDecl
>(ManglingContextDecl
)) {
316 } else if (isa
<ImplicitConceptSpecializationDecl
>(ManglingContextDecl
)) {
321 // Itanium ABI [5.1.7]:
322 // In the following contexts [...] the one-definition rule requires closure
323 // types in different translation units to "correspond":
326 // -- the bodies of inline or templated functions
327 if ((IsInNonspecializedTemplate
&&
328 !(ManglingContextDecl
&& isa
<ParmVarDecl
>(ManglingContextDecl
))) ||
329 isInInlineFunction(CurContext
)) {
330 while (auto *CD
= dyn_cast
<CapturedDecl
>(DC
))
331 DC
= CD
->getParent();
332 return std::make_tuple(&Context
.getManglingNumberContext(DC
), nullptr);
335 return std::make_tuple(nullptr, nullptr);
339 // Concept definitions aren't code generated and thus aren't mangled,
340 // however the ManglingContextDecl is important for the purposes of
341 // re-forming the template argument list of the lambda for constraint
344 // -- default member initializers
345 case DefaultArgument
:
346 // -- default arguments appearing in class definitions
348 case TemplatedVariable
:
349 // -- the initializers of inline or templated variables
350 return std::make_tuple(
351 &Context
.getManglingNumberContext(ASTContext::NeedExtraManglingDecl
,
352 ManglingContextDecl
),
353 ManglingContextDecl
);
356 llvm_unreachable("unexpected context");
360 buildTypeForLambdaCallOperator(Sema
&S
, clang::CXXRecordDecl
*Class
,
361 TemplateParameterList
*TemplateParams
,
362 TypeSourceInfo
*MethodTypeInfo
) {
363 assert(MethodTypeInfo
&& "expected a non null type");
365 QualType MethodType
= MethodTypeInfo
->getType();
366 // If a lambda appears in a dependent context or is a generic lambda (has
367 // template parameters) and has an 'auto' return type, deduce it to a
369 if (Class
->isDependentContext() || TemplateParams
) {
370 const FunctionProtoType
*FPT
= MethodType
->castAs
<FunctionProtoType
>();
371 QualType Result
= FPT
->getReturnType();
372 if (Result
->isUndeducedType()) {
373 Result
= S
.SubstAutoTypeDependent(Result
);
374 MethodType
= S
.Context
.getFunctionType(Result
, FPT
->getParamTypes(),
375 FPT
->getExtProtoInfo());
381 void Sema::handleLambdaNumbering(
382 CXXRecordDecl
*Class
, CXXMethodDecl
*Method
,
383 std::optional
<CXXRecordDecl::LambdaNumbering
> NumberingOverride
) {
384 if (NumberingOverride
) {
385 Class
->setLambdaNumbering(*NumberingOverride
);
389 ContextRAII
ManglingContext(*this, Class
->getDeclContext());
391 auto getMangleNumberingContext
=
392 [this](CXXRecordDecl
*Class
,
393 Decl
*ManglingContextDecl
) -> MangleNumberingContext
* {
394 // Get mangle numbering context if there's any extra decl context.
395 if (ManglingContextDecl
)
396 return &Context
.getManglingNumberContext(
397 ASTContext::NeedExtraManglingDecl
, ManglingContextDecl
);
398 // Otherwise, from that lambda's decl context.
399 auto DC
= Class
->getDeclContext();
400 while (auto *CD
= dyn_cast
<CapturedDecl
>(DC
))
401 DC
= CD
->getParent();
402 return &Context
.getManglingNumberContext(DC
);
405 CXXRecordDecl::LambdaNumbering Numbering
;
406 MangleNumberingContext
*MCtx
;
407 std::tie(MCtx
, Numbering
.ContextDecl
) =
408 getCurrentMangleNumberContext(Class
->getDeclContext());
409 if (!MCtx
&& (getLangOpts().CUDA
|| getLangOpts().SYCLIsDevice
||
410 getLangOpts().SYCLIsHost
)) {
411 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
412 // ODR. Both device- and host-compilation need to have a consistent naming
413 // on kernel functions. As lambdas are potential part of these `__global__`
414 // function names, they needs numbering following ODR.
415 // Also force for SYCL, since we need this for the
416 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
418 MCtx
= getMangleNumberingContext(Class
, Numbering
.ContextDecl
);
419 assert(MCtx
&& "Retrieving mangle numbering context failed!");
420 Numbering
.HasKnownInternalLinkage
= true;
423 Numbering
.IndexInContext
= MCtx
->getNextLambdaIndex();
424 Numbering
.ManglingNumber
= MCtx
->getManglingNumber(Method
);
425 Numbering
.DeviceManglingNumber
= MCtx
->getDeviceManglingNumber(Method
);
426 Class
->setLambdaNumbering(Numbering
);
429 dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
430 Source
->AssignedLambdaNumbering(Class
);
434 static void buildLambdaScopeReturnType(Sema
&S
, LambdaScopeInfo
*LSI
,
435 CXXMethodDecl
*CallOperator
,
436 bool ExplicitResultType
) {
437 if (ExplicitResultType
) {
438 LSI
->HasImplicitReturnType
= false;
439 LSI
->ReturnType
= CallOperator
->getReturnType();
440 if (!LSI
->ReturnType
->isDependentType() && !LSI
->ReturnType
->isVoidType())
441 S
.RequireCompleteType(CallOperator
->getBeginLoc(), LSI
->ReturnType
,
442 diag::err_lambda_incomplete_result
);
444 LSI
->HasImplicitReturnType
= true;
448 void Sema::buildLambdaScope(LambdaScopeInfo
*LSI
, CXXMethodDecl
*CallOperator
,
449 SourceRange IntroducerRange
,
450 LambdaCaptureDefault CaptureDefault
,
451 SourceLocation CaptureDefaultLoc
,
452 bool ExplicitParams
, bool Mutable
) {
453 LSI
->CallOperator
= CallOperator
;
454 CXXRecordDecl
*LambdaClass
= CallOperator
->getParent();
455 LSI
->Lambda
= LambdaClass
;
456 if (CaptureDefault
== LCD_ByCopy
)
457 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByval
;
458 else if (CaptureDefault
== LCD_ByRef
)
459 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByref
;
460 LSI
->CaptureDefaultLoc
= CaptureDefaultLoc
;
461 LSI
->IntroducerRange
= IntroducerRange
;
462 LSI
->ExplicitParams
= ExplicitParams
;
463 LSI
->Mutable
= Mutable
;
466 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo
*LSI
) {
467 LSI
->finishedExplicitCaptures();
470 void Sema::ActOnLambdaExplicitTemplateParameterList(
471 LambdaIntroducer
&Intro
, SourceLocation LAngleLoc
,
472 ArrayRef
<NamedDecl
*> TParams
, SourceLocation RAngleLoc
,
473 ExprResult RequiresClause
) {
474 LambdaScopeInfo
*LSI
= getCurLambda();
475 assert(LSI
&& "Expected a lambda scope");
476 assert(LSI
->NumExplicitTemplateParams
== 0 &&
477 "Already acted on explicit template parameters");
478 assert(LSI
->TemplateParams
.empty() &&
479 "Explicit template parameters should come "
480 "before invented (auto) ones");
481 assert(!TParams
.empty() &&
482 "No template parameters to act on");
483 LSI
->TemplateParams
.append(TParams
.begin(), TParams
.end());
484 LSI
->NumExplicitTemplateParams
= TParams
.size();
485 LSI
->ExplicitTemplateParamsRange
= {LAngleLoc
, RAngleLoc
};
486 LSI
->RequiresClause
= RequiresClause
;
489 /// If this expression is an enumerator-like expression of some type
490 /// T, return the type T; otherwise, return null.
492 /// Pointer comparisons on the result here should always work because
493 /// it's derived from either the parent of an EnumConstantDecl
494 /// (i.e. the definition) or the declaration returned by
495 /// EnumType::getDecl() (i.e. the definition).
496 static EnumDecl
*findEnumForBlockReturn(Expr
*E
) {
497 // An expression is an enumerator-like expression of type T if,
498 // ignoring parens and parens-like expressions:
499 E
= E
->IgnoreParens();
501 // - it is an enumerator whose enum type is T or
502 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
503 if (EnumConstantDecl
*D
504 = dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
505 return cast
<EnumDecl
>(D
->getDeclContext());
510 // - it is a comma expression whose RHS is an enumerator-like
511 // expression of type T or
512 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
513 if (BO
->getOpcode() == BO_Comma
)
514 return findEnumForBlockReturn(BO
->getRHS());
518 // - it is a statement-expression whose value expression is an
519 // enumerator-like expression of type T or
520 if (StmtExpr
*SE
= dyn_cast
<StmtExpr
>(E
)) {
521 if (Expr
*last
= dyn_cast_or_null
<Expr
>(SE
->getSubStmt()->body_back()))
522 return findEnumForBlockReturn(last
);
526 // - it is a ternary conditional operator (not the GNU ?:
527 // extension) whose second and third operands are
528 // enumerator-like expressions of type T or
529 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
530 if (EnumDecl
*ED
= findEnumForBlockReturn(CO
->getTrueExpr()))
531 if (ED
== findEnumForBlockReturn(CO
->getFalseExpr()))
537 // - it is an implicit integral conversion applied to an
538 // enumerator-like expression of type T or
539 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
540 // We can sometimes see integral conversions in valid
541 // enumerator-like expressions.
542 if (ICE
->getCastKind() == CK_IntegralCast
)
543 return findEnumForBlockReturn(ICE
->getSubExpr());
545 // Otherwise, just rely on the type.
548 // - it is an expression of that formal enum type.
549 if (const EnumType
*ET
= E
->getType()->getAs
<EnumType
>()) {
550 return ET
->getDecl();
557 /// Attempt to find a type T for which the returned expression of the
558 /// given statement is an enumerator-like expression of that type.
559 static EnumDecl
*findEnumForBlockReturn(ReturnStmt
*ret
) {
560 if (Expr
*retValue
= ret
->getRetValue())
561 return findEnumForBlockReturn(retValue
);
565 /// Attempt to find a common type T for which all of the returned
566 /// expressions in a block are enumerator-like expressions of that
568 static EnumDecl
*findCommonEnumForBlockReturns(ArrayRef
<ReturnStmt
*> returns
) {
569 ArrayRef
<ReturnStmt
*>::iterator i
= returns
.begin(), e
= returns
.end();
571 // Try to find one for the first return.
572 EnumDecl
*ED
= findEnumForBlockReturn(*i
);
573 if (!ED
) return nullptr;
575 // Check that the rest of the returns have the same enum.
576 for (++i
; i
!= e
; ++i
) {
577 if (findEnumForBlockReturn(*i
) != ED
)
581 // Never infer an anonymous enum type.
582 if (!ED
->hasNameForLinkage()) return nullptr;
587 /// Adjust the given return statements so that they formally return
588 /// the given type. It should require, at most, an IntegralCast.
589 static void adjustBlockReturnsToEnum(Sema
&S
, ArrayRef
<ReturnStmt
*> returns
,
590 QualType returnType
) {
591 for (ArrayRef
<ReturnStmt
*>::iterator
592 i
= returns
.begin(), e
= returns
.end(); i
!= e
; ++i
) {
593 ReturnStmt
*ret
= *i
;
594 Expr
*retValue
= ret
->getRetValue();
595 if (S
.Context
.hasSameType(retValue
->getType(), returnType
))
598 // Right now we only support integral fixup casts.
599 assert(returnType
->isIntegralOrUnscopedEnumerationType());
600 assert(retValue
->getType()->isIntegralOrUnscopedEnumerationType());
602 ExprWithCleanups
*cleanups
= dyn_cast
<ExprWithCleanups
>(retValue
);
604 Expr
*E
= (cleanups
? cleanups
->getSubExpr() : retValue
);
605 E
= ImplicitCastExpr::Create(S
.Context
, returnType
, CK_IntegralCast
, E
,
606 /*base path*/ nullptr, VK_PRValue
,
607 FPOptionsOverride());
609 cleanups
->setSubExpr(E
);
616 void Sema::deduceClosureReturnType(CapturingScopeInfo
&CSI
) {
617 assert(CSI
.HasImplicitReturnType
);
618 // If it was ever a placeholder, it had to been deduced to DependentTy.
619 assert(CSI
.ReturnType
.isNull() || !CSI
.ReturnType
->isUndeducedType());
620 assert((!isa
<LambdaScopeInfo
>(CSI
) || !getLangOpts().CPlusPlus14
) &&
621 "lambda expressions use auto deduction in C++14 onwards");
623 // C++ core issue 975:
624 // If a lambda-expression does not include a trailing-return-type,
625 // it is as if the trailing-return-type denotes the following type:
626 // - if there are no return statements in the compound-statement,
627 // or all return statements return either an expression of type
628 // void or no expression or braced-init-list, the type void;
629 // - otherwise, if all return statements return an expression
630 // and the types of the returned expressions after
631 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
632 // array-to-pointer conversion (4.2 [conv.array]), and
633 // function-to-pointer conversion (4.3 [conv.func]) are the
634 // same, that common type;
635 // - otherwise, the program is ill-formed.
637 // C++ core issue 1048 additionally removes top-level cv-qualifiers
638 // from the types of returned expressions to match the C++14 auto
641 // In addition, in blocks in non-C++ modes, if all of the return
642 // statements are enumerator-like expressions of some type T, where
643 // T has a name for linkage, then we infer the return type of the
644 // block to be that type.
646 // First case: no return statements, implicit void return type.
647 ASTContext
&Ctx
= getASTContext();
648 if (CSI
.Returns
.empty()) {
649 // It's possible there were simply no /valid/ return statements.
650 // In this case, the first one we found may have at least given us a type.
651 if (CSI
.ReturnType
.isNull())
652 CSI
.ReturnType
= Ctx
.VoidTy
;
656 // Second case: at least one return statement has dependent type.
657 // Delay type checking until instantiation.
658 assert(!CSI
.ReturnType
.isNull() && "We should have a tentative return type.");
659 if (CSI
.ReturnType
->isDependentType())
662 // Try to apply the enum-fuzz rule.
663 if (!getLangOpts().CPlusPlus
) {
664 assert(isa
<BlockScopeInfo
>(CSI
));
665 const EnumDecl
*ED
= findCommonEnumForBlockReturns(CSI
.Returns
);
667 CSI
.ReturnType
= Context
.getTypeDeclType(ED
);
668 adjustBlockReturnsToEnum(*this, CSI
.Returns
, CSI
.ReturnType
);
673 // Third case: only one return statement. Don't bother doing extra work!
674 if (CSI
.Returns
.size() == 1)
677 // General case: many return statements.
678 // Check that they all have compatible return types.
680 // We require the return types to strictly match here.
681 // Note that we've already done the required promotions as part of
682 // processing the return statement.
683 for (const ReturnStmt
*RS
: CSI
.Returns
) {
684 const Expr
*RetE
= RS
->getRetValue();
686 QualType ReturnType
=
687 (RetE
? RetE
->getType() : Context
.VoidTy
).getUnqualifiedType();
688 if (Context
.getCanonicalFunctionResultType(ReturnType
) ==
689 Context
.getCanonicalFunctionResultType(CSI
.ReturnType
)) {
690 // Use the return type with the strictest possible nullability annotation.
691 auto RetTyNullability
= ReturnType
->getNullability();
692 auto BlockNullability
= CSI
.ReturnType
->getNullability();
693 if (BlockNullability
&&
694 (!RetTyNullability
||
695 hasWeakerNullability(*RetTyNullability
, *BlockNullability
)))
696 CSI
.ReturnType
= ReturnType
;
700 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
701 // TODO: It's possible that the *first* return is the divergent one.
702 Diag(RS
->getBeginLoc(),
703 diag::err_typecheck_missing_return_type_incompatible
)
704 << ReturnType
<< CSI
.ReturnType
<< isa
<LambdaScopeInfo
>(CSI
);
705 // Continue iterating so that we keep emitting diagnostics.
709 QualType
Sema::buildLambdaInitCaptureInitialization(
710 SourceLocation Loc
, bool ByRef
, SourceLocation EllipsisLoc
,
711 std::optional
<unsigned> NumExpansions
, IdentifierInfo
*Id
,
712 bool IsDirectInit
, Expr
*&Init
) {
713 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
715 QualType DeductType
= Context
.getAutoDeductType();
717 AutoTypeLoc TL
= TLB
.push
<AutoTypeLoc
>(DeductType
);
720 DeductType
= BuildReferenceType(DeductType
, true, Loc
, Id
);
721 assert(!DeductType
.isNull() && "can't build reference to auto");
722 TLB
.push
<ReferenceTypeLoc
>(DeductType
).setSigilLoc(Loc
);
724 if (EllipsisLoc
.isValid()) {
725 if (Init
->containsUnexpandedParameterPack()) {
726 Diag(EllipsisLoc
, getLangOpts().CPlusPlus20
727 ? diag::warn_cxx17_compat_init_capture_pack
728 : diag::ext_init_capture_pack
);
729 DeductType
= Context
.getPackExpansionType(DeductType
, NumExpansions
,
730 /*ExpectPackInType=*/false);
731 TLB
.push
<PackExpansionTypeLoc
>(DeductType
).setEllipsisLoc(EllipsisLoc
);
733 // Just ignore the ellipsis for now and form a non-pack variable. We'll
734 // diagnose this later when we try to capture it.
737 TypeSourceInfo
*TSI
= TLB
.getTypeSourceInfo(Context
, DeductType
);
739 // Deduce the type of the init capture.
740 QualType DeducedType
= deduceVarTypeFromInitializer(
741 /*VarDecl*/nullptr, DeclarationName(Id
), DeductType
, TSI
,
742 SourceRange(Loc
, Loc
), IsDirectInit
, Init
);
743 if (DeducedType
.isNull())
746 // Are we a non-list direct initialization?
747 ParenListExpr
*CXXDirectInit
= dyn_cast
<ParenListExpr
>(Init
);
749 // Perform initialization analysis and ensure any implicit conversions
750 // (such as lvalue-to-rvalue) are enforced.
751 InitializedEntity Entity
=
752 InitializedEntity::InitializeLambdaCapture(Id
, DeducedType
, Loc
);
753 InitializationKind Kind
=
755 ? (CXXDirectInit
? InitializationKind::CreateDirect(
756 Loc
, Init
->getBeginLoc(), Init
->getEndLoc())
757 : InitializationKind::CreateDirectList(Loc
))
758 : InitializationKind::CreateCopy(Loc
, Init
->getBeginLoc());
760 MultiExprArg Args
= Init
;
763 MultiExprArg(CXXDirectInit
->getExprs(), CXXDirectInit
->getNumExprs());
765 InitializationSequence
InitSeq(*this, Entity
, Kind
, Args
);
766 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Args
, &DclT
);
768 if (Result
.isInvalid())
771 Init
= Result
.getAs
<Expr
>();
775 VarDecl
*Sema::createLambdaInitCaptureVarDecl(
776 SourceLocation Loc
, QualType InitCaptureType
, SourceLocation EllipsisLoc
,
777 IdentifierInfo
*Id
, unsigned InitStyle
, Expr
*Init
, DeclContext
*DeclCtx
) {
778 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
779 // rather than reconstructing it here.
780 TypeSourceInfo
*TSI
= Context
.getTrivialTypeSourceInfo(InitCaptureType
, Loc
);
781 if (auto PETL
= TSI
->getTypeLoc().getAs
<PackExpansionTypeLoc
>())
782 PETL
.setEllipsisLoc(EllipsisLoc
);
784 // Create a dummy variable representing the init-capture. This is not actually
785 // used as a variable, and only exists as a way to name and refer to the
787 // FIXME: Pass in separate source locations for '&' and identifier.
788 VarDecl
*NewVD
= VarDecl::Create(Context
, DeclCtx
, Loc
, Loc
, Id
,
789 InitCaptureType
, TSI
, SC_Auto
);
790 NewVD
->setInitCapture(true);
791 NewVD
->setReferenced(true);
792 // FIXME: Pass in a VarDecl::InitializationStyle.
793 NewVD
->setInitStyle(static_cast<VarDecl::InitializationStyle
>(InitStyle
));
794 NewVD
->markUsed(Context
);
795 NewVD
->setInit(Init
);
796 if (NewVD
->isParameterPack())
797 getCurLambda()->LocalPacks
.push_back(NewVD
);
801 void Sema::addInitCapture(LambdaScopeInfo
*LSI
, VarDecl
*Var
, bool ByRef
) {
802 assert(Var
->isInitCapture() && "init capture flag should be set");
803 LSI
->addCapture(Var
, /*isBlock=*/false, ByRef
,
804 /*isNested=*/false, Var
->getLocation(), SourceLocation(),
805 Var
->getType(), /*Invalid=*/false);
808 // Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
809 // check that the current lambda is in a consistent or fully constructed state.
810 static LambdaScopeInfo
*getCurrentLambdaScopeUnsafe(Sema
&S
) {
811 assert(!S
.FunctionScopes
.empty());
812 return cast
<LambdaScopeInfo
>(S
.FunctionScopes
[S
.FunctionScopes
.size() - 1]);
815 static TypeSourceInfo
*
816 getDummyLambdaType(Sema
&S
, SourceLocation Loc
= SourceLocation()) {
817 // C++11 [expr.prim.lambda]p4:
818 // If a lambda-expression does not include a lambda-declarator, it is as
819 // if the lambda-declarator were ().
820 FunctionProtoType::ExtProtoInfo
EPI(S
.Context
.getDefaultCallingConvention(
821 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
822 EPI
.HasTrailingReturn
= true;
823 EPI
.TypeQuals
.addConst();
824 LangAS AS
= S
.getDefaultCXXMethodAddrSpace();
825 if (AS
!= LangAS::Default
)
826 EPI
.TypeQuals
.addAddressSpace(AS
);
828 // C++1y [expr.prim.lambda]:
829 // The lambda return type is 'auto', which is replaced by the
830 // trailing-return type if provided and/or deduced from 'return'
832 // We don't do this before C++1y, because we don't support deduced return
834 QualType DefaultTypeForNoTrailingReturn
= S
.getLangOpts().CPlusPlus14
835 ? S
.Context
.getAutoDeductType()
836 : S
.Context
.DependentTy
;
837 QualType MethodTy
= S
.Context
.getFunctionType(DefaultTypeForNoTrailingReturn
,
839 return S
.Context
.getTrivialTypeSourceInfo(MethodTy
, Loc
);
842 static TypeSourceInfo
*getLambdaType(Sema
&S
, LambdaIntroducer
&Intro
,
843 Declarator
&ParamInfo
, Scope
*CurScope
,
845 bool &ExplicitResultType
) {
847 ExplicitResultType
= false;
850 (ParamInfo
.getDeclSpec().getStorageClassSpec() ==
851 DeclSpec::SCS_unspecified
||
852 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
) &&
853 "Unexpected storage specifier");
854 bool IsLambdaStatic
=
855 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
;
857 TypeSourceInfo
*MethodTyInfo
;
859 if (ParamInfo
.getNumTypeObjects() == 0) {
860 MethodTyInfo
= getDummyLambdaType(S
, Loc
);
862 DeclaratorChunk::FunctionTypeInfo
&FTI
= ParamInfo
.getFunctionTypeInfo();
863 ExplicitResultType
= FTI
.hasTrailingReturnType();
864 if (!FTI
.hasMutableQualifier() && !IsLambdaStatic
)
865 FTI
.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const
, Loc
);
867 if (ExplicitResultType
&& S
.getLangOpts().HLSL
) {
868 QualType RetTy
= FTI
.getTrailingReturnType().get();
869 if (!RetTy
.isNull()) {
870 // HLSL does not support specifying an address space on a lambda return
872 LangAS AddressSpace
= RetTy
.getAddressSpace();
873 if (AddressSpace
!= LangAS::Default
)
874 S
.Diag(FTI
.getTrailingReturnTypeLoc(),
875 diag::err_return_value_with_address_space
);
879 MethodTyInfo
= S
.GetTypeForDeclarator(ParamInfo
, CurScope
);
880 assert(MethodTyInfo
&& "no type from lambda-declarator");
882 // Check for unexpanded parameter packs in the method type.
883 if (MethodTyInfo
->getType()->containsUnexpandedParameterPack())
884 S
.DiagnoseUnexpandedParameterPack(Intro
.Range
.getBegin(), MethodTyInfo
,
885 S
.UPPC_DeclarationType
);
890 CXXMethodDecl
*Sema::CreateLambdaCallOperator(SourceRange IntroducerRange
,
891 CXXRecordDecl
*Class
) {
893 // C++20 [expr.prim.lambda.closure]p3:
894 // The closure type for a lambda-expression has a public inline function
895 // call operator (for a non-generic lambda) or function call operator
896 // template (for a generic lambda) whose parameters and return type are
897 // described by the lambda-expression's parameter-declaration-clause
898 // and trailing-return-type respectively.
899 DeclarationName MethodName
=
900 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
901 DeclarationNameLoc MethodNameLoc
=
902 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange
.getBegin());
903 CXXMethodDecl
*Method
= CXXMethodDecl::Create(
904 Context
, Class
, SourceLocation(),
905 DeclarationNameInfo(MethodName
, IntroducerRange
.getBegin(),
907 QualType(), /*Tinfo=*/nullptr, SC_None
,
908 getCurFPFeatures().isFPConstrained(),
909 /*isInline=*/true, ConstexprSpecKind::Unspecified
, SourceLocation(),
910 /*TrailingRequiresClause=*/nullptr);
911 Method
->setAccess(AS_public
);
915 void Sema::CompleteLambdaCallOperator(
916 CXXMethodDecl
*Method
, SourceLocation LambdaLoc
,
917 SourceLocation CallOperatorLoc
, Expr
*TrailingRequiresClause
,
918 TypeSourceInfo
*MethodTyInfo
, ConstexprSpecKind ConstexprKind
,
919 StorageClass SC
, ArrayRef
<ParmVarDecl
*> Params
,
920 bool HasExplicitResultType
) {
922 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
924 if (TrailingRequiresClause
)
925 Method
->setTrailingRequiresClause(TrailingRequiresClause
);
927 TemplateParameterList
*TemplateParams
=
928 getGenericLambdaTemplateParameterList(LSI
, *this);
930 DeclContext
*DC
= Method
->getLexicalDeclContext();
931 Method
->setLexicalDeclContext(LSI
->Lambda
);
932 if (TemplateParams
) {
933 FunctionTemplateDecl
*TemplateMethod
= FunctionTemplateDecl::Create(
934 Context
, LSI
->Lambda
, Method
->getLocation(), Method
->getDeclName(),
935 TemplateParams
, Method
);
936 TemplateMethod
->setAccess(AS_public
);
937 Method
->setDescribedFunctionTemplate(TemplateMethod
);
938 LSI
->Lambda
->addDecl(TemplateMethod
);
939 TemplateMethod
->setLexicalDeclContext(DC
);
941 LSI
->Lambda
->addDecl(Method
);
943 LSI
->Lambda
->setLambdaIsGeneric(TemplateParams
);
944 LSI
->Lambda
->setLambdaTypeInfo(MethodTyInfo
);
946 Method
->setLexicalDeclContext(DC
);
947 Method
->setLocation(LambdaLoc
);
948 Method
->setInnerLocStart(CallOperatorLoc
);
949 Method
->setTypeSourceInfo(MethodTyInfo
);
950 Method
->setType(buildTypeForLambdaCallOperator(*this, LSI
->Lambda
,
951 TemplateParams
, MethodTyInfo
));
952 Method
->setConstexprKind(ConstexprKind
);
953 Method
->setStorageClass(SC
);
954 if (!Params
.empty()) {
955 CheckParmsForFunctionDef(Params
, /*CheckParameterNames=*/false);
956 Method
->setParams(Params
);
957 for (auto P
: Method
->parameters()) {
958 assert(P
&& "null in a parameter list");
959 P
->setOwningFunction(Method
);
963 buildLambdaScopeReturnType(*this, LSI
, Method
, HasExplicitResultType
);
966 void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer
&Intro
,
967 Scope
*CurrentScope
) {
969 LambdaScopeInfo
*LSI
= getCurLambda();
970 assert(LSI
&& "LambdaScopeInfo should be on stack!");
972 if (Intro
.Default
== LCD_ByCopy
)
973 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByval
;
974 else if (Intro
.Default
== LCD_ByRef
)
975 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByref
;
976 LSI
->CaptureDefaultLoc
= Intro
.DefaultLoc
;
977 LSI
->IntroducerRange
= Intro
.Range
;
978 LSI
->AfterParameterList
= false;
980 assert(LSI
->NumExplicitTemplateParams
== 0);
982 // Determine if we're within a context where we know that the lambda will
983 // be dependent, because there are template parameters in scope.
984 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind
=
985 CXXRecordDecl::LDK_Unknown
;
986 if (LSI
->NumExplicitTemplateParams
> 0) {
987 Scope
*TemplateParamScope
= CurScope
->getTemplateParamParent();
988 assert(TemplateParamScope
&&
989 "Lambda with explicit template param list should establish a "
990 "template param scope");
991 assert(TemplateParamScope
->getParent());
992 if (TemplateParamScope
->getParent()->getTemplateParamParent() != nullptr)
993 LambdaDependencyKind
= CXXRecordDecl::LDK_AlwaysDependent
;
994 } else if (CurScope
->getTemplateParamParent() != nullptr) {
995 LambdaDependencyKind
= CXXRecordDecl::LDK_AlwaysDependent
;
998 CXXRecordDecl
*Class
= createLambdaClosureType(
999 Intro
.Range
, /*Info=*/nullptr, LambdaDependencyKind
, Intro
.Default
);
1000 LSI
->Lambda
= Class
;
1002 CXXMethodDecl
*Method
= CreateLambdaCallOperator(Intro
.Range
, Class
);
1003 LSI
->CallOperator
= Method
;
1004 Method
->setLexicalDeclContext(CurContext
);
1006 PushDeclContext(CurScope
, Method
);
1008 bool ContainsUnexpandedParameterPack
= false;
1010 // Distinct capture names, for diagnostics.
1011 llvm::DenseMap
<IdentifierInfo
*, ValueDecl
*> CaptureNames
;
1013 // Handle explicit captures.
1014 SourceLocation PrevCaptureLoc
=
1015 Intro
.Default
== LCD_None
? Intro
.Range
.getBegin() : Intro
.DefaultLoc
;
1016 for (auto C
= Intro
.Captures
.begin(), E
= Intro
.Captures
.end(); C
!= E
;
1017 PrevCaptureLoc
= C
->Loc
, ++C
) {
1018 if (C
->Kind
== LCK_This
|| C
->Kind
== LCK_StarThis
) {
1019 if (C
->Kind
== LCK_StarThis
)
1020 Diag(C
->Loc
, !getLangOpts().CPlusPlus17
1021 ? diag::ext_star_this_lambda_capture_cxx17
1022 : diag::warn_cxx14_compat_star_this_lambda_capture
);
1024 // C++11 [expr.prim.lambda]p8:
1025 // An identifier or this shall not appear more than once in a
1027 if (LSI
->isCXXThisCaptured()) {
1028 Diag(C
->Loc
, diag::err_capture_more_than_once
)
1029 << "'this'" << SourceRange(LSI
->getCXXThisCapture().getLocation())
1030 << FixItHint::CreateRemoval(
1031 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1035 // C++20 [expr.prim.lambda]p8:
1036 // If a lambda-capture includes a capture-default that is =,
1037 // each simple-capture of that lambda-capture shall be of the form
1038 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1039 // redundant but accepted for compatibility with ISO C++14. --end note ]
1040 if (Intro
.Default
== LCD_ByCopy
&& C
->Kind
!= LCK_StarThis
)
1041 Diag(C
->Loc
, !getLangOpts().CPlusPlus20
1042 ? diag::ext_equals_this_lambda_capture_cxx20
1043 : diag::warn_cxx17_compat_equals_this_lambda_capture
);
1045 // C++11 [expr.prim.lambda]p12:
1046 // If this is captured by a local lambda expression, its nearest
1047 // enclosing function shall be a non-static member function.
1048 QualType ThisCaptureType
= getCurrentThisType();
1049 if (ThisCaptureType
.isNull()) {
1050 Diag(C
->Loc
, diag::err_this_capture
) << true;
1054 CheckCXXThisCapture(C
->Loc
, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1055 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1056 C
->Kind
== LCK_StarThis
);
1057 if (!LSI
->Captures
.empty())
1058 LSI
->ExplicitCaptureRanges
[LSI
->Captures
.size() - 1] = C
->ExplicitRange
;
1062 assert(C
->Id
&& "missing identifier for capture");
1064 if (C
->Init
.isInvalid())
1067 ValueDecl
*Var
= nullptr;
1068 if (C
->Init
.isUsable()) {
1069 Diag(C
->Loc
, getLangOpts().CPlusPlus14
1070 ? diag::warn_cxx11_compat_init_capture
1071 : diag::ext_init_capture
);
1073 // If the initializer expression is usable, but the InitCaptureType
1074 // is not, then an error has occurred - so ignore the capture for now.
1075 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1076 // FIXME: we should create the init capture variable and mark it invalid
1078 if (C
->InitCaptureType
.get().isNull())
1081 if (C
->Init
.get()->containsUnexpandedParameterPack() &&
1082 !C
->InitCaptureType
.get()->getAs
<PackExpansionType
>())
1083 DiagnoseUnexpandedParameterPack(C
->Init
.get(), UPPC_Initializer
);
1086 switch (C
->InitKind
) {
1087 case LambdaCaptureInitKind::NoInit
:
1088 llvm_unreachable("not an init-capture?");
1089 case LambdaCaptureInitKind::CopyInit
:
1090 InitStyle
= VarDecl::CInit
;
1092 case LambdaCaptureInitKind::DirectInit
:
1093 InitStyle
= VarDecl::CallInit
;
1095 case LambdaCaptureInitKind::ListInit
:
1096 InitStyle
= VarDecl::ListInit
;
1099 Var
= createLambdaInitCaptureVarDecl(C
->Loc
, C
->InitCaptureType
.get(),
1100 C
->EllipsisLoc
, C
->Id
, InitStyle
,
1101 C
->Init
.get(), Method
);
1102 assert(Var
&& "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1103 if (auto *V
= dyn_cast
<VarDecl
>(Var
))
1104 CheckShadow(CurrentScope
, V
);
1105 PushOnScopeChains(Var
, CurrentScope
, false);
1107 assert(C
->InitKind
== LambdaCaptureInitKind::NoInit
&&
1108 "init capture has valid but null init?");
1110 // C++11 [expr.prim.lambda]p8:
1111 // If a lambda-capture includes a capture-default that is &, the
1112 // identifiers in the lambda-capture shall not be preceded by &.
1113 // If a lambda-capture includes a capture-default that is =, [...]
1114 // each identifier it contains shall be preceded by &.
1115 if (C
->Kind
== LCK_ByRef
&& Intro
.Default
== LCD_ByRef
) {
1116 Diag(C
->Loc
, diag::err_reference_capture_with_reference_default
)
1117 << FixItHint::CreateRemoval(
1118 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1120 } else if (C
->Kind
== LCK_ByCopy
&& Intro
.Default
== LCD_ByCopy
) {
1121 Diag(C
->Loc
, diag::err_copy_capture_with_copy_default
)
1122 << FixItHint::CreateRemoval(
1123 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1127 // C++11 [expr.prim.lambda]p10:
1128 // The identifiers in a capture-list are looked up using the usual
1129 // rules for unqualified name lookup (3.4.1)
1130 DeclarationNameInfo
Name(C
->Id
, C
->Loc
);
1131 LookupResult
R(*this, Name
, LookupOrdinaryName
);
1132 LookupName(R
, CurScope
);
1133 if (R
.isAmbiguous())
1136 // FIXME: Disable corrections that would add qualification?
1137 CXXScopeSpec ScopeSpec
;
1138 DeclFilterCCC
<VarDecl
> Validator
{};
1139 if (DiagnoseEmptyLookup(CurScope
, ScopeSpec
, R
, Validator
))
1143 if (auto *BD
= R
.getAsSingle
<BindingDecl
>())
1146 Var
= R
.getAsSingle
<VarDecl
>();
1147 if (Var
&& DiagnoseUseOfDecl(Var
, C
->Loc
))
1151 // C++11 [expr.prim.lambda]p10:
1152 // [...] each such lookup shall find a variable with automatic storage
1153 // duration declared in the reaching scope of the local lambda expression.
1154 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1156 Diag(C
->Loc
, diag::err_capture_does_not_name_variable
) << C
->Id
;
1160 // C++11 [expr.prim.lambda]p8:
1161 // An identifier or this shall not appear more than once in a
1163 if (auto [It
, Inserted
] = CaptureNames
.insert(std::pair
{C
->Id
, Var
});
1165 if (C
->InitKind
== LambdaCaptureInitKind::NoInit
&&
1166 !Var
->isInitCapture()) {
1167 Diag(C
->Loc
, diag::err_capture_more_than_once
)
1168 << C
->Id
<< It
->second
->getBeginLoc()
1169 << FixItHint::CreateRemoval(
1170 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1171 Var
->setInvalidDecl();
1172 } else if (Var
&& Var
->isPlaceholderVar(getLangOpts())) {
1173 DiagPlaceholderVariableDefinition(C
->Loc
);
1175 // Previous capture captured something different (one or both was
1176 // an init-capture): no fixit.
1177 Diag(C
->Loc
, diag::err_capture_more_than_once
) << C
->Id
;
1182 // Ignore invalid decls; they'll just confuse the code later.
1183 if (Var
->isInvalidDecl())
1186 VarDecl
*Underlying
= Var
->getPotentiallyDecomposedVarDecl();
1188 if (!Underlying
->hasLocalStorage()) {
1189 Diag(C
->Loc
, diag::err_capture_non_automatic_variable
) << C
->Id
;
1190 Diag(Var
->getLocation(), diag::note_previous_decl
) << C
->Id
;
1194 // C++11 [expr.prim.lambda]p23:
1195 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1196 SourceLocation EllipsisLoc
;
1197 if (C
->EllipsisLoc
.isValid()) {
1198 if (Var
->isParameterPack()) {
1199 EllipsisLoc
= C
->EllipsisLoc
;
1201 Diag(C
->EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
1202 << (C
->Init
.isUsable() ? C
->Init
.get()->getSourceRange()
1203 : SourceRange(C
->Loc
));
1205 // Just ignore the ellipsis.
1207 } else if (Var
->isParameterPack()) {
1208 ContainsUnexpandedParameterPack
= true;
1211 if (C
->Init
.isUsable()) {
1212 addInitCapture(LSI
, cast
<VarDecl
>(Var
), C
->Kind
== LCK_ByRef
);
1213 PushOnScopeChains(Var
, CurScope
, false);
1215 TryCaptureKind Kind
= C
->Kind
== LCK_ByRef
? TryCapture_ExplicitByRef
1216 : TryCapture_ExplicitByVal
;
1217 tryCaptureVariable(Var
, C
->Loc
, Kind
, EllipsisLoc
);
1219 if (!LSI
->Captures
.empty())
1220 LSI
->ExplicitCaptureRanges
[LSI
->Captures
.size() - 1] = C
->ExplicitRange
;
1222 finishLambdaExplicitCaptures(LSI
);
1223 LSI
->ContainsUnexpandedParameterPack
|= ContainsUnexpandedParameterPack
;
1227 void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer
&Intro
,
1228 SourceLocation MutableLoc
) {
1230 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1231 LSI
->Mutable
= MutableLoc
.isValid();
1232 ContextRAII
Context(*this, LSI
->CallOperator
, /*NewThisContext*/ false);
1234 // C++11 [expr.prim.lambda]p9:
1235 // A lambda-expression whose smallest enclosing scope is a block scope is a
1236 // local lambda expression; any other lambda expression shall not have a
1237 // capture-default or simple-capture in its lambda-introducer.
1239 // For simple-captures, this is covered by the check below that any named
1240 // entity is a variable that can be captured.
1242 // For DR1632, we also allow a capture-default in any context where we can
1243 // odr-use 'this' (in particular, in a default initializer for a non-static
1245 if (Intro
.Default
!= LCD_None
&&
1246 !LSI
->Lambda
->getParent()->isFunctionOrMethod() &&
1247 (getCurrentThisType().isNull() ||
1248 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1249 /*BuildAndDiagnose=*/false)))
1250 Diag(Intro
.DefaultLoc
, diag::err_capture_default_non_local
);
1253 void Sema::ActOnLambdaClosureParameters(
1254 Scope
*LambdaScope
, MutableArrayRef
<DeclaratorChunk::ParamInfo
> Params
) {
1255 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1256 PushDeclContext(LambdaScope
, LSI
->CallOperator
);
1258 for (const DeclaratorChunk::ParamInfo
&P
: Params
) {
1259 auto *Param
= cast
<ParmVarDecl
>(P
.Param
);
1260 Param
->setOwningFunction(LSI
->CallOperator
);
1261 if (Param
->getIdentifier())
1262 PushOnScopeChains(Param
, LambdaScope
, false);
1265 LSI
->AfterParameterList
= true;
1268 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer
&Intro
,
1269 Declarator
&ParamInfo
,
1270 const DeclSpec
&DS
) {
1272 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1273 LSI
->CallOperator
->setConstexprKind(DS
.getConstexprSpecifier());
1275 SmallVector
<ParmVarDecl
*, 8> Params
;
1276 bool ExplicitResultType
;
1278 SourceLocation TypeLoc
, CallOperatorLoc
;
1279 if (ParamInfo
.getNumTypeObjects() == 0) {
1280 CallOperatorLoc
= TypeLoc
= Intro
.Range
.getEnd();
1283 ParamInfo
.isFunctionDeclarator(Index
);
1284 const auto &Object
= ParamInfo
.getTypeObject(Index
);
1286 Object
.Loc
.isValid() ? Object
.Loc
: ParamInfo
.getSourceRange().getEnd();
1287 CallOperatorLoc
= ParamInfo
.getSourceRange().getEnd();
1290 CXXRecordDecl
*Class
= LSI
->Lambda
;
1291 CXXMethodDecl
*Method
= LSI
->CallOperator
;
1293 TypeSourceInfo
*MethodTyInfo
= getLambdaType(
1294 *this, Intro
, ParamInfo
, getCurScope(), TypeLoc
, ExplicitResultType
);
1296 LSI
->ExplicitParams
= ParamInfo
.getNumTypeObjects() != 0;
1298 if (ParamInfo
.isFunctionDeclarator() != 0 &&
1299 !FTIHasSingleVoidParameter(ParamInfo
.getFunctionTypeInfo())) {
1300 const auto &FTI
= ParamInfo
.getFunctionTypeInfo();
1301 Params
.reserve(Params
.size());
1302 for (unsigned I
= 0; I
< FTI
.NumParams
; ++I
) {
1303 auto *Param
= cast
<ParmVarDecl
>(FTI
.Params
[I
].Param
);
1304 Param
->setScopeInfo(0, Params
.size());
1305 Params
.push_back(Param
);
1309 bool IsLambdaStatic
=
1310 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
;
1312 CompleteLambdaCallOperator(
1313 Method
, Intro
.Range
.getBegin(), CallOperatorLoc
,
1314 ParamInfo
.getTrailingRequiresClause(), MethodTyInfo
,
1315 ParamInfo
.getDeclSpec().getConstexprSpecifier(),
1316 IsLambdaStatic
? SC_Static
: SC_None
, Params
, ExplicitResultType
);
1318 CheckCXXDefaultArguments(Method
);
1320 // This represents the function body for the lambda function, check if we
1321 // have to apply optnone due to a pragma.
1322 AddRangeBasedOptnone(Method
);
1324 // code_seg attribute on lambda apply to the method.
1325 if (Attr
*A
= getImplicitCodeSegOrSectionAttrForFunction(
1326 Method
, /*IsDefinition=*/true))
1329 // Attributes on the lambda apply to the method.
1330 ProcessDeclAttributes(CurScope
, Method
, ParamInfo
);
1332 // CUDA lambdas get implicit host and device attributes.
1333 if (getLangOpts().CUDA
)
1334 CUDASetLambdaAttrs(Method
);
1336 // OpenMP lambdas might get assumumption attributes.
1337 if (LangOpts
.OpenMP
)
1338 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method
);
1340 handleLambdaNumbering(Class
, Method
);
1342 for (auto &&C
: LSI
->Captures
) {
1343 if (!C
.isVariableCapture())
1345 ValueDecl
*Var
= C
.getVariable();
1346 if (Var
&& Var
->isInitCapture()) {
1347 PushOnScopeChains(Var
, CurScope
, false);
1351 auto CheckRedefinition
= [&](ParmVarDecl
*Param
) {
1352 for (const auto &Capture
: Intro
.Captures
) {
1353 if (Capture
.Id
== Param
->getIdentifier()) {
1354 Diag(Param
->getLocation(), diag::err_parameter_shadow_capture
);
1355 Diag(Capture
.Loc
, diag::note_var_explicitly_captured_here
)
1356 << Capture
.Id
<< true;
1363 for (ParmVarDecl
*P
: Params
) {
1364 if (!P
->getIdentifier())
1366 if (CheckRedefinition(P
))
1367 CheckShadow(CurScope
, P
);
1368 PushOnScopeChains(P
, CurScope
);
1371 // C++23 [expr.prim.lambda.capture]p5:
1372 // If an identifier in a capture appears as the declarator-id of a parameter
1373 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1374 // template parameter of the lambda-expression's template-parameter-list, the
1375 // program is ill-formed.
1376 TemplateParameterList
*TemplateParams
=
1377 getGenericLambdaTemplateParameterList(LSI
, *this);
1378 if (TemplateParams
) {
1379 for (const auto *TP
: TemplateParams
->asArray()) {
1380 if (!TP
->getIdentifier())
1382 for (const auto &Capture
: Intro
.Captures
) {
1383 if (Capture
.Id
== TP
->getIdentifier()) {
1384 Diag(Capture
.Loc
, diag::err_template_param_shadow
) << Capture
.Id
;
1385 Diag(TP
->getLocation(), diag::note_template_param_here
);
1391 // C++20: dcl.decl.general p4:
1392 // The optional requires-clause ([temp.pre]) in an init-declarator or
1393 // member-declarator shall be present only if the declarator declares a
1394 // templated function ([dcl.fct]).
1395 if (Expr
*TRC
= Method
->getTrailingRequiresClause()) {
1397 // An entity is templated if it is
1399 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1400 // templated entity,
1401 // - a member of a templated entity,
1402 // - an enumerator for an enumeration that is a templated entity, or
1403 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1404 // appearing in the declaration of a templated entity. [Note 6: A local
1405 // class, a local or block variable, or a friend function defined in a
1406 // templated entity is a templated entity. — end note]
1408 // A templated function is a function template or a function that is
1409 // templated. A templated class is a class template or a class that is
1410 // templated. A templated variable is a variable template or a variable
1411 // that is templated.
1413 // Note: we only have to check if this is defined in a template entity, OR
1414 // if we are a template, since the rest don't apply. The requires clause
1415 // applies to the call operator, which we already know is a member function,
1417 if (!Method
->getDescribedFunctionTemplate() && !Method
->isTemplated()) {
1418 Diag(TRC
->getBeginLoc(), diag::err_constrained_non_templated_function
);
1422 // Enter a new evaluation context to insulate the lambda from any
1423 // cleanups from the enclosing full-expression.
1424 PushExpressionEvaluationContext(
1425 LSI
->CallOperator
->isConsteval()
1426 ? ExpressionEvaluationContext::ImmediateFunctionContext
1427 : ExpressionEvaluationContext::PotentiallyEvaluated
);
1428 ExprEvalContexts
.back().InImmediateFunctionContext
=
1429 LSI
->CallOperator
->isConsteval();
1430 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
1431 getLangOpts().CPlusPlus20
&& LSI
->CallOperator
->isImmediateEscalating();
1434 void Sema::ActOnLambdaError(SourceLocation StartLoc
, Scope
*CurScope
,
1435 bool IsInstantiation
) {
1436 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(FunctionScopes
.back());
1438 // Leave the expression-evaluation context.
1439 DiscardCleanupsInEvaluationContext();
1440 PopExpressionEvaluationContext();
1442 // Leave the context of the lambda.
1443 if (!IsInstantiation
)
1446 // Finalize the lambda.
1447 CXXRecordDecl
*Class
= LSI
->Lambda
;
1448 Class
->setInvalidDecl();
1449 SmallVector
<Decl
*, 4> Fields(Class
->fields());
1450 ActOnFields(nullptr, Class
->getLocation(), Class
, Fields
, SourceLocation(),
1451 SourceLocation(), ParsedAttributesView());
1452 CheckCompletedCXXClass(nullptr, Class
);
1454 PopFunctionScopeInfo();
1457 template <typename Func
>
1458 static void repeatForLambdaConversionFunctionCallingConvs(
1459 Sema
&S
, const FunctionProtoType
&CallOpProto
, Func F
) {
1460 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
1461 CallOpProto
.isVariadic(), /*IsCXXMethod=*/false);
1462 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
1463 CallOpProto
.isVariadic(), /*IsCXXMethod=*/true);
1464 CallingConv CallOpCC
= CallOpProto
.getCallConv();
1466 /// Implement emitting a version of the operator for many of the calling
1467 /// conventions for MSVC, as described here:
1468 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1469 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1470 /// vectorcall are generated by MSVC when it is supported by the target.
1471 /// Additionally, we are ensuring that the default-free/default-member and
1472 /// call-operator calling convention are generated as well.
1473 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1474 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1475 /// that someone who intentionally places 'thiscall' on the lambda call
1476 /// operator will still get that overload, since we don't have the a way of
1477 /// detecting the attribute by the time we get here.
1478 if (S
.getLangOpts().MSVCCompat
) {
1479 CallingConv Convs
[] = {
1480 CC_C
, CC_X86StdCall
, CC_X86FastCall
, CC_X86VectorCall
,
1481 DefaultFree
, DefaultMember
, CallOpCC
};
1483 llvm::iterator_range
<CallingConv
*> Range(
1484 std::begin(Convs
), std::unique(std::begin(Convs
), std::end(Convs
)));
1485 const TargetInfo
&TI
= S
.getASTContext().getTargetInfo();
1487 for (CallingConv C
: Range
) {
1488 if (TI
.checkCallingConvention(C
) == TargetInfo::CCCR_OK
)
1494 if (CallOpCC
== DefaultMember
&& DefaultMember
!= DefaultFree
) {
1502 // Returns the 'standard' calling convention to be used for the lambda
1503 // conversion function, that is, the 'free' function calling convention unless
1504 // it is overridden by a non-default calling convention attribute.
1506 getLambdaConversionFunctionCallConv(Sema
&S
,
1507 const FunctionProtoType
*CallOpProto
) {
1508 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
1509 CallOpProto
->isVariadic(), /*IsCXXMethod=*/false);
1510 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
1511 CallOpProto
->isVariadic(), /*IsCXXMethod=*/true);
1512 CallingConv CallOpCC
= CallOpProto
->getCallConv();
1514 // If the call-operator hasn't been changed, return both the 'free' and
1515 // 'member' function calling convention.
1516 if (CallOpCC
== DefaultMember
&& DefaultMember
!= DefaultFree
)
1521 QualType
Sema::getLambdaConversionFunctionResultType(
1522 const FunctionProtoType
*CallOpProto
, CallingConv CC
) {
1523 const FunctionProtoType::ExtProtoInfo CallOpExtInfo
=
1524 CallOpProto
->getExtProtoInfo();
1525 FunctionProtoType::ExtProtoInfo InvokerExtInfo
= CallOpExtInfo
;
1526 InvokerExtInfo
.ExtInfo
= InvokerExtInfo
.ExtInfo
.withCallingConv(CC
);
1527 InvokerExtInfo
.TypeQuals
= Qualifiers();
1528 assert(InvokerExtInfo
.RefQualifier
== RQ_None
&&
1529 "Lambda's call operator should not have a reference qualifier");
1530 return Context
.getFunctionType(CallOpProto
->getReturnType(),
1531 CallOpProto
->getParamTypes(), InvokerExtInfo
);
1534 /// Add a lambda's conversion to function pointer, as described in
1535 /// C++11 [expr.prim.lambda]p6.
1536 static void addFunctionPointerConversion(Sema
&S
, SourceRange IntroducerRange
,
1537 CXXRecordDecl
*Class
,
1538 CXXMethodDecl
*CallOperator
,
1539 QualType InvokerFunctionTy
) {
1540 // This conversion is explicitly disabled if the lambda's function has
1541 // pass_object_size attributes on any of its parameters.
1542 auto HasPassObjectSizeAttr
= [](const ParmVarDecl
*P
) {
1543 return P
->hasAttr
<PassObjectSizeAttr
>();
1545 if (llvm::any_of(CallOperator
->parameters(), HasPassObjectSizeAttr
))
1548 // Add the conversion to function pointer.
1549 QualType PtrToFunctionTy
= S
.Context
.getPointerType(InvokerFunctionTy
);
1551 // Create the type of the conversion function.
1552 FunctionProtoType::ExtProtoInfo
ConvExtInfo(
1553 S
.Context
.getDefaultCallingConvention(
1554 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1555 // The conversion function is always const and noexcept.
1556 ConvExtInfo
.TypeQuals
= Qualifiers();
1557 ConvExtInfo
.TypeQuals
.addConst();
1558 ConvExtInfo
.ExceptionSpec
.Type
= EST_BasicNoexcept
;
1560 S
.Context
.getFunctionType(PtrToFunctionTy
, std::nullopt
, ConvExtInfo
);
1562 SourceLocation Loc
= IntroducerRange
.getBegin();
1563 DeclarationName ConversionName
1564 = S
.Context
.DeclarationNames
.getCXXConversionFunctionName(
1565 S
.Context
.getCanonicalType(PtrToFunctionTy
));
1566 // Construct a TypeSourceInfo for the conversion function, and wire
1567 // all the parameters appropriately for the FunctionProtoTypeLoc
1568 // so that everything works during transformation/instantiation of
1570 // The main reason for wiring up the parameters of the conversion
1571 // function with that of the call operator is so that constructs
1572 // like the following work:
1573 // auto L = [](auto b) { <-- 1
1574 // return [](auto a) -> decltype(a) { <-- 2
1578 // int (*fp)(int) = L(5);
1579 // Because the trailing return type can contain DeclRefExprs that refer
1580 // to the original call operator's variables, we hijack the call
1581 // operators ParmVarDecls below.
1582 TypeSourceInfo
*ConvNamePtrToFunctionTSI
=
1583 S
.Context
.getTrivialTypeSourceInfo(PtrToFunctionTy
, Loc
);
1584 DeclarationNameLoc ConvNameLoc
=
1585 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI
);
1587 // The conversion function is a conversion to a pointer-to-function.
1588 TypeSourceInfo
*ConvTSI
= S
.Context
.getTrivialTypeSourceInfo(ConvTy
, Loc
);
1589 FunctionProtoTypeLoc ConvTL
=
1590 ConvTSI
->getTypeLoc().getAs
<FunctionProtoTypeLoc
>();
1591 // Get the result of the conversion function which is a pointer-to-function.
1592 PointerTypeLoc PtrToFunctionTL
=
1593 ConvTL
.getReturnLoc().getAs
<PointerTypeLoc
>();
1594 // Do the same for the TypeSourceInfo that is used to name the conversion
1596 PointerTypeLoc ConvNamePtrToFunctionTL
=
1597 ConvNamePtrToFunctionTSI
->getTypeLoc().getAs
<PointerTypeLoc
>();
1599 // Get the underlying function types that the conversion function will
1600 // be converting to (should match the type of the call operator).
1601 FunctionProtoTypeLoc CallOpConvTL
=
1602 PtrToFunctionTL
.getPointeeLoc().getAs
<FunctionProtoTypeLoc
>();
1603 FunctionProtoTypeLoc CallOpConvNameTL
=
1604 ConvNamePtrToFunctionTL
.getPointeeLoc().getAs
<FunctionProtoTypeLoc
>();
1606 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1607 // These parameter's are essentially used to transform the name and
1608 // the type of the conversion operator. By using the same parameters
1609 // as the call operator's we don't have to fix any back references that
1610 // the trailing return type of the call operator's uses (such as
1611 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1612 // - we can simply use the return type of the call operator, and
1613 // everything should work.
1614 SmallVector
<ParmVarDecl
*, 4> InvokerParams
;
1615 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
) {
1616 ParmVarDecl
*From
= CallOperator
->getParamDecl(I
);
1618 InvokerParams
.push_back(ParmVarDecl::Create(
1620 // Temporarily add to the TU. This is set to the invoker below.
1621 S
.Context
.getTranslationUnitDecl(), From
->getBeginLoc(),
1622 From
->getLocation(), From
->getIdentifier(), From
->getType(),
1623 From
->getTypeSourceInfo(), From
->getStorageClass(),
1624 /*DefArg=*/nullptr));
1625 CallOpConvTL
.setParam(I
, From
);
1626 CallOpConvNameTL
.setParam(I
, From
);
1629 CXXConversionDecl
*Conversion
= CXXConversionDecl::Create(
1630 S
.Context
, Class
, Loc
,
1631 DeclarationNameInfo(ConversionName
, Loc
, ConvNameLoc
), ConvTy
, ConvTSI
,
1632 S
.getCurFPFeatures().isFPConstrained(),
1633 /*isInline=*/true, ExplicitSpecifier(),
1634 S
.getLangOpts().CPlusPlus17
? ConstexprSpecKind::Constexpr
1635 : ConstexprSpecKind::Unspecified
,
1636 CallOperator
->getBody()->getEndLoc());
1637 Conversion
->setAccess(AS_public
);
1638 Conversion
->setImplicit(true);
1640 // A non-generic lambda may still be a templated entity. We need to preserve
1641 // constraints when converting the lambda to a function pointer. See GH63181.
1642 if (Expr
*Requires
= CallOperator
->getTrailingRequiresClause())
1643 Conversion
->setTrailingRequiresClause(Requires
);
1645 if (Class
->isGenericLambda()) {
1646 // Create a template version of the conversion operator, using the template
1647 // parameter list of the function call operator.
1648 FunctionTemplateDecl
*TemplateCallOperator
=
1649 CallOperator
->getDescribedFunctionTemplate();
1650 FunctionTemplateDecl
*ConversionTemplate
=
1651 FunctionTemplateDecl::Create(S
.Context
, Class
,
1652 Loc
, ConversionName
,
1653 TemplateCallOperator
->getTemplateParameters(),
1655 ConversionTemplate
->setAccess(AS_public
);
1656 ConversionTemplate
->setImplicit(true);
1657 Conversion
->setDescribedFunctionTemplate(ConversionTemplate
);
1658 Class
->addDecl(ConversionTemplate
);
1660 Class
->addDecl(Conversion
);
1662 // If the lambda is not static, we need to add a static member
1663 // function that will be the result of the conversion with a
1664 // certain unique ID.
1665 // When it is static we just return the static call operator instead.
1666 if (CallOperator
->isInstance()) {
1667 DeclarationName InvokerName
=
1668 &S
.Context
.Idents
.get(getLambdaStaticInvokerName());
1669 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1670 // we should get a prebuilt TrivialTypeSourceInfo from Context
1671 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1672 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1673 // loop below and then use its Params to set Invoke->setParams(...) below.
1674 // This would avoid the 'const' qualifier of the calloperator from
1675 // contaminating the type of the invoker, which is currently adjusted
1676 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1677 // trailing return type of the invoker would require a visitor to rebuild
1678 // the trailing return type and adjusting all back DeclRefExpr's to refer
1679 // to the new static invoker parameters - not the call operator's.
1680 CXXMethodDecl
*Invoke
= CXXMethodDecl::Create(
1681 S
.Context
, Class
, Loc
, DeclarationNameInfo(InvokerName
, Loc
),
1682 InvokerFunctionTy
, CallOperator
->getTypeSourceInfo(), SC_Static
,
1683 S
.getCurFPFeatures().isFPConstrained(),
1684 /*isInline=*/true, CallOperator
->getConstexprKind(),
1685 CallOperator
->getBody()->getEndLoc());
1686 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
)
1687 InvokerParams
[I
]->setOwningFunction(Invoke
);
1688 Invoke
->setParams(InvokerParams
);
1689 Invoke
->setAccess(AS_private
);
1690 Invoke
->setImplicit(true);
1691 if (Class
->isGenericLambda()) {
1692 FunctionTemplateDecl
*TemplateCallOperator
=
1693 CallOperator
->getDescribedFunctionTemplate();
1694 FunctionTemplateDecl
*StaticInvokerTemplate
=
1695 FunctionTemplateDecl::Create(
1696 S
.Context
, Class
, Loc
, InvokerName
,
1697 TemplateCallOperator
->getTemplateParameters(), Invoke
);
1698 StaticInvokerTemplate
->setAccess(AS_private
);
1699 StaticInvokerTemplate
->setImplicit(true);
1700 Invoke
->setDescribedFunctionTemplate(StaticInvokerTemplate
);
1701 Class
->addDecl(StaticInvokerTemplate
);
1703 Class
->addDecl(Invoke
);
1707 /// Add a lambda's conversion to function pointers, as described in
1708 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1709 /// single pointer conversion. In the event that the default calling convention
1710 /// for free and member functions is different, it will emit both conventions.
1711 static void addFunctionPointerConversions(Sema
&S
, SourceRange IntroducerRange
,
1712 CXXRecordDecl
*Class
,
1713 CXXMethodDecl
*CallOperator
) {
1714 const FunctionProtoType
*CallOpProto
=
1715 CallOperator
->getType()->castAs
<FunctionProtoType
>();
1717 repeatForLambdaConversionFunctionCallingConvs(
1718 S
, *CallOpProto
, [&](CallingConv CC
) {
1719 QualType InvokerFunctionTy
=
1720 S
.getLambdaConversionFunctionResultType(CallOpProto
, CC
);
1721 addFunctionPointerConversion(S
, IntroducerRange
, Class
, CallOperator
,
1726 /// Add a lambda's conversion to block pointer.
1727 static void addBlockPointerConversion(Sema
&S
,
1728 SourceRange IntroducerRange
,
1729 CXXRecordDecl
*Class
,
1730 CXXMethodDecl
*CallOperator
) {
1731 const FunctionProtoType
*CallOpProto
=
1732 CallOperator
->getType()->castAs
<FunctionProtoType
>();
1733 QualType FunctionTy
= S
.getLambdaConversionFunctionResultType(
1734 CallOpProto
, getLambdaConversionFunctionCallConv(S
, CallOpProto
));
1735 QualType BlockPtrTy
= S
.Context
.getBlockPointerType(FunctionTy
);
1737 FunctionProtoType::ExtProtoInfo
ConversionEPI(
1738 S
.Context
.getDefaultCallingConvention(
1739 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1740 ConversionEPI
.TypeQuals
= Qualifiers();
1741 ConversionEPI
.TypeQuals
.addConst();
1743 S
.Context
.getFunctionType(BlockPtrTy
, std::nullopt
, ConversionEPI
);
1745 SourceLocation Loc
= IntroducerRange
.getBegin();
1746 DeclarationName Name
1747 = S
.Context
.DeclarationNames
.getCXXConversionFunctionName(
1748 S
.Context
.getCanonicalType(BlockPtrTy
));
1749 DeclarationNameLoc NameLoc
= DeclarationNameLoc::makeNamedTypeLoc(
1750 S
.Context
.getTrivialTypeSourceInfo(BlockPtrTy
, Loc
));
1751 CXXConversionDecl
*Conversion
= CXXConversionDecl::Create(
1752 S
.Context
, Class
, Loc
, DeclarationNameInfo(Name
, Loc
, NameLoc
), ConvTy
,
1753 S
.Context
.getTrivialTypeSourceInfo(ConvTy
, Loc
),
1754 S
.getCurFPFeatures().isFPConstrained(),
1755 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified
,
1756 CallOperator
->getBody()->getEndLoc());
1757 Conversion
->setAccess(AS_public
);
1758 Conversion
->setImplicit(true);
1759 Class
->addDecl(Conversion
);
1762 ExprResult
Sema::BuildCaptureInit(const Capture
&Cap
,
1763 SourceLocation ImplicitCaptureLoc
,
1764 bool IsOpenMPMapping
) {
1765 // VLA captures don't have a stored initialization expression.
1766 if (Cap
.isVLATypeCapture())
1767 return ExprResult();
1769 // An init-capture is initialized directly from its stored initializer.
1770 if (Cap
.isInitCapture())
1771 return cast
<VarDecl
>(Cap
.getVariable())->getInit();
1773 // For anything else, build an initialization expression. For an implicit
1774 // capture, the capture notionally happens at the capture-default, so use
1775 // that location here.
1776 SourceLocation Loc
=
1777 ImplicitCaptureLoc
.isValid() ? ImplicitCaptureLoc
: Cap
.getLocation();
1779 // C++11 [expr.prim.lambda]p21:
1780 // When the lambda-expression is evaluated, the entities that
1781 // are captured by copy are used to direct-initialize each
1782 // corresponding non-static data member of the resulting closure
1783 // object. (For array members, the array elements are
1784 // direct-initialized in increasing subscript order.) These
1785 // initializations are performed in the (unspecified) order in
1786 // which the non-static data members are declared.
1788 // C++ [expr.prim.lambda]p12:
1789 // An entity captured by a lambda-expression is odr-used (3.2) in
1790 // the scope containing the lambda-expression.
1792 IdentifierInfo
*Name
= nullptr;
1793 if (Cap
.isThisCapture()) {
1794 QualType ThisTy
= getCurrentThisType();
1795 Expr
*This
= BuildCXXThisExpr(Loc
, ThisTy
, ImplicitCaptureLoc
.isValid());
1796 if (Cap
.isCopyCapture())
1797 Init
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
1801 assert(Cap
.isVariableCapture() && "unknown kind of capture");
1802 ValueDecl
*Var
= Cap
.getVariable();
1803 Name
= Var
->getIdentifier();
1804 Init
= BuildDeclarationNameExpr(
1805 CXXScopeSpec(), DeclarationNameInfo(Var
->getDeclName(), Loc
), Var
);
1808 // In OpenMP, the capture kind doesn't actually describe how to capture:
1809 // variables are "mapped" onto the device in a process that does not formally
1810 // make a copy, even for a "copy capture".
1811 if (IsOpenMPMapping
)
1814 if (Init
.isInvalid())
1817 Expr
*InitExpr
= Init
.get();
1818 InitializedEntity Entity
= InitializedEntity::InitializeLambdaCapture(
1819 Name
, Cap
.getCaptureType(), Loc
);
1820 InitializationKind InitKind
=
1821 InitializationKind::CreateDirect(Loc
, Loc
, Loc
);
1822 InitializationSequence
InitSeq(*this, Entity
, InitKind
, InitExpr
);
1823 return InitSeq
.Perform(*this, Entity
, InitKind
, InitExpr
);
1826 ExprResult
Sema::ActOnLambdaExpr(SourceLocation StartLoc
, Stmt
*Body
,
1828 LambdaScopeInfo LSI
= *cast
<LambdaScopeInfo
>(FunctionScopes
.back());
1829 ActOnFinishFunctionBody(LSI
.CallOperator
, Body
);
1830 return BuildLambdaExpr(StartLoc
, Body
->getEndLoc(), &LSI
);
1833 static LambdaCaptureDefault
1834 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS
) {
1836 case CapturingScopeInfo::ImpCap_None
:
1838 case CapturingScopeInfo::ImpCap_LambdaByval
:
1840 case CapturingScopeInfo::ImpCap_CapturedRegion
:
1841 case CapturingScopeInfo::ImpCap_LambdaByref
:
1843 case CapturingScopeInfo::ImpCap_Block
:
1844 llvm_unreachable("block capture in lambda");
1846 llvm_unreachable("Unknown implicit capture style");
1849 bool Sema::CaptureHasSideEffects(const Capture
&From
) {
1850 if (From
.isInitCapture()) {
1851 Expr
*Init
= cast
<VarDecl
>(From
.getVariable())->getInit();
1852 if (Init
&& Init
->HasSideEffects(Context
))
1856 if (!From
.isCopyCapture())
1859 const QualType T
= From
.isThisCapture()
1860 ? getCurrentThisType()->getPointeeType()
1861 : From
.getCaptureType();
1863 if (T
.isVolatileQualified())
1866 const Type
*BaseT
= T
->getBaseElementTypeUnsafe();
1867 if (const CXXRecordDecl
*RD
= BaseT
->getAsCXXRecordDecl())
1868 return !RD
->isCompleteDefinition() || !RD
->hasTrivialCopyConstructor() ||
1869 !RD
->hasTrivialDestructor();
1874 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange
,
1875 const Capture
&From
) {
1876 if (CaptureHasSideEffects(From
))
1879 if (From
.isVLATypeCapture())
1882 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
1884 if (From
.isInitCapture() &&
1885 From
.getVariable()->isPlaceholderVar(getLangOpts()))
1888 auto diag
= Diag(From
.getLocation(), diag::warn_unused_lambda_capture
);
1889 if (From
.isThisCapture())
1892 diag
<< From
.getVariable();
1893 diag
<< From
.isNonODRUsed();
1894 diag
<< FixItHint::CreateRemoval(CaptureRange
);
1898 /// Create a field within the lambda class or captured statement record for the
1900 FieldDecl
*Sema::BuildCaptureField(RecordDecl
*RD
,
1901 const sema::Capture
&Capture
) {
1902 SourceLocation Loc
= Capture
.getLocation();
1903 QualType FieldType
= Capture
.getCaptureType();
1905 TypeSourceInfo
*TSI
= nullptr;
1906 if (Capture
.isVariableCapture()) {
1907 const auto *Var
= dyn_cast_or_null
<VarDecl
>(Capture
.getVariable());
1908 if (Var
&& Var
->isInitCapture())
1909 TSI
= Var
->getTypeSourceInfo();
1912 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1913 // appropriate, at least for an implicit capture.
1915 TSI
= Context
.getTrivialTypeSourceInfo(FieldType
, Loc
);
1917 // Build the non-static data member.
1919 FieldDecl::Create(Context
, RD
, /*StartLoc=*/Loc
, /*IdLoc=*/Loc
,
1920 /*Id=*/nullptr, FieldType
, TSI
, /*BW=*/nullptr,
1921 /*Mutable=*/false, ICIS_NoInit
);
1922 // If the variable being captured has an invalid type, mark the class as
1924 if (!FieldType
->isDependentType()) {
1925 if (RequireCompleteSizedType(Loc
, FieldType
,
1926 diag::err_field_incomplete_or_sizeless
)) {
1927 RD
->setInvalidDecl();
1928 Field
->setInvalidDecl();
1931 FieldType
->isIncompleteType(&Def
);
1932 if (Def
&& Def
->isInvalidDecl()) {
1933 RD
->setInvalidDecl();
1934 Field
->setInvalidDecl();
1938 Field
->setImplicit(true);
1939 Field
->setAccess(AS_private
);
1942 if (Capture
.isVLATypeCapture())
1943 Field
->setCapturedVLAType(Capture
.getCapturedVLAType());
1948 ExprResult
Sema::BuildLambdaExpr(SourceLocation StartLoc
, SourceLocation EndLoc
,
1949 LambdaScopeInfo
*LSI
) {
1950 // Collect information from the lambda scope.
1951 SmallVector
<LambdaCapture
, 4> Captures
;
1952 SmallVector
<Expr
*, 4> CaptureInits
;
1953 SourceLocation CaptureDefaultLoc
= LSI
->CaptureDefaultLoc
;
1954 LambdaCaptureDefault CaptureDefault
=
1955 mapImplicitCaptureStyle(LSI
->ImpCaptureStyle
);
1956 CXXRecordDecl
*Class
;
1957 CXXMethodDecl
*CallOperator
;
1958 SourceRange IntroducerRange
;
1959 bool ExplicitParams
;
1960 bool ExplicitResultType
;
1961 CleanupInfo LambdaCleanup
;
1962 bool ContainsUnexpandedParameterPack
;
1963 bool IsGenericLambda
;
1965 CallOperator
= LSI
->CallOperator
;
1966 Class
= LSI
->Lambda
;
1967 IntroducerRange
= LSI
->IntroducerRange
;
1968 ExplicitParams
= LSI
->ExplicitParams
;
1969 ExplicitResultType
= !LSI
->HasImplicitReturnType
;
1970 LambdaCleanup
= LSI
->Cleanup
;
1971 ContainsUnexpandedParameterPack
= LSI
->ContainsUnexpandedParameterPack
;
1972 IsGenericLambda
= Class
->isGenericLambda();
1974 CallOperator
->setLexicalDeclContext(Class
);
1975 Decl
*TemplateOrNonTemplateCallOperatorDecl
=
1976 CallOperator
->getDescribedFunctionTemplate()
1977 ? CallOperator
->getDescribedFunctionTemplate()
1978 : cast
<Decl
>(CallOperator
);
1980 // FIXME: Is this really the best choice? Keeping the lexical decl context
1981 // set as CurContext seems more faithful to the source.
1982 TemplateOrNonTemplateCallOperatorDecl
->setLexicalDeclContext(Class
);
1984 PopExpressionEvaluationContext();
1986 // True if the current capture has a used capture or default before it.
1987 bool CurHasPreviousCapture
= CaptureDefault
!= LCD_None
;
1988 SourceLocation PrevCaptureLoc
= CurHasPreviousCapture
?
1989 CaptureDefaultLoc
: IntroducerRange
.getBegin();
1991 for (unsigned I
= 0, N
= LSI
->Captures
.size(); I
!= N
; ++I
) {
1992 const Capture
&From
= LSI
->Captures
[I
];
1994 if (From
.isInvalid())
1997 assert(!From
.isBlockCapture() && "Cannot capture __block variables");
1998 bool IsImplicit
= I
>= LSI
->NumExplicitCaptures
;
1999 SourceLocation ImplicitCaptureLoc
=
2000 IsImplicit
? CaptureDefaultLoc
: SourceLocation();
2002 // Use source ranges of explicit captures for fixits where available.
2003 SourceRange CaptureRange
= LSI
->ExplicitCaptureRanges
[I
];
2005 // Warn about unused explicit captures.
2006 bool IsCaptureUsed
= true;
2007 if (!CurContext
->isDependentContext() && !IsImplicit
&&
2008 !From
.isODRUsed()) {
2009 // Initialized captures that are non-ODR used may not be eliminated.
2010 // FIXME: Where did the IsGenericLambda here come from?
2011 bool NonODRUsedInitCapture
=
2012 IsGenericLambda
&& From
.isNonODRUsed() && From
.isInitCapture();
2013 if (!NonODRUsedInitCapture
) {
2014 bool IsLast
= (I
+ 1) == LSI
->NumExplicitCaptures
;
2015 SourceRange FixItRange
;
2016 if (CaptureRange
.isValid()) {
2017 if (!CurHasPreviousCapture
&& !IsLast
) {
2018 // If there are no captures preceding this capture, remove the
2020 FixItRange
= SourceRange(CaptureRange
.getBegin(),
2021 getLocForEndOfToken(CaptureRange
.getEnd()));
2023 // Otherwise, remove the comma since the last used capture.
2024 FixItRange
= SourceRange(getLocForEndOfToken(PrevCaptureLoc
),
2025 CaptureRange
.getEnd());
2029 IsCaptureUsed
= !DiagnoseUnusedLambdaCapture(FixItRange
, From
);
2033 if (CaptureRange
.isValid()) {
2034 CurHasPreviousCapture
|= IsCaptureUsed
;
2035 PrevCaptureLoc
= CaptureRange
.getEnd();
2038 // Map the capture to our AST representation.
2039 LambdaCapture Capture
= [&] {
2040 if (From
.isThisCapture()) {
2041 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2042 // because it results in a reference capture. Don't warn prior to
2043 // C++2a; there's nothing that can be done about it before then.
2044 if (getLangOpts().CPlusPlus20
&& IsImplicit
&&
2045 CaptureDefault
== LCD_ByCopy
) {
2046 Diag(From
.getLocation(), diag::warn_deprecated_this_capture
);
2047 Diag(CaptureDefaultLoc
, diag::note_deprecated_this_capture
)
2048 << FixItHint::CreateInsertion(
2049 getLocForEndOfToken(CaptureDefaultLoc
), ", this");
2051 return LambdaCapture(From
.getLocation(), IsImplicit
,
2052 From
.isCopyCapture() ? LCK_StarThis
: LCK_This
);
2053 } else if (From
.isVLATypeCapture()) {
2054 return LambdaCapture(From
.getLocation(), IsImplicit
, LCK_VLAType
);
2056 assert(From
.isVariableCapture() && "unknown kind of capture");
2057 ValueDecl
*Var
= From
.getVariable();
2058 LambdaCaptureKind Kind
=
2059 From
.isCopyCapture() ? LCK_ByCopy
: LCK_ByRef
;
2060 return LambdaCapture(From
.getLocation(), IsImplicit
, Kind
, Var
,
2061 From
.getEllipsisLoc());
2065 // Form the initializer for the capture field.
2066 ExprResult Init
= BuildCaptureInit(From
, ImplicitCaptureLoc
);
2068 // FIXME: Skip this capture if the capture is not used, the initializer
2069 // has no side-effects, the type of the capture is trivial, and the
2070 // lambda is not externally visible.
2072 // Add a FieldDecl for the capture and form its initializer.
2073 BuildCaptureField(Class
, From
);
2074 Captures
.push_back(Capture
);
2075 CaptureInits
.push_back(Init
.get());
2078 CUDACheckLambdaCapture(CallOperator
, From
);
2081 Class
->setCaptures(Context
, Captures
);
2083 // C++11 [expr.prim.lambda]p6:
2084 // The closure type for a lambda-expression with no lambda-capture
2085 // has a public non-virtual non-explicit const conversion function
2086 // to pointer to function having the same parameter and return
2087 // types as the closure type's function call operator.
2088 if (Captures
.empty() && CaptureDefault
== LCD_None
)
2089 addFunctionPointerConversions(*this, IntroducerRange
, Class
,
2093 // The closure type for a lambda-expression has a public non-virtual
2094 // non-explicit const conversion function to a block pointer having the
2095 // same parameter and return types as the closure type's function call
2097 // FIXME: Fix generic lambda to block conversions.
2098 if (getLangOpts().Blocks
&& getLangOpts().ObjC
&& !IsGenericLambda
)
2099 addBlockPointerConversion(*this, IntroducerRange
, Class
, CallOperator
);
2101 // Finalize the lambda class.
2102 SmallVector
<Decl
*, 4> Fields(Class
->fields());
2103 ActOnFields(nullptr, Class
->getLocation(), Class
, Fields
, SourceLocation(),
2104 SourceLocation(), ParsedAttributesView());
2105 CheckCompletedCXXClass(nullptr, Class
);
2108 Cleanup
.mergeFrom(LambdaCleanup
);
2110 LambdaExpr
*Lambda
= LambdaExpr::Create(Context
, Class
, IntroducerRange
,
2111 CaptureDefault
, CaptureDefaultLoc
,
2112 ExplicitParams
, ExplicitResultType
,
2113 CaptureInits
, EndLoc
,
2114 ContainsUnexpandedParameterPack
);
2115 // If the lambda expression's call operator is not explicitly marked constexpr
2116 // and we are not in a dependent context, analyze the call operator to infer
2117 // its constexpr-ness, suppressing diagnostics while doing so.
2118 if (getLangOpts().CPlusPlus17
&& !CallOperator
->isInvalidDecl() &&
2119 !CallOperator
->isConstexpr() &&
2120 !isa
<CoroutineBodyStmt
>(CallOperator
->getBody()) &&
2121 !Class
->getDeclContext()->isDependentContext()) {
2122 CallOperator
->setConstexprKind(
2123 CheckConstexprFunctionDefinition(CallOperator
,
2124 CheckConstexprKind::CheckValid
)
2125 ? ConstexprSpecKind::Constexpr
2126 : ConstexprSpecKind::Unspecified
);
2129 // Emit delayed shadowing warnings now that the full capture list is known.
2130 DiagnoseShadowingLambdaDecls(LSI
);
2132 if (!CurContext
->isDependentContext()) {
2133 switch (ExprEvalContexts
.back().Context
) {
2134 // C++11 [expr.prim.lambda]p2:
2135 // A lambda-expression shall not appear in an unevaluated operand
2137 case ExpressionEvaluationContext::Unevaluated
:
2138 case ExpressionEvaluationContext::UnevaluatedList
:
2139 case ExpressionEvaluationContext::UnevaluatedAbstract
:
2140 // C++1y [expr.const]p2:
2141 // A conditional-expression e is a core constant expression unless the
2142 // evaluation of e, following the rules of the abstract machine, would
2143 // evaluate [...] a lambda-expression.
2145 // This is technically incorrect, there are some constant evaluated contexts
2146 // where this should be allowed. We should probably fix this when DR1607 is
2147 // ratified, it lays out the exact set of conditions where we shouldn't
2148 // allow a lambda-expression.
2149 case ExpressionEvaluationContext::ConstantEvaluated
:
2150 case ExpressionEvaluationContext::ImmediateFunctionContext
:
2151 // We don't actually diagnose this case immediately, because we
2152 // could be within a context where we might find out later that
2153 // the expression is potentially evaluated (e.g., for typeid).
2154 ExprEvalContexts
.back().Lambdas
.push_back(Lambda
);
2157 case ExpressionEvaluationContext::DiscardedStatement
:
2158 case ExpressionEvaluationContext::PotentiallyEvaluated
:
2159 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
2164 return MaybeBindToTemporary(Lambda
);
2167 ExprResult
Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation
,
2168 SourceLocation ConvLocation
,
2169 CXXConversionDecl
*Conv
,
2171 // Make sure that the lambda call operator is marked used.
2172 CXXRecordDecl
*Lambda
= Conv
->getParent();
2173 CXXMethodDecl
*CallOperator
2174 = cast
<CXXMethodDecl
>(
2176 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
)).front());
2177 CallOperator
->setReferenced();
2178 CallOperator
->markUsed(Context
);
2180 ExprResult Init
= PerformCopyInitialization(
2181 InitializedEntity::InitializeLambdaToBlock(ConvLocation
, Src
->getType()),
2182 CurrentLocation
, Src
);
2183 if (!Init
.isInvalid())
2184 Init
= ActOnFinishFullExpr(Init
.get(), /*DiscardedValue*/ false);
2186 if (Init
.isInvalid())
2189 // Create the new block to be returned.
2190 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, ConvLocation
);
2192 // Set the type information.
2193 Block
->setSignatureAsWritten(CallOperator
->getTypeSourceInfo());
2194 Block
->setIsVariadic(CallOperator
->isVariadic());
2195 Block
->setBlockMissingReturnType(false);
2198 SmallVector
<ParmVarDecl
*, 4> BlockParams
;
2199 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
) {
2200 ParmVarDecl
*From
= CallOperator
->getParamDecl(I
);
2201 BlockParams
.push_back(ParmVarDecl::Create(
2202 Context
, Block
, From
->getBeginLoc(), From
->getLocation(),
2203 From
->getIdentifier(), From
->getType(), From
->getTypeSourceInfo(),
2204 From
->getStorageClass(),
2205 /*DefArg=*/nullptr));
2207 Block
->setParams(BlockParams
);
2209 Block
->setIsConversionFromLambda(true);
2211 // Add capture. The capture uses a fake variable, which doesn't correspond
2212 // to any actual memory location. However, the initializer copy-initializes
2213 // the lambda object.
2214 TypeSourceInfo
*CapVarTSI
=
2215 Context
.getTrivialTypeSourceInfo(Src
->getType());
2216 VarDecl
*CapVar
= VarDecl::Create(Context
, Block
, ConvLocation
,
2217 ConvLocation
, nullptr,
2218 Src
->getType(), CapVarTSI
,
2220 BlockDecl::Capture
Capture(/*variable=*/CapVar
, /*byRef=*/false,
2221 /*nested=*/false, /*copy=*/Init
.get());
2222 Block
->setCaptures(Context
, Capture
, /*CapturesCXXThis=*/false);
2224 // Add a fake function body to the block. IR generation is responsible
2225 // for filling in the actual body, which cannot be expressed as an AST.
2226 Block
->setBody(new (Context
) CompoundStmt(ConvLocation
));
2228 // Create the block literal expression.
2229 Expr
*BuildBlock
= new (Context
) BlockExpr(Block
, Conv
->getConversionType());
2230 ExprCleanupObjects
.push_back(Block
);
2231 Cleanup
.setExprNeedsCleanups(true);